def change_mode(self, name_mode): Logger.info("Change mode : {} => {}".format( self.list_modes.selected().name, name_mode)) mode_select = self.get_mode(name_mode) self.global_environnement.change_mode(mode_select) self.list_modes.change_select(mode_select) self.global_environnement.do_current_scenar()
def press_inter(self, name_env, name_inter, state): Logger.info("press inter {}, state = {}, env = {}".format( name_inter, state, name_env)) if name_env.split(".")[0] == "mode": self.change_mode(name_env.split(".")[1]) else: self.get_env(name_env).press_inter(name_inter, state)
def check_for_disconnection(self): """ check if the connection exceed the TIME_OUT since the last send """ while (time() - self.timeout) < TIME_OUT: sleep(0.1) Logger.info("Disconnect from {}".format(self.name)) self.disconnect()
def start(self): Logger.info("Waiting for a connection, Server Started") self.started = True while self.started: conn, addr = self.socket.accept() Logger.info("Connected to: "+ str(addr)) process = Thread(target=self.threaded_client, args=[conn]) process.start()
def do(self, scenar): # start the scenario self.current_scenar.set_state(False) self.current_scenar = scenar self.current_scenar.set_state(True) self.current_scenar.do() Logger.info("Do scenario {}.{}".format(self.name, self.current_scenar.name))
def write_reg(self, ip, register, data): self.mutex.acquire() try: self.bus.write_byte_data(ip, register, data) except Exception as e: Logger.error("I2C write reg error : " + str(e)) sleep(0.01) # to make sure all the infos are sent self.mutex.release()
def connect(self): self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=self.host, username=self.user, password=self.password, port=22) Logger.info("ssh connected to " + self.host)
def connect(self): self.lock() # start the pc if it is down if not (self.state()): Logger.info("Power on {}".format(self.name)) self.power_on() sleep(75) # time to the pc to startup # now the serveur should be launch self.unlock()
def connect(self): if not (self.port): self.mutex.acquire() try: self.port = Serial(self.addr, baudrate=9600, timeout=0.1) except: Logger.error("Fail to connect to the amp") return False self.mutex.release() return True
def send(self, char, valeur): self.mutex_send.acquire() try: char[0].write(valeur) except: Logger.error("Connection error in the bluetooth sending") self.mutex_send.release() return 1 self.mutex_send.release() return 0
def read_reg(self, ip, register): self.mutex.acquire() try: data = self.bus.read_byte_data(ip, register) except Exception as e: Logger.error("I2C read reg error : " + str(e)) self.mutex.release() return None sleep(0.01) self.mutex.release() return data
def write_data(self, ip, data): self.mutex.acquire() try: self.bus.write_i2c_block_data(ip, 0, data) except Exception as e: Logger.error("I2C write data error : " + str(e)) self.mutex.release() return 1 sleep(0.01) self.mutex.release() return 0
def connect(self): self.mutex.acquire() try: self.client.connect(self.addr) self.connected = True data = pickle.loads(self.client.recv(4096)) self.mutex.release() return data except : Logger.error("The connection to the server failed") self.mutex.release() return None
def disconnect(self, periph): if periph != None: try: self.mutex_disconnect.acquire() periph.disconnect() periph = None self.mutex_disconnect.release() except BrokenPipeError as e: Logger.error("Bluetooth disconnection error : "+str(e)) self.mutex_connect.acquire() self.nb_connection -= 1 self.mutex_connect.release()
def start(self, attemps = 0): try: self.sp.transfer_playback(self.pi_id, force_play=True) self.sp.repeat("context", device_id=self.pi_id) except spotipy.exceptions.SpotifyException as e: self.refresh_token() os.system("sudo systemctl restart raspotify.service") sleep(2) if attemps < 3: self.start(attemps+1) else: Logger.error("Could not start raspotify : "+str(e)) self.state = True
def __init__(self, name, addr): try: self.port = Serial(addr, baudrate=9600) except: Logger.error("The st_nucleo {} could not open it's port {}".format(name, addr)) self.port = None self.name = name # the i2c bus that control the relay can out of order the st nucleo # if it is used at the same time (probably some interferrences) # so I used the same mutex self.mutex = I2C.mutex self.addr = addr self.list_boards_triak = Dico()
def send(self, message): self.lock() self.timeout = time() if not (self.client.state()): if self.client.connect(): Logger.info("Connect from {}".format(self.name)) Thread(target=self.check_for_disconnection).start() else: Logger.error("Could not connect to {} at {}".format( self.name, self.addr)) self.unlock() return data = self.client.send(message) self.unlock() return data
def repair(self): if isinstance(self.controler, Wifi_device): Logger.info("Trying to connect to " + self.name) self.set_state(STATE.ON) ko = self.controler.connect(attempts=5) if ko: Logger.error("The led {} is out of order".format(self.name)) for _ in range(0, 3): self.set_state(STATE.OFF) sleep(3) self.set_state(STATE.ON) sleep(3) return True self.disconnect() self.set_state(STATE.OFF) return False
def connect(self): if not (self.connected): if self.color.is_black() and not (self.force): self.set_state(True) sleep(1) self.connected = self.controler.connect() if not (self.connected): # the led is out of order Logger.error("The led {} is out of order".format(self.name)) self.set_state(False) else: Logger.info("Connected to {}".format(self.name)) # only one type of led have a real dimmer, # but need to be up self.controler.send_dimmer(100) return self.connected
def __init__(self, getter, port = 5555): """ This is a Server, it allows the client to send message to it and it just do that the message need to do and respond to the client """ self.ip_address = socket.gethostbyname(socket.gethostname()) self.port = port self.getter = getter self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.bind(("", self.port)) except socket.error as e: Logger.error(str(e)) self.socket.listen(2) self.started = False
def run(self, barrier): """ Setup a try/finally to allow kill from another instruction """ try: super().run() self.light.lock() delay = time() x_init, y_init = self.light.get_position() x_final, y_final = self.eval(self.x), self.eval(self.y) if self.duration == 0: return nb_points = RESOLUTION * self.duration if x_init != x_final: liste_x = np.arange(x_init, x_final, (x_final - x_init) / nb_points) else: liste_x = [x_init] * int(nb_points) if y_init != y_final: liste_y = np.arange(y_init, y_final, (y_final - y_init) / nb_points) else: liste_y = [y_init] * int(nb_points) barrier.wait() for x, y in zip(liste_x, liste_y): temps = time() if self.light.test(): raise SystemExit("kill inst") self.light.set_position(int(x), int(y)) barrier.wait() dodo = 1 / RESOLUTION - (time() - temps) if dodo > 0: sleep(dodo) except SystemExit: Logger.info("The instruction on {} was killed".format( self.light.name)) finally: Logger.info("{} took {}s to move instead of {}s".format( self.light.name, time() - delay, self.duration)) self.light.set_position(x_final, y_final) self.light.unlock()
def send_bytes(self, *bytes): """Send commands to the device. If the device hasn't been communicated to in 5 minutes, reestablish the connection. """ check_connection_time = (datetime.datetime.now() - self.latest_connection).total_seconds() try: message_length = len(bytes) self.s.send(struct.pack("B"*message_length, *bytes)) # Close the connection unless requested not to if self.keep_alive is False: self.s.close except socket.error as exc: Logger.error("Caught exception socket.error : %s" % exc) if self.s: self.s.close()
def send(self, msg): try: self.mutex.acquire() self.client.send(pickle.dumps(msg)) lenght = int(pickle.loads(self.client.recv(4096))) raw_data = b"".join([self.client.recv(4096) for i in range(0,lenght, 4096)]) data = "" if raw_data != b'': data = pickle.loads(raw_data) if type(data) == Exception: trace = traceback.format_exc() Logger.error("Error during request : {}\n{}".format(trace, str(data))) self.mutex.release() return data except socket.error as e: Logger.error(e) self.mutex.release()
def inter(self, getter, status, volume, track, position): Logger.debug("Spotify : {} : volume={} : track ={} : position {}".format(status, volume, track, position)) if status == "start": if self.analysis: self.player.start() self.track = Track(self.sp, self.player, track) elif status == "playing": if self.analysis: self.player.start() print("music = {} : player = {} : diff = {}".format(position, self.player.tps, int(position)-self.player.tps)) self.player.set(int(position)) if not(self.state) and self.scenar_start: self.scenar_start.do() self.state = True elif status == "paused": if self.analysis: self.player.stop() print("music = {} : player = {} : diff = {}".format(position, self.player.tps, int(position)-self.player.tps)) if self.state and self.scenar_stop: self.scenar_stop.do() self.state = False elif status == "stop": if self.analysis: self.player.stop() if self.state and self.scenar_stop: self.scenar_stop.do() self.state = False elif status == "volume_set": # on set le nv volume print("nv volume = "+str(volume)) if abs(volume-self.volume) > 20: self.scenar_volume.do() self.volume = volume elif status == "change": if self.analysis: track = Track(self.sp, self.player, track) if self.track != None: self.track.kill() self.track = track
def restart(self): """ Restart the bluetooth of the rpi NEEDED FOR LONG TIME RUNNING RPI """ self.mutex_reset.acquire() if not(self.reset): Logger.info("Want to reset the bluetooth") self.reset = True self.mutex_reset.release() # just wait until all devices are disconnected debut = time() while self.nb_connection > 0 and time()-debut < 30: sleep(1) # on restart le bluetooth os.system("sudo systemctl restart bluetooth") Logger.info("Bluetooth restart") sleep(20) self.mutex_reset.acquire() self.reset = False self.mutex_reset.release()
def run(self, barrier): super().run() if self.action == ACTIONS.power_on: self.pc.connect() Logger.info("Power on {}".format(self.pc.name)) elif self.action == ACTIONS.power_off: self.pc.disconnect() Logger.info("Power off {}".format(self.pc.name)) elif self.action == ACTIONS.key: self.pc.send(Press_key(self.args[0])) Logger.info("press " + self.args[0]) elif self.action == ACTIONS.mouse: double_clic = False clic_right = False x, y = self.args[0:2] if len(self.args) > 2: double_clic = (self.args[3] == "double") clic_right = (self.args[3] == "droit") self.pc.send(Press_mouse(x, y, clic_right, double_clic)) Logger.info("clic " + self.args)
def detect_interrupt(self, event): data = self.bus.read(self.port_bus,0x12 + self.add_register) Logger.info("interrupt {} : {}:{} data={}".format(self.port_interrupt, self.port_bus, self.add_register, data)) if data == ['0']*8 or data == ['1']*8 or data == None: return for i,pin in enumerate(data): # check if the pin is up #TODO need to change for the radar.. if int(pin) == 1: Logger.info("pin {} is on".format(i)) try: self.list_inter.get(i).press() sleep(1) return except KeyError: Logger.info("This pin haven't any interrupt on board :\n {}".format(str(self)))
def initialize(self): if self.output_interrupts: # check if the interrupts exist remotely all_inter = self.send(Get_network_interrupt(self.me)) if all_inter: if isinstance(all_inter, list): for inter in self.output_interrupts: if inter not in all_inter: Logger.error( "No link to the interrupt {} for {}".format( inter, self.name)) else: Logger.error( "Exception during interrupt initialization on {} : {}". format(self.name, all_inter)) else: Logger.error("No connection or interrupt to {} at {}".format( self.name, self.addr))
def get_channel(self, i): try: return self.channels[i-1] except: Logger.error("") return None
def press_inter(self, getter, name, state): Logger.info("receive {}:{} from {}".format(name, state, self.name)) if name in self.input_interrrupts.keys(): getter.get_tree().press_inter(self.input_interrrupts.get(name), name, state)