def stop(signum=0, frame=None): global RUNNING if RUNNING: logger.info("Stopping...") RUNNING = False for task in TASKS: task.stop()
def findRoute(self, path): for source in self.routes: if path.startswith(source): route = path.replace(source, self.routes[source]) logger.info("Routing /%s => /%s" % (path, route)) return route return path
def addRoute(self, source, destination): if source[0] == "/": source = source[1:] if destination[0] == "/": destination = destination[1:] self.routes[source] = destination logger.info("Added Route /%s => /%s" % (source, destination))
def run(self): info("CoAP Server binded on coap://%s:%s/" % (self.host, self.port)) while self.running == True: try: (request, client) = self.socket.recvfrom(1500) requestBytes = bytearray(request) coapRequest = COAPRequest() coapRequest.parseByteArray(requestBytes) coapResponse = COAPResponse() # self.logger.debug("Received Request:\n%s" % coapRequest) self.processMessage(coapRequest, coapResponse) # self.logger.debug("Sending Response:\n%s" % coapResponse) responseBytes = coapResponse.getBytes() self.socket.sendto(responseBytes, client) self.logger.debug( '"%s %s CoAP/%.1f" - %s (Client: %s)' % ( coapRequest.CODES[coapRequest.code], coapRequest.uri_path, coapRequest.version, coapResponse.CODES[coapResponse.code], client[0], ) ) except socket.timeout as e: continue except Exception as e: if self.running == True: exception(e) info("CoAP Server stopped")
def run(self): info("CoAP Server binded on coap://%s:%s/" % (self.host, self.port)) while self.running == True: try: (request, client) = self.socket.recvfrom(1500) requestBytes = bytearray(request) coapRequest = COAPRequest() coapRequest.parseByteArray(requestBytes) coapResponse = COAPResponse() #self.logger.debug("Received Request:\n%s" % coapRequest) self.processMessage(coapRequest, coapResponse) #self.logger.debug("Sending Response:\n%s" % coapResponse) responseBytes = coapResponse.getBytes() self.socket.sendto(responseBytes, client) self.logger.debug( '"%s %s CoAP/%.1f" - %s (Client: %s)' % (coapRequest.CODES[coapRequest.code], coapRequest.uri_path, coapRequest.version, coapResponse.CODES[coapResponse.code], client[0])) except socket.timeout as e: continue except Exception as e: if self.running == True: exception(e) info("CoAP Server stopped")
def main(argv): port = 8000 configfile = None scriptfile = None logfile = None i = 1 while i < len(argv): if argv[i] in ["-c", "-C", "--config-file"]: configfile = argv[i+1] i+=1 elif argv[i] in ["-l", "-L", "--log-file"]: logfile = argv[i+1] i+=1 elif argv[i] in ["-s", "-S", "--script-file"]: scriptfile = argv[i+1] i+=1 elif argv[i] in ["-h", "-H", "--help"]: displayHelp() elif argv[i] in ["-d", "--debug"]: setDebug() else: try: port = int(argv[i]) except ValueError: displayHelp() i+=1 if logfile: logToFile(logfile) info("Starting %s" % VERSION_STRING) server = Server(port=port, configfile=configfile, scriptfile=scriptfile) runLoop() server.stop()
def run(self): info("HTTP Server binded on http://%s:%s%s" % (self.host, self.port, self.context)) try: self.serve_forever() except Exception as e: if self.running == True: exception(e) info("HTTP Server stopped")
def enableMulticast(self): while not self.running: pass mreq = struct.pack("4sl", socket.inet_aton(self.multicast_ip), socket.INADDR_ANY) self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) info("CoAP Server binded on coap://%s:%s/ (MULTICAST)" % (self.multicast_ip, self.port))
def loadModules(bus): if BUSLIST[bus]["enabled"] == False and not modulesLoaded(bus): info("Loading %s modules" % bus) for module in BUSLIST[bus]["modules"]: loadModule(module) if "wait" in BUSLIST[bus]: info("Sleeping %ds to let %s modules load" % (BUSLIST[bus]["wait"], bus)) time.sleep(BUSLIST[bus]["wait"]) BUSLIST[bus]["enabled"] = True
def loadScript(name, source, handler = None): logger.info("Loading %s from %s" % (name, source)) script = imp.load_source(name, source) SCRIPTS[name] = script if hasattr(script, "setup"): script.setup() if handler: for aname in dir(script): attr = getattr(script, aname) if callable(attr) and hasattr(attr, "macro"): handler.addMacro(attr) if hasattr(script, "loop"): thread.runLoop(script.loop, True)
def loadScript(name, source, handler=None): logger.info("Loading %s from %s" % (name, source)) script = imp.load_source(name, source) SCRIPTS[name] = script if hasattr(script, "setup"): script.setup() if handler: for aname in dir(script): attr = getattr(script, aname) if callable(attr) and hasattr(attr, "macro"): handler.addMacro(attr) if hasattr(script, "loop"): thread.runLoop(script.loop, True)
def addDeviceInstance(name, dev, args): funcs = {"GET": {}, "POST": {}} for att in dir(dev): func = getattr(dev, att) if callable(func) and hasattr(func, "routed"): if name == "GPIO": logger.debug("Mapping %s.%s to REST %s /GPIO/%s" % (dev, att, func.method, func.path)) else: logger.debug("Mapping %s.%s to REST %s /devices/%s/%s" % (dev, att, func.method, name, func.path)) funcs[func.method][func.path] = func DEVICES[name] = {'device': dev, 'functions': funcs} if name == "GPIO": logger.info("GPIO - Native mapped to REST API /GPIO") else: logger.info("%s - %s mapped to REST API /devices/%s" % (dev.__family__(), dev, name))
def readAll(self): logger.info('Getting all GrovePi readings') inputs = {} outputs = {} for i in range(8): inputs[i] = self.digitalRead(i) outputs[i] = self.digitalReadOutput(i) logger.info('Inputs are {}'.format(inputs)) logger.info('Outputs are {}'.format(outputs)) return {"input": inputs, "output": outputs}
def left(): info("Turn Left") monster.turn_left()
def right(): info("Turn Right") monster.turn_right()
def main(argv): port = 8000 configfile = None logfile = None i = 1 while i < len(argv): if argv[i] in ["-c", "-C", "--config-file"]: configfile = argv[i + 1] i += 1 elif argv[i] in ["-l", "-L", "--log-file"]: logfile = argv[i + 1] i += 1 elif argv[i] in ["-h", "-H", "--help"]: displayHelp() elif argv[i] in ["-d", "--debug"]: setDebug() else: try: port = int(argv[i]) except ValueError: displayHelp() i += 1 if logfile: logToFile(logfile) info("Starting XBee %s" % VERSION) # setup serial serial = Serial() serial.port = '/dev/ttyAMA0' serial.baudrate = 9600 serial.timeout = 1 serial.writeTimeout = 1 serial.open() # disregard any pending data in xbee buffer serial.flushInput() # force to show xbee boot menu time.sleep(.5) serial.writelines("\r") time.sleep(.5) # read menu while serial.inWaiting() > 0: debug("%s" % serial.readline()) # trigger bypass automatically serial.writelines("B") # post startup message to other XBee's and at stdout #serial.writelines("RPi #1 is up and running.\r\n") info("RPi #1 is up and running.") try: while True: waitToSend = True # read a line from XBee and convert it from b'xxx\r\n' to xxx and send to webiopi while serial.inWaiting() > 0: try: line = serial.readline().decode('utf-8').strip('\n\r') if line: waitToSend = False debug("Received: %s" % line) try: client = PiHttpClient("127.0.0.1") macro = Macro(client, "setCarInfo") macro.call(line.replace(",", "%2C")) except: exception("setting car info failed!") except KeyboardInterrupt: raise except Exception as e: exception(e) time.sleep(1.) try: time.sleep(1.) client = PiHttpClient("127.0.0.1") macro = Macro(client, "getPitInfo") data = macro.call() if data: debug("Sending: %s" % data) serial.writelines(data + "\n") except KeyboardInterrupt: raise except Exception as e: exception(e) time.sleep(1.) except KeyboardInterrupt: info("*** Ctrl-C keyboard interrupt ***")
exception(e) time.sleep(1.) try: time.sleep(1.) client = PiHttpClient("127.0.0.1") macro = Macro(client, "getPitInfo") data = macro.call() if data: debug("Sending: %s" % data) serial.writelines(data + "\n") except KeyboardInterrupt: raise except Exception as e: exception(e) time.sleep(1.) except KeyboardInterrupt: info("*** Ctrl-C keyboard interrupt ***") if __name__ == "__main__": try: main(sys.argv) except Exception as e: exception(e) stop() info("RPi #1 is going down")
def digitalRead(self, channel): logger.info("Executing read_i2c_block") self.write_i2c_block(self.__address, self.__dRead_cmd + [channel, self.__unused, self.__unused]) time.sleep(.1) n = self.read_i2c_byte(self.__address) return n
def forward(): info("Go Forward") monster.forward_speed_up()
def __init__(self, port=8000, coap_port=5683, login=None, password=None, passwdfile=None, configfile=None, scriptfile=None): self.host = getLocalIP() self.gpio = NativeGPIO() self.restHandler = rest.RESTHandler() manager.addDeviceInstance("GPIO", self.gpio, []) if configfile != None: logger.info("Loading configuration from %s" % configfile) config = Config(configfile) else: config = Config() self.gpio.addSetups(config.items("GPIO")) self.gpio.addResets(config.items("~GPIO")) self.gpio.setup() #ADDED OVK self.gpiox = ExtendedGPIO() manager.addDeviceInstance("GPIOX", self.gpiox, []) self.gpiox.addCards(config.get("GPIOX", "cards", None)) #TODO Add setup and reset to set initial state, if needed #self.gpiox.addSetups(config.items("GPIOX")) #self.gpiox.addResets(config.items("~GPIOX")) #self.gpiox.setup() #ADDED OVK devices = config.items("DEVICES") for (name, params) in devices: values = params.split(" ") driver = values[0]; args = {} i = 1 while i < len(values): (arg, val) = values[i].split(":") args[arg] = val i+=1 manager.addDevice(name, driver, args) if scriptfile != None: scriptname = scriptfile.split("/")[-1].split(".")[0] loader.loadScript(scriptname, scriptfile, self.restHandler) scripts = config.items("SCRIPTS") for (name, source) in scripts: loader.loadScript(name, source, self.restHandler) self.restHandler.device_mapping = config.getboolean("REST", "device-mapping", True) self.gpio.post_value = config.getboolean("REST", "gpio-post-value", True) self.gpio.post_function = config.getboolean("REST", "gpio-post-function", True) #ADDED OVK self.gpiox.post_value = True self.gpiox.post_function = True #ADDED OVK exports = config.get("REST", "gpio-export", None) if exports != None: self.gpio.export = [int(s) for s in exports.split(",")] self.restHandler.export = self.gpio.export http_port = config.getint("HTTP", "port", port) http_enabled = config.getboolean("HTTP", "enabled", http_port > 0) http_passwdfile = config.get("HTTP", "passwd-file", passwdfile) context = config.get("HTTP", "context", None) docroot = config.get("HTTP", "doc-root", None) index = config.get("HTTP", "welcome-file", None) coap_port = config.getint("COAP", "port", coap_port) coap_enabled = config.getboolean("COAP", "enabled", coap_port > 0) coap_multicast = config.getboolean("COAP", "multicast", coap_enabled) routes = config.items("ROUTES") for (source, destination) in routes: self.restHandler.addRoute(source, destination) auth = None if http_passwdfile != None: if os.path.exists(http_passwdfile): f = open(http_passwdfile) auth = f.read().strip(" \r\n") f.close() if len(auth) > 0: logger.info("Access protected using %s" % http_passwdfile) else: logger.info("Passwd file %s is empty" % http_passwdfile) else: logger.error("Passwd file %s not found" % http_passwdfile) elif login != None or password != None: auth = crypto.encryptCredentials(login, password) logger.info("Access protected using login/password") if auth == None or len(auth) == 0: logger.warn("Access unprotected") realm = config.get("HTTP", "prompt", None) if http_enabled: self.http_server = http.HTTPServer(self.host, http_port, self.restHandler, context, docroot, index, auth, realm) else: self.http_server = None if coap_enabled: self.coap_server = coap.COAPServer(self.host, coap_port, self.restHandler) if coap_multicast: self.coap_server.enableMulticast() else: self.coap_server = None
def turn_completed(): info("Turn completed") monster.turn_completed()
def stop(): info("Stop the motors") monster.turnOffMotors()
def initiate(): info("Initialize") monster.initiate()
def unloadModules(bus): info("Unloading %s modules" % bus) for module in BUSLIST[bus]["modules"]: unloadModule(module) BUSLIST[bus]["enabled"] = False
def __init__(self, port=8000, coap_port=5683, login=None, password=None, passwdfile=None, configfile=None): self.host = getLocalIP() self.gpio = NativeGPIO() self.restHandler = rest.RESTHandler() manager.addDeviceInstance("GPIO", self.gpio, []) if configfile != None: logger.info("Loading configuration from %s" % configfile) config = Config(configfile) else: config = Config() self.gpio.addSetups(config.items("GPIO")) self.gpio.addResets(config.items("~GPIO")) self.gpio.setup() devices = config.items("DEVICES") for (name, params) in devices: values = params.split(" ") driver = values[0]; args = {} i = 1 while i < len(values): (arg, val) = values[i].split(":") args[arg] = val i+=1 manager.addDevice(name, driver, args) scripts = config.items("SCRIPTS") for (name, source) in scripts: loader.loadScript(name, source, self.restHandler) self.restHandler.device_mapping = config.getboolean("REST", "device-mapping", True) self.gpio.post_value = config.getboolean("REST", "gpio-post-value", True) self.gpio.post_function = config.getboolean("REST", "gpio-post-function", True) exports = config.get("REST", "gpio-export", None) if exports != None: self.gpio.export = [int(s) for s in exports.split(",")] self.restHandler.export = self.gpio.export http_port = config.getint("HTTP", "port", port) http_enabled = config.getboolean("HTTP", "enabled", http_port > 0) http_passwdfile = config.get("HTTP", "passwd-file", passwdfile) context = config.get("HTTP", "context", None) docroot = config.get("HTTP", "doc-root", None) index = config.get("HTTP", "welcome-file", None) coap_port = config.getint("COAP", "port", coap_port) coap_enabled = config.getboolean("COAP", "enabled", coap_port > 0) coap_multicast = config.getboolean("COAP", "multicast", coap_enabled) routes = config.items("ROUTES") for (source, destination) in routes: self.restHandler.addRoute(source, destination) auth = None if http_passwdfile != None: if os.path.exists(http_passwdfile): f = open(http_passwdfile) auth = f.read().strip(" \r\n") f.close() if len(auth) > 0: logger.info("Access protected using %s" % http_passwdfile) else: logger.info("Passwd file %s is empty" % http_passwdfile) else: logger.error("Passwd file %s not found" % http_passwdfile) elif login != None or password != None: auth = crypto.encryptCredentials(login, password) logger.info("Access protected using login/password") if auth == None or len(auth) == 0: logger.warn("Access unprotected") if http_enabled: self.http_server = http.HTTPServer(self.host, http_port, self.restHandler, context, docroot, index, auth) else: self.http_server = None if coap_enabled: self.coap_server = coap.COAPServer(self.host, coap_port, self.restHandler) if coap_multicast: self.coap_server.enableMulticast() else: self.coap_server = None
except Exception as e: exception(e) time.sleep(1.) try: time.sleep(1.) client = PiHttpClient("127.0.0.1") macro = Macro(client, "getPitInfo") data = macro.call() if data: debug("Sending: %s" % data) serial.writelines(data + "\n") except KeyboardInterrupt: raise except Exception as e: exception(e) time.sleep(1.) except KeyboardInterrupt: info("*** Ctrl-C keyboard interrupt ***") if __name__ == "__main__": try: main(sys.argv) except Exception as e: exception(e) stop() info("RPi #1 is going down")
def slow_down(): info("Slow Down") monster.speed_down()
def digitalWrite(self, channel, value): logger.info("Executing write_i2c_block") self.write_i2c_block(self.__address, self.__dWrite_cmd + [channel, value, self.__unused]) return 1
def reverse(): info("Go Reverse") monster.reverse_speed_up()
def main(argv): port = 8000 configfile = None logfile = None i = 1 while i < len(argv): if argv[i] in ["-c", "-C", "--config-file"]: configfile = argv[i+1] i+=1 elif argv[i] in ["-l", "-L", "--log-file"]: logfile = argv[i+1] i+=1 elif argv[i] in ["-h", "-H", "--help"]: displayHelp() elif argv[i] in ["-d", "--debug"]: setDebug() else: try: port = int(argv[i]) except ValueError: displayHelp() i+=1 if logfile: logToFile(logfile) info("Starting XBee %s" % VERSION) # setup serial serial = Serial() serial.port = '/dev/ttyAMA0' serial.baudrate = 9600 serial.timeout = 1 serial.writeTimeout = 1 serial.open() # disregard any pending data in xbee buffer serial.flushInput() # force to show xbee boot menu time.sleep(.5) serial.writelines("\r") time.sleep(.5) # read menu while serial.inWaiting() > 0: debug("%s" % serial.readline()) # trigger bypass automatically serial.writelines("B") # post startup message to other XBee's and at stdout #serial.writelines("RPi #1 is up and running.\r\n") info("RPi #1 is up and running.") try: while True: waitToSend = True # read a line from XBee and convert it from b'xxx\r\n' to xxx and send to webiopi while serial.inWaiting() > 0: try: line = serial.readline().decode('utf-8').strip('\n\r') if line: waitToSend = False debug("Received: %s" % line) try: client = PiHttpClient("127.0.0.1") macro = Macro(client, "setCarInfo") macro.call(line.replace(",", "%2C")) except: exception("setting car info failed!") except KeyboardInterrupt: raise except Exception as e: exception(e) time.sleep(1.) try: time.sleep(1.) client = PiHttpClient("127.0.0.1") macro = Macro(client, "getPitInfo") data = macro.call() if data: debug("Sending: %s" % data) serial.writelines(data + "\n") except KeyboardInterrupt: raise except Exception as e: exception(e) time.sleep(1.) except KeyboardInterrupt: info("*** Ctrl-C keyboard interrupt ***")