105 lines
3.0 KiB
Python
105 lines
3.0 KiB
Python
# -*- encoding: utf-8 -*-
|
|
|
|
# @author : vincent.benoit@scle.fr
|
|
# @brief : Client UNIX Socket Manager
|
|
|
|
#########################################################
|
|
# Importation de modules externes #
|
|
|
|
import sys, re, os
|
|
import socket
|
|
import select
|
|
import time
|
|
|
|
#########################################################
|
|
# Classes et Methodes #
|
|
|
|
class TimeoutError(Exception):
|
|
''' TimeoutError for socket '''
|
|
|
|
def __init__(self):
|
|
super().__init__("socket timeout")
|
|
|
|
class Sock:
|
|
''' Socket class '''
|
|
|
|
def __init__(self, addr="", logger=None):
|
|
''' Class constructor
|
|
'''
|
|
self.addr = addr
|
|
self.log = logger
|
|
self.isConnected = False
|
|
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
|
|
def connect(self):
|
|
''' connect to KineIntercom server
|
|
'''
|
|
ret = False
|
|
idx = 0
|
|
while not ret and idx < 3:
|
|
try:
|
|
self.sock.connect(self.addr)
|
|
ret = True
|
|
except TimeoutError as e:
|
|
self.log.error("Erreur de connexion avec le processus KineIntercom")
|
|
except ConnectionRefusedError as e:
|
|
self.log.error("Connexion refusée avec le processus KineIntercom")
|
|
except FileNotFoundError as e:
|
|
self.log.error("Connexion inexistante")
|
|
idx = idx + 1
|
|
time.sleep(1)
|
|
self.isConnected = ret
|
|
return ret
|
|
|
|
def disconnect(self):
|
|
''' Disconnect from KineIntercom server
|
|
'''
|
|
self.sock.close()
|
|
|
|
def send(self, msg):
|
|
''' Send message to Server
|
|
|
|
:param msg:
|
|
message (bytes) send to server
|
|
|
|
return bool:
|
|
True if OK, otherwise False
|
|
'''
|
|
totalsent = 0
|
|
ret = True
|
|
while totalsent < len(msg):
|
|
sent = self.sock.send(msg[totalsent:])
|
|
if sent == 0:
|
|
self.log.error("socket connection broken")
|
|
ret = False
|
|
break
|
|
totalsent = totalsent + sent
|
|
return ret
|
|
|
|
def recv_timeout(self, bytes_to_read=0, timeout_seconds=0):
|
|
''' Receive message from Server
|
|
|
|
:param bytes_to_read:
|
|
bytes to read from socket
|
|
|
|
:param timeout_seconds:
|
|
timeout to raise custom exception
|
|
|
|
:return bytes:
|
|
datas received from socket
|
|
'''
|
|
self.sock.setblocking(0)
|
|
self.log.debug("waiting datas ...")
|
|
ready = select.select([self.sock], [], [], timeout_seconds)
|
|
if ready[0]:
|
|
return self.sock.recv(bytes_to_read)
|
|
|
|
self.log.error("sock timeout")
|
|
raise TimeoutError
|
|
|
|
#########################################################
|
|
# Decorators #
|
|
|
|
#########################################################
|
|
# Instantiation #
|