def __init__(self, working_dir): ''' Constructor @param working_dir: Working directory ''' LagartoClient.__init__(self, working_dir) addr = self.config.broadcast.split(':') if len(addr) < 3: raise LagartoException("Incorrect broadcast address:port, " + self.config.broadcast) port = int(addr[2]) + 1 pub_address = addr[0] + ':' + addr[1] + ':' + str(port) # ZMQ PUB socket self.pub_socket = None # PUB socket between broker and clients try: self.pub_socket = self.context.socket(zmq.PUB) if self.pub_socket.bind(pub_address) == -1: raise LagartoException("Unable to bind ZMQ PUB socket to " + pub_address) else: print "ZMQ PUB socket binded to", pub_address except zmq.ZMQError as ex: raise LagartoException("Unable to bind ZMQ PUB socket to " + pub_address + ": " + str(ex))
def eval_upload(self): """ Evaluate possible transmissions. To be called once per minute """ if self.tx_config is None: return transmissions = self.tx_config["cloud"] update = False current = datetime.now() for name, tx in transmissions.iteritems(): interval = tx["interval"] if interval == "1m": update = True elif interval == "5m": if current.minute % 5 == 0: update = True elif interval == "15m": if current.minute % 15 == 0: update = True elif interval == "30m": if current.minute % 30 == 0: update = True elif interval == "1h": if current.minute == 0: update = True elif interval == "12h": if current.hour % 12 == 0: update = True elif interval == "1d": if current.hour == 0: update = True if update: update = False # Fill endpoint data endpoint_values = [] for field_id in tx["endpoints"]: endp_name = tx["endpoints"][field_id] endp = network.get_endpoint(endp_name) if endp is None: raise LagartoException("Unable to find a matching endpoint for " + endp_name + " before updating " + name + " from database") elif endp.value is None: raise LagartoException(endp_name + " has an invalid value. Unable to upload " + name + " to " + tx["service"]) else: endpoint_values.append((field_id, endp.value)) update = True if update: if tx["service"] == "ThingSpeak": thinkspeak = ThingSpeakPacket(tx["apikey"], endpoint_values) thinkspeak.push()
def save(self): """ Save current configuration file in disk """ try: f = open(self.file_name, 'w') f.write("<?xml version=\"1.0\"?>\n") f.write("<lagarto>\n") f.write("\t<procname>" + self.procname + "</procname>\n") f.write("\t<comms>\n") if self.address is not None: f.write("\t\t<address>" + self.address + "</address>\n") if self.mqttserver is not None: f.write("\t\t<mqttserver>" + self.mqttserver + "</mqttserver>\n") if self.mqttport is not None: f.write("\t\t<mqttport>" + self.mqttport + "</mqttport>\n") if self.publish is not None: f.write("\t\t<publish>" + self.publish + "</publish>\n") if self.httpport is not None: f.write("\t\t<httpport>" + str(self.httpport) + "</httpport>\n") f.write("\t</comms>\n") f.write("</lagarto>\n") f.close() except: raise LagartoException("Unable to save " + self.file_name)
def config_mote(self, address, new_address, txinterval): """ Configure device @param address current device address @param new_address new address to be configured for the mote @param txinterval Tx interval """ try: # Get mote object mote = self.server.network.get_mote(address=int(address)) if mote is not None: # Save commands if txinterval != "": res = mote.save_txinterval_command(int(txinterval)) if new_address != "": newaddr = int(new_address) if mote.address != newaddr: res = mote.save_address_command(newaddr) return res except: raise LagartoException("Unable to config device with address = " + str(address))
def set_endpoint(self, endpoint): """ Set endpoint value @param endpoint: lagarto endpoint @return network data in JSON format """ if endpoint.procname is None: return None if endpoint.procname not in self.http_servers: return None server = self.http_servers[endpoint.procname] try: conn = httplib.HTTPConnection(server, timeout=20) if endpoint.id is not None: conn.request( "GET", "/values/?id=" + endpoint.id + "&value=" + str(endpoint.value)) elif endpoint.location is not None and endpoint.name is not None: conn.request( "GET", "/values/?location=" + endpoint.location + "&name=" + endpoint.name + "&value=" + str(endpoint.value)) response = conn.getresponse() if response.reason == "OK": return json.loads(response.read()) except: raise LagartoException("Unable to get response from HTTP server") return None
def general_settings(self, debug, local, remote, update, serial, network, swapnet): """ Configure serial modem @param debug debug level @param local local device definition folder @param remote remote device definition folder @param update update local device definition folder on start-up @param serial serial gateway config file @param network wireless config file @param swapnet SWAP network file """ try: config = XmlSettings(self.swap_settings) config.debug = int(debug) config.device_localdir = local config.device_remote = remote if update is not None: config.updatedef = update == "true" config.serial_file = serial config.network_file = network config.swap_file = swapnet # Save config file config.save() except: raise LagartoException("Unable to save general settings")
def __init__(self, working_dir): ''' Constructor @param working_dir: Working directory ''' threading.Thread.__init__(self) LagartoProcess.__init__(self, working_dir) self.running = True # ZMQ PUSH socket self.sub_socket = None # Create ZeroMQ sockets self.context = zmq.Context() # ZMQ PUB socket self.sub_socket = None if self.config.broadcast is not None: self.sub_socket = self.context.socket(zmq.SUB) # Bind/connect ZMQ SUB socket try: # Try binding socket first if self.sub_socket.bind(self.config.broadcast) == -1: raise LagartoException( "Unable to bind zmq sub socket to " + self.config.broadcast) else: self.sub_socket.setsockopt(zmq.SUBSCRIBE, "") print "ZMQ SUB socket binded to", self.config.broadcast except zmq.ZMQError as ex: try: # Now try connecting to the socket if self.sub_socket.connect(self.config.broadcast) == -1: raise LagartoException( "Unable to connect zmq sub socket to " + self.config.broadcast) else: print "ZMQ SUB socket connected to ", self.config.broadcast except zmq.ZMQError as ex: raise LagartoException( "Unable to establish connection with zmq sub socket") # List of HTTP servers self.http_servers = {}
def request_status(self, procname, req): """ Query/command network/endpoint status from server @param procname: name of the process to be queried @param req: queried/controlled endpoints @return status """ if len(req) > 0: control = False if "value" in req[0]: control = True cmd_list = [] for endp in req: if endp["location"] is not None and endp["name"] is not None: cmd = "location=" + endp[ "location"] + "&" + "name=" + endp["name"] elif endp["id"] is not None: cmd = "id=" + endp["id"] else: raise LagartoException( "Insufficient data to identify endpoint") if control: cmd += "&value=" + endp["value"] cmd_list.append(cmd) if procname in self.http_servers: try: conn = httplib.HTTPConnection(self.http_servers[procname], timeout=5) conn.request("GET", "/values/?" + "&".join(cmd_list)) response = conn.getresponse() if response.reason == "OK": status_response = json.loads(response.read()) status_msg = LagartoMessage(status_response) return status_msg.status except: raise LagartoException( "Unable to get response from HTTP server") return None
def run(self): """ Run database manager on its own thread """ try: # Connection to SQLite database self._dbconn = sqlite3.connect(self.database_path) except sqlite3.Error, e: raise LagartoException(e.args[0])
def save_config(self): """ Save configuration file containing metadata """ try: tx_cfg_file = open(self.config_path, 'w') json.dump(self.tx_config, tx_cfg_file, sort_keys=False, indent=2) tx_cfg_file.close() except IOError: raise LagartoException("Unable to save cloud configuration in " + self.config_path)
def delete(self): """ Delete current graph from config file """ if self.name in self.graph_config["graphs"]: del self.graph_config["graphs"][self.name] self.save() else: raise LagartoException("Unable to delete " + self.name + " from " + self.config_path)
def save(self): """ Save properties in configuration file """ try: cfg_file = open(self.config_path, 'w') json.dump(self.graph_config, cfg_file, sort_keys=False, indent=2) cfg_file.close() except IOError: raise LagartoException("Unable to save graph configuration in " + self.config_path)
def delete_mote(self, address): """ Delete device @param address current device address """ try: self.network.delete_mote(int(address)) self.network.save() except: raise LagartoException("Unable to delete device with address = " + str(address))
def __init__(self, working_dir): ''' Constructor @param working_dir: Working directory ''' LagartoProcess.__init__(self, working_dir) context = zmq.Context() # ZMQ PUB socket self.pub_socket = None if self.config.broadcast is not None: self.pub_socket = context.socket(zmq.PUB) # Bind/connect socket try: # Try binding socket first if self.pub_socket.bind(self.config.broadcast) == -1: raise LagartoException("Unable to bind zmq pub socket") else: print "ZMQ PUB socket binded to ", self.config.broadcast except zmq.ZMQError as ex: try: # Now try connecting to the socket if self.pub_socket.connect(self.config.broadcast) == -1: raise LagartoException( "Unable to connect to zmq pub socket") else: print "ZMQ PUB socket connected to", self.config.broadcast except zmq.ZMQError as ex: raise LagartoException( "Unable to establish connection with zmq pub socket: " + str(ex)) self.publish_lock = threading.Lock() # Heart beat transmission thread hbeat_process = PeriodicHeartBeat(self.publish_status) hbeat_process.start()
def save(self): """ Save current network data into file """ network = self.dumps() try: print "Saving", self.filepath network_file = open(self.filepath, 'w') # Write network data into file json.dump(network, network_file, sort_keys=False, indent=2) network_file.close() except IOError: raise LagartoException( "Unable to save speech recognition network data in file " + self.filepath)
def runquery(self, query): """ Run database query @param query SQL query to be run @return response from database """ # Put query in queue self._queue.put(query, block=True) # Block until the query is run self._queue.join() if self._db_error is not None: raise LagartoException(self._db_error) return self._db_response
def config_modem(self, port, speed): """ Configure serial modem @param port serial port @param serial baudrate """ try: # Open network configuration config = XmlSerial(self.main_settings.serial_file) # Change parameters config.port = port config.speed = int(speed) # Save config file config.save() except: raise LagartoException("Unable to save modem serial settings")
def config_endpoint(self, id, name, location, unit=None): """ Configure endpoint @param id unique id @param name name of endpoint @param location location of endpoint @param unit units shown for the endpoint value """ try: endp = self.get_endpoint(endpid=id) endp.name = name endp.location = location if unit is not None: endp.setUnit(unit) self.network.save() except: raise LagartoException("Unable to save endpoint settings")
def get_endpoints(self, server): """ Serialize network data from lagarto server @param server: lagarto http address:port @return network data in JSON format """ try: conn = httplib.HTTPConnection(server, timeout=5) conn.request("GET", "/values") response = conn.getresponse() if response.reason == "OK": return json.loads(response.read()) except: raise LagartoException("Unable to get response from HTTP server") return None
def config_network(self, channel, netid, address, security, password): """ Configure network parameters from the serial modem @param channel RF channel @param netid SWAP network ID @param address network address @param security wireless security flag @param password password for wireless security """ try: # Open network configuration config = XmlNetwork(self.main_settings.network_file) # Change parameters config.freq_channel = int(channel) config.network_id = int(netid, 16) config.devaddress = int(address) config.security = int(security) config.password = password config.save() except: raise LagartoException("Unable to save modem network settings")
def update_tables(self): """ Update table contents """ if self.db_config is None: return tables = self.db_config["database"] current = datetime.now() for name, table in tables.iteritems(): # Get table object from database dbtable = self.get_table(name) update = False # Get latest timestamp fromdatabase last = dbtable.get_last_timestamp() if last is None: update = True else: elapsed = current - last if not update: if table["interval"] == "1m": if elapsed >= timedelta(minutes=1): update = True elif table["interval"] == "5m": if elapsed >= timedelta(minutes=5): update = True elif table["interval"] == "15m": if elapsed >= timedelta(minutes=15): update = True elif table["interval"] == "30m": if elapsed >= timedelta(minutes=30): update = True elif table["interval"] == "1h": if elapsed >= timedelta(hours=1): update = True elif table["interval"] == "12h": if elapsed >= timedelta(hours=12): update = True elif table["interval"] == "1d": if elapsed >= timedelta(days=1): update = True elif table["interval"] == "1w": if elapsed >= timedelta(weeks=1): update = True elif table["interval"] == "2w": if elapsed >= timedelta(weeks=2): update = True elif table["interval"] == "1M": if current.month != last.month: update = True if update: # Fill endpoint data endpoint_values = [] for endp_id in table["endpoints"]: endp = network.get_endpoint(endp_id) if endp is None: raise LagartoException( "Unable to find a matching endpoint for " + endp_id + " before updating " + name + " from database") if endp.value is None: raise LagartoException( endp_id + " has an invalid value. Unable to update " + name + " from database") endpoint_values.append(endp.value) # Update table dbtable.update(endpoint_values)