def _execute_all_modules(class_name, method_name, method_args=None): ''' Execute on alla available modules (in modules/) Execute a method in a module or class(classmethod) if exists ''' for name, mod in loaded_modules.iteritems(): try: if class_name != None: mod = getattr(mod, class_name) mod = getattr(mod, method_name) try: if method_args == None: mod() else: mod(*method_args) except: if class_name == None: steelsquid_utils.shout("Module error: " + name + "." + method_name + "(" + str(method_args) + ")", is_error=True) else: steelsquid_utils.shout("Module error: " + name + "." + class_name + "." + method_name + "(" + str(method_args) + ")", is_error=True) except: pass
def _read(heading_zero=True, switch_roll_pitch=False): ''' Get BNO055 angles heading, roll, pitch Return None, None, None : Error in read data ''' global starting global offset global heading global roll global pitch global is_ok if is_ok: try: heading, roll, pitch = bno.read_euler() if heading_zero: if heading > 180 and heading <= 360: heading = heading - 360 if offset == None: offset = heading heading = heading - offset if switch_roll_pitch: return heading, pitch, roll else: return heading, roll, pitch except: steelsquid_utils.shout() is_ok=False if switch_roll_pitch: return 0, pitch, roll else: return 0, roll, pitch
def do_mount(): ''' Mount sshfs and samba ''' mount_list = steelsquid_utils.get_list("sshfs") for row in mount_list: row = row.split("|") ip = row[0] port = row[1] user = row[2] password = row[3] local = row[4] remote = row[5] if len(password) > 0 and not steelsquid_utils.is_mounted(local): try: steelsquid_utils.mount_sshfs(ip, port, user, password, remote, local) except: steelsquid_utils.shout() mount_list = steelsquid_utils.get_list("samba") for row in mount_list: row = row.split("|") ip = row[0] user = row[1] password = row[2] local = row[3] remote = row[4] if not steelsquid_utils.is_mounted(local): try: steelsquid_utils.mount_samba(ip, user, password, remote, local) except: steelsquid_utils.shout()
def loop(self): last_left = 0 last_right = 0 while True: sleep = 0.012 try: left = self.left right = self.right if left != last_left or right != last_right: diff_left = abs(last_left - left) diff_right = abs(last_right - left) if self.ramping or diff_left > 30 or diff_right > 30: if diff_left > 10: if last_left > left: left = last_left - 1 elif last_left < left: left = last_left + 1 if diff_right > 10: if last_right > right: right = last_right - 1 elif last_right < right: right = last_right + 1 self._set_dc_speed(left, right) last_left = left last_right = right else: sleep = 0.012 except: steelsquid_utils.shout() time.sleep(sleep)
def loop(self): last_left = 0 last_right = 0 while True: sleep = 0.012 try: left = self.left right = self.right if left != last_left or right != last_right: diff_left = abs(last_left - left) diff_right = abs(last_right - left) if self.ramping or diff_left > 30 or diff_right > 30: if diff_left > 10: if last_left > left: left = last_left - 1 elif last_left < left: left = last_left + 1 if diff_right > 10: if last_right > right: right = last_right - 1 elif last_right < right: right = last_right + 1 self._set_dc_speed(left, right) last_left = left last_right = right else: sleep = 0.012 except: steelsquid_utils.shout() time.sleep(sleep)
def update_lcd_and_voltage(): ''' Execute every 2 second ''' try: # Print IP/voltage to LCD if not DYNAMIC.stop_next_lcd_message: print_this = [] print_this.append(steelsquid_utils.get_date_time()) connected = False # Get network status if steelsquid_kiss_global.last_net: if steelsquid_kiss_global.last_wifi_name!="---": print_this.append(steelsquid_kiss_global.last_wifi_name) print_this.append(steelsquid_kiss_global.last_wifi_ip) connected=True if steelsquid_kiss_global.last_lan_ip!="---": print_this.append(steelsquid_kiss_global.last_lan_ip) connected=True # Write text to LCD if len(print_this)>0: new_lcd_message = "\n".join(print_this) if new_lcd_message!=DYNAMIC.last_lcd_message: DYNAMIC.last_lcd_message = new_lcd_message steelsquid_pi.ssd1306_write(new_lcd_message, 0) else: DYNAMIC.stop_next_lcd_message=False # Read rover voltage RADIO_SYNC.SERVER.voltage_rover = GLOBAL.voltage() except: if steelsquid_kiss_boot.running: steelsquid_utils.shout() return 2 # Execute this method again in 2 second
def write(self, message): ''' Redirect sys.stdout to shout ''' if message != None: if len(str(message).strip())>0: steelsquid_utils.shout(message, always_show=True, to_lcd=False)
def _read(heading_zero=True, switch_roll_pitch=False): ''' Get BNO055 angles heading, roll, pitch Return None, None, None : Error in read data ''' global starting global offset global heading global roll global pitch global is_ok if is_ok: try: heading, roll, pitch = bno.read_euler() if heading_zero: if heading > 180 and heading <= 360: heading = heading - 360 if offset == None: offset = heading heading = heading - offset if switch_roll_pitch: return heading, pitch, roll else: return heading, roll, pitch except: steelsquid_utils.shout() is_ok = False if switch_roll_pitch: return 0, pitch, roll else: return 0, roll, pitch
def on_close_connection(self, connection_object, error_message): ''' Override this to close the connection. Will also execute on connection lost or no connection @param server_object: The connection (Can be None) @param error_message: I a error (Can be None) ''' steelsquid_utils.shout("Connection: Connection closed", debug=True)
def on_client_close(self, client, error): ''' Override this to close connection to client. This will also execute if error in connection to client @param client: Close this client @param error: optionally error (Can be None) ''' steelsquid_utils.shout("Server: Client closed\n" + str(client), debug=True)
def on_close_listener(self, listener_object, error_message): ''' Override this to close the listener. Will also execute on unable to listen @param listener_object: The listener (Can be None) @param error_message: I a error (Can be None) ''' steelsquid_utils.shout("Connection: Listener closed", debug=True)
def on_close_listener(self, listener_object, error_message): ''' Override this to close the listener. Will also execute on unable to listen @param listener_object: The listener (Can be None) @param error_message: I a error (Can be None) ''' steelsquid_utils.shout("Connection: Listener closed", debug=True)
def on_close_connection(self, connection_object, error_message): ''' Override this to close the connection. Will also execute on connection lost or no connection @param server_object: The connection (Can be None) @param error_message: I a error (Can be None) ''' steelsquid_utils.shout("Connection: Connection closed", debug=True)
def _thread(): ''' Thread read from mpu6050 ''' while True: try: _worker() except: steelsquid_utils.shout()
def on_start(): ''' This will execute when system starts Do not execute long running stuff here, do it in on_loop... ''' # Startup message steelsquid_utils.shout("Steelsquid Irrbloss start") if SETTINGS.control == 1: co = "Radio" elif SETTINGS.control == 2: co = "WIFI" elif SETTINGS.control == 3: co = "3G/4G" else: co = "Not saved" steelsquid_utils.shout("Control: " + co + "\n" + "Control IP: " + SETTINGS.control_ip + "\n" + "Video stream IP: " + SETTINGS.video_ip + "\n" + "Audio stream IP: " + SETTINGS.audio_ip + "\n" + "Resolution: " + SETTINGS.width + "x" + SETTINGS.height + "\n" + "FPS: " + SETTINGS.fps + "\n") # Set the on OK and ERROR callback methods...they just flash some LED steelsquid_utils.on_ok_callback_method = UTILS.on_ok steelsquid_utils.on_err_callback_method = UTILS.on_err # Enable network by default try: steelsquid_nm.set_network_status(True) except: pass # Enable and disable networkcards UTILS.set_net_status(SETTINGS.control) # Reset some GPIO IO.OUTPUT.sum_flash() IO.UNITS.headlight(False) IO.UNITS.highbeam(False) IO.UNITS.siren(False) IO.UNITS.speeker(True) IO.OUTPUT.mood(0) # Way ??? steelsquid_pi.gpio_set(26, True) # Max volume steelsquid_utils.execute_system_command_blind( ["amixer", "set", "PCM", "unmute"], wait_for_finish=True) steelsquid_utils.execute_system_command_blind( ["amixer", "set", "PCM", "100%"], wait_for_finish=True) steelsquid_utils.execute_system_command_blind(["alsactl", "store"], wait_for_finish=True) # Center camera IO.UNITS.camera(0, STATIC.servo_position_tilt_start, False) # Setup gstreamer steelsquid_gstreamer.setup_camera_mic(SETTINGS.video_ip, 6607, SETTINGS.audio_ip, 6608, SETTINGS.width, SETTINGS.height, SETTINGS.fps, SETTINGS.bitrate, SETTINGS.tcp_video, SETTINGS.low_light)
def _thread(): ''' Thread read from gps ''' while True: try: gpsd.next() except: steelsquid_utils.shout()
def on_listen_close(self, listener, error): ''' Close the listener. Will also execute on error in listener Override this to log or other thing @param listener: The listener (Can be None) @param error: The error (Can be None) ''' steelsquid_utils.shout("Server: Listener closed", debug=True)
def _thread(): ''' Thread read from mpu6050 ''' while True: try: _worker() except: steelsquid_utils.shout()
def execute(self, connection_object, command, parameters=None): ''' Execute the command (method with same name as the command) Will raise a RuntimeError on error The parameters will be convertet to a list of strings before sent to command. String => [String] int => [String] bool => [True/False] @param connection_object: To read remote adress from (IP) @param command: Command to execute @param paramaters: Paramaters (list of bool, int, float, string or a single bool, int, float, string) @return: Answer list ''' try: remote_add = self.on_get_remote_address(connection_object) if not parameters == None: if isinstance(parameters, (list)): count = 0 for string in parameters: parameters[count] = steelsquid_utils.decode_string( str(string)) count = count + 1 else: parameters = [ steelsquid_utils.decode_string(str(parameters)) ] else: parameters = [] the_answer = None is_found = False if hasattr(self, command): is_found = True fn = getattr(self, command) the_answer = fn(remote_add, parameters) else: for o in self.external_objects: if hasattr(o, command): is_found = True fn = getattr(o, command) the_answer = fn(remote_add, parameters) if not is_found: raise RuntimeError("Command " + command + " not found!") if the_answer != None: if isinstance(the_answer, (list)): count = 0 for string in the_answer: the_answer[count] = steelsquid_utils.encode_string( str(string)) count = count + 1 return the_answer else: return [steelsquid_utils.encode_string(str(the_answer))] except RuntimeError, err: steelsquid_utils.shout() raise err
def start(self): ''' Start server/client ''' self.listen_thread = ListenThread(self) self.listen_thread.start() try: self.on_start() except: steelsquid_utils.shout()
def start(self): ''' Start server/client ''' self.listen_thread = ListenThread(self) self.listen_thread.start() try: self.on_start() except: steelsquid_utils.shout()
def on_setup_client(self): ''' Override this to setup the client. Example setup socket Will loop until server is stopped. @return: Connection object (example socket) ''' sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM) steelsquid_utils.shout("Bluettoth Connection: Client\n"+self.host +":"+ str(self.port), debug=True) return sock
def on_connect(self, connection_object): ''' Override this to connect to a server. Example connect to a socket. Will loop until server is stopped. @param connection_object: The object from on_setup_client @return: connection_object (the connection_object object) ''' connection_object.connect((self.host, self.port)) steelsquid_utils.shout("Socket Connection: Connected to server", debug=True) return connection_object
def on_setup_server(self): ''' Override this to setup the server. Example setup the serversocket Will loop until server is stopped. @return: Listener object (example serversocket) ''' server_sock.bind(("", self.port)) server_sock.listen(3) steelsquid_utils.shout("Bluetooth Connection: Server "+str(self.port), debug=True) return s
def stop(self): ''' Stop server/client ''' try: self.listen_thread.stop_thread() except: pass try: self.on_stop() except: steelsquid_utils.shout()
def stop(self): ''' Stop server/client ''' try: self.listen_thread.stop_thread() except: pass try: self.on_stop() except: steelsquid_utils.shout()
def restart(delay=0): ''' Restart steelsquid daemon ''' if delay == 0: try: steelsquid_kiss_boot._cleanup() except: steelsquid_utils.shout() os.system('systemctl restart steelsquid') else: thread.start_new_thread(_restart, (delay, ))
def reboot(delay=0): ''' Reboot the computer ''' if delay == 0: try: steelsquid_kiss_boot._cleanup() except: steelsquid_utils.shout() os.system("reboot") else: thread.start_new_thread(_reboot, (delay, ))
def on_connect(self, connection_object): ''' Override this to connect to a server. Example connect to a socket. Will loop until server is stopped. @param connection_object: The object from on_setup_client @return: connection_object (the connection_object object) ''' sock.connect((self.host, self.port)) steelsquid_utils.shout("Bluetooth Connection: Connected to server", debug=True) return connection_object
def on_setup_client(self): ''' Override this to setup the client. Example setup socket Will loop until server is stopped. @return: Connection object (example socket) ''' sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) steelsquid_utils.shout("Bluettoth Connection: Client\n" + self.host + ":" + str(self.port), debug=True) return sock
def execute(self, connection_object, command, parameters=None): ''' Execute the command (method with same name as the command) Will raise a RuntimeError on error The parameters will be convertet to a list of strings before sent to command. String => [String] int => [String] bool => [True/False] @param connection_object: To read remote adress from (IP) @param command: Command to execute @param paramaters: Paramaters (list of bool, int, float, string or a single bool, int, float, string) @return: Answer list ''' try: remote_add = self.on_get_remote_address(connection_object) if not parameters == None: if isinstance(parameters, (list)): count = 0 for string in parameters: parameters[count] = steelsquid_utils.decode_string(str(string)) count = count + 1 else: parameters = [steelsquid_utils.decode_string(str(parameters))] else: parameters = [] the_answer = None is_found=False if hasattr(self, command): is_found=True fn = getattr(self, command) the_answer = fn(remote_add, parameters) else: for o in self.external_objects: if hasattr(o, command): is_found=True fn = getattr(o, command) the_answer = fn(remote_add, parameters) if not is_found: raise RuntimeError("Command "+command+" not found!") if the_answer != None: if isinstance(the_answer, (list)): count = 0 for string in the_answer: the_answer[count] = steelsquid_utils.encode_string(str(string)) count = count + 1 return the_answer else: return [steelsquid_utils.encode_string(str(the_answer))] except RuntimeError, err: steelsquid_utils.shout() raise err
def nrf24_callback(command): ''' Master get a command from the slave ''' try: # Execute method on_receive in module RADIO class com = command.split("|") if len(com)>1: steelsquid_kiss_global._execute_first_modules_and_return("RADIO", com[0], (com[1:],)) else: steelsquid_kiss_global._execute_first_modules_and_return("RADIO", com[0], ([],)) except: steelsquid_utils.shout()
def on_start(): ''' This will execute when system starts Do not execute long running stuff here, do it in on_loop... ''' # Startup message steelsquid_utils.shout("Steelsquid SquidRover started") # Enable network by default try: steelsquid_nm.set_network_status(True) except: pass GLOBAL.camera(STATIC.servo_position_pan_start, STATIC.servo_position_tilt_start)
def on_setup_server(self): ''' Override this to setup the server. Example setup the serversocket Will loop until server is stopped. @return: Listener object (example serversocket) ''' server_sock.bind(("", self.port)) server_sock.listen(3) steelsquid_utils.shout("Bluetooth Connection: Server " + str(self.port), debug=True) return s
def _event_data_handler(): ''' Fire the event data events ''' while len(event_data_callback_methods)>0: key, value = event_data_queue.get() last = "Unknown" try: for method in event_data_callback_methods: last = method method(key, value) except: steelsquid_utils.shout("Fatal error in event_data_handler: "+last, is_error=True)
def on_listen(self, listener_object): ''' Override this to start the server listen for connection functionality. Example listen for clients on a socket. Will loop until server is stopped. @param listener_object: The object from on_setup_server @return: connection_object (None = do nothing) ''' try: sock, _ = listener_object.accept() steelsquid_utils.shout("Socket Connection: Client connected", debug=True) return sock except socket.timeout: return None
def on_setup_server(self): ''' Override this to setup the server. Example setup the serversocket Will loop until server is stopped. @return: Listener object (example serversocket) ''' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.settimeout(2) s.bind(('', self.port)) s.listen(3) steelsquid_utils.shout("Socket Connection (Server)\nPort: "+str(self.port), debug=False) return s
def do_on_loop(t_m_obj): ''' Execute the on_loop functions ''' run = 0 try: while run != None and run>=0: run = t_m_obj() if run!=None and run>0: event.wait(run) if event.is_set(): run=None except: steelsquid_utils.shout("Fatal error in LOOP", is_error=True)
def nrf24_slave_thread(): ''' Start slave thread for the NRF24L01 radio transiver listen for data from the master and execute method in RADIO class ''' while running: try: # Listen for data from master data = steelsquid_nrf24.receive(timeout=2) if data!=None: # Execute method on_receive in module RADIO class steelsquid_kiss_global._execute_first_modules_and_return("RADIO", "on_receive", (data,)) except: steelsquid_utils.shout()
def module_status(name, status, argument=None, restart=True): ''' Enable or disable a module name: Name of the mopule status: True/False argument: Send data to the enable or disable method in the module Usually a string to tell the start/stop something restart: restart the steelsquid daemon Return: Is it found ''' try: pkgpath = os.path.dirname(modules.__file__) doit = False for f in pkgutil.iter_modules([pkgpath]): if f[1] == name: doit = True if doit: try: mod = import_module('modules.' + name) if status: steelsquid_utils.set_flag("module_" + name) try: mod.enable(argument) except: steelsquid_utils.del_flag("module_" + name) steelsquid_utils.shout(string="Enable module error", is_error=True) return False else: steelsquid_utils.del_flag("module_" + name) try: mod.disable(argument) except: steelsquid_utils.set_flag("module_" + name) steelsquid_utils.shout(string="Disable module error", is_error=True) return False if restart: os.system('systemctl restart steelsquid') return True except: steelsquid_utils.shout(string="Import module error", is_error=True) return False else: return False steelsquid_utils.shout(string="Module not found") except: steelsquid_utils.shout() return False
def on_start(): ''' This will execute when system starts Do not execute long running stuff here, do it in on_loop... ''' steelsquid_utils.shout("Steelsquid PIIO board enabled") # Reset all LED steelsquid_piio.led(1, False) steelsquid_piio.led(2, False) steelsquid_piio.led(3, False) steelsquid_piio.led(4, False) steelsquid_piio.led(5, False) steelsquid_piio.led(6, False) steelsquid_piio.buz(False) steelsquid_piio.error(False) steelsquid_piio.ok(False) steelsquid_piio.bt(False) # Listen for clicka on power off button steelsquid_piio.power_off_click(SYSTEM.on_button_poweroff) # Listen for clicka on info button steelsquid_piio.info_click(SYSTEM.on_button_info) # Listen for clicka on buttons if there is some modules that listen if steelsquid_kiss_global._has_modules_method("PIIO", "on_button"): steelsquid_piio.button_click(1, SYSTEM.on_button) steelsquid_piio.button_click(2, SYSTEM.on_button) steelsquid_piio.button_click(3, SYSTEM.on_button) steelsquid_piio.button_click(4, SYSTEM.on_button) steelsquid_piio.button_click(5, SYSTEM.on_button) steelsquid_piio.button_click(6, SYSTEM.on_button) # Listen for event on switch if there is some modules that listen if steelsquid_kiss_global._has_modules_method("PIIO", "on_switch"): steelsquid_piio.switch_event(1, SYSTEM.on_switch) steelsquid_piio.switch_event(2, SYSTEM.on_switch) steelsquid_piio.switch_event(3, SYSTEM.on_switch) steelsquid_piio.switch_event(4, SYSTEM.on_switch) steelsquid_piio.switch_event(5, SYSTEM.on_switch) steelsquid_piio.switch_event(6, SYSTEM.on_switch) # Listen for movement if there is some modules that listen if steelsquid_kiss_global._has_modules_method("PIIO", "on_movement"): steelsquid_piio.movement_event(SYSTEM.on_movement) # Listen for rotation if there is some modules that listen if steelsquid_kiss_global._has_modules_method("PIIO", "on_rotation"): steelsquid_piio.rotation_event(SYSTEM.on_rotation) # Load voltage varning and power off LOOP.voltage_waring = float( steelsquid_utils.get_parameter("voltage_warning", "-1")) LOOP.voltage_poweroff = float( steelsquid_utils.get_parameter("voltage_poweroff", "-1"))
def on_listen(self, listener_object): ''' Override this to start the server listen for connection functionality. Example listen for clients on a socket. Will loop until server is stopped. @param listener_object: The object from on_setup_server @return: connection_object (None = do nothing) ''' try: sock, _ = listener_object.accept() steelsquid_utils.shout("Bluetooth Connection: Client connected", debug=True) return sock except socket.timeout: return None
def _event_data_handler(): ''' Fire the event data events ''' while len(event_data_callback_methods) > 0: key, value = event_data_queue.get() last = "Unknown" try: for method in event_data_callback_methods: last = method method(key, value) except: steelsquid_utils.shout("Fatal error in event_data_handler: " + last, is_error=True)
def _exec_method(obj, name, method_args=None): ''' Execute a method inside a object ''' try: obj = getattr(obj, name) try: if method_args==None: obj() else: obj(*method_args) except: steelsquid_utils.shout("Module error: " + name + "("+str(method_args)+")", is_error=True) except: pass
def import_file_dyn(obj): ''' Load custom module ''' try: class_settings = steelsquid_kiss_global._get_object(obj, "SETTINGS") if class_settings!=None: persistent_off=False try: persistent_off = getattr(class_settings, "_persistent_off")==True except: pass if not persistent_off: members = [attr for attr in dir(class_settings) if not callable(getattr(class_settings, attr)) and not attr.startswith("_")] for var_name in members: the_var = getattr(class_settings, var_name, None) if isinstance(the_var, (bool)): the_var = steelsquid_utils.get_flag(var_name) setattr(class_settings, var_name, the_var) elif isinstance(the_var, list): the_var = steelsquid_utils.get_list(var_name, the_var) setattr(class_settings, var_name, the_var) elif isinstance(the_var, int): the_var = steelsquid_utils.get_parameter(var_name, str(the_var)) setattr(class_settings, var_name, int(the_var)) elif isinstance(the_var, float): the_var = steelsquid_utils.get_parameter(var_name, str(the_var)) setattr(class_settings, var_name, float(the_var)) else: the_var = steelsquid_utils.get_parameter(var_name, str(the_var)) setattr(class_settings, var_name, the_var) class_system = steelsquid_kiss_global._get_object(obj, "SYSTEM") if class_system!=None: steelsquid_kiss_global._exec_method_set_started(class_system, "on_start", is_started=True) method_event = steelsquid_kiss_global._get_object(class_system, "on_event_data") if method_event!=None: steelsquid_kiss_global.add_event_data_callback(method_event) class_events = steelsquid_kiss_global._get_object(obj, "EVENTS") if class_events!=None: steelsquid_kiss_global.add_broadcast_event_callback(class_events) class_loop = steelsquid_kiss_global._get_object(obj, "LOOP") if class_loop!=None: for ob in vars(class_loop): m = getattr(class_loop, ob, None) if callable(m): thread.start_new_thread(do_on_loop, (m,)) except: steelsquid_utils.shout("Fatal error when load module: " +obj.__name__, is_error=True)
def on_loop(): ''' Check voltage level ''' global last_print_voltage new_voltage = steelsquid_piio.volt(2, 4) steelsquid_kiss_global.last_voltage = new_voltage v_warn = "" if new_voltage < LOOP.voltage_waring: v_warn = " (Warning)" steelsquid_piio.low_bat(True) steelsquid_kiss_global._execute_all_modules( "PIIO", "on_low_bat", (new_voltage, )) else: steelsquid_piio.low_bat(False) if new_voltage < LOOP.voltage_poweroff: if LOOP.voltage_poweroff_count >= 3: LOOP.voltage_poweroff_count = 0 steelsquid_piio.shutdown() else: LOOP.voltage_poweroff_count = LOOP.voltage_poweroff_count + 1 else: LOOP.voltage_poweroff_count = 0 if new_voltage != steelsquid_piio.last_voltage: steelsquid_piio.last_voltage = new_voltage if abs(new_voltage - last_print_voltage) >= 0.1: if last_print_voltage == 0: steelsquid_utils.shout("Voltage is: " + str(new_voltage), to_lcd=False) last_print_voltage = new_voltage steelsquid_kiss_global._execute_all_modules( "PIIO", "on_voltage_change", (new_voltage, )) if not steelsquid_utils.get_flag( "no_lcd_voltage") and not steelsquid_utils.get_flag( "no_net_to_lcd"): last = steelsquid_pi.lcd_last_text if last != None and "VOLTAGE: " in last: i1 = last.find("VOLTAGE: ", 0) + 9 if i1 != -1: i2 = last.find("\n", i1) if i2 == -1: news = last[:i1] + str(new_voltage) + v_warn else: news = last[:i1] + str( new_voltage) + v_warn + last[i2:] steelsquid_piio.lcd(news, number_of_seconds=0) return 1
def on_setup_server(self): ''' Override this to setup the server. Example setup the serversocket Will loop until server is stopped. @return: Listener object (example serversocket) ''' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.settimeout(2) s.bind(('', self.port)) s.listen(3) steelsquid_utils.shout("Socket Connection (Server)\nPort: " + str(self.port), debug=False) return s
def module_status(name, status, argument = None, restart=True): ''' Enable or disable a module name: Name of the mopule status: True/False argument: Send data to the enable or disable method in the module Usually a string to tell the start/stop something restart: restart the steelsquid daemon Return: Is it found ''' try: pkgpath = os.path.dirname(modules.__file__) doit=False for f in pkgutil.iter_modules([pkgpath]): if f[1]==name: doit=True if doit: try: mod = import_module('modules.'+name) if status: steelsquid_utils.set_flag("module_"+name) try: mod.enable(argument) except: steelsquid_utils.del_flag("module_"+name) steelsquid_utils.shout(string="Enable module error", is_error=True) return False else: steelsquid_utils.del_flag("module_"+name) try: mod.disable(argument) except: steelsquid_utils.set_flag("module_"+name) steelsquid_utils.shout(string="Disable module error", is_error=True) return False if restart: os.system('systemctl restart steelsquid') return True except: steelsquid_utils.shout(string="Import module error", is_error=True) return False else: return False steelsquid_utils.shout(string="Module not found") except: steelsquid_utils.shout() return False
def on_start(): ''' This will execute when system starts Do not execute long running stuff here, do it in on_loop... ''' steelsquid_utils.shout("Steelsquid PIIO board enabled") # Reset all LED steelsquid_piio.led(1, False) steelsquid_piio.led(2, False) steelsquid_piio.led(3, False) steelsquid_piio.led(4, False) steelsquid_piio.led(5, False) steelsquid_piio.led(6, False) steelsquid_piio.buz(False) steelsquid_piio.error(False) steelsquid_piio.ok(False) steelsquid_piio.bt(False) # Listen for clicka on power off button steelsquid_piio.power_off_click(SYSTEM.on_button_poweroff) # Listen for clicka on info button steelsquid_piio.info_click(SYSTEM.on_button_info) # Listen for clicka on buttons if there is some modules that listen if steelsquid_kiss_global._has_modules_method("PIIO", "on_button"): steelsquid_piio.button_click(1, SYSTEM.on_button) steelsquid_piio.button_click(2, SYSTEM.on_button) steelsquid_piio.button_click(3, SYSTEM.on_button) steelsquid_piio.button_click(4, SYSTEM.on_button) steelsquid_piio.button_click(5, SYSTEM.on_button) steelsquid_piio.button_click(6, SYSTEM.on_button) # Listen for event on switch if there is some modules that listen if steelsquid_kiss_global._has_modules_method("PIIO", "on_switch"): steelsquid_piio.switch_event(1, SYSTEM.on_switch) steelsquid_piio.switch_event(2, SYSTEM.on_switch) steelsquid_piio.switch_event(3, SYSTEM.on_switch) steelsquid_piio.switch_event(4, SYSTEM.on_switch) steelsquid_piio.switch_event(5, SYSTEM.on_switch) steelsquid_piio.switch_event(6, SYSTEM.on_switch) # Listen for movement if there is some modules that listen if steelsquid_kiss_global._has_modules_method("PIIO", "on_movement"): steelsquid_piio.movement_event(SYSTEM.on_movement) # Listen for rotation if there is some modules that listen if steelsquid_kiss_global._has_modules_method("PIIO", "on_rotation"): steelsquid_piio.rotation_event(SYSTEM.on_rotation) # Load voltage varning and power off LOOP.voltage_waring = float(steelsquid_utils.get_parameter("voltage_warning", "-1")) LOOP.voltage_poweroff = float(steelsquid_utils.get_parameter("voltage_poweroff", "-1"))
def _exec_method(obj, name, method_args=None): ''' Execute a method inside a object ''' try: obj = getattr(obj, name) try: if method_args == None: obj() else: obj(*method_args) except: steelsquid_utils.shout("Module error: " + name + "(" + str(method_args) + ")", is_error=True) except: pass
def on_setup_client(self): ''' Override this to setup the client. Example setup socket Will loop until server is stopped. @return: Connection object (example socket) ''' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) global only_once if steelsquid_utils.development(): steelsquid_utils.shout("Socket Connection (Client)\n"+self.host +":"+ str(self.port), debug=True) else: if not only_once: only_once = True steelsquid_utils.shout("Socket Connection (Client)\n"+self.host +":"+ str(self.port), debug=False) return sock
def nrf24_server_thread(): ''' Start server for the NRF24L01 radio transiver ''' while running: try: # Listen for request from the client command, data = steelsquid_nrf24.listen(timeout=2) if command!=None: # Execute a method with the sam ename as the command i module RADIO class try: answer = steelsquid_kiss_global._execute_first_modules_and_return("RADIO", command, (data,)) steelsquid_nrf24.response(answer) except Exception, e: steelsquid_nrf24.error(e.message) except: if running: steelsquid_utils.shout()
def send_mail(): ''' Send alarm mail ''' try: urllib.urlretrieve("http://localhost:8080/?action=snapshot", "/tmp/snapshot1.jpg") time.sleep(1.5) urllib.urlretrieve("http://localhost:8080/?action=snapshot", "/tmp/snapshot2.jpg") time.sleep(1.5) urllib.urlretrieve("http://localhost:8080/?action=snapshot", "/tmp/snapshot3.jpg") ip = steelsquid_utils.network_ip_test_all() if steelsquid_utils.get_flag("web_https"): link = 'https://'+ip+'/utils?alarm' else: link = 'http://'+ip+'/utils?alarm' steelsquid_utils.notify("Security alarm from: " + os.popen("hostname").read()+"\n"+link, ["/tmp/snapshot1.jpg", "/tmp/snapshot2.jpg", "/tmp/snapshot3.jpg"]) except: steelsquid_utils.shout()
def _broadcast_event_handler(): ''' Fire the broadcast event ''' while len(broadcast_event_callback_classes) > 0: event, parameters_to_event = broadcast_event_queue.get() last = "Unknown" try: for aclass in broadcast_event_callback_classes: last = aclass if hasattr(aclass, event): m = getattr(aclass, event) if parameters_to_event == None: m() else: m(*parameters_to_event) except: steelsquid_utils.shout("Fatal error in broadcast_event_handler: " + last, is_error=True)
def send(data): ''' Send data to the client Return True/False if succesfull ''' del buff[:] # Split the data into chucks if data == None: chunks = [] else: chunks = steelsquid_utils.split_chunks(data, package_size - 1) if len(chunks) == 0: chunks.append(None) for chunk in chunks: del buff[:] if chunk == None or chunk == chunks[-1]: # No more data to send after this buff.append(0) else: # More datat to send after this buff.append(1) if chunk != None: buff.extend(bytearray(chunk)) # Send the chunk if radio.write(buff): radio.whatHappened() # did it return with a payload (slave send back command) #if radio.isAckPayloadAvailable(): del buff[:] radio.read(buff, radio.getDynamicPayloadSize()) if len(buff) > 1: command = bytearray(buff).decode("utf-8") # Execute the callbackmethod try: command_callback_method(command) except: steelsquid_utils.shout() else: radio.whatHappened() return False return True
def on_setup_client(self): ''' Override this to setup the client. Example setup socket Will loop until server is stopped. @return: Connection object (example socket) ''' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) global only_once if steelsquid_utils.development(): steelsquid_utils.shout("Socket Connection (Client)\n" + self.host + ":" + str(self.port), debug=True) else: if not only_once: only_once = True steelsquid_utils.shout("Socket Connection (Client)\n" + self.host + ":" + str(self.port), debug=False) return sock
def send_command_return_answer(command): ''' ''' answer = [] if len(base_remote_server) > 0: try: stdin, stdout, stderr = ssh[0].exec_command("export TERM=xterm;export PYTHONPATH=/opt/steelsquid/python:/usr/lib/python3/dist-packages;"+command) for line in stdout.readlines(): line = line.replace("\n","").replace("\r","") answer.append(line) except: try: answer = [] connect() stdin, stdout, stderr = ssh[0].exec_command("export TERM=xterm;export PYTHONPATH=/opt/steelsquid/python:/usr/lib/python3/dist-packages;"+command) for line in stdout.readlines(): line = line.replace("\n","").replace("\r","") answer.append(line) except: import steelsquid_utils steelsquid_utils.shout() return answer
def _exec_method_set_started(obj, name, method_args=None, is_started=True): ''' Execute a method inside a object Also try to set the is_started variable ''' try: obj = getattr(obj, name) ok = True try: if method_args == None: obj() else: obj(*method_args) except: ok = False steelsquid_utils.shout("Module error: " + name + "(" + str(method_args) + ")", is_error=True) if ok: obj.is_started = is_started except: pass
def handle(self, client): ''' Handle a client. ''' self.clients.append(client) execute = True error = None try: remote_add = self.server.on_get_remote_address(client) try: for o in self.server.external_objects: if hasattr(o, "is_server"): o.is_server = self.server.is_server if hasattr(o, "on_connect"): fn = getattr(o, "on_connect") fn(remote_add) except: steelsquid_utils.shout() while execute: the_type, command, parameters = self.server.on_read(client) if not self.running: execute = False if command != None: if the_type == "request": answer_list = None try: answer_list = self.server.execute( client, command + "_request", parameters) except: import traceback import sys exc_type, exc_var, exc_traceback = sys.exc_info() answer_list = [str(exc_var)] del exc_traceback with self.server.lock: execute = self.server.on_write( "error", client, command, answer_list) else: if answer_list != None: with self.server.lock: execute = self.server.on_write( "response", client, command, answer_list) elif the_type == "response": try: self.server.execute(command + "_response", parameters) except: steelsquid_utils.shout() elif the_type == "error": try: self.server.execute(client, command + "_error", parameters) except: steelsquid_utils.shout() except Exception, err: error = str(err)
def _thread(): ''' Thread initialize BNO055 ''' global bno global is_ok is_ok = False while True: if not is_ok: for i in range(10): try: bno = BNO055.BNO055(serial_port='/dev/ttyS0', rst=18) break except: time.sleep(0.5) for i in range(10): try: if bno.begin(): break else: time.sleep(0.5) except: steelsquid_utils.shout() time.sleep(0.5) for i in range(10): try: status, self_test, error = bno.get_system_status() if status == 0x01: time.sleep(0.5) else: break except: time.sleep(0.5) is_ok = True else: time.sleep(0.5)