Example #1
0
def stop(signum=0, frame=None):
    global RUNNING
    if RUNNING:
        logger.info("Stopping...")
        RUNNING = False
        for task in TASKS:
            task.stop()
Example #2
0
 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
Example #3
0
def stop(signum=0, frame=None):
    global RUNNING
    if RUNNING:
        logger.info("Stopping...")
        RUNNING = False
        for task in TASKS:
            task.stop()
Example #4
0
 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))
Example #5
0
 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))
Example #6
0
 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
Example #7
0
    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")
Example #8
0
    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")
Example #9
0
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()
Example #10
0
 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")
Example #11
0
 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")
Example #12
0
 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))
Example #13
0
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
Example #14
0
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
Example #15
0
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)
Example #16
0
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)
Example #17
0
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))
Example #18
0
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))
Example #19
0
 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}
Example #20
0
def left():
    info("Turn Left")
    monster.turn_left()
Example #21
0
def right():
    info("Turn Right")
    monster.turn_right()
Example #22
0
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 ***")
Example #23
0
                    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")
Example #24
0
 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
Example #25
0
def forward():
    info("Go Forward")
    monster.forward_speed_up()
Example #26
0
    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
Example #27
0
def turn_completed():
    info("Turn completed")
    monster.turn_completed()
Example #28
0
def stop():
    info("Stop the motors")
    monster.turnOffMotors()
Example #29
0
def initiate():
    info("Initialize")
    monster.initiate()
Example #30
0
def unloadModules(bus):
    info("Unloading %s modules" % bus)
    for module in BUSLIST[bus]["modules"]:
        unloadModule(module)
    BUSLIST[bus]["enabled"] = False
Example #31
0
def unloadModules(bus):
    info("Unloading %s modules" % bus)
    for module in BUSLIST[bus]["modules"]:
        unloadModule(module)
    BUSLIST[bus]["enabled"] = False
Example #32
0
    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
Example #33
0
				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")
Example #34
0
def slow_down():
    info("Slow Down")
    monster.speed_down()
Example #35
0
 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))
Example #36
0
 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
Example #37
0
def reverse():
    info("Go Reverse")
    monster.reverse_speed_up()
Example #38
0
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 ***")