def __exit__(self, exc_type, exc_value, traceback): PWM_PORT_RUNNING[self.pwm_port]["channels"] -= 1 self.primary = True self.board.low_level_io(0, encode_sfp(1, [self.logical_pin])) # set pin primary function if PWM_PORT_RUNNING[self.pwm_port]["channels"] == 0: PWM_PORT_RUNNING[self.pwm_port]["period"] = 0 self.board.low_level_io(0, encode_sfp(PWM._PWM_PORT_FUNCTIONS[self.pwm_port][2], [self.pwm_pin]))
def set_pulse_time(self, pulse_us): """ Set PWM high (on state) time. :param pulse_us: Pulse time in microseconds. :type pulse_us: int :raise: IoTPy_APIError """ if self.primary: self.board.low_level_io(0, encode_sfp( 2, [self.logical_pin])) # set pin secondary function self.primary = False if 0 <= pulse_us <= PWM_PORT_RUNNING[self.pwm_port]['period']: self.pulse_time = pulse_us high_time = pulse_us if self.polarity == 0: high_time = PWM_PORT_RUNNING[ self.pwm_port]['period'] - pulse_us self.board.low_level_io( 0, encode_sfp(PWM._PWM_PORT_FUNCTIONS[self.pwm_port][1], [self.pwm_pin, high_time])) else: errmsg( "UPER error: PWM high time is out of range on logical pin %d." % self.logical_pin) raise IoTPy_APIError("PWM high time is out of range.")
def __exit__(self, exc_type, exc_value, traceback): PWM_PORT_RUNNING[self.pwm_port]['channels'] -= 1 self.primary = True self.board.low_level_io(0, encode_sfp( 1, [self.logical_pin])) # set pin primary function if PWM_PORT_RUNNING[self.pwm_port]['channels'] == 0: PWM_PORT_RUNNING[self.pwm_port]['period'] = 0 self.board.low_level_io( 0, encode_sfp(PWM._PWM_PORT_FUNCTIONS[self.pwm_port][2], [self.pwm_pin]))
def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_ADC: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("IO API: Pin "+str(pin)+" is not an ADC pin.") raise IoTPy_APIError("Trying to assign ADC function to non ADC pin.") self.adc_pin = self.board.pinout[pin].extra[0] self.board.low_level_io(0, encode_sfp(3, [self.logical_pin, 0])) # set GPIO to HIGH_Z self.board.low_level_io(0, encode_sfp(2, [self.logical_pin])) # set secondary pin function self.primary = False
def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_ADC: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("IO API: Pin " + str(pin) + " is not an ADC pin.") raise IoTPy_APIError( "Trying to assign ADC function to non ADC pin.") self.adc_pin = self.board.pinout[pin].extra[0] self.board.low_level_io(0, encode_sfp( 3, [self.logical_pin, 0])) # set GPIO to HIGH_Z self.board.low_level_io(0, encode_sfp( 2, [self.logical_pin])) # set secondary pin function self.primary = False
def transaction(self, address, write_data, read_length): """ Perform I2C data transaction. I2C data transaction consists of (optional) write transaction, followed by (optional) read transaction. :param address: I2C device address. :type address: int :param write_data: A byte sequence to be transmitted. If write_data is empty string, no write transaction \ will be executed. :type write_data: str :param read_length: A number of bytes to be received. If read_length is 0, no read transaction will be executed. :type read_length: int :return: Received data and I2C transaction status/error code. :rtype: (str, int) :raise: IoTPy_APIError, IoTPy_ThingError """ try: result = decode_sfp(self.board.low_level_io(1, encode_sfp(41, [address, write_data, read_length]))) except IoTPy_APIError: errmsg("UPER API: I2C bus not connected.") raise IoTPy_IOError("I2C bus not connected.") return result[1][1], result[1][2] # return read buffer and error
def get_device_info(self): """ Return information about the device. :return: A list containing board type, major and minor firmware versions, 16 byte unique identifier, \ microcontroller part and bootcode version numbers. """ sfp_code, args = decode_sfp(self.low_level_io(1, encode_sfp(255, []))) if sfp_code != 255: errmsg("IoTPy error: get_device_info wrong code.") # raise IoTPy_APIError("") device_data = args if device_data[0] >> 24 != 0x55: # 0x55 = 'U' print("IoTPy error: getDeviceInfo unknown device/firmware type") # return device_info = { 'fw_maj': (device_data[0] & 0x00ff0000) >> 16, # Firmware major version number 'fw_min': device_data[0] & 0x0000ffff, # Firmware minor version number 'uid': UUID(bytes=device_data[1]), # 128bit unique ID 'cpu_id': device_data[2], # UPER LPC CPU part number 'boot': device_data[3], # UPER LPC CPU bootload code version } return device_info
def setup(self, direction, resistor=GPIO.PULL_UP): if not direction in [self.OUTPUT, self.INPUT]: raise IoTPy_APIError( "Invalid digital pin direction. Should be INPUT or OUTPUT") if direction == self.INPUT and not resistor in [ GPIO.NONE, GPIO.PULL_UP, GPIO.PULL_DOWN ]: raise IoTPy_APIError( "Invalid GPIO resistor setting. Should be GPIO.NONE, GPIO.PULL_UP or GPIO.PULL_DOWN" ) self.direction = direction if direction == self.INPUT: self.resistor = resistor if resistor == self.PULL_UP: mode = 4 # PULL_UP elif resistor == self.PULL_DOWN: mode = 2 # PULL_DOWN else: mode = 0 # HIGH_Z else: mode = 1 # OUTPUT self.board.low_level_io( 0, encode_sfp( 3, [self._logical_pins, chr(mode) * len(self._logical_pins)]))
def read_pulse(self, level=HIGH, timeout=100000): if self.direction != self.INPUT: self.setup(self.INPUT, self.resistor) return decode_sfp( self.board.low_level_io( 1, encode_sfp(9, [self.logical_pin, level, timeout])))[1][0]
def read_raw(self): """ Read ADC value :return: Raw ADC value. :rtype: int """ return decode_sfp(self.board.low_level_io(1, encode_sfp(10, [self.adc_pin])))[1][1]
def read_raw(self): """ Read ADC value :return: Raw ADC value. :rtype: int """ return decode_sfp( self.board.low_level_io(1, encode_sfp(10, [self.adc_pin])))[1][1]
def attach_irq(self, event, callback=None, user_object=None, debounce_time=50): """ Attach (enable) or reconfigure GPIO interrupt event. :param event: GPIO interrupt event. Can have one of these values: GPIO.RISE, GPIO.FALL, GPIO.CHANGE, \ GPIO.LOW or GPIO.HIGH. :param callback: User callback function. This function is executed when the interrupt event is received. \ It should take two arguments: interrupt event description and user object. Interrupt event descriptor is \ dictionary with three fields: 'id' - the interrupt ID (interrupt channel), 'event' - interrupt event type \ and 'values' - the logical values on each of interrupt channel (N-th bit represents logical pin value of \ interrupt channel N). User object is the same object as user_object. :param user_object: User defined object, which will be passed back to the callback function. Optional, \ default is None. :param debounce_time: Interrupt disable time in milliseconds after the triggering event. This is used to \ "debounce" buttons or to protect communication channel from data flood. Optional, default is 50ms. :return: Logical interrupt ID :rtype: int :raise: IoTPy_APIError """ try: irq_id = self.board.interrupts.index(self.logical_pin) self.board.low_level_io(0, encode_sfp(7, [irq_id])) # detach interrupt except ValueError: try: irq_id = self.board.interrupts.index(None) self.board.interrupts[irq_id] = self.logical_pin except ValueError: errmsg("UPER API: more than 8 interrupts requested") raise IoTPy_APIError("Too many interrupts.") self.board.callbackdict[self.logical_pin] = { 'mode': event, 'callback': callback, 'userobject': user_object } self.board.low_level_io( 0, encode_sfp(6, [irq_id, self.logical_pin, event, debounce_time])) return irq_id
def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_GPIO: self.logical_pin = self.board.pinout[pin].pinID else: raise IoTPy_APIError("Trying to assign OneWire function to non GPIO pin.") #self.board.low_level_io(0, encode_sfp(1, [self.logical_pin])) # set primary #self.board.low_level_io(0, encode_sfp(3, [self.logical_pin, 1])) # gpio mode output self.board.low_level_io(0, encode_sfp(100, [self.logical_pin]))
def write(self, value): """ Write a digital value (0 or 1). If GPIO pin is not configured as output, set it's GPIO mode to GPIO.OUTPUT. :param value: Digital output value (0 or 1) :type value: int """ if self.direction != self.OUTPUT: self.setup(self.OUTPUT) self.board.low_level_io(0, encode_sfp(4, [self.logical_pin, value]))
def test_encode_sfp(self): sfp_parameters = [ b'09876543210987654321098765432109876543210987654321098765432109876543210987654321', b'0987654321', 0, 1, 64, 6000, 70000 ] sfp_command = 255 encode_result = sfp.encode_sfp(sfp_command, sfp_parameters) self.assertEqual( encode_result, b'\xd4\x00i\xff\xc4P09876543210987654321098765432109876543210987654321098765432109876543210987654321J0987654321\x00\x01\xc0@\xc1\x17p\xc2\x01\x11p' )
def __exit__(self, exc_type, exc_value, traceback): self.board.low_level_io(0, encode_sfp(22 + self.port * 10, [])) if self.port: self.board.low_level_io(0, encode_sfp(1, [4])) # set pin primary function self.board.low_level_io(0, encode_sfp(1, [5])) self.board.low_level_io(0, encode_sfp(1, [11])) else: self.board.low_level_io(0, encode_sfp(1, [12])) # set pin primary function self.board.low_level_io(0, encode_sfp(1, [13])) self.board.low_level_io(0, encode_sfp(1, [14]))
def read(self): """ Read a digital signal value. If GPIO pis in not configure as input, set it to GPIO.PULL_UP pin mode. :return: Digital signal value: 0 (LOW) or 1 (HIGH). :rtype: int """ if self.direction != self.INPUT: self.setup(self.INPUT, self.resistor) return decode_sfp( self.board.low_level_io(1, encode_sfp(5, [self.logical_pin])))[1][1]
def set_pulse_time(self, pulse_us): """ Set PWM high (on state) time. :param pulse_us: Pulse time in microseconds. :type pulse_us: int :raise: IoTPy_APIError """ if self.primary: self.board.low_level_io(0, encode_sfp(2, [self.logical_pin])) # set pin secondary function self.primary = False if 0 <= pulse_us <= PWM_PORT_RUNNING[self.pwm_port]["period"]: self.pulse_time = pulse_us high_time = pulse_us if self.polarity == 0: high_time = PWM_PORT_RUNNING[self.pwm_port]["period"] - pulse_us self.board.low_level_io(0, encode_sfp(PWM._PWM_PORT_FUNCTIONS[self.pwm_port][1], [self.pwm_pin, high_time])) else: errmsg("UPER error: PWM high time is out of range on logical pin %d." % self.logical_pin) raise IoTPy_APIError("PWM high time is out of range.")
def write(self, value): """ Write a digital port value. If GPIO port is not configured as output, set it's GPIO mode to GPIO.OUTPUT. :param value: Digital output value :type value: int """ if self.direction != GPIO.OUTPUT: self.setup(GPIO.OUTPUT) values = list( ((value >> i) & 1) for i in xrange(len(self._logical_pins))) values = struct.pack("B" * len(self._logical_pins), *values) self.board.low_level_io(0, encode_sfp(4, [self._logical_pins, values]))
def transaction(self, write_data, read_from_slave=True): """ Perform SPI data transaction. :param write_data: Data to be shifted on MOSI line. :type write_data: str :param read_from_slave: Flag indicating whether the data received on MISO line should be ignored or not. Optional, default True. :type read_from_slave: bool :return: Data received on MISO line, if read_from_slave is True. :rtype: str """ res = self.board.low_level_io(read_from_slave, encode_sfp(21 + self.port * 10, [write_data, int(read_from_slave)])) if res: return decode_sfp(res)[1][0]
def detect_sfp_serial(uid=None): ports_list = [] my_platform = platform.system() if uid: uid = UUID(uid) if my_platform == "Windows": for i in range(256): try: serial_tmp = serial.Serial("COM" + str(i)) ports_list.append(serial_tmp.portstr) serial_tmp.close() except serial.SerialException: pass elif my_platform == "Darwin": ports_list = glob.glob("/dev/tty.usbmodem*") elif my_platform == "Linux": ports_list = glob.glob("/dev/ttyACM*") for my_port in ports_list: try: port_to_try = serial.Serial( port=my_port, baudrate=230400, # virtual com port on USB is always max speed parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1, ) komanda_siuntimui = encode_sfp(255, []) port_to_try.write(komanda_siuntimui) response = port_to_try.read(1) # read one, blocking n = port_to_try.inWaiting() # look if there is more if n: response = response + port_to_try.read(n) sfp = decode_sfp(response) if sfp[0] == 255: # device info sfp packet dev_uid = UUID(bytes=sfp[1][1]) if not uid or uid == dev_uid: return port_to_try port_to_try.close() except: pass raise IoTPy_APIError("No SFP device was found on serial ports.")
def scan(self): """ Scan I2C interface for connected devices. :return: A list of active I2C device addresses. :rtype: list """ dev_list = [] for address in range(1, 128): try: result = self.board.low_level_io(1, encode_sfp(41, [address, b'', 0])) if result[-1] == 'X': dev_list.append(address) except IoTPy_APIError: errmsg("UPER API: I2C bus not connected.") raise IoTPy_IOError("I2C bus not connected.") return dev_list
def detach_irq(self): """ Detach (disable) GPIO interrupt. :return: True on success, False otherwise :raise: IoTPy_APIError """ try: irq_id = self.board.interrupts.index(self.logical_pin) except ValueError: #errmsg("UPER API: trying to detach non existing interrupt.") return False self.board.interrupts[irq_id] = None del self.board.callbackdict[self.logical_pin] self.board.low_level_io(0, encode_sfp(7, [irq_id])) return True
def detect_sfp_serial(uid=None): ports_list = [] my_platform = platform.system() if uid: uid = UUID(uid) if my_platform == "Windows": for i in range(256): try: serial_tmp = serial.Serial('COM' + str(i)) ports_list.append(serial_tmp.portstr) serial_tmp.close() except serial.SerialException: pass elif my_platform == "Darwin": ports_list = glob.glob("/dev/tty.usbmodem*") elif my_platform == "Linux": ports_list = glob.glob("/dev/ttyACM*") for my_port in ports_list: try: port_to_try = serial.Serial( port=my_port, baudrate=230400, # virtual com port on USB is always max speed parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1) komanda_siuntimui = encode_sfp(255, []) port_to_try.write(komanda_siuntimui) response = port_to_try.read(1) # read one, blocking n = port_to_try.inWaiting() # look if there is more if n: response = response + port_to_try.read(n) sfp = decode_sfp(response) if sfp[0] == 255: # device info sfp packet dev_uid = UUID(bytes=sfp[1][1]) if not uid or uid == dev_uid: return port_to_try port_to_try.close() except: pass raise IoTPy_APIError("No SFP device was found on serial ports.")
def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_GPIO: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("UPER API: Pin No:%d is not GPIO pin.", pin) raise IoTPy_APIError( "Trying to assign GPIO function to non GPIO pin.") # Configure default state to be input with pull-up resistor self.board.low_level_io(0, encode_sfp(1, [self.logical_pin])) # set primary self.direction = self.INPUT self.resistor = self.PULL_UP self.setup( self.direction, self.resistor) # default GPIO pin state is INPUT and PULL_UP
def set_period(self, period_us): """ Set PWM period. :param period_us: PWM signal period in microseconds. :type period_us: int :raise: IoTPy_APIError """ if 0 <= period_us <= self._PWM_PORT_MAX[self.pwm_port]: if PWM_PORT_RUNNING[self.pwm_port]["period"] != period_us: self.board.low_level_io(0, encode_sfp(self._PWM_PORT_FUNCTIONS[self.pwm_port][0], [period_us])) PWM_PORT_RUNNING[self.pwm_port]["period"] = period_us else: errmsg( "UPER API: PWM period for port %d can be only between 0-%d" % (self.pwm_port, self._PWM_PORT_MAX[self.pwm_port]) ) raise IoTPy_APIError("PWM period is out of range.")
def __init__(self, board, pins): self.board = board for pin in pins: if not self.board.pinout[pin].capabilities & CAP_GPIO: raise IoTPy_APIError( "Trying to assign GPIO function to non GPIO pin.") self._logical_pins = list(self.board.pinout[pin].pinID for pin in pins) self._logical_pins = struct.pack("B" * len(self._logical_pins), *self._logical_pins) # Configure default state to be input with pull-up resistor self.direction = GPIO.INPUT self.resistor = GPIO.PULL_UP self.setup(self.direction, self.resistor) self.board.low_level_io(0, encode_sfp( 1, [self._logical_pins])) # set primary
def read(self): """ Read a digital port value. If GPIO port in not configure as input, set it to GPIO.PULL_UP pin mode. :return: Digital port value. :rtype: int """ if self.direction != GPIO.INPUT: self.setup(GPIO.INPUT, self.resistor) values = decode_sfp( self.board.low_level_io(1, encode_sfp(5, [self._logical_pins])))[1][1] value = 0 for i, bit in enumerate(values): value |= (ord(bit) & 0x1) << i return value
def __init__(self, board, port=0, divider=1, mode=MODE_0): divider = min(max(divider, 1), 256) self.board = board self.port = port self.divider = divider self.mode = mode if self.port == 1: self.board.low_level_io(0, encode_sfp(2, [4])) self.board.low_level_io(0, encode_sfp(2, [5])) self.board.low_level_io(0, encode_sfp(2, [11])) self.board.low_level_io(0, encode_sfp(30, [self.divider, self.mode])) elif self.port == 0: self.board.low_level_io(0, encode_sfp(2, [12])) self.board.low_level_io(0, encode_sfp(2, [13])) self.board.low_level_io(0, encode_sfp(2, [14])) self.board.low_level_io(0, encode_sfp(20, [self.divider, self.mode])) else: errmsg("UPER API: Wrong SPI port number.", self.port) raise IoTPy_APIError("SPI port must be 0 or 1, trying to assign something else.")
def set_period(self, period_us): """ Set PWM period. :param period_us: PWM signal period in microseconds. :type period_us: int :raise: IoTPy_APIError """ if 0 <= period_us <= self._PWM_PORT_MAX[self.pwm_port]: if PWM_PORT_RUNNING[self.pwm_port]['period'] != period_us: self.board.low_level_io( 0, encode_sfp(self._PWM_PORT_FUNCTIONS[self.pwm_port][0], [period_us])) PWM_PORT_RUNNING[self.pwm_port]['period'] = period_us else: errmsg( "UPER API: PWM period for port %d can be only between 0-%d" % (self.pwm_port, self._PWM_PORT_MAX[self.pwm_port])) raise IoTPy_APIError("PWM period is out of range.")
def setup(self, direction, resistor=PULL_UP): """ Configure GPIO. :param direction: GPIO direction: GPIO.OUTPUT or GPIO.INPUT :param resistor: GPIO internal resistor mode. Used when direction is GPIO.INPUT. Should be GPIO.PULL_UP, \ GPIO.PULL_DOWN or GPIO.NONE. :raise: IoTPy_APIError """ if not direction in [self.OUTPUT, self.INPUT]: raise IoTPy_APIError( "Invalid digital pin direction. Should be INPUT or OUTPUT") if direction == self.INPUT and not resistor in [ self.NONE, self.PULL_UP, self.PULL_DOWN ]: raise IoTPy_APIError( "Invalid digital pin resistor setting. Should be GPIO.NONE, GPIO.PULL_UP or GPIO.PULL_DOWN" ) self.direction = direction if direction == self.INPUT: self.resistor = resistor if resistor == self.PULL_UP: mode = 4 # PULL_UP elif resistor == self.PULL_DOWN: mode = 2 # PULL_DOWN else: mode = 0 # HIGH_Z else: mode = 1 # OUTPUT self.board.low_level_io(0, encode_sfp(3, [self.logical_pin, mode]))
def test_encode_sfp(self): sfp_parameters = [b'09876543210987654321098765432109876543210987654321098765432109876543210987654321', b'0987654321', 0, 1, 64, 6000, 70000] sfp_command = 255 encode_result = sfp.encode_sfp(sfp_command, sfp_parameters) self.assertEqual(encode_result, b'\xd4\x00i\xff\xc4P09876543210987654321098765432109876543210987654321098765432109876543210987654321J0987654321\x00\x01\xc0@\xc1\x17p\xc2\x01\x11p')
def test_simple_sfp_encode1(self): self.assertEqual(sfp.encode_sfp(5, [0]), b'\xd4\x00\x02\x05\x00')
def test_simple_sfp_encode(self): self.assertEqual(sfp.encode_sfp(255, []), b'\xd4\x00\x01\xff')
def trans(self, data): self.board.low_level_io(0, encode_sfp(101, [data]))
def reset(self): """ Perform software restart. """ self.low_level_io(0, encode_sfp(251, []))
def execute_sfp(self, binary_sfp_command): decoded_sfp_command = decode_sfp(binary_sfp_command) results = self.sfp_comands[decoded_sfp_command[0]](decoded_sfp_command[1]) if results: return encode_sfp(decoded_sfp_command[0], results)
def __exit__(self, exc_type, exc_value, traceback): self.board.low_level_io(0, encode_sfp(42, []))
def __init__(self, board, port=0): self.board = board self.port = port self.board.low_level_io(0, encode_sfp(2, [34])) self.board.low_level_io(0, encode_sfp(2, [35])) self.board.low_level_io(0, encode_sfp(40, []))