def getsock(): timeout = 10 # Create a TCP/IP socket while (get_local_ip('8.8.8.8') == None): time.sleep(1) myip = get_local_ip('8.8.8.8') log("GetSock got the IP : " + str(myip), "debug") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) log( "Bind the socket to the IP:Port : " + str(myip) + ":" + str(core.SRV_PORT), "info") server_address = ('', core.SRV_PORT) try: sock.bind(server_address) log("Starting up socket on port : " + str(core.SRV_PORT), "debug") except socket.error: log( "Port : " + str(core.SRV_PORT) + " is already in use, changing port", "info") core.SRV_PORT += 1 server_address = ('', core.SRV_PORT) sock.bind(server_address) log("Starting up socket on port : " + str(core.SRV_PORT), "info") return sock
def writing_default_config_to_file(): core.CFG = ConfigParser.RawConfigParser() core.CFG.add_section('SPOT') core.CFG.set('SPOT', 'LOG_FILE_LOCATION', '/opt/spot/log') core.CFG.set('SPOT', 'SLEEP_TIMER_SEC', 40) core.CFG.set('SPOT', 'MAX_TIME_NOT_SEEN', 2) core.CFG.add_section('CLIENTS') core.CFG.set('CLIENTS', 'LOG_FILE_LOCATIONS_CLIENTS', '/opt/spot/log') core.CFG.add_section('CCU') core.CFG.set('CCU', 'IP_CCU', '192.168.180.220') core.CFG.add_section('PIFACECAD') core.CFG.set('PIFACECAD', 'PIFACECAD_SUPPORT', False) core.CFG.add_section('RGBLED') core.CFG.set('RGBLED', 'RGBLED_SUPPORT', False) core.CFG.set('RGBLED', 'RGBLED_RED', 24) core.CFG.set('RGBLED', 'RGBLED_GREEN', 23) core.CFG.set('RGBLED', 'RGBLED_BLUE', 25) core.CFG.add_section('BLUETOOTH') core.CFG.set('BLUETOOTH', 'BT_SUPPORT', True) try: # Writing the configuration file to 'spot.cfg' with open((core.PROG_DIR + '/' + file_name), 'wb') as configfile: core.CFG.write(configfile) configfile.close() except IOError: log("unable to write the Config File. Exiting", "error") print('unable to write in : ' + core.PROG_DIR + '/' + file_name) os._exit(0)
def get_device_to_check(): try: response = urllib2.urlopen('http://' + str(core.IP_CCU) + '/config/xmlapi/sysvarlist.cgi', timeout=2) except (urllib2.URLError) as e: log("Timeout by connection to the CCU : " + str(core.IP_CCU), "error") print("There was an error: %r" % e) device_dict = None return device_dict except: log("Timeout by connection to the CCU : " + str(core.IP_CCU), "error") device_dict = None return device_dict html = response.read() # Lode XML files into the variable device_dict = {} # import xml.etree.ElementTree as ET # root = ET.fromstring(html) # read the xml information for var_spot in root.findall('systemVariable'): # walk through the xml elements with the name 'systemVariable' var_mac = var_spot.get('name') # read element if var_mac.find('spot_') != -1: # look for the name 'spot_' nametmp = var_spot.get('name') nametmp = nametmp.split('_') # separate the individual values (spot_CC:29:F5:67:B7:EC_marius_iPhone) device_dic_val = {} device_dic_val["presence"] = str(var_spot.get('value')) device_dic_val['name'] = str(nametmp[3]) device_dic_val['ise_id'] = str(var_spot.get('ise_id')) device_dic_val['first_not_seen'] = None device_dic_val['times_not_seen'] = 0 device_dict[nametmp[2]] = device_dic_val return device_dict
def writing_default_config_to_file(): core.CFG = ConfigParser.RawConfigParser() core.CFG.add_section('SPOT') core.CFG.set('SPOT', 'LOG_FILE_LOCATION', '/opt/spot/log') core.CFG.set('SPOT', 'SLEEP_TIMER_SEC', 40) core.CFG.set('SPOT', 'MAX_TIME_NOT_SEEN', 2) core.CFG.add_section('CLIENTS') core.CFG.set('CLIENTS', 'LOG_FILE_LOCATIONS_CLIENTS', '/opt/spot/log') core.CFG.add_section('CCU') core.CFG.set('CCU', 'IP_CCU', '192.168.180.220') core.CFG.add_section('PIFACECAD') core.CFG.set('PIFACECAD', 'PIFACECAD_SUPPORT', False) try: # Writing the configuration file to 'spot.cfg' with open((core.PROG_DIR + '/' + file_name), 'wb') as configfile: core.CFG.write(configfile) configfile.close() except IOError: log("unable to write the Config File. Exiting", "error") print ('unable to write in : ' + core.PROG_DIR + '/' + file_name) os._exit(0)
def valid_command(v): log("Sensor - Checking command: " + str(v), "debug") try: return v.lower() in ("checkdevice", "displaytext") except AttributeError: print("Attribute Error") return False
def Init(self): try: interface = self.ConectToServer().init('192.168.1.250:8990', '12345678') return True except xmlrpclib.Fault as err: log (err.faultString, 'error')
def valid_command(v): log("Sensor - Checking command: " + str(v), "debug") try: return v.lower() in ("ping", "checkdevice", "displaytext", "gethostname", "rgbled") except AttributeError: print("Attribute Error") return False
def getValueFromHMDimmer(self, device): try: result = self.ConectToServer().gettValue(device, 'LEVEL') log('Value for Device: %s is %s'% (device, result), 'debug') except xmlrpclib.Fault as err: log (err.faultString, 'error'), err.faultString
def display_msg_on_sensors_display(MSG_Text): # send the MSG to all sensors, store all in sensor_data[k] for k, v in core.SPOT_SENSOR.items(): # (k)ey = IP-Address # (v)alue = Port log(str(k) + " sending msg to sensor's display : " + MSG_Text, "debug") check_sensor(k, v) time.sleep(1) display_msg(k, v, MSG_Text)
def deleteHMDevice(self, serial): try: interface = self.ConectToServer().deleteDevice(serial) log('The interface with the Serial: %s was deleted'%(serial), 'info') sleep(3) except xmlrpclib.Fault as err: log (err.faultString, 'error')
def addHMDevice(self, serial): try: interface = self.ConectToServer().addDevice(serial) log('The interface with the Serial: %s was added'%(serial), 'info') return True except xmlrpclib.Fault as err: log ('%s', 'error'), err.faultString
def str2bool(v): try: return v.lower() in ("yes", "true", "t", "1", "-1") except AttributeError: if type(v) is bool: return v else: log("str2bool. Konnte variable nicht umwandeln Exit : " + str(v), "info") os._exit(0)
def getHMDeviceDescription(self, serial): try: self.result = self.ConectToServer().getDeviceDescription(serial) log('The interface with the Serial: %s was deleted'% (serial), 'info') return self.result except xmlrpclib.Fault as err: log (err.faultStringg, 'error')
def display_msg_on_sensors_display(MSG_Text): # send the MSG to all sensors, store all in sensor_data[k] for k, v in core.SPOT_SENSOR.items(): # (k)ey = IP-Address # (v)alue = Port log(str(k) + " sending msg to sensor's display : " + MSG_Text, "debug") check_sensor(k, v) time.sleep(1) display_msg(k, v, MSG_Text) '''
def str2bool(v): try: return v.lower() in ("yes", "true", "t", "1", "-1") except AttributeError: if (type(v) is bool): return v else: log("str2bool. Konnte variable nicht umwandeln Exit : " + str(v), "info") os._exit(0)
def handle(self): request = self.request[0].strip() if request == "spot": # is it our UDP client? Handler.number_client += 1 log("Detected client : " + str(Handler.number_client) + " on " + str(self.client_address), "debug") socket = self.request[1] reply = "%s:%i " % (Handler.my_addr, core.SRV_PORT) socket.sendto(reply, self.client_address) else: log("Detected wrong UDP request from client : " + str(self.client_address), "debug")
def getHMChildren(self, serial): try: self.description = self.getHMDeviceDescription(serial) for key, values in self.description.items(): if key == 'CHILDREN': log('Function [getHMChildren : ' + str(values) + ']', 'debug') return values except: log ('Function [getHMChildren : ]Do not return CHILDREN', 'error')
def display_rgbled_on_sensors(rgb_code): # send the RGB LED to all sensors, store all in sensor_data[k] for k, v in core.SPOT_SENSOR.items(): # (k)ey = IP-Address # (v)alue = Port log( str(k) + " sending rgb LED to sensor's LED : " + str(rgb_code), "debug") check_sensor(k, v) time.sleep(1) display_rgbled(k, v, rgb_code)
def SonosFunctions(self, zonenip, function, value=''): sonos = SoCo(zonenip) func = getattr(sonos,function) if value == '': func() else: func(value) log('Function %s for %s IP'% (function, zonenip), 'debug')
def setValueToHMDevice(self, devicetype, device, value=''): try: if value == '': value = self.getParamsetFromHMDevice(device) value = self.toggleSwitch(value) interfaces = self.ConectToServer().setValue(device, devicetype, value) log('Set Device with serial :%s to %s : %s"'%(device, devicetype, value), 'debug') except xmlrpclib.Fault as err: log (err.faultString, 'error')
def GetDeviceList(self): info = {} for ip in sonos_devices.get_speaker_ips(): device = SoCo(ip) zone_name = device.get_speaker_info()['zone_name'] if zone_name != None: info[zone_name] = ip log('Function [GetDeviceList: %s ]'% (info.items()), 'debug') return info.items()
def getParamsetFromHMDevice(self, devices): try: self.Paramsets = [] for device in devices: self.Paramset = self.ConectToServer().getParamset(device, 'VALUES') self.Paramsets.append(self.Paramset) return self.Paramsets except xmlrpclib.Fault as err: log (err.faultString, 'error')
def GetHmDescription(self): """ Return information of all devices witch are added to the HomeMatic interface. """ try: interfaces = self.ConectToServer().listDevices() return interfaces except xmlrpclib.Fault as err: log ('%s', 'error'), err.faultString
def send_device_status_to_ccu(ise_id, var_status): # send one Device Status at a time command = "http://" + str(core.IP_CCU) + "/config/xmlapi/statechange.cgi?ise_id=" + ise_id + "&new_value=" + \ var_status log("sendVariableToCCU2.befehl : " + str(command), "debug") try: response = urllib2.urlopen(command, timeout=2) except urllib2.URLError, e: log("Timeout by connection to the CCU : " + str(core.IP_CCU), "error") if not core.PROG_DAEMONIZE: print("There was an error: %r" % e) return False
def start_local_sensor(scrip_parameters): import subprocess scrip_name = 'spot_sensor.py' script_abspath = core.PROG_DIR + '/' + scrip_name if os.path.isfile(script_abspath): # Check if the Script is already running log("Script file is present, OK .", "debug") cmd_command = 'ps aux | grep ' + scrip_name + ' | grep -v grep' process = subprocess.Popen(cmd_command, shell=True, stdout=subprocess.PIPE) output, err = process.communicate() if len(output) > 0: log("Script is already running, OK .", "debug") else: log("Starting : " + scrip_name, "debug") os.system(('python ' + script_abspath + ' -s')) # just in case, old pid-file is present time.sleep(1) # giving the os time os.system(('python ' + script_abspath + ' ' + scrip_parameters)) else: log( "Not able to start local SENSOR due to its absence: " + script_abspath + " ! System will try to discover " " remote Sensor ", "error")
def set_color(rgb_code): if not is_initialized: log("set_color call initialize RGB LED", "debug") initialize() time.sleep(0.2) request = rgb_code if (len(request) == 3): if request is not '000': GPIO.output(RED, int(request[0])) GPIO.output(GREEN, int(request[1])) GPIO.output(BLUE, int(request[2])) else: log("set_color call cleanup RGB LED", "debug") cleanup()
def pid_file_create(): #/usr/bin/env python pid = str(os.getpid()) pidfile = core.PDI_FILE if os.path.isfile(pidfile): log("PID file already exists : " + str(pidfile), "warning") # ex_pid = open(pidfile).read() if isProcessRunning(ex_pid): log("Spot is already runing, exiting : " + str(pidfile), "error") sys.exit() else: log("overwriting PID file : " + str(pidfile), "warning") file(pidfile, 'w').write(pid) else: try: file(pidfile, 'w').write(pid) except IOError: log( "overwriting PID file not possible maybe: Permission denied: " + str(pidfile), "error") return pid
def Event(self,*args): i = iter(args) eventid = i.next() serial= i.next() type = i.next() value = i.next() #print args if type in validdatatyps: DBFunction().UpdateDevice(serial, type, value) log('Device with the Serial : %s switch to %s : %s'% (serial, type, value), 'debug') else: data = '' return data
def GetCamList(self): result = [] connection = sqlite3.connect(core.DB_FILE, timeout=20) cursor = connection.cursor() try: sql = "SELECT CamIP, CamName, CamRoom FROM cams ORDER BY OrderID" cursor.execute(sql) result = cursor.fetchall() cursor.close() except Exception,e: log(e, 'error')
def CeckDatabase(self): connection = sqlite3.connect(core.DB_FILE, timeout=20) cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS interfaces (InterfaceID INTEGER, InterfaceSerial TEXT, InterfaceIP TEXT, InterfaceName TEXT ) ') cursor.execute('CREATE TABLE IF NOT EXISTS devices (OrderID INTEGER, DeviceTyp TETX, DeviceName TEXT, DeviceSerial TEXT, RoomName TEXT, ValueType TEXT, DeviceValue TEXT) ') cursor.execute('CREATE TABLE IF NOT EXISTS rooms (OrderID INTEGER, RoomName TEXT) ') cursor.execute('CREATE TABLE IF NOT EXISTS scenes (OrderID INTEGER, SceneName TEXT) ') cursor.execute('CREATE TABLE IF NOT EXISTS xbmc (OrderID INTEGER, XbmcIP TEXT, XbmcName TEXT, XbmcUsername TEXT, XbmcPassword TEXT, XbmcRoom TEXT) ') cursor.execute('CREATE TABLE IF NOT EXISTS sonos (OrderID INTEGER, SonosIP TEXT, SonosName TEXT, SonosRoom TEXT) ') cursor.execute('CREATE TABLE IF NOT EXISTS cams (OrderID INTEGER, CamIP TEXT, CamName TEXT, CamRoom TEXT) ') connection.commit() cursor.close() log("Checking DB", 'info')
def ConectToServer(self, **kwargs): """ Connect to Api from Homematice interface There you can add different arguments. For example: - verbose=True - multical=True """ try: server = xmlrpclib.ServerProxy("http://192.168.1.150:2001") return server except xmlrpclib.Fault as err: log (err.faultString, 'error')
def start(self): try: self.s.register_function(self.Event, 'event') self.s.register_function(self.listDevices, 'listDevices') self.s.register_function(self.newDevices, 'newDevices') self.s.register_introspection_functions() self.s.register_multicall_functions() #Starting the Server log('Starting EventServer' , 'info') self.s.serve_forever() except: log('EventServer do not start', 'error') return
def GetDeviceList(self, roomName=''): connection = sqlite3.connect(core.DB_FILE, timeout=20) cursor = connection.cursor() if roomName == '': sql = "SELECT DeviceTyp , DeviceName , DeviceSerial , RoomName, DeviceValue FROM devices ORDER BY OrderID" log(sql, 'debug') else: sql = "SELECT DeviceTyp , DeviceName , DeviceSerial , RoomName, DeviceValue FROM devices WHERE RoomName='%s'"% (roomName) log(sql, 'debug') cursor.execute(sql) self.result = cursor.fetchall() cursor.close() return self.result
def updclientstart(): core.SPOT_SENSOR = None core.SPOT_SENSOR = {} s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) s.settimeout(TIME_TO_DISCOVERY) log("sending broadcast to discover the sensors", "debug") s.sendto("spot", ("<broadcast>", PORT)) try: for n in range(1, 10, 1): (sensor_ip, sensor_port) = s.recv(23).split(":") core.SPOT_SENSOR[sensor_ip] = sensor_port except socket.timeout: log(str(len(core.SPOT_SENSOR)) + " sensors discovered : " + str(core.SPOT_SENSOR), "debug") s.close()
def Multicall(slef, methoddic): """ This function send a multicall request to server. The methoddic specificate must be a dictionary. The key is the methodecall and the value must be a list for the arguments for the call. """ self.multicall = xmlrpclib.MultiCall(self.ConectToServer) for methode, values in methoddic: self.call = getattr(self.multicall, methode) self.call(values) log('[ HomeMatic Multicall ] The %s multicall function send %s arguments'% (methode, values), 'debug') self.multicall() return
def getsock(): # Create a TCP/IP socket while (get_local_ip('8.8.8.8') == None): time.sleep(1) myip = get_local_ip('8.8.8.8') log("GetSock got the IP : " + str(myip), "debug") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) log("Bind the socket to the Port : " + str(core.SRV_PORT), "info") server_address = ('', core.SRV_PORT) try: sock.bind(server_address) log("starting up socket, port: " + str(core.SRV_PORT), "debug") except socket.error: log("Port : " + str(core.SRV_PORT) + " is already in use, changing port", "info") core.SRV_PORT += 1 server_address = ('', core.SRV_PORT) sock.bind(server_address) log("starting up socket, port: " + str(core.SRV_PORT), "info") return sock
def updclientstart(): core.SPOT_SENSOR = None core.SPOT_SENSOR = {} s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) s.settimeout(TIME_TO_DISCOVERY) log("sending broadcast to discover the sensors", "debug") s.sendto("spot", ("<broadcast>", PORT)) try: for n in range(1, 10, 1): (sensor_ip, sensor_port) = s.recv(23).split(":") core.SPOT_SENSOR[sensor_ip] = sensor_port except socket.timeout: log( str(len(core.SPOT_SENSOR)) + " sensors discovered : " + str(core.SPOT_SENSOR), "debug") s.close()
def discovery_devices(wait_till_found=True): # get the devices from the ccu2 try: while get_local_ip("8.8.8.8") is None: # check if we have a ip time.sleep(1) devices_to_check = get_device_to_check() if wait_till_found: while devices_to_check is None: time.sleep(2) devices_to_check = get_device_to_check() return devices_to_check except KeyboardInterrupt: log("Got signal to STOP", "info") if core.PROG_DAEMONIZE: startstop(pidfile=core.PDI_FILE, startmsg='stopping daemon', action='stop') else: print("KeyboardInterrupt received, stopping work ") os._exit(0)
def RemoveSonos(self, sonosName): connection = sqlite3.connect(core.DB_FILE, timeout=20) cursor = connection.cursor() sql = "DELETE FROM sonos WHERE SonosName = '" + sonosName + "'" cursor.execute(sql) connection.commit() cursor.close() connection = sqlite3.connect(core.SONOS_DB_FILE, timeout=20) cursor = connection.cursor() sql = "DROP TABLE IF EXISTS '" + sonosName + "'" cursor.execute(sql) connection.commit() cursor.close() log('Remove sonos device with %s Name from DB'% (sonosName), 'info') return
def discovery_sensors(wait_till_found=True): # look up for the sensors # sensors are stored at core.SPOT_SENSOR try: while get_local_ip("8.8.8.8") is None: # check if we have a ip time.sleep(1) if wait_till_found: updclientstart() while len(core.SPOT_SENSOR) == 0: updclientstart() time.sleep(1) else: updclientstart() except KeyboardInterrupt: log("Got signal to STOP", "info") if core.PROG_DAEMONIZE: startstop(pidfile=core.PDI_FILE, startmsg='stopping daemon', action='stop') else: print("KeyboardInterrupt received, stopping work ") os._exit(0)
def stop_local_sensor(): import subprocess scrip_name = 'spot_sensor.py' script_abspath = core.PROG_DIR + '/' + scrip_name if os.path.isfile(script_abspath): # Check if the Script is running log("Script file is present: OK .", "debug") cmd_command = 'ps aux | grep ' + scrip_name + ' | grep -v grep' process = subprocess.Popen(cmd_command, shell=True, stdout=subprocess.PIPE) output, err = process.communicate() if len(output) > 0: log("Sending shutdown command: OK .", "debug") os.system(('python ' + script_abspath + ' -s')) else: log("Script is not running : " + scrip_name, "debug") else: log( "Can not determine if script is running. Script-file not present : " + scrip_name, "error")
def send_device_status_to_ccu(ise_id, var_status): # send one Device Status at a time command = "http://" + str(core.IP_CCU) + "/config/xmlapi/statechange.cgi?ise_id=" + ise_id + "&new_value=" + \ var_status log("sendVariableToCCU2 Command : " + str(command), "debug") try: response = urllib2.urlopen(command, timeout=2) if not core.CCU_CONNECTION_OK: log("Connection to the CCU establish (TX): " + str(core.IP_CCU), "info") core.CCU_CONNECTION_OK = True except urllib2.URLError, e: if core.CCU_CONNECTION_OK: log("Timeout by connection to the CCU (TX): " + str(core.IP_CCU), "error") core.CCU_CONNECTION_OK = False if not core.PROG_DAEMONIZE: print("There was an error: %r" % e) return False
def checkdevice(mac): if core.BT_SUPPORT: try: result2 = bluetooth.lookup_name(mac, timeout=3) except (bluetooth.btcommon.BluetoothError, NameError) as e: log( "bluetooth python Module is not installed - returning : devices are not present", "error") result2 = "None" time.sleep(1.2) else: result2 = "None" if str(result2) != "None": log("bluetooth lookup for MAC : " + str(result2) + " : True ", "debug") return True else: log("bluetooth lookup for MAC : " + str(result2) + " : False ", "debug") return False
# send one Device Status at a time command = "http://" + str(core.IP_CCU) + "/config/xmlapi/statechange.cgi?ise_id=" + ise_id + "&new_value=" + \ var_status log("sendVariableToCCU2 Command : " + str(command), "debug") try: response = urllib2.urlopen(command, timeout=2) if not core.CCU_CONNECTION_OK: log("Connection to the CCU establish (TX): " + str(core.IP_CCU), "info") core.CCU_CONNECTION_OK = True except urllib2.URLError, e: if core.CCU_CONNECTION_OK: log("Timeout by connection to the CCU (TX): " + str(core.IP_CCU), "error") core.CCU_CONNECTION_OK = False if not core.PROG_DAEMONIZE: print("There was an error: %r" % e) return False html = response.read() log("sendVariableToCCU2.html Answer from CCU2 : " + str(html), "debug") if response.msg == 'OK': return True else: return False #if __name__ == "__main__": # getDeviceToCheck()
def main(): if core.PIFACECAD_SUPPORT: import core.piface_display as lcd_display lcd_display.init_support_switches() # Optional lcd_display.display_banner() print("PIFACECAD_SUPPORT is Active") if core.RGBLED_SUPPORT: import core.rgbled as rgb_led rgb_led.set_color('011') print("RGBLED_SUPPORT is Active") log("checking if ip interface is ready", "debug") # wait till we have an ip while get_local_ip("8.8.8.8") == None: time.sleep(1) myip = get_local_ip('8.8.8.8') log("IP-Interface ready! - " + str(myip), "debug") # start to listing port 55555 for clients updserverstart() log("Local Hostname is : " + hostname, "info") # Bind the socket to the address given on the command line sock = getsock() sock.listen(1) while True: time.sleep(1) # check if we did lost the IP if str(myip) != str(get_local_ip('8.8.8.8')): log( "ip interface changed - closing socket and tying to get a new IP", "info") sock.close() while get_local_ip("8.8.8.8") == None: time.sleep(1) myip = get_local_ip('8.8.8.8') log("IP-Interface ready! - " + str(myip), "info") sock = getsock() sock.listen(1) try: log("Waiting for connection", "debug") sock.settimeout(600) connection, client_address = sock.accept() sock.settimeout(60) except (KeyboardInterrupt, socket.error, 'Bad file descriptor') as e: if str(e) == 'KeyboardInterrupt': if core.PROG_DAEMONIZE: log(str(e) + " !! STOPPING !!", "info") startstop(pidfile=core.PDI_FILE_SENSOR, startmsg='stopping daemon', action='stop') else: print("KeyboardInterrupt received, stopping work ") sock.close() os._exit(0) else: if core.PROG_DAEMONIZE: log( str(e) + " !! Restarting after Socket Error !!", "error") else: print("Got a error : %s - restarting socket ") % str(e) sock.close() sock = getsock() sock.listen(1) try: log("Client is connected, IP : " + str(client_address), "debug") while True: line = read_tcp(connection) # test if valid_command(line) == False: writeline(connection, "Fals") log("Unknown command received: discarded : " + str(line), "debug") log("Responding with Fals", "debug") break if line == "checkdevice": log("command received and accepted : " + str(line), "debug") log("responding with True", "debug") writeline(connection, "True") log("waiting for command parameters", "debug") parameters = readlines_to_dict(connection) log("parameters: " + str(parameters), "debug") # checking if parameter is a mac address, if not delete this item for k, v in parameters.items(): if is_mac(k) == False: log( "parameters: " + str(k) + " is not a mac address and will be removed", "debug") del parameters[k] # remove entry with key 'Name' # check if something left number_of_items_in_dic = len(parameters) if number_of_items_in_dic > 0: log( "The number of valid parameters (MAC-Address) is: " + str(number_of_items_in_dic), "debug") # we have some mac-addresses to work with # sent a ok to the client writeline(connection, "True") time.sleep(1) # check if the mac can be seen and sent the result back to the client log( "Transmitting the results back to the client (Spot collector)", "debug") writeline_dict(connection, check_device_dict(parameters)) log("Transition is done", "debug") else: # we didn't find any mac address writeline(connection, "Fals") break # stopping the processing elif line == "displaytext": log("Received text to Display, responding with True", "debug") writeline(connection, "True") line = read_tcp(connection) if core.PIFACECAD_SUPPORT: if str(line) == "ALL OUT": log("Display backlight OFF ", "debug") lcd_display.display_off() else: log("Displaying Text : " + str(line), "debug") lcd_display.display_msg(str(line)) writeline(connection, "True") else: log("PIFACECAD_SUPPORT is not Enabled", "debug") writeline(connection, "Fals") elif line == "ping": log("Received ping, responding with True", "debug") writeline(connection, "True") elif line == "gethostname": log("Get Hostname received, responding with hostname", "debug") writeline(connection, hostname) elif line == "rgbled": log("Received RGB Code to Display, responding with True", "debug") writeline(connection, "True") line = read_tcp(connection) if core.RGBLED_SUPPORT: log("Displaying RGB LED : " + str(line), "debug") rgb_led.set_color(line) writeline(connection, "True") else: log("RGBLED_SUPPORT is not Enabled", "debug") writeline(connection, "Fals") else: if line != "": log( "Unknown command received: discarded : " + str(line), "debug") log("Responding with Fals", "debug") writeline(connection, "Fals") break except (KeyboardInterrupt, socket.error, 'Bad file descriptor', UnboundLocalError) as e: if str(e) == 'KeyboardInterrupt': if core.PROG_DAEMONIZE: startstop(pidfile=core.PDI_FILE_SENSOR, startmsg='stopping daemon', action='stop') else: print("KeyboardInterrupt received, stopping work ") sock.close() os._exit(0) else: if core.PROG_DAEMONIZE: log("got a error : " + str(e), "error") else: print("got a error : %s - restarting socket ") % str(e) sock.close() sock = getsock() sock.listen(1) if core.RGBLED_SUPPORT: rgb_led.set_color('000')
#core.SPOT_SENSOR = options.manually.split(':') core.SPOT_SENSOR = dict( item.split(":") for item in options.manually.split(",")) #except error: print "------------------- IP manual set to " + options.manually + " -------------------" if len(core.SPOT_SENSOR) > 8: p.error( "Sensor IP and Port (10.1.1.2:10002) Mandatory if you not using Automatic Discovery Mode" ) else: core.AUTO_DISCOVERY = True # PIDfile if options.pidfile: print "------------------- Set PID file to " + options.pidfile + " -------------------" log("Set PIDfile to " + options.pidfile, "info") core.PDI_FILE = str(options.pidfile) # Set LOG if options.log: print "------------------- Log DEBUG manual set to True -------------------" core.DEBUG_LOG = True log("DEBUG LOG manual set to True ", "debug") else: core.DEBUG_LOG = None # Teste Funktion! if options.test: print "------------------- Test of a function -------------------" core.DEBUG_LOG = True log("Test of a function, auto debug True", "debug")
core.CFG.set('PIFACECAD', 'PIFACECAD_SUPPORT', False) core.CFG.add_section('RGBLED') core.CFG.set('RGBLED', 'RGBLED_SUPPORT', False) core.CFG.set('RGBLED', 'RGBLED_RED', 24) core.CFG.set('RGBLED', 'RGBLED_GREEN', 23) core.CFG.set('RGBLED', 'RGBLED_BLUE', 25) core.CFG.add_section('BLUETOOTH') core.CFG.set('BLUETOOTH', 'BT_SUPPORT', True) try: # Writing the configuration file to 'spot.cfg' with open((core.PROG_DIR + '/' + file_name), 'wb') as configfile: core.CFG.write(configfile) configfile.close() except IOError: log("unable to write the Config File. Exiting", "error") print('unable to write in : ' + core.PROG_DIR + '/' + file_name) os._exit(0) if not check_file(): writing_default_config_to_file() parse_config() log("Make sure the configuration apply for you", "info") else: load_config_from_file() parse_config() log("Load Config file.. " + core.PROG_DIR + '/' + file_name, "info")
def readlines_to_dict(sock): message = {} for line in readlines(sock): log("Command parameter received : " + str(line), "debug") message[line] = "" return message
def get_device_to_check(): log("Connecting to the CCU to get device list : " + str(core.IP_CCU), "debug") try: response = urllib2.urlopen('http://' + str(core.IP_CCU) + '/config/xmlapi/sysvarlist.cgi', timeout=2) if not core.CCU_CONNECTION_OK: log("Connection to the CCU establish (RX): " + str(core.IP_CCU), "info") core.CCU_CONNECTION_OK = True except (urllib2.URLError) as e: # disrupted if core.CCU_CONNECTION_OK: log("Timeout by connection to the CCU (RX): " + str(core.IP_CCU), "error") core.CCU_CONNECTION_OK = False print("There was an error: %r" % e) device_dict = None return device_dict except: if core.CCU_CONNECTION_OK: log("Timeout by connection to the CCU (RX): " + str(core.IP_CCU), "error") core.CCU_CONNECTION_OK = False device_dict = None return device_dict html = response.read() # Lode XML files into the variable device_dict = {} # import xml.etree.ElementTree as ET # try: root = ET.fromstring(html) # read the xml information except: if core.CCU_CONNECTION_OK: log("XML ParseError CCU (RX): " + str(core.IP_CCU), "error") core.CCU_CONNECTION_OK = False print("There was an error") device_dict = None return device_dict for var_spot in root.findall( 'systemVariable' ): # walk through the xml elements with the name 'systemVariable' var_mac = var_spot.get('name') # read element if var_mac.find('spot_') != -1: # look for the name 'spot_' nametmp = var_spot.get('name') nametmp = nametmp.split( '_' ) # separate the individual values (spot_CC:29:F5:67:B7:EC_marius_iPhone) device_dic_val = {} try: device_dic_val["presence"] = str(var_spot.get('value')) device_dic_val['name'] = str(nametmp[3]) device_dic_val['ise_id'] = str(var_spot.get('ise_id')) device_dic_val['first_not_seen'] = None device_dic_val['times_not_seen'] = 0 device_dic_val['seen_by'] = {} device_dic_val['device'] = str(nametmp[4]) device_dict[nametmp[2]] = device_dic_val except IndexError: log( "sysvar from CCU has wrong format! We need var_spot_80:B0:3D:2D:5F:16_Paulina_iPhone", "error") exit() return device_dict
def main(): nearby_devices_counter = 0 # how many devices are in the coverage of Spot / in the Homezone devices_to_check_counter = 0 # how many devices to check nearby_devices_counter_last_run = 0 log("Starting to collect parameters", "info") log("checking if ip interface is ready", "debug") # wait till we have an ip while get_local_ip("8.8.8.8") is None: time.sleep(1) log( "IP interface is ready to go! local IP : " + str(get_local_ip("8.8.8.8")), "debug") if core.AUTO_DISCOVERY: log("Running Auto Discovery for Sensors ", "debug") discovery_sensors() log("Getting Devices for check from CCU2", "debug") # we will work with devices_to_check all the time and save the response from the sensors here devices_to_check = discovery_devices() devices_to_check_counter = devices_to_check.__len__() log("All parameters collected. System OK -> STARTING WORK", "info") try: request_discovery = False # from time to time I'll rediscover sensors and the "device to check list" counter = 0 # loop counter while True: counter += 1 # count every loop sensor_data = {} pre_lookup = True # to speed up detection if request_discovery: # in some cases we will need to rediscover sensors and devices request_discovery = False log("Rediscovering Sensor and devices. Loop : " + str(counter), "debug") devices_to_check = {} devices_to_check = copy.deepcopy(discovery_devices()) devices_to_check_counter = devices_to_check.__len__() # to see if we got a new sensor tmp_sensor_before = {} tmp_sensor_before = copy.deepcopy(core.SPOT_SENSOR) discovery_sensors() tmp_sensor_after = {} tmp_sensor_after = copy.deepcopy(core.SPOT_SENSOR) for sensor in tmp_sensor_after: # send to log if a new sensor was found if sensor not in tmp_sensor_before.keys(): try: hostnamesensor = get_sensor_name( sensor, sensor_port) except UnboundLocalError: hostnamesensor = "-Err-" log( "main 235 local variable 'sensor_port' referenced before assignment", "error") log( "Sensor :" + str(sensor) + " (" + str(hostnamesensor) + ") is online", "info") # send the device list to all sensors, store all in sensor_data[k] threads = [] thread_counter = 0 for k, v in core.SPOT_SENSOR.items(): # (k)ey = IP-Address of the Sensor # (v)alue = Port of the Sensor log( "checking if : " + str(k) + " . ready to receive the device list", "debug") if check_sensor(k, v): # ping the sensor log(str(k) + ". Sensor is waiting for Data..", "debug") cp_device = {} cp_device = copy.deepcopy( devices_to_check) # deepcopy to avoiding references if (counter % 2) == 0: # just check VIP every second time for mac_of_device, value_of_device in cp_device.items( ): if cp_device[mac_of_device]['device'].lower( ) == "novip": del cp_device[mac_of_device] thread_counter += 1 thread = myThread(thread_counter, k, v, cp_device) thread.start() threads.append(thread) log(str(k) + " sending data to Sensor", "debug") if not core.SENSOR_AVAILABLE: # zu beginn, eine Liste mit den gefundenenen Sensoren erstellen und ausgeben for sensor_ip, sensor_port in core.SPOT_SENSOR.items(): hostnamesensor = get_sensor_name( sensor_ip, sensor_port) log( "Sensor :" + str(sensor_ip) + " (" + str(hostnamesensor) + ") is online", "info") core.SENSOR_AVAILABLE = True else: log( "Sensor ping failed to : " + str(k) + " . Moving on to the next sensor", "debug") log("Sensor : " + str(k) + " . Disconnected", "info") request_discovery = True # Wait for all threads to complete for t in threads: t.join() sensor_data[str(t.ip_address)] = t.get_list() log( "Beginning to calculate the presence information from the Sensors", "debug") presence_of_devices = {} presence_of_devices = accumulate_sensor_data( sensor_data, devices_to_check) # create a time stamp time_now = time.time() time_stamp = datetime.datetime.fromtimestamp(time_now).strftime( '%Y-%m-%d-%H:%M:%S') if len(presence_of_devices) == 0: if core.SENSOR_AVAILABLE: log("All Sensor are offline!", "error") core.SENSOR_AVAILABLE = False log("All Sensors Down. loop counter " + str(counter), "debug") request_discovery = True else: # checking if device presence has changed for k, v in devices_to_check.items(): # k = mac-address try: if devices_to_check[k]['presence'].lower( ) == 'true' and presence_of_devices[k] > 0: # was visible ist visible do nothing devices_to_check[k]['first_not_seen'] = None devices_to_check[k]['times_not_seen'] = 0 seen_by = "" for items in devices_to_check[k]['seen_by']: if devices_to_check[k]['seen_by'][items]: seen_by = seen_by + str(items) + " " log( str(k) + " is still present. Loop : " + str(counter) + " Seen by : " + seen_by, "debug") elif devices_to_check[k]['presence'].lower() == 'true' and presence_of_devices[k] == 0 and \ devices_to_check[k]['times_not_seen'] < core.MAX_TIME_NOT_SEEN: # was visible ist not visible < MAX count not seen + 1, set first time not seen devices_to_check[k]['times_not_seen'] += 1 if devices_to_check[k]['first_not_seen'] is None: devices_to_check[k][ 'first_not_seen'] = time_stamp log( str(k) + " is first time no seen. Loop : " + str(counter), "debug") elif devices_to_check[k]['presence'].lower() == 'true' and presence_of_devices[k] == 0 and \ devices_to_check[k]['times_not_seen'] >= core.MAX_TIME_NOT_SEEN: # was visible ist not visible = MAX! update ccu2, was visible = False # send update to ccu2 send_ok = send_device_status_to_ccu( devices_to_check[k]['ise_id'], 'false') log("OUT - " + str(devices_to_check[k]['name']) + " since " + \ str(devices_to_check[k]['first_not_seen']) + ".", "info") log(str(k) + " - " + str(devices_to_check[k]['name']) + \ " is last seen at " + \ str(devices_to_check[k]['first_not_seen']) + ". going to update the CCU2", "debug") if send_ok: # successful log( str(k) + " changes successfully updated to CCU2", "debug") else: log( str(k) + " problem trying to update changes to CCU2", "debug") devices_to_check[k][ 'presence'] = 'False' # update the dict display_msg_on_sensors_display( "O:" + str(devices_to_check[k]['name'])) time.sleep(1) # passing to a DB -> elif devices_to_check[k]['presence'].lower( ) == 'false' and presence_of_devices[k] > 0: # was not visible ist visible update ccu2, was visible = True, reset counter and stamp # send update to ccu2 send_ok = send_device_status_to_ccu( devices_to_check[k]['ise_id'], 'true') seen_by = "" for items in devices_to_check[k]['seen_by']: if devices_to_check[k]['seen_by'][items]: seen_by = seen_by + str(items) + " " log(" IN - " + str(devices_to_check[k]['name']) + " since " + str(time_stamp) + ". Seen by : " + \ seen_by, "info") log(str(k) + " - " + str(devices_to_check[k]['name']) + \ " is here now. Update is sent to CCU2", "debug") if send_ok: # successful log( str(k) + " changes successfully updated to CCU2", "debug") else: log( str(k) + " problem trying to update changes to CCU2", "debug") devices_to_check[k][ 'times_not_seen'] = 0 # reset not seen counter to 0 devices_to_check[k][ 'first_not_seen'] = None # reset first time stamp devices_to_check[k][ 'presence'] = 'True' # update the dict display_msg_on_sensors_display( "I:" + str(devices_to_check[k]['name'])) display_rgbled_on_sensors('001') time.sleep(1) # passing to a DB -> else: log(str(k) + " remains unavailable", "debug") except KeyError: log( str(k) + " skipping this loop because its no VIP ", "debug") # if activated, send a alive signal to ccu2. To activate it, u need to create a # system variable ('last_update_') on the ccu2 #if core.CCU_LAST_UPDATE is not None: # send_ok = send_device_status_to_ccu('last_update_', '"' + time_stamp + '"') # calculate how many devices are around, for this run nearby_devices_counter = 0 for dev, int_presence in presence_of_devices.items( ): # dev = int (0 / 1) nearby_devices_counter += int(int_presence) log( str(nearby_devices_counter) + " of " + str(devices_to_check_counter) + " are in the coverage of Spot", "debug") #if nearby_devices_counter_last_run != nearby_devices_counter: # nearby_devices_counter_last_run = nearby_devices_counter if nearby_devices_counter == 0: log("no more devices around", "debug") # no one there. Start process core.SLEEP_TIMER = core.SLEEP_TIMER_OUT display_msg_on_sensors_display("ALL OUT") display_rgbled_on_sensors('100') else: # someone is there. Start process log(str(nearby_devices_counter) + " devices around", "debug") core.SLEEP_TIMER = core.SLEEP_TIMER_IN display_rgbled_on_sensors('010') if counter > 15: # Rediscover after every 15 loops counter = 0 request_discovery = True log("going sleep for " + str(core.SLEEP_TIMER) + " s", "debug") time.sleep(core.SLEEP_TIMER) except KeyboardInterrupt: log("Got signal to STOP", "info") display_rgbled_on_sensors('000') display_msg_on_sensors_display("ALL OUT") if core.PROG_DAEMONIZE: startstop(pidfile=core.PDI_FILE, startmsg='stopping daemon', action='stop') else: print("KeyboardInterrupt received, stopping work ") os._exit(0)
#!/usr/bin/env python # # -*- coding: <utf-8> -*- """ The Protocol: """ import core import time import RPi.GPIO as GPIO from core.Logger import log version = "1.0.2" log("Loading Module RGBLED.", "debug") is_initialized = False RED = int(core.RGBLED_RED) GREEN = int(core.RGBLED_GREEN) BLUE = int(core.RGBLED_BLUE) def set_color(rgb_code): if not is_initialized: log("set_color call initialize RGB LED", "debug") initialize() time.sleep(0.2) request = rgb_code if (len(request) == 3): if request is not '000': GPIO.output(RED, int(request[0])) GPIO.output(GREEN, int(request[1]))
def run(self): addr = ("", PORT) log("UDP server listening on : " + str(addr), "debug") server = UDPServer(addr, Handler) server.serve_forever()