def closeDevices(): devices = [k for k in DEVICES.keys()] for name in devices: device = DEVICES[name]["device"] logger.debug("Closing device %s - %s" % (name, device)) del DEVICES[name] device.close()
def __calculateMillimeter__(self, raw_proximity_counts): # According to chip spec the proximity counts are strong non-linear with distance and cannot be calculated # with a direct formula. From experience found on web this chip is generally not suited for really exact # distance calculations. This is a rough distance estimation lookup table for now. Maybe someone can # provide a more exact approximation in the future. debug("VCNL4000: prox real raw counts = %d" % (raw_proximity_counts)) if raw_proximity_counts >= 10000: estimated_distance = 0 elif raw_proximity_counts >= 3000: estimated_distance = 5 elif raw_proximity_counts >= 900: estimated_distance = 10 elif raw_proximity_counts >= 300: estimated_distance = 20 elif raw_proximity_counts >= 150: estimated_distance = 30 elif raw_proximity_counts >= 75: estimated_distance = 40 elif raw_proximity_counts >= 50: estimated_distance = 50 elif raw_proximity_counts >= 25: estimated_distance = 70 else: estimated_distance = 100 return estimated_distance
def setup(self): for g in self.gpio_setup: gpio = g["gpio"] debug("Setup GPIO %d" % gpio) GPIO.setFunction(gpio, g["func"]) if g["value"] >= 0 and GPIO.getFunction(gpio) == GPIO.OUT: GPIO.digitalWrite(gpio, g["value"])
def __calculateMillimeter__(self, raw_proximity_counts): # According to chip spec the proximity counts are strong non-linear with distance and cannot be calculated # with a direct formula. From experience found on web this chip is generally not suited for really exact # distance calculations. This is a rough distance estimation lookup table for now. Maybe someone can # provide a more exact approximation in the future. debug ("VCNL4000: prox real raw counts = %d" % (raw_proximity_counts)) if raw_proximity_counts >= 10000: estimated_distance = 0 elif raw_proximity_counts >= 3000: estimated_distance = 5 elif raw_proximity_counts >= 900: estimated_distance = 10 elif raw_proximity_counts >= 300: estimated_distance = 20 elif raw_proximity_counts >= 150: estimated_distance = 30 elif raw_proximity_counts >= 75: estimated_distance = 40 elif raw_proximity_counts >= 50: estimated_distance = 50 elif raw_proximity_counts >= 25: estimated_distance = 70 else: estimated_distance = 100 return estimated_distance
def __setCurrent__(self): if not self.current in range(0, 201): raise ValueError("%d mA LED current out of range [%d..%d] mA" % (self.current, 0, 201)) self.writeRegister(self.REG_IR_LED_CURRENT, int(self.current / 10)) debug("VCNL4000: new curr = %d" % (self.readRegister(self.REG_IR_LED_CURRENT)))
def _disconnect(self): debug("Disconnect from port = %s" % self.ser.port) if self.ser.port != "": # Turn the green led off self.ser.write(("SET PE15 0\r").encode('ascii')) self.ser.close() self.ser.port = ""
def close(self): for g in self.gpio_reset: gpio = g["gpio"] debug("Reset GPIO %d" % gpio) GPIO.setFunction(gpio, g["func"]) if g["value"] >= 0 and GPIO.getFunction(gpio) == GPIO.OUT: GPIO.digitalWrite(gpio, g["value"])
def __readProximityCounts__(self): self.writeRegister(self.REG_COMMAND, self.VAL_START_PROX) while not (self.readRegister(self.REG_COMMAND) & self.MASK_PROX_READY): time.sleep(0.001) proximity_bytes = self.readRegisters(self.REG_PROX_RESULT_HIGH, 2) debug ("VCNL4000: prox raw value = %d" % (proximity_bytes[0] << 8 | proximity_bytes[1])) return (proximity_bytes[0] << 8 | proximity_bytes[1])
def __readProximityCounts__(self): self.writeRegister(self.REG_COMMAND, self.VAL_START_PROX) while not (self.readRegister(self.REG_COMMAND) & self.MASK_PROX_READY): time.sleep(0.001) proximity_bytes = self.readRegisters(self.REG_PROX_RESULT_HIGH, 2) debug("VCNL4000: prox raw value = %d" % (proximity_bytes[0] << 8 | proximity_bytes[1])) return (proximity_bytes[0] << 8 | proximity_bytes[1])
def setfunction(self, channel, function): if self._connect() == -1: return -1 out = self._write("INIT %s SET %s NO" % (channel, getStrFromFunction(function))) time.sleep(1) while self.ser.inWaiting() > 0: out += self.ser.read(1).decode('ascii') if out.startswith("*KO*"): debug("READ GPIOX KO : %s" % out) #Raise an error self._disconnect()
def __setFrequency__(self): if not self.frequency in [391, 781, 1563, 3125]: raise ValueError("Frequency %d out of range [%d,%d,%d,,%d]" % (self.frequency, 391, 781, 1563, 3125)) if self.frequency == 391: bits_frequency = self.VAL_PR_FREQ_390K625HZ elif self.frequency == 781: bits_frequency = self.VAL_PR_FREQ_781K25HZ elif self.frequency == 1563: bits_frequency = self.VAL_PR_FREQ_1M5625HZ elif self.frequency == 3125: bits_frequency = self.VAL_PR_FREQ_3M125HZ self.writeRegister(self.REG_PROX_FREQUENCY, bits_frequency) debug ("VCNL4000: new freq = %d" % (self.readRegister(self.REG_PROX_FREQUENCY)))
def read(self, channel): out = '' debug("read gpio %s" % channel) out = self._write("GET %s" % channel) value = -1 if out.startswith("*OK*"): value = int(out.split(":")[1]) elif out.startswith("*KO*"): debug("READ GPIOX KO : %s" % out) #Raise an error return value
def trigger(self, channel, value, timems): out = self._write("SET %s %d" % (channel, value)) if out.startswith("*KO*"): debug("WRITE GPIOX KO : %s" % out) #TODO Raise error time.sleep(timems / 1000) if value == 0: out = self._write("SET %s 1" % channel) else: out = self._write("SET %s 0" % channel) if out.startswith("*KO*"): debug("WRITE GPIOX KO : %s" % out)
def __setFrequency__(self): if not self.frequency in [391, 781, 1563, 3125]: raise ValueError("Frequency %d out of range [%d,%d,%d,,%d]" % (self.frequency, 391, 781, 1563, 3125)) if self.frequency == 391: bits_frequency = self.VAL_PR_FREQ_390K625HZ elif self.frequency == 781: bits_frequency = self.VAL_PR_FREQ_781K25HZ elif self.frequency == 1563: bits_frequency = self.VAL_PR_FREQ_1M5625HZ elif self.frequency == 3125: bits_frequency = self.VAL_PR_FREQ_3M125HZ self.writeRegister(self.REG_PROX_FREQUENCY, bits_frequency) debug("VCNL4000: new freq = %d" % (self.readRegister(self.REG_PROX_FREQUENCY)))
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 connect(self): debug("Connect %s for device id %s" % (self.ser.baudrate, self.ser.port)) self.ser.open() out = self._write("CONFIG DUMP") devices = [] for line in out.splitlines(): if line and line[0] == 'P': #How we recognize a gpio name temp = line.split(" ") dev = { "name": temp[0], "function": getFunctionFromStr(temp[1]), "value": temp[4] } devices.append(dev) self.ser.close() return devices
def __analogWrite__(self, channel, value): #printBytes(self.values) self.values[channel] = value & 0xFF #printBytes(self.values) chipAddr = channel % self.slice addressString = (bin(chipAddr)[2:]).rjust(self.ADDRESS_BITS, '0') debug("Address=%s" % addressString) slotValues = self.values[chipAddr::self.slice] #printBytes(slotValues) slotValues.reverse() printBytes(slotValues) unpaddedNumberBits = (self.ADDRESS_BITS + 8) * self.chips debug("Unpadlength=%s" % unpaddedNumberBits) lastBit = (unpaddedNumberBits % 8) if lastBit > 0: padLength = 8 - lastBit else: padLength = 0 debug("Padlength=%s" % padLength) padString = "".rjust(padLength, '0') debug("Padding=%s" % padString) for i in range(len(slotValues)): slotValues[i] = (bin(slotValues[i])[2:]).rjust(8, '0') bitSequence = "" for valueString in slotValues: bitSequence = bitSequence + addressString + valueString bitSequence = padString + bitSequence debug("Bitsequence=%s" % bitSequence) data = [] for s in range(0, len(bitSequence), 8): data.append(int(bitSequence[s:s + 8], 2)) printBytes(data) self.writeBytes(bytearray(data))
def write(self, channel, value): debug("write gpio %s, with value %d" % (channel, value)) try: out = self._write("SET %s %d" % (channel, value)) except: debug("Retry connection to card %s" % self.cardname) self.ser.port = findCard(self.cardname) self._connect() out = self._write("SET %s %d" % (channel, value)) if out.startswith("*KO*"): debug("WRITE GPIOX KO : %s" % out)
def loadModule(module): debug("Loading module : %s" % module) subprocess.call(["modprobe", module])
def calibrate(self): self.offset = self.__measureOffset__() debug ("VCNL4000: offset = %d" % (self.offset)) return self.offset
def _connect(self): try: self.ser.open() except: debug("Error connecting to card %s on port %s" % (self.cardname, self.ser.port))
def disconnect(self): debug("Disconnect from %s" % self.cardname) self._disconnect()
def __setCurrent__(self): if not self.current in range(0,201): raise ValueError("%d mA LED current out of range [%d..%d] mA" % (self.current, 0, 201)) self.writeRegister(self.REG_IR_LED_CURRENT, int(self.current / 10)) debug ("VCNL4000: new curr = %d" % (self.readRegister(self.REG_IR_LED_CURRENT)))
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 ***")
def calibrate(self): self.offset = self.__measureOffset__() debug("VCNL4000: offset = %d" % (self.offset)) return self.offset
def findCard(name): ser = serial.Serial() ser.baudrate = 230400 ser.timeout = 2 ser.write_timeout = 2 for port in glob.glob("/dev/ttyACM*"): ser.port = port debug('DEBUG port : %s ; name : %s' % (port, name)) ser.open() time.sleep(1) ser.flushInput() ser.flushOutput() for i in range(5): try: ser.write(("GETNAME\r").encode('ascii')) time.sleep(0.01) except SerialTimeoutException: debug('ERROR timeoutException') out = "" while ser.inWaiting() > 0: out += ser.read(1).decode('ascii', 'ignore') debug('DEBUG response %s out : %s' % (i, out)) if out.find("*OK*") != -1: value = out.split(":")[1].rstrip() if (value == name): # Turn the green led on ser.write(("SET PE15 1\r").encode('ascii')) ser.close() debug("EXIT OK card found !") # : %s" % out) return port else: debug("DEBUG OK but continue") # : %s" % out) break #elif out.find("*KO*") != -1: # debug("ERROR KO : %s" % out) #ser.close() #Raise an error #return "" debug("DEBUG close port : %s" % ser.port) ser.close() return ""
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 ***")