code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from . import HT16K33 # Digit value to bitmask mapping: DIGIT_VALUES = { ' ': 0b0000000000000000, '!': 0b0000000000000110, '"': 0b0000001000100000, '#': 0b0001001011001110, '$': 0b0001001011101101, '%': 0b0000110000100100, '&': 0b0010001101011101, '\'': 0b0000010000000000, '(': 0b0010010000000000, ')': 0b0000100100000000, '*': 0b0011111111000000, '+': 0b0001001011000000, ',': 0b0000100000000000, '-': 0b0000000011000000, '.': 0b0000000000000000, '/': 0b0000110000000000, '0': 0b0000110000111111, '1': 0b0000000000000110, '2': 0b0000000011011011, '3': 0b0000000010001111, '4': 0b0000000011100110, '5': 0b0010000001101001, '6': 0b0000000011111101, '7': 0b0000000000000111, '8': 0b0000000011111111, '9': 0b0000000011101111, ':': 0b0001001000000000, ';': 0b0000101000000000, '<': 0b0010010000000000, '=': 0b0000000011001000, '>': 0b0000100100000000, '?': 0b0001000010000011, '@': 0b0000001010111011, 'A': 0b0000000011110111, 'B': 0b0001001010001111, 'C': 0b0000000000111001, 'D': 0b0001001000001111, 'E': 0b0000000011111001, 'F': 0b0000000001110001, 'G': 0b0000000010111101, 'H': 0b0000000011110110, 'I': 0b0001001000000000, 'J': 0b0000000000011110, 'K': 0b0010010001110000, 'L': 0b0000000000111000, 'M': 0b0000010100110110, 'N': 0b0010000100110110, 'O': 0b0000000000111111, 'P': 0b0000000011110011, 'Q': 0b0010000000111111, 'R': 0b0010000011110011, 'S': 0b0000000011101101, 'T': 0b0001001000000001, 'U': 0b0000000000111110, 'V': 0b0000110000110000, 'W': 0b0010100000110110, 'X': 0b0010110100000000, 'Y': 0b0001010100000000, 'Z': 0b0000110000001001, '[': 0b0000000000111001, '\\': 0b0010000100000000, ']': 0b0000000000001111, '^': 0b0000110000000011, '_': 0b0000000000001000, '`': 0b0000000100000000, 'a': 0b0001000001011000, 'b': 0b0010000001111000, 'c': 0b0000000011011000, 'd': 0b0000100010001110, 'e': 0b0000100001011000, 'f': 0b0000000001110001, 'g': 0b0000010010001110, 'h': 0b0001000001110000, 'i': 0b0001000000000000, 'j': 0b0000000000001110, 'k': 0b0011011000000000, 'l': 0b0000000000110000, 'm': 0b0001000011010100, 'n': 0b0001000001010000, 'o': 0b0000000011011100, 'p': 0b0000000101110000, 'q': 0b0000010010000110, 'r': 0b0000000001010000, 's': 0b0010000010001000, 't': 0b0000000001111000, 'u': 0b0000000000011100, 'v': 0b0010000000000100, 'w': 0b0010100000010100, 'x': 0b0010100011000000, 'y': 0b0010000000001100, 'z': 0b0000100001001000, '{': 0b0000100101001001, '|': 0b0001001000000000, '}': 0b0010010010001001, '~': 0b0000010100100000 } class AlphaNum4(HT16K33.HT16K33): """Alphanumeric 14 segment LED backpack display.""" def __init__(self, **kwargs): """Initialize display. All arguments will be passed to the HT16K33 class initializer, including optional I2C address and bus number parameters. """ super(AlphaNum4, self).__init__(**kwargs) def set_digit_raw(self, pos, bitmask): """Set digit at position to raw bitmask value. Position should be a value of 0 to 3 with 0 being the left most digit on the display.""" if pos < 0 or pos > 3: # Ignore out of bounds digits. return # Set the digit bitmask value at the appropriate position. # Also set bit 7 (decimal point) if decimal is True. self.buffer[pos*2] = bitmask & 0xFF self.buffer[pos*2+1] = (bitmask >> 8) & 0xFF def set_decimal(self, pos, decimal): """Turn decimal point on or off at provided position. Position should be a value 0 to 3 with 0 being the left most digit on the display. Decimal should be True to turn on the decimal point and False to turn it off. """ if pos < 0 or pos > 3: # Ignore out of bounds digits. return # Set bit 14 (decimal point) based on provided value. if decimal: self.buffer[pos*2+1] |= (1 << 6) else: self.buffer[pos*2+1] &= ~(1 << 6) def set_digit(self, pos, digit, decimal=False): """Set digit at position to provided value. Position should be a value of 0 to 3 with 0 being the left most digit on the display. Digit should be any ASCII value 32-127 (printable ASCII). """ self.set_digit_raw(pos, DIGIT_VALUES.get(str(digit), 0x00)) if decimal: self.set_decimal(pos, True) def print_str(self, value, justify_right=True): """Print a 4 character long string of values to the display. Characters in the string should be any ASCII value 32 to 127 (printable ASCII). """ # Calculcate starting position of digits based on justification. pos = (4-len(value)) if justify_right else 0 # Go through each character and print it on the display. for i, ch in enumerate(value): self.set_digit(i+pos, ch) def print_number_str(self, value, justify_right=True): """Print a 4 character long string of numeric values to the display. This function is similar to print_str but will interpret periods not as characters but as decimal points associated with the previous character. """ # Calculate length of value without decimals. length = len(value.translate(None, '.')) # Error if value without decimals is longer than 4 characters. if length > 4: self.print_str('----') return # Calculcate starting position of digits based on justification. pos = (4-length) if justify_right else 0 # Go through each character and print it on the display. for i, ch in enumerate(value): if ch == '.': # Print decimal points on the previous digit. self.set_decimal(pos-1, True) else: self.set_digit(pos, ch) pos += 1 def print_float(self, value, decimal_digits=2, justify_right=True): """Print a numeric value to the display. If value is negative it will be printed with a leading minus sign. Decimal digits is the desired number of digits after the decimal point. """ format_string = '{{0:0.{0}F}}'.format(decimal_digits) self.print_number_str(format_string.format(value), justify_right) def print_hex(self, value, justify_right=True): """Print a numeric value in hexadecimal. Value should be from 0 to FFFF. """ if value < 0 or value > 0xFFFF: # Ignore out of range values. return self.print_str('{0:X}'.format(value), justify_right)
Adafruit-LED-Backpack
/Adafruit_LED_Backpack-1.8.1.tar.gz/Adafruit_LED_Backpack-1.8.1/Adafruit_LED_Backpack/AlphaNum4.py
AlphaNum4.py
import struct # Minimal constants carried over from Arduino library: LSM303_ADDRESS_ACCEL = (0x32 >> 1) # 0011001x LSM303_ADDRESS_MAG = (0x3C >> 1) # 0011110x # Default Type LSM303_REGISTER_ACCEL_CTRL_REG1_A = 0x20 # 00000111 rw LSM303_REGISTER_ACCEL_CTRL_REG4_A = 0x23 # 00000000 rw LSM303_REGISTER_ACCEL_OUT_X_L_A = 0x28 LSM303_REGISTER_MAG_CRB_REG_M = 0x01 LSM303_REGISTER_MAG_MR_REG_M = 0x02 LSM303_REGISTER_MAG_OUT_X_H_M = 0x03 # Gain settings for set_mag_gain() LSM303_MAGGAIN_1_3 = 0x20 # +/- 1.3 LSM303_MAGGAIN_1_9 = 0x40 # +/- 1.9 LSM303_MAGGAIN_2_5 = 0x60 # +/- 2.5 LSM303_MAGGAIN_4_0 = 0x80 # +/- 4.0 LSM303_MAGGAIN_4_7 = 0xA0 # +/- 4.7 LSM303_MAGGAIN_5_6 = 0xC0 # +/- 5.6 LSM303_MAGGAIN_8_1 = 0xE0 # +/- 8.1 class LSM303(object): """LSM303 accelerometer & magnetometer.""" def __init__(self, hires=True, accel_address=LSM303_ADDRESS_ACCEL, mag_address=LSM303_ADDRESS_MAG, i2c=None, **kwargs): """Initialize the LSM303 accelerometer & magnetometer. The hires boolean indicates if high resolution (12-bit) mode vs. low resolution (10-bit, faster and lower power) mode should be used. """ # Setup I2C interface for accelerometer and magnetometer. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._accel = i2c.get_i2c_device(accel_address, **kwargs) self._mag = i2c.get_i2c_device(mag_address, **kwargs) # Enable the accelerometer self._accel.write8(LSM303_REGISTER_ACCEL_CTRL_REG1_A, 0x27) # Select hi-res (12-bit) or low-res (10-bit) output mode. # Low-res mode uses less power and sustains a higher update rate, # output is padded to compatible 12-bit units. if hires: self._accel.write8(LSM303_REGISTER_ACCEL_CTRL_REG4_A, 0b00001000) else: self._accel.write8(LSM303_REGISTER_ACCEL_CTRL_REG4_A, 0) # Enable the magnetometer self._mag.write8(LSM303_REGISTER_MAG_MR_REG_M, 0x00) def read(self): """Read the accelerometer and magnetometer value. A tuple of tuples will be returned with: ((accel X, accel Y, accel Z), (mag X, mag Y, mag Z)) """ # Read the accelerometer as signed 16-bit little endian values. accel_raw = self._accel.readList(LSM303_REGISTER_ACCEL_OUT_X_L_A | 0x80, 6) accel = struct.unpack('<hhh', accel_raw) # Convert to 12-bit values by shifting unused bits. accel = (accel[0] >> 4, accel[1] >> 4, accel[2] >> 4) # Read the magnetometer. mag_raw = self._mag.readList(LSM303_REGISTER_MAG_OUT_X_H_M, 6) mag = struct.unpack('>hhh', mag_raw) return (accel, mag) def set_mag_gain(gain=LSM303_MAGGAIN_1_3): """Set the magnetometer gain. Gain should be one of the following constants: - LSM303_MAGGAIN_1_3 = +/- 1.3 (default) - LSM303_MAGGAIN_1_9 = +/- 1.9 - LSM303_MAGGAIN_2_5 = +/- 2.5 - LSM303_MAGGAIN_4_0 = +/- 4.0 - LSM303_MAGGAIN_4_7 = +/- 4.7 - LSM303_MAGGAIN_5_6 = +/- 5.6 - LSM303_MAGGAIN_8_1 = +/- 8.1 """ self._mag.write8(LSM303_REGISTER_MAG_CRB_REG_M, gain)
Adafruit-LSM303
/Adafruit_LSM303-1.0.1.tar.gz/Adafruit_LSM303-1.0.1/Adafruit_LSM303/LSM303.py
LSM303.py
import logging import math import Adafruit_GPIO as GPIO import Adafruit_GPIO.SPI as SPI class MAX31855(object): """Class to represent an Adafruit MAX31855 thermocouple temperature measurement board. """ def __init__(self, clk=None, cs=None, do=None, spi=None, gpio=None): """Initialize MAX31855 device with software SPI on the specified CLK, CS, and DO pins. Alternatively can specify hardware SPI by sending an Adafruit_GPIO.SPI.SpiDev device in the spi parameter. """ self._logger = logging.getLogger('Adafruit_MAX31855.MAX31855') self._spi = None # Handle hardware SPI if spi is not None: self._logger.debug('Using hardware SPI') self._spi = spi elif clk is not None and cs is not None and do is not None: self._logger.debug('Using software SPI') # Default to platform GPIO if not provided. if gpio is None: gpio = GPIO.get_platform_gpio() self._spi = SPI.BitBang(gpio, clk, None, do, cs) else: raise ValueError('Must specify either spi for for hardware SPI or clk, cs, and do for softwrare SPI!') self._spi.set_clock_hz(5000000) self._spi.set_mode(0) self._spi.set_bit_order(SPI.MSBFIRST) def readInternalC(self): """Return internal temperature value in degrees celsius.""" v = self._read32() # Ignore bottom 4 bits of thermocouple data. v >>= 4 # Grab bottom 11 bits as internal temperature data. internal = v & 0x7FF if v & 0x800: # Negative value, take 2's compliment. Compute this with subtraction # because python is a little odd about handling signed/unsigned. internal -= 4096 # Scale by 0.0625 degrees C per bit and return value. return internal * 0.0625 def readTempC(self): """Return the thermocouple temperature value in degrees celsius.""" v = self._read32() # Check for error reading value. if v & 0x7: return float('NaN') # Check if signed bit is set. if v & 0x80000000: # Negative value, take 2's compliment. Compute this with subtraction # because python is a little odd about handling signed/unsigned. v >>= 18 v -= 16384 else: # Positive value, just shift the bits to get the value. v >>= 18 # Scale by 0.25 degrees C per bit and return value. return v * 0.25 def readState(self): """Return dictionary containing fault codes and hardware problems """ v = self._read32() return { 'openCircuit': (v & (1 << 0)) > 0, 'shortGND': (v & (1 << 1)) > 0, 'shortVCC': (v & (1 << 2)) > 0, 'fault': (v & (1 << 16)) > 0 } def readLinearizedTempC(self): """Return the NIST-linearized thermocouple temperature value in degrees celsius. See https://learn.adafruit.com/calibrating-sensors/maxim-31855-linearization for more info. """ # MAX31855 thermocouple voltage reading in mV thermocoupleVoltage = (self.readTempC() - self.readInternalC()) * 0.041276 # MAX31855 cold junction voltage reading in mV coldJunctionTemperature = self.readInternalC() coldJunctionVoltage = (-0.176004136860E-01 + 0.389212049750E-01 * coldJunctionTemperature + 0.185587700320E-04 * math.pow(coldJunctionTemperature, 2.0) + -0.994575928740E-07 * math.pow(coldJunctionTemperature, 3.0) + 0.318409457190E-09 * math.pow(coldJunctionTemperature, 4.0) + -0.560728448890E-12 * math.pow(coldJunctionTemperature, 5.0) + 0.560750590590E-15 * math.pow(coldJunctionTemperature, 6.0) + -0.320207200030E-18 * math.pow(coldJunctionTemperature, 7.0) + 0.971511471520E-22 * math.pow(coldJunctionTemperature, 8.0) + -0.121047212750E-25 * math.pow(coldJunctionTemperature, 9.0) + 0.118597600000E+00 * math.exp(-0.118343200000E-03 * math.pow((coldJunctionTemperature-0.126968600000E+03), 2.0))) # cold junction voltage + thermocouple voltage voltageSum = thermocoupleVoltage + coldJunctionVoltage # calculate corrected temperature reading based on coefficients for 3 different ranges # float b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10; if thermocoupleVoltage < 0: b0 = 0.0000000E+00 b1 = 2.5173462E+01 b2 = -1.1662878E+00 b3 = -1.0833638E+00 b4 = -8.9773540E-01 b5 = -3.7342377E-01 b6 = -8.6632643E-02 b7 = -1.0450598E-02 b8 = -5.1920577E-04 b9 = 0.0000000E+00 elif thermocoupleVoltage < 20.644: b0 = 0.000000E+00 b1 = 2.508355E+01 b2 = 7.860106E-02 b3 = -2.503131E-01 b4 = 8.315270E-02 b5 = -1.228034E-02 b6 = 9.804036E-04 b7 = -4.413030E-05 b8 = 1.057734E-06 b9 = -1.052755E-08 elif thermocoupleVoltage < 54.886: b0 = -1.318058E+02 b1 = 4.830222E+01 b2 = -1.646031E+00 b3 = 5.464731E-02 b4 = -9.650715E-04 b5 = 8.802193E-06 b6 = -3.110810E-08 b7 = 0.000000E+00 b8 = 0.000000E+00 b9 = 0.000000E+00 else: # TODO: handle error - out of range return 0 return (b0 + b1 * voltageSum + b2 * pow(voltageSum, 2.0) + b3 * pow(voltageSum, 3.0) + b4 * pow(voltageSum, 4.0) + b5 * pow(voltageSum, 5.0) + b6 * pow(voltageSum, 6.0) + b7 * pow(voltageSum, 7.0) + b8 * pow(voltageSum, 8.0) + b9 * pow(voltageSum, 9.0)) def _read32(self): # Read 32 bits from the SPI bus. raw = self._spi.read(4) if raw is None or len(raw) != 4: raise RuntimeError('Did not read expected number of bytes from device!') value = raw[0] << 24 | raw[1] << 16 | raw[2] << 8 | raw[3] self._logger.debug('Raw value: 0x{0:08X}'.format(value & 0xFFFFFFFF)) return value
Adafruit-MAX31855
/Adafruit_MAX31855-1.6.1.tar.gz/Adafruit_MAX31855-1.6.1/Adafruit_MAX31855/MAX31855.py
MAX31855.py
# DEPRECATED LIBRARY Adafruit Python MAX9744 This library has been deprecated! We are now only using our CircuitPython sensor libraries in Python. We are leaving the code up for historical/research purposes but archiving the repository. Check out this guide for using the MAX9744 with Python! https://learn.adafruit.com/adafruit-20w-stereo-audio-amplifier-class-d-max9744/python-circuitpython ---- Python library for controlling the MAX9744 class D amplifier with I2C volume control on a Raspberry Pi or BeagleBone Black. Made to work with Adafruit's MAX9744 20-watt stereo amplifier board: https://www.adafruit.com/product/1752 ## Wiring Connect the MAX9744 board to your hardware's I2C bus as follows: On a Raspberry Pi connect: * Pi 3.3V power to MAX9744 Vi2c pin. * Pi GND to MAX9744 GND pin. * Pi SCL to MAX9744 SCL pin. * Pi SDA to MAX9744 SDA pin. Additionally make sure you've enabled I2C on your Raspberry Pi, see: https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-i2c On a BeagleBone Black connect: * BeagleBone Black 3.3V power pin P9_3 to MAX9744 Vi2c pin. * BeagleBone Black GND pin P9_1 to MAX9744 GND pin. * BeagleBone Black SCL pin P9_19 to MAX9744 SCL pin. * BeagleBone Black SDA pin P9_20 to MAX9744 SDA pin. Make sure you don't have a device tree overlay enabled which might interfere with the BBB's default I2C bus above. See this guide for more information device tree overlays: https://learn.adafruit.com/introduction-to-the-beaglebone-black-device-tree/overview ## Installation & Example Usage Before you get started make sure you've assembled and tested your MAX9744 board. Follow the guide here for more information: https://learn.adafruit.com/adafruit-20w-stereo-audio-amplifier-class-d-max9744/overview Make sure your board is connected to the internet, then connect to its command line terminal and run the following commands (assuming a Debian-based operating system like Raspbian on the Pi, or Debian on the BeagleBone Black): sudo apt-get update sudo apt-get install -y python-dev build-essential python-smbus git cd ~ git clone https://github.com/adafruit/Adafruit_Python_MAX9744.git cd Adafruit_Python_MAX9744 sudo python setup.py install That's it, the library should be installed and ready to use! To run the provided simpletest.py example that demonstrates changing the volume of the MAX9744 run the following commands (from inside the Adafruit_Python_MAX9744 directory where the software was downloaded): cd examples sudo python simpletest.py The example will set the volume to a moderate level (32 out of 63), mute it, and ramp it up and down.
Adafruit-MAX9744
/Adafruit_MAX9744-1.0.4.tar.gz/Adafruit_MAX9744-1.0.4/README.md
README.md
import Adafruit_GPIO as GPIO import Adafruit_GPIO.SPI as SPI class MCP3008(object): """Class to represent an Adafruit MCP3008 analog to digital converter. """ def __init__(self, clk=None, cs=None, miso=None, mosi=None, spi=None, gpio=None): """Initialize MAX31855 device with software SPI on the specified CLK, CS, and DO pins. Alternatively can specify hardware SPI by sending an Adafruit_GPIO.SPI.SpiDev device in the spi parameter. """ self._spi = None # Handle hardware SPI if spi is not None: self._spi = spi elif clk is not None and cs is not None and miso is not None and mosi is not None: # Default to platform GPIO if not provided. if gpio is None: gpio = GPIO.get_platform_gpio() self._spi = SPI.BitBang(gpio, clk, mosi, miso, cs) else: raise ValueError('Must specify either spi for for hardware SPI or clk, cs, miso, and mosi for softwrare SPI!') self._spi.set_clock_hz(1000000) self._spi.set_mode(0) self._spi.set_bit_order(SPI.MSBFIRST) def read_adc(self, adc_number): """Read the current value of the specified ADC channel (0-7). The values can range from 0 to 1023 (10-bits). """ assert 0 <= adc_number <= 7, 'ADC number must be a value of 0-7!' # Build a single channel read command. # For example channel zero = 0b11000000 command = 0b11 << 6 # Start bit, single channel read command |= (adc_number & 0x07) << 3 # Channel number (in 3 bits) # Note the bottom 3 bits of command are 0, this is to account for the # extra clock to do the conversion, and the low null bit returned at # the start of the response. resp = self._spi.transfer([command, 0x0, 0x0]) # Parse out the 10 bits of response data and return it. result = (resp[0] & 0x01) << 9 result |= (resp[1] & 0xFF) << 1 result |= (resp[2] & 0x80) >> 7 return result & 0x3FF def read_adc_difference(self, differential): """Read the difference between two channels. Differential should be a value of: - 0: Return channel 0 minus channel 1 - 1: Return channel 1 minus channel 0 - 2: Return channel 2 minus channel 3 - 3: Return channel 3 minus channel 2 - 4: Return channel 4 minus channel 5 - 5: Return channel 5 minus channel 4 - 6: Return channel 6 minus channel 7 - 7: Return channel 7 minus channel 6 """ assert 0 <= differential <= 7, 'Differential number must be a value of 0-7!' # Build a difference channel read command. command = 0b10 << 6 # Start bit, differential read command |= (differential & 0x07) << 3 # Channel number (in 3 bits) # Note the bottom 3 bits of command are 0, this is to account for the # extra clock to do the conversion, and the low null bit returned at # the start of the response. resp = self._spi.transfer([command, 0x0, 0x0]) # Parse out the 10 bits of response data and return it. result = (resp[0] & 0x01) << 9 result |= (resp[1] & 0xFF) << 1 result |= (resp[2] & 0x80) >> 7 return result & 0x3FF
Adafruit-MCP3008
/Adafruit_MCP3008-1.0.2.tar.gz/Adafruit_MCP3008-1.0.2/Adafruit_MCP3008/MCP3008.py
MCP3008.py
DEPRECATED LIBRARY Adafruit Python MCP4725 =================== This library has been deprecated! we are now only using our circuitpython sensor libraries in python we are leaving the code up for historical/research purposes but archiving the repository. check out this guide for using the mcp4725 with python! https://learn.adafruit.com/mcp4725-12-bit-dac-tutorial/python-circuitpython # Python code to use the MCP4725 digital to analog converter with a Raspberry Pi or BeagleBone black. ## Installation To install the library from source (recommended) run the following commands on a Raspberry Pi or other Debian-based OS system: sudo apt-get install git build-essential python-dev cd ~ git clone https://github.com/adafruit/Adafruit_Python_MCP4725.git cd Adafruit_Python_MCP4725 sudo python setup.py install Alternatively you can install from pip with: sudo pip install adafruit-mcp4725 Note that the pip install method **won't** install the example code.
Adafruit-MCP4725
/Adafruit_MCP4725-1.0.4.tar.gz/Adafruit_MCP4725-1.0.4/README.md
README.md
DEPRECATED LIBRARY Adafruit Python MCP9808 =================== This library has been deprecated! we are now only using our circuitpython sensor libraries in python we are leaving the code up for historical/research purposes but archiving the repository. check out this guide for using the mcp9808 with python! https://learn.adafruit.com/adafruit-mcp9808-precision-i2c-temperature-sensor-guide # Python library for accessing the MCP9808 precision temperature sensor on a Raspberry Pi or Beaglebone Black. Designed specifically to work with the Adafruit MCP9808 sensor ----> https://www.adafruit.com/product/1782 To install, first make sure some dependencies are available by running the following commands (on a Raspbian or Beaglebone Black Debian install): ```` sudo apt-get update sudo apt-get install build-essential python-dev python-smbus ```` Then download the library by clicking the download zip link to the right and unzip the archive somewhere on your Raspberry Pi or Beaglebone Black. Then execute the following command in the directory of the library: ```` sudo python setup.py install ```` Make sure you have internet access on the device so it can download the required dependencies. See examples of usage in the examples folder. Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Tony DiCola for Adafruit Industries. MIT license, all text above must be included in any redistribution
Adafruit-MCP9808
/Adafruit_MCP9808-1.5.6.tar.gz/Adafruit_MCP9808-1.5.6/README.md
README.md
import logging import math # Default I2C address for device. MCP9808_I2CADDR_DEFAULT = 0x18 # Register addresses. MCP9808_REG_CONFIG = 0x01 MCP9808_REG_UPPER_TEMP = 0x02 MCP9808_REG_LOWER_TEMP = 0x03 MCP9808_REG_CRIT_TEMP = 0x04 MCP9808_REG_AMBIENT_TEMP = 0x05 MCP9808_REG_MANUF_ID = 0x06 MCP9808_REG_DEVICE_ID = 0x07 # Configuration register values. MCP9808_REG_CONFIG_SHUTDOWN = 0x0100 MCP9808_REG_CONFIG_CRITLOCKED = 0x0080 MCP9808_REG_CONFIG_WINLOCKED = 0x0040 MCP9808_REG_CONFIG_INTCLR = 0x0020 MCP9808_REG_CONFIG_ALERTSTAT = 0x0010 MCP9808_REG_CONFIG_ALERTCTRL = 0x0008 MCP9808_REG_CONFIG_ALERTSEL = 0x0002 MCP9808_REG_CONFIG_ALERTPOL = 0x0002 MCP9808_REG_CONFIG_ALERTMODE = 0x0001 class MCP9808(object): """Class to represent an Adafruit MCP9808 precision temperature measurement board. """ def __init__(self, address=MCP9808_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize MCP9808 device on the specified I2C address and bus number. Address defaults to 0x18 and bus number defaults to the appropriate bus for the hardware. """ self._logger = logging.getLogger('Adafruit_MCP9808.MCP9808') if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._device = i2c.get_i2c_device(address, **kwargs) def begin(self): """Start taking temperature measurements. Returns True if the device is intialized, False otherwise. """ # Check manufacturer and device ID match expected values. mid = self._device.readU16BE(MCP9808_REG_MANUF_ID) did = self._device.readU16BE(MCP9808_REG_DEVICE_ID) self._logger.debug('Read manufacturer ID: {0:04X}'.format(mid)) self._logger.debug('Read device ID: {0:04X}'.format(did)) return mid == 0x0054 and did == 0x0400 def readTempC(self): """Read sensor and return its value in degrees celsius.""" # Read temperature register value. t = self._device.readU16BE(MCP9808_REG_AMBIENT_TEMP) self._logger.debug('Raw ambient temp register value: 0x{0:04X}'.format(t & 0xFFFF)) # Scale and convert to signed value. temp = (t & 0x0FFF) / 16.0 if t & 0x1000: temp -= 256.0 return temp
Adafruit-MCP9808
/Adafruit_MCP9808-1.5.6.tar.gz/Adafruit_MCP9808-1.5.6/Adafruit_MCP9808/MCP9808.py
MCP9808.py
import time # Register addresses. MPR121_I2CADDR_DEFAULT = 0x5A MPR121_TOUCHSTATUS_L = 0x00 MPR121_TOUCHSTATUS_H = 0x01 MPR121_FILTDATA_0L = 0x04 MPR121_FILTDATA_0H = 0x05 MPR121_BASELINE_0 = 0x1E MPR121_MHDR = 0x2B MPR121_NHDR = 0x2C MPR121_NCLR = 0x2D MPR121_FDLR = 0x2E MPR121_MHDF = 0x2F MPR121_NHDF = 0x30 MPR121_NCLF = 0x31 MPR121_FDLF = 0x32 MPR121_NHDT = 0x33 MPR121_NCLT = 0x34 MPR121_FDLT = 0x35 MPR121_TOUCHTH_0 = 0x41 MPR121_RELEASETH_0 = 0x42 MPR121_DEBOUNCE = 0x5B MPR121_CONFIG1 = 0x5C MPR121_CONFIG2 = 0x5D MPR121_CHARGECURR_0 = 0x5F MPR121_CHARGETIME_1 = 0x6C MPR121_ECR = 0x5E MPR121_AUTOCONFIG0 = 0x7B MPR121_AUTOCONFIG1 = 0x7C MPR121_UPLIMIT = 0x7D MPR121_LOWLIMIT = 0x7E MPR121_TARGETLIMIT = 0x7F MPR121_GPIODIR = 0x76 MPR121_GPIOEN = 0x77 MPR121_GPIOSET = 0x78 MPR121_GPIOCLR = 0x79 MPR121_GPIOTOGGLE = 0x7A MPR121_SOFTRESET = 0x80 MAX_I2C_RETRIES = 5 class MPR121(object): """Representation of a MPR121 capacitive touch sensor.""" def __init__(self): """Create an instance of the MPR121 device.""" # Nothing to do here since there is very little state in the class. pass def begin(self, address=MPR121_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults to platform's I2C bus). Returns True if communication with the MPR121 was established, otherwise returns False. """ # Assume we're using platform's default I2C bus if none is specified. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C # Require repeated start conditions for I2C register reads. Unfortunately # the MPR121 is very sensitive and requires repeated starts to read all # the registers. I2C.require_repeated_start() # Save a reference to the I2C device instance for later communication. self._device = i2c.get_i2c_device(address, **kwargs) return self._reset() def _reset(self): # Soft reset of device. self._i2c_retry(self._device.write8, MPR121_SOFTRESET, 0x63) time.sleep(0.001) # This 1ms delay here probably isn't necessary but can't hurt. # Set electrode configuration to default values. self._i2c_retry(self._device.write8, MPR121_ECR, 0x00) # Check CDT, SFI, ESI configuration is at default values. c = self._i2c_retry(self._device.readU8, MPR121_CONFIG2) if c != 0x24: return False # Set threshold for touch and release to default values. self.set_thresholds(12, 6) # Configure baseline filtering control registers. self._i2c_retry(self._device.write8, MPR121_MHDR, 0x01) self._i2c_retry(self._device.write8, MPR121_NHDR, 0x01) self._i2c_retry(self._device.write8, MPR121_NCLR, 0x0E) self._i2c_retry(self._device.write8, MPR121_FDLR, 0x00) self._i2c_retry(self._device.write8, MPR121_MHDF, 0x01) self._i2c_retry(self._device.write8, MPR121_NHDF, 0x05) self._i2c_retry(self._device.write8, MPR121_NCLF, 0x01) self._i2c_retry(self._device.write8, MPR121_FDLF, 0x00) self._i2c_retry(self._device.write8, MPR121_NHDT, 0x00) self._i2c_retry(self._device.write8, MPR121_NCLT, 0x00) self._i2c_retry(self._device.write8, MPR121_FDLT, 0x00) # Set other configuration registers. self._i2c_retry(self._device.write8, MPR121_DEBOUNCE, 0) self._i2c_retry(self._device.write8, MPR121_CONFIG1, 0x10) # default, 16uA charge current self._i2c_retry(self._device.write8, MPR121_CONFIG2, 0x20) # 0.5uS encoding, 1ms period # Enable all electrodes. self._i2c_retry(self._device.write8, MPR121_ECR, 0x8F) # start with first 5 bits of baseline tracking # All done, everything succeeded! return True def _i2c_retry(self, func, *params): # Run specified I2C request and ignore IOError 110 (timeout) up to # retries times. For some reason the Pi 2 hardware I2C appears to be # flakey and randomly return timeout errors on I2C reads. This will # catch those errors, reset the MPR121, and retry. count = 0 while True: try: return func(*params) except IOError as ex: # Re-throw anything that isn't a timeout (110) error. if ex.errno != 110: raise ex # Else there was a timeout, so reset the device and retry. self._reset() # Increase count and fail after maximum number of retries. count += 1 if count >= MAX_I2C_RETRIES: raise RuntimeError('Exceeded maximum number or retries attempting I2C communication!') def set_thresholds(self, touch, release): """Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive). """ assert touch >= 0 and touch <= 255, 'touch must be between 0-255 (inclusive)' assert release >= 0 and release <= 255, 'release must be between 0-255 (inclusive)' # Set the touch and release register value for all the inputs. for i in range(12): self._i2c_retry(self._device.write8, MPR121_TOUCHTH_0 + 2*i, touch) self._i2c_retry(self._device.write8, MPR121_RELEASETH_0 + 2*i, release) def filtered_data(self, pin): """Return filtered data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' return self._i2c_retry(self._device.readU16LE, MPR121_FILTDATA_0L + pin*2) def baseline_data(self, pin): """Return baseline data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' bl = self._i2c_retry(self._device.readU8, MPR121_BASELINE_0 + pin) return bl << 2 def touched(self): """Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched. """ t = self._i2c_retry(self._device.readU16LE, MPR121_TOUCHSTATUS_L) return t & 0x0FFF def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 0
Adafruit-MPR121
/Adafruit_MPR121-1.1.2.tar.gz/Adafruit_MPR121-1.1.2/Adafruit_MPR121/MPR121.py
MPR121.py
Introduction ============ .. image:: https://readthedocs.org/projects/adafruit-micropython-blinka/badge/?version=latest :target: https://circuitpython.readthedocs.io/projects/blinka/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/discord/327254708534116352.svg :target: https://discord.gg/nBQh6qu :alt: Discord .. image:: https://travis-ci.org/adafruit/Adafruit_Micropython_Blinka.svg?branch=master :target: https://travis-ci.org/adafruit/Adafruit__Micropython_Blinka :alt: Build Status This repository contains a selection of packages mirroring the CircuitPython API on hosts running micropython. Working code exists to emulate the CircuitPython packages; * **board** - breakout-specific pin identities * **microcontroller** - chip-specific pin identities * **digitalio** - digital input/output pins, using pin identities from board+microcontroller packages * **bitbangio** - software-driven interfaces for I2C, SPI * **busio** - hardware-driven interfaces for I2C, SPI, UART * **time** * - substitute functions monkey-patched to time module Dependencies ============= The Micropython compatibility layers described above are intended to provide a CircuitPython-like API for devices which are running Micropython. Since corresponding packages should be built-in to any standard CircuitPython image, they have no value on a device already running CircuitPython and would likely conflict in unhappy ways. The test suites in the test/src folder under **testing.universal** are by design intended to run on *either* CircuitPython *or* Micropython+compatibility layer to prove conformance. Usage Example ============= At the time of writing (`git:7fc1f8ab <https://github.com/cefn/Adafruit_Micropython_Blinka/tree/7fc1f8ab477124628a5afebbf6826005955805f9>`_), the following sequence runs through some basic testing of the digitalio compatibility layer... .. code-block:: python from testing import test_module_name test_module_name("testing.universal.digitalio") An example log from running the suites is `here <https://github.com/cefn/Adafruit_Micropython_Blinka/issues/2#issuecomment-366713394>`_ . Contributing ============ Contributions are welcome! Please read our `Code of Conduct <https://github.com/adafruit/Adafruit_Micropython_Blinka/blob/master/CODE_OF_CONDUCT.md>`_ before contributing to help this project stay welcoming. Building locally ================ Sphinx documentation ----------------------- Sphinx is used to build the documentation based on rST files and comments in the code. First, install dependencies (feel free to reuse the virtual environment from above): .. code-block:: shell python3 -m venv .env source .env/bin/activate pip install Sphinx sphinx-rtd-theme Now, once you have the virtual environment activated: .. code-block:: shell cd docs sphinx-build -E -W -b html . _build/html This will output the documentation to ``docs/_build/html``. Open the index.html in your browser to view them. It will also (due to -W) error out on any warning like Travis will. This is a good way to locally verify it will pass.
Adafruit-Micropython-Blinka
/Adafruit-Micropython-Blinka-1.0.0.tar.gz/Adafruit-Micropython-Blinka-1.0.0/README.rst
README.rst
from adafruit_blinka import Enum, Lockable, agnostic class I2C(Lockable): def __init__(self, scl, sda, frequency=400000): self.init(scl, sda, frequency) def init(self, scl, sda, frequency): self.deinit() from machine import I2C as _I2C from microcontroller.pin import i2cPorts for portId, portScl, portSda in i2cPorts: if scl == portScl and sda == portSda: self._i2c = I2C(portId, mode=_I2C.MASTER, baudrate=frequency) break else: raise NotImplementedError("No Hardware I2C on (scl,sda)={}\nValid UART ports".format( (scl, sda), i2cPorts)) def deinit(self): try: del self._i2c except AttributeError: pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.deinit() def scan(self): return self._i2c.scan() def readfrom_into(self, address, buffer, start=0, end=None): if start is not 0 or end is not None: if end is None: end = len(buffer) buffer = memoryview(buffer)[start:end] stop = True # remove for efficiency later return self._i2c.readfrom_into(address, buffer, stop) def writeto(self, address, buffer, start=0, end=None, stop=True): if start is not 0 or end is not None: if end is None: return self._i2c.writeto(address, memoryview(buffer)[start:], stop) else: return self._i2c.writeto(address, memoryview(buffer)[start:end], stop) return self._i2c.writeto(address, buffer, stop) class SPI(Lockable): def __init__(self, clock, MOSI=None, MISO=None): from microcontroller.pin import spiPorts for portId, portSck, portMosi, portMiso in spiPorts: if clock == portSck and MOSI == portMosi and MISO == portMiso: self._spi = SPI(portId) self._pins = (portSck, portMosi, portMiso) break else: raise NotImplementedError( "No Hardware SPI on (clock, MOSI, MISO)={}\nValid SPI ports:{}". format((clock, MOSI, MISO), spiPorts)) def configure(self, baudrate=100000, polarity=0, phase=0, bits=8): if self._locked: from machine import Pin # TODO check if #init ignores MOSI=None rather than unsetting, to save _pinIds attribute self._spi.init( baudrate=baudrate, polarity=polarity, phase=phase, bits=bits, firstbit=SPI.MSB, sck=Pin(self._pins[0].id), mosi=Pin(self._pins[1].id), miso=Pin(self._pins[2].id) ) else: raise RuntimeError("First call try_lock()") def deinit(self): self._spi = None self._pinIds = None def write(self, buf): return self._spi.write(buf) def readinto(self, buf): return self.readinto(buf) def write_readinto(self, buffer_out, buffer_in): return self.write_readinto(buffer_out, buffer_in) class UART(Lockable): class Parity(Enum): pass Parity.ODD = Parity() Parity.EVEN = Parity() def __init__(self, tx, rx, baudrate=9600, bits=8, parity=None, stop=1, timeout=1000, receiver_buffer_size=64, flow=None): from machine import UART as _UART from microcontroller.pin import uartPorts self.baudrate = baudrate if flow is not None: # default 0 raise NotImplementedError( "Parameter '{}' unsupported on {}".format( "flow", agnostic.board)) # translate parity flag for Micropython if parity is UART.Parity.ODD: parity = 1 elif parity is UART.Parity.EVEN: parity = 0 elif parity is None: pass else: raise ValueError("Invalid parity") # check tx and rx have hardware support for portId, portTx, portRx in uartPorts: # if portTx == tx and portRx == rx: self._uart = _UART( portId, baudrate, bits=bits, parity=parity, stop=stop, timeout=timeout, read_buf_len=receiver_buffer_size ) break else: raise NotImplementedError( "No Hardware UART on (tx,rx)={}\nValid UART ports".format( (tx, rx), uartPorts)) def deinit(self): self._uart = None def read(self, nbytes=None): return self._uart.read(nbytes) def readinto(self, buf, nbytes=None): return self._uart.readinto(buf, nbytes) def readline(self): return self._uart.readline() def write(self, buf): return self._uart.write(buf)
Adafruit-Micropython-Blinka
/Adafruit-Micropython-Blinka-1.0.0.tar.gz/Adafruit-Micropython-Blinka-1.0.0/src/busio.py
busio.py
from machine import Pin from adafruit_blinka.agnostic import board as boardId from adafruit_blinka import Enum, ContextManaged class DriveMode(Enum): PUSH_PULL = None OPEN_DRAIN = None DriveMode.PUSH_PULL = DriveMode() DriveMode.OPEN_DRAIN = DriveMode() class Direction(Enum): INPUT = None OUTPUT = None Direction.INPUT = Direction() Direction.OUTPUT = Direction() class Pull(Enum): UP = None DOWN = None #NONE=None Pull.UP = Pull() Pull.DOWN = Pull() #Pull.NONE = Pull() class DigitalInOut(ContextManaged): _pin = None def __init__(self, pin): self._pin = Pin(pin.id) self.direction = Direction.INPUT def switch_to_output(self, value=False, drive_mode=DriveMode.PUSH_PULL): self.direction = Direction.OUTPUT self.value = value self.drive_mode = drive_mode def switch_to_input(self, pull=None): self.direction = Direction.INPUT self.pull = pull def deinit(self): del self._pin @property def direction(self): return self.__direction @direction.setter def direction(self, dir): self.__direction = dir if dir is Direction.OUTPUT: self._pin.init(mode=Pin.OUT) self.value = False self.drive_mode = DriveMode.PUSH_PULL elif dir is Direction.INPUT: self._pin.init(mode=Pin.IN) self.pull = None else: raise AttributeError("Not a Direction") @property def value(self): return self._pin.value() is 1 @value.setter def value(self, val): if self.direction is Direction.OUTPUT: self._pin.value(1 if val else 0) else: raise AttributeError("Not an output") @property def pull(self): if self.direction is Direction.INPUT: return self.__pull else: raise AttributeError("Not an input") @pull.setter def pull(self, pul): if self.direction is Direction.INPUT: self.__pull = pul if pul is Pull.UP: self._pin.init(mode=Pin.IN, pull=Pin.PULL_UP) elif pul is Pull.DOWN: if hasattr(Pin, "PULL_DOWN"): self._pin.init(mode=Pin.IN, pull=Pin.PULL_DOWN) else: raise NotImplementedError("{} unsupported on {}".format( Pull.DOWN, boardId)) elif pul is None: self._pin.init(mode=Pin.IN, pull=None) else: raise AttributeError("Not a Pull") else: raise AttributeError("Not an input") @property def drive_mode(self): if self.direction is Direction.OUTPUT: return self.__drive_mode # else: raise AttributeError("Not an output") @drive_mode.setter def drive_mode(self, mod): self.__drive_mode = mod if mod is DriveMode.OPEN_DRAIN: self._pin.init(mode=Pin.OPEN_DRAIN) elif mod is DriveMode.PUSH_PULL: self._pin.init(mode=Pin.OUT)
Adafruit-Micropython-Blinka
/Adafruit-Micropython-Blinka-1.0.0.tar.gz/Adafruit-Micropython-Blinka-1.0.0/src/digitalio.py
digitalio.py
from adafruit_blinka import Lockable, agnostic class I2C(Lockable): def __init__(self, scl, sda, frequency=400000): if agnostic.microcontroller == "stm32": raise NotImplementedError("No software I2C on {}".format(agnostic.board)) self.init(scl, sda, frequency) def init(self, scl, sda, frequency): from machine import Pin from machine import I2C as _I2C self.deinit() id = -1 # force bitbanging implementation - in future introspect platform if SDA/SCL matches hardware I2C self._i2c = _I2C(id, Pin(scl.id), Pin(sda.id), freq=frequency) def deinit(self): try: del self._i2c except AttributeError: pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.deinit() def scan(self): return self._i2c.scan() def readfrom_into(self, address, buffer, start=0, end=None): if start is not 0 or end is not None: if end is None: end = len(buffer) buffer = memoryview(buffer)[start:end] stop = True # remove for efficiency later return self._i2c.readfrom_into(address, buffer, stop) def writeto(self, address, buffer, start=0, end=None, stop=True): if start is not 0 or end is not None: if end is None: return self._i2c.writeto(address, memoryview(buffer)[start:], stop) else: return self._i2c.writeto(address, memoryview(buffer)[start:end], stop) return self._i2c.writeto(address, buffer, stop) # TODO untested, as actually busio.SPI was on tasklist https://github.com/adafruit/Adafruit_Micropython_Blinka/issues/2 :( class SPI(Lockable): def __init__(self, clock, MOSI=None, MISO=None): from machine import SPI self._spi = SPI(-1) self._pins = (clock, MOSI, MISO) def configure(self, baudrate=100000, polarity=0, phase=0, bits=8): from machine import SPI,Pin if self._locked: # TODO verify if _spi obj 'caches' sck, mosi, miso to avoid storing in _attributeIds (duplicated in busio) # i.e. #init ignores MOSI=None rather than unsetting self._spi.init( baudrate=baudrate, polarity=polarity, phase=phase, bits=bits, firstbit=SPI.MSB, sck=Pin(self._pins[0].id), mosi=Pin(self._pins[1].id), miso=Pin(self._pins[2].id)) else: raise RuntimeError("First call try_lock()") def write(self, buf): return self._spi.write(buf) def readinto(self, buf): return self.readinto(buf) def write_readinto(self, buffer_out, buffer_in): return self.write_readinto(buffer_out, buffer_in)
Adafruit-Micropython-Blinka
/Adafruit-Micropython-Blinka-1.0.0.tar.gz/Adafruit-Micropython-Blinka-1.0.0/src/bitbangio.py
bitbangio.py
import logging import math import time logger = logging.getLogger(__name__) def get_i2c_device(address, i2c, i2c_bus): # Helper method to get a device at the specified address from the I2C bus. # If no i2c bus is specified (i2c param is None) then the default I2C bus # for the platform will be used. if i2c is not None: return i2c.get_i2c_device(address) else: import Adafruit_GPIO.I2C as I2C if i2c_bus is None: return I2C.get_i2c_device(address) else: return I2C.get_i2c_device(address, busnum=i2c_bus) class PWM(object): # Registers/etc. __MODE1 = 0x00 __MODE2 = 0x01 __SUBADR1 = 0x02 __SUBADR2 = 0x03 __SUBADR3 = 0x04 __PRESCALE = 0xFE __LED0_ON_L = 0x06 __LED0_ON_H = 0x07 __LED0_OFF_L = 0x08 __LED0_OFF_H = 0x09 __ALL_LED_ON_L = 0xFA __ALL_LED_ON_H = 0xFB __ALL_LED_OFF_L = 0xFC __ALL_LED_OFF_H = 0xFD # Bits __RESTART = 0x80 __SLEEP = 0x10 __ALLCALL = 0x01 __INVRT = 0x10 __OUTDRV = 0x04 @classmethod def softwareReset(cls, i2c=None, i2c_bus=None): "Sends a software reset (SWRST) command to all the servo drivers on the bus" general_call_i2c = get_i2c_device(0x00, i2c, i2c_bus) general_call_i2c.writeRaw8(0x06) # SWRST def __init__(self, address=0x40, debug=False, i2c=None, i2c_bus=None): self.i2c = get_i2c_device(address, i2c, i2c_bus) logger.debug("Reseting PCA9685 MODE1 (without SLEEP) and MODE2") self.setAllPWM(0, 0) self.i2c.write8(self.__MODE2, self.__OUTDRV) self.i2c.write8(self.__MODE1, self.__ALLCALL) time.sleep(0.005) # wait for oscillator mode1 = self.i2c.readU8(self.__MODE1) mode1 = mode1 & ~self.__SLEEP # wake up (reset sleep) self.i2c.write8(self.__MODE1, mode1) time.sleep(0.005) # wait for oscillator def setPWMFreq(self, freq): "Sets the PWM frequency" prescaleval = 25000000.0 # 25MHz prescaleval /= 4096.0 # 12-bit prescaleval /= float(freq) prescaleval -= 1.0 logger.debug("Setting PWM frequency to %d Hz" % freq) logger.debug("Estimated pre-scale: %d" % prescaleval) prescale = math.floor(prescaleval + 0.5) logger.debug("Final pre-scale: %d" % prescale) oldmode = self.i2c.readU8(self.__MODE1); newmode = (oldmode & 0x7F) | 0x10 # sleep self.i2c.write8(self.__MODE1, newmode) # go to sleep self.i2c.write8(self.__PRESCALE, int(math.floor(prescale))) self.i2c.write8(self.__MODE1, oldmode) time.sleep(0.005) self.i2c.write8(self.__MODE1, oldmode | 0x80) def setPWM(self, channel, on, off): "Sets a single PWM channel" self.i2c.write8(self.__LED0_ON_L+4*channel, on & 0xFF) self.i2c.write8(self.__LED0_ON_H+4*channel, on >> 8) self.i2c.write8(self.__LED0_OFF_L+4*channel, off & 0xFF) self.i2c.write8(self.__LED0_OFF_H+4*channel, off >> 8) def setAllPWM(self, on, off): "Sets a all PWM channels" self.i2c.write8(self.__ALL_LED_ON_L, on & 0xFF) self.i2c.write8(self.__ALL_LED_ON_H, on >> 8) self.i2c.write8(self.__ALL_LED_OFF_L, off & 0xFF) self.i2c.write8(self.__ALL_LED_OFF_H, off >> 8)
Adafruit-MotorHAT
/Adafruit_MotorHAT-1.4.0-py3-none-any.whl/Adafruit_MotorHAT/Adafruit_PWM_Servo_Driver.py
Adafruit_PWM_Servo_Driver.py
import time from Adafruit_MotorHAT.Adafruit_PWM_Servo_Driver import PWM class Adafruit_StepperMotor: MICROSTEPS = 8 MICROSTEP_CURVE = [0, 50, 98, 142, 180, 212, 236, 250, 255] #MICROSTEPS = 16 # a sinusoidal curve NOT LINEAR! #MICROSTEP_CURVE = [0, 25, 50, 74, 98, 120, 141, 162, 180, 197, 212, 225, 236, 244, 250, 253, 255] def __init__(self, controller, num, steps=200): self.MC = controller self.revsteps = steps self.motornum = num self.sec_per_step = 0.1 self.steppingcounter = 0 self.currentstep = 0 num -= 1 if (num == 0): self.PWMA = 8 self.AIN2 = 9 self.AIN1 = 10 self.PWMB = 13 self.BIN2 = 12 self.BIN1 = 11 elif (num == 1): self.PWMA = 2 self.AIN2 = 3 self.AIN1 = 4 self.PWMB = 7 self.BIN2 = 6 self.BIN1 = 5 else: raise NameError('MotorHAT Stepper must be between 1 and 2 inclusive') def setSpeed(self, rpm): self.sec_per_step = 60.0 / (self.revsteps * rpm) self.steppingcounter = 0 def oneStep(self, dir, style): pwm_a = pwm_b = 255 # first determine what sort of stepping procedure we're up to if (style == Adafruit_MotorHAT.SINGLE): if ((self.currentstep//(self.MICROSTEPS//2)) % 2): # we're at an odd step, weird if (dir == Adafruit_MotorHAT.FORWARD): self.currentstep += self.MICROSTEPS//2 else: self.currentstep -= self.MICROSTEPS//2 else: # go to next even step if (dir == Adafruit_MotorHAT.FORWARD): self.currentstep += self.MICROSTEPS else: self.currentstep -= self.MICROSTEPS if (style == Adafruit_MotorHAT.DOUBLE): if not (self.currentstep//(self.MICROSTEPS//2) % 2): # we're at an even step, weird if (dir == Adafruit_MotorHAT.FORWARD): self.currentstep += self.MICROSTEPS//2 else: self.currentstep -= self.MICROSTEPS//2 else: # go to next odd step if (dir == Adafruit_MotorHAT.FORWARD): self.currentstep += self.MICROSTEPS else: self.currentstep -= self.MICROSTEPS if (style == Adafruit_MotorHAT.INTERLEAVE): if (dir == Adafruit_MotorHAT.FORWARD): self.currentstep += self.MICROSTEPS//2 else: self.currentstep -= self.MICROSTEPS//2 if (style == Adafruit_MotorHAT.MICROSTEP): if (dir == Adafruit_MotorHAT.FORWARD): self.currentstep += 1 else: self.currentstep -= 1 # go to next 'step' and wrap around self.currentstep += self.MICROSTEPS * 4 self.currentstep %= self.MICROSTEPS * 4 pwm_a = pwm_b = 0 if (self.currentstep >= 0) and (self.currentstep < self.MICROSTEPS): pwm_a = self.MICROSTEP_CURVE[self.MICROSTEPS - self.currentstep] pwm_b = self.MICROSTEP_CURVE[self.currentstep] elif (self.currentstep >= self.MICROSTEPS) and (self.currentstep < self.MICROSTEPS*2): pwm_a = self.MICROSTEP_CURVE[self.currentstep - self.MICROSTEPS] pwm_b = self.MICROSTEP_CURVE[self.MICROSTEPS*2 - self.currentstep] elif (self.currentstep >= self.MICROSTEPS*2) and (self.currentstep < self.MICROSTEPS*3): pwm_a = self.MICROSTEP_CURVE[self.MICROSTEPS*3 - self.currentstep] pwm_b = self.MICROSTEP_CURVE[self.currentstep - self.MICROSTEPS*2] elif (self.currentstep >= self.MICROSTEPS*3) and (self.currentstep < self.MICROSTEPS*4): pwm_a = self.MICROSTEP_CURVE[self.currentstep - self.MICROSTEPS*3] pwm_b = self.MICROSTEP_CURVE[self.MICROSTEPS*4 - self.currentstep] # go to next 'step' and wrap around self.currentstep += self.MICROSTEPS * 4 self.currentstep %= self.MICROSTEPS * 4 # only really used for microstepping, otherwise always on! self.MC._pwm.setPWM(self.PWMA, 0, pwm_a*16) self.MC._pwm.setPWM(self.PWMB, 0, pwm_b*16) # set up coil energizing! coils = [0, 0, 0, 0] if (style == Adafruit_MotorHAT.MICROSTEP): if (self.currentstep >= 0) and (self.currentstep < self.MICROSTEPS): coils = [1, 1, 0, 0] elif (self.currentstep >= self.MICROSTEPS) and (self.currentstep < self.MICROSTEPS*2): coils = [0, 1, 1, 0] elif (self.currentstep >= self.MICROSTEPS*2) and (self.currentstep < self.MICROSTEPS*3): coils = [0, 0, 1, 1] elif (self.currentstep >= self.MICROSTEPS*3) and (self.currentstep < self.MICROSTEPS*4): coils = [1, 0, 0, 1] else: step2coils = [ [1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [1, 0, 0, 1] ] coils = step2coils[self.currentstep//(self.MICROSTEPS//2)] #print "coils state = " + str(coils) self.MC.setPin(self.AIN2, coils[0]) self.MC.setPin(self.BIN1, coils[1]) self.MC.setPin(self.AIN1, coils[2]) self.MC.setPin(self.BIN2, coils[3]) return self.currentstep def step(self, steps, direction, stepstyle): s_per_s = self.sec_per_step lateststep = 0 if (stepstyle == Adafruit_MotorHAT.INTERLEAVE): s_per_s = s_per_s / 2.0 if (stepstyle == Adafruit_MotorHAT.MICROSTEP): s_per_s /= self.MICROSTEPS steps *= self.MICROSTEPS print("{} sec per step".format(s_per_s)) for s in range(steps): lateststep = self.oneStep(direction, stepstyle) time.sleep(s_per_s) if (stepstyle == Adafruit_MotorHAT.MICROSTEP): # this is an edge case, if we are in between full steps, lets just keep going # so we end on a full step while (lateststep != 0) and (lateststep != self.MICROSTEPS): lateststep = self.oneStep(direction, stepstyle) time.sleep(s_per_s) class Adafruit_DCMotor: def __init__(self, controller, num): self.MC = controller self.motornum = num pwm = in1 = in2 = 0 if (num == 0): pwm = 8 in2 = 9 in1 = 10 elif (num == 1): pwm = 13 in2 = 12 in1 = 11 elif (num == 2): pwm = 2 in2 = 3 in1 = 4 elif (num == 3): pwm = 7 in2 = 6 in1 = 5 else: raise NameError('MotorHAT Motor must be between 1 and 4 inclusive') self.PWMpin = pwm self.IN1pin = in1 self.IN2pin = in2 def run(self, command): if not self.MC: return if (command == Adafruit_MotorHAT.FORWARD): self.MC.setPin(self.IN2pin, 0) self.MC.setPin(self.IN1pin, 1) if (command == Adafruit_MotorHAT.BACKWARD): self.MC.setPin(self.IN1pin, 0) self.MC.setPin(self.IN2pin, 1) if (command == Adafruit_MotorHAT.RELEASE): self.MC.setPin(self.IN1pin, 0) self.MC.setPin(self.IN2pin, 0) def setSpeed(self, speed): if (speed < 0): speed = 0 if (speed > 255): speed = 255 self.MC._pwm.setPWM(self.PWMpin, 0, speed*16) class Adafruit_MotorHAT: FORWARD = 1 BACKWARD = 2 BRAKE = 3 RELEASE = 4 SINGLE = 1 DOUBLE = 2 INTERLEAVE = 3 MICROSTEP = 4 def __init__(self, addr = 0x60, freq = 1600, i2c=None, i2c_bus=None): self._frequency = freq self.motors = [ Adafruit_DCMotor(self, m) for m in range(4) ] self.steppers = [ Adafruit_StepperMotor(self, 1), Adafruit_StepperMotor(self, 2) ] self._pwm = PWM(addr, debug=False, i2c=i2c, i2c_bus=i2c_bus) self._pwm.setPWMFreq(self._frequency) def setPin(self, pin, value): if (pin < 0) or (pin > 15): raise NameError('PWM pin must be between 0 and 15 inclusive') if (value != 0) and (value != 1): raise NameError('Pin value must be 0 or 1!') if (value == 0): self._pwm.setPWM(pin, 0, 4096) if (value == 1): self._pwm.setPWM(pin, 4096, 0) def getStepper(self, steps, num): if (num < 1) or (num > 2): raise NameError('MotorHAT Stepper must be between 1 and 2 inclusive') return self.steppers[num-1] def getMotor(self, num): if (num < 1) or (num > 4): raise NameError('MotorHAT Motor must be between 1 and 4 inclusive') return self.motors[num-1]
Adafruit-MotorHAT
/Adafruit_MotorHAT-1.4.0-py3-none-any.whl/Adafruit_MotorHAT/Adafruit_MotorHAT_Motors.py
Adafruit_MotorHAT_Motors.py
from __future__ import division import logging import time import math # Registers/etc: PCA9685_ADDRESS = 0x40 MODE1 = 0x00 MODE2 = 0x01 SUBADR1 = 0x02 SUBADR2 = 0x03 SUBADR3 = 0x04 PRESCALE = 0xFE LED0_ON_L = 0x06 LED0_ON_H = 0x07 LED0_OFF_L = 0x08 LED0_OFF_H = 0x09 ALL_LED_ON_L = 0xFA ALL_LED_ON_H = 0xFB ALL_LED_OFF_L = 0xFC ALL_LED_OFF_H = 0xFD # Bits: RESTART = 0x80 SLEEP = 0x10 ALLCALL = 0x01 INVRT = 0x10 OUTDRV = 0x04 logger = logging.getLogger(__name__) def software_reset(i2c=None, **kwargs): """Sends a software reset (SWRST) command to all servo drivers on the bus.""" # Setup I2C interface for device 0x00 to talk to all of them. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._device = i2c.get_i2c_device(0x00, **kwargs) self._device.writeRaw8(0x06) # SWRST class PCA9685(object): """PCA9685 PWM LED/servo controller.""" def __init__(self, address=PCA9685_ADDRESS, i2c=None, **kwargs): """Initialize the PCA9685.""" # Setup I2C interface for the device. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._device = i2c.get_i2c_device(address, **kwargs) self.set_all_pwm(0, 0) self._device.write8(MODE2, OUTDRV) self._device.write8(MODE1, ALLCALL) time.sleep(0.005) # wait for oscillator mode1 = self._device.readU8(MODE1) mode1 = mode1 & ~SLEEP # wake up (reset sleep) self._device.write8(MODE1, mode1) time.sleep(0.005) # wait for oscillator def set_pwm_freq(self, freq_hz): """Set the PWM frequency to the provided value in hertz.""" prescaleval = 25000000.0 # 25MHz prescaleval /= 4096.0 # 12-bit prescaleval /= float(freq_hz) prescaleval -= 1.0 logger.debug('Setting PWM frequency to {0} Hz'.format(freq_hz)) logger.debug('Estimated pre-scale: {0}'.format(prescaleval)) prescale = int(math.floor(prescaleval + 0.5)) logger.debug('Final pre-scale: {0}'.format(prescale)) oldmode = self._device.readU8(MODE1); newmode = (oldmode & 0x7F) | 0x10 # sleep self._device.write8(MODE1, newmode) # go to sleep self._device.write8(PRESCALE, prescale) self._device.write8(MODE1, oldmode) time.sleep(0.005) self._device.write8(MODE1, oldmode | 0x80) def set_pwm(self, channel, on, off): """Sets a single PWM channel.""" self._device.write8(LED0_ON_L+4*channel, on & 0xFF) self._device.write8(LED0_ON_H+4*channel, on >> 8) self._device.write8(LED0_OFF_L+4*channel, off & 0xFF) self._device.write8(LED0_OFF_H+4*channel, off >> 8) def set_all_pwm(self, on, off): """Sets all PWM channels.""" self._device.write8(ALL_LED_ON_L, on & 0xFF) self._device.write8(ALL_LED_ON_H, on >> 8) self._device.write8(ALL_LED_OFF_L, off & 0xFF) self._device.write8(ALL_LED_OFF_H, off >> 8)
Adafruit-PCA9685
/Adafruit_PCA9685-1.0.1.tar.gz/Adafruit_PCA9685-1.0.1/Adafruit_PCA9685/PCA9685.py
PCA9685.py
import binascii from functools import reduce import logging import time import Adafruit_GPIO as GPIO import Adafruit_GPIO.SPI as SPI PN532_PREAMBLE = 0x00 PN532_STARTCODE1 = 0x00 PN532_STARTCODE2 = 0xFF PN532_POSTAMBLE = 0x00 PN532_HOSTTOPN532 = 0xD4 PN532_PN532TOHOST = 0xD5 # PN532 Commands PN532_COMMAND_DIAGNOSE = 0x00 PN532_COMMAND_GETFIRMWAREVERSION = 0x02 PN532_COMMAND_GETGENERALSTATUS = 0x04 PN532_COMMAND_READREGISTER = 0x06 PN532_COMMAND_WRITEREGISTER = 0x08 PN532_COMMAND_READGPIO = 0x0C PN532_COMMAND_WRITEGPIO = 0x0E PN532_COMMAND_SETSERIALBAUDRATE = 0x10 PN532_COMMAND_SETPARAMETERS = 0x12 PN532_COMMAND_SAMCONFIGURATION = 0x14 PN532_COMMAND_POWERDOWN = 0x16 PN532_COMMAND_RFCONFIGURATION = 0x32 PN532_COMMAND_RFREGULATIONTEST = 0x58 PN532_COMMAND_INJUMPFORDEP = 0x56 PN532_COMMAND_INJUMPFORPSL = 0x46 PN532_COMMAND_INLISTPASSIVETARGET = 0x4A PN532_COMMAND_INATR = 0x50 PN532_COMMAND_INPSL = 0x4E PN532_COMMAND_INDATAEXCHANGE = 0x40 PN532_COMMAND_INCOMMUNICATETHRU = 0x42 PN532_COMMAND_INDESELECT = 0x44 PN532_COMMAND_INRELEASE = 0x52 PN532_COMMAND_INSELECT = 0x54 PN532_COMMAND_INAUTOPOLL = 0x60 PN532_COMMAND_TGINITASTARGET = 0x8C PN532_COMMAND_TGSETGENERALBYTES = 0x92 PN532_COMMAND_TGGETDATA = 0x86 PN532_COMMAND_TGSETDATA = 0x8E PN532_COMMAND_TGSETMETADATA = 0x94 PN532_COMMAND_TGGETINITIATORCOMMAND = 0x88 PN532_COMMAND_TGRESPONSETOINITIATOR = 0x90 PN532_COMMAND_TGGETTARGETSTATUS = 0x8A PN532_RESPONSE_INDATAEXCHANGE = 0x41 PN532_RESPONSE_INLISTPASSIVETARGET = 0x4B PN532_WAKEUP = 0x55 PN532_SPI_STATREAD = 0x02 PN532_SPI_DATAWRITE = 0x01 PN532_SPI_DATAREAD = 0x03 PN532_SPI_READY = 0x01 PN532_MIFARE_ISO14443A = 0x00 # Mifare Commands MIFARE_CMD_AUTH_A = 0x60 MIFARE_CMD_AUTH_B = 0x61 MIFARE_CMD_READ = 0x30 MIFARE_CMD_WRITE = 0xA0 MIFARE_CMD_TRANSFER = 0xB0 MIFARE_CMD_DECREMENT = 0xC0 MIFARE_CMD_INCREMENT = 0xC1 MIFARE_CMD_STORE = 0xC2 MIFARE_ULTRALIGHT_CMD_WRITE = 0xA2 # Prefixes for NDEF Records (to identify record type) NDEF_URIPREFIX_NONE = 0x00 NDEF_URIPREFIX_HTTP_WWWDOT = 0x01 NDEF_URIPREFIX_HTTPS_WWWDOT = 0x02 NDEF_URIPREFIX_HTTP = 0x03 NDEF_URIPREFIX_HTTPS = 0x04 NDEF_URIPREFIX_TEL = 0x05 NDEF_URIPREFIX_MAILTO = 0x06 NDEF_URIPREFIX_FTP_ANONAT = 0x07 NDEF_URIPREFIX_FTP_FTPDOT = 0x08 NDEF_URIPREFIX_FTPS = 0x09 NDEF_URIPREFIX_SFTP = 0x0A NDEF_URIPREFIX_SMB = 0x0B NDEF_URIPREFIX_NFS = 0x0C NDEF_URIPREFIX_FTP = 0x0D NDEF_URIPREFIX_DAV = 0x0E NDEF_URIPREFIX_NEWS = 0x0F NDEF_URIPREFIX_TELNET = 0x10 NDEF_URIPREFIX_IMAP = 0x11 NDEF_URIPREFIX_RTSP = 0x12 NDEF_URIPREFIX_URN = 0x13 NDEF_URIPREFIX_POP = 0x14 NDEF_URIPREFIX_SIP = 0x15 NDEF_URIPREFIX_SIPS = 0x16 NDEF_URIPREFIX_TFTP = 0x17 NDEF_URIPREFIX_BTSPP = 0x18 NDEF_URIPREFIX_BTL2CAP = 0x19 NDEF_URIPREFIX_BTGOEP = 0x1A NDEF_URIPREFIX_TCPOBEX = 0x1B NDEF_URIPREFIX_IRDAOBEX = 0x1C NDEF_URIPREFIX_FILE = 0x1D NDEF_URIPREFIX_URN_EPC_ID = 0x1E NDEF_URIPREFIX_URN_EPC_TAG = 0x1F NDEF_URIPREFIX_URN_EPC_PAT = 0x20 NDEF_URIPREFIX_URN_EPC_RAW = 0x21 NDEF_URIPREFIX_URN_EPC = 0x22 NDEF_URIPREFIX_URN_NFC = 0x23 PN532_GPIO_VALIDATIONBIT = 0x80 PN532_GPIO_P30 = 0 PN532_GPIO_P31 = 1 PN532_GPIO_P32 = 2 PN532_GPIO_P33 = 3 PN532_GPIO_P34 = 4 PN532_GPIO_P35 = 5 PN532_ACK = bytearray([0x01, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00]) PN532_FRAME_START = bytearray([0x01, 0x00, 0x00, 0xFF]) logger = logging.getLogger(__name__) class PN532(object): """PN532 breakout board representation. Requires a SPI connection to the breakout board. A software SPI connection is recommended as the hardware SPI on the Raspberry Pi has some issues with the LSB first mode used by the PN532 (see: http://www.raspberrypi.org/forums/viewtopic.php?f=32&t=98070&p=720659#p720659) """ def __init__(self, cs, sclk=None, mosi=None, miso=None, gpio=None, spi=None): """Create an instance of the PN532 class using either software SPI (if the sclk, mosi, and miso pins are specified) or hardware SPI if a spi parameter is passed. The cs pin must be a digital GPIO pin. Optionally specify a GPIO controller to override the default that uses the board's GPIO pins. """ # Default to platform GPIO if not provided. self._gpio = gpio if self._gpio is None: self._gpio = GPIO.get_platform_gpio() # Initialize CS line. self._cs = cs self._gpio.setup(self._cs, GPIO.OUT) self._gpio.set_high(self._cs) # Setup SPI provider. if spi is not None: logger.debug('Using hardware SPI.') # Handle using hardware SPI. self._spi = spi self._spi.set_clock_hz(1000000) else: logger.debug('Using software SPI') # Handle using software SPI. Note that the CS/SS pin is not used # as it will be manually controlled by this library for better # timing. self._spi = SPI.BitBang(self._gpio, sclk, mosi, miso) # Set SPI mode and LSB first bit order. self._spi.set_mode(0) self._spi.set_bit_order(SPI.LSBFIRST) def _uint8_add(self, a, b): """Add add two values as unsigned 8-bit values.""" return ((a & 0xFF) + (b & 0xFF)) & 0xFF def _busy_wait_ms(self, ms): """Busy wait for the specified number of milliseconds.""" start = time.time() delta = ms/1000.0 while (time.time() - start) <= delta: pass def _write_frame(self, data): """Write a frame to the PN532 with the specified data bytearray.""" assert data is not None and 0 < len(data) < 255, 'Data must be array of 1 to 255 bytes.' # Build frame to send as: # - SPI data write (0x01) # - Preamble (0x00) # - Start code (0x00, 0xFF) # - Command length (1 byte) # - Command length checksum # - Command bytes # - Checksum # - Postamble (0x00) length = len(data) frame = bytearray(length+8) frame[0] = PN532_SPI_DATAWRITE frame[1] = PN532_PREAMBLE frame[2] = PN532_STARTCODE1 frame[3] = PN532_STARTCODE2 frame[4] = length & 0xFF frame[5] = self._uint8_add(~length, 1) frame[6:-2] = data checksum = reduce(self._uint8_add, data, 0xFF) frame[-2] = ~checksum & 0xFF frame[-1] = PN532_POSTAMBLE # Send frame. logger.debug('Write frame: 0x{0}'.format(binascii.hexlify(frame))) self._gpio.set_low(self._cs) self._busy_wait_ms(2) self._spi.write(frame) self._gpio.set_high(self._cs) def _read_data(self, count): """Read a specified count of bytes from the PN532.""" # Build a read request frame. frame = bytearray(count) frame[0] = PN532_SPI_DATAREAD # Send the frame and return the response, ignoring the SPI header byte. self._gpio.set_low(self._cs) self._busy_wait_ms(2) response = self._spi.transfer(frame) self._gpio.set_high(self._cs) return response def _read_frame(self, length): """Read a response frame from the PN532 of at most length bytes in size. Returns the data inside the frame if found, otherwise raises an exception if there is an error parsing the frame. Note that less than length bytes might be returned! """ # Read frame with expected length of data. response = self._read_data(length+8) logger.debug('Read frame: 0x{0}'.format(binascii.hexlify(response))) # Check frame starts with 0x01 and then has 0x00FF (preceeded by optional # zeros). if response[0] != 0x01: raise RuntimeError('Response frame does not start with 0x01!') # Swallow all the 0x00 values that preceed 0xFF. offset = 1 while response[offset] == 0x00: offset += 1 if offset >= len(response): raise RuntimeError('Response frame preamble does not contain 0x00FF!') if response[offset] != 0xFF: raise RuntimeError('Response frame preamble does not contain 0x00FF!') offset += 1 if offset >= len(response): raise RuntimeError('Response contains no data!') # Check length & length checksum match. frame_len = response[offset] if (frame_len + response[offset+1]) & 0xFF != 0: raise RuntimeError('Response length checksum did not match length!') # Check frame checksum value matches bytes. checksum = reduce(self._uint8_add, response[offset+2:offset+2+frame_len+1], 0) if checksum != 0: raise RuntimeError('Response checksum did not match expected value!') # Return frame data. return response[offset+2:offset+2+frame_len] def _wait_ready(self, timeout_sec=1): """Wait until the PN532 is ready to receive commands. At most wait timeout_sec seconds for the PN532 to be ready. If the PN532 is ready before the timeout is exceeded then True will be returned, otherwise False is returned when the timeout is exceeded. """ start = time.time() # Send a SPI status read command and read response. self._gpio.set_low(self._cs) self._busy_wait_ms(2) response = self._spi.transfer([PN532_SPI_STATREAD, 0x00]) self._gpio.set_high(self._cs) # Loop until a ready response is received. while response[1] != PN532_SPI_READY: # Check if the timeout has been exceeded. if time.time() - start >= timeout_sec: return False # Wait a little while and try reading the status again. time.sleep(0.01) self._gpio.set_low(self._cs) self._busy_wait_ms(2) response = self._spi.transfer([PN532_SPI_STATREAD, 0x00]) self._gpio.set_high(self._cs) return True def call_function(self, command, response_length=0, params=[], timeout_sec=1): """Send specified command to the PN532 and expect up to response_length bytes back in a response. Note that less than the expected bytes might be returned! Params can optionally specify an array of bytes to send as parameters to the function call. Will wait up to timeout_secs seconds for a response and return a bytearray of response bytes, or None if no response is available within the timeout. """ # Build frame data with command and parameters. data = bytearray(2+len(params)) data[0] = PN532_HOSTTOPN532 data[1] = command & 0xFF data[2:] = params # Send frame and wait for response. self._write_frame(data) if not self._wait_ready(timeout_sec): return None # Verify ACK response and wait to be ready for function response. response = self._read_data(len(PN532_ACK)) if response != PN532_ACK: raise RuntimeError('Did not receive expected ACK from PN532!') if not self._wait_ready(timeout_sec): return None # Read response bytes. response = self._read_frame(response_length+2) # Check that response is for the called function. if not (response[0] == PN532_PN532TOHOST and response[1] == (command+1)): raise RuntimeError('Received unexpected command response!') # Return response data. return response[2:] def begin(self): """Initialize communication with the PN532. Must be called before any other calls are made against the PN532. """ # Assert CS pin low for a second for PN532 to be ready. self._gpio.set_low(self._cs) time.sleep(1.0) # Call GetFirmwareVersion to sync up with the PN532. This might not be # required but is done in the Arduino library and kept for consistency. self.get_firmware_version() self._gpio.set_high(self._cs) def get_firmware_version(self): """Call PN532 GetFirmwareVersion function and return a tuple with the IC, Ver, Rev, and Support values. """ response = self.call_function(PN532_COMMAND_GETFIRMWAREVERSION, 4) if response is None: raise RuntimeError('Failed to detect the PN532! Make sure there is sufficient power (use a 1 amp or greater power supply), the PN532 is wired correctly to the device, and the solder joints on the PN532 headers are solidly connected.') return (response[0], response[1], response[2], response[3]) def SAM_configuration(self): """Configure the PN532 to read MiFare cards.""" # Send SAM configuration command with configuration for: # - 0x01, normal mode # - 0x14, timeout 50ms * 20 = 1 second # - 0x01, use IRQ pin # Note that no other verification is necessary as call_function will # check the command was executed as expected. self.call_function(PN532_COMMAND_SAMCONFIGURATION, params=[0x01, 0x14, 0x01]) def read_passive_target(self, card_baud=PN532_MIFARE_ISO14443A, timeout_sec=1): """Wait for a MiFare card to be available and return its UID when found. Will wait up to timeout_sec seconds and return None if no card is found, otherwise a bytearray with the UID of the found card is returned. """ # Send passive read command for 1 card. Expect at most a 7 byte UUID. response = self.call_function(PN532_COMMAND_INLISTPASSIVETARGET, params=[0x01, card_baud], response_length=17) # If no response is available return None to indicate no card is present. if response is None: return None # Check only 1 card with up to a 7 byte UID is present. if response[0] != 0x01: raise RuntimeError('More than one card detected!') if response[5] > 7: raise RuntimeError('Found card with unexpectedly long UID!') # Return UID of card. return response[6:6+response[5]] def mifare_classic_authenticate_block(self, uid, block_number, key_number, key): """Authenticate specified block number for a MiFare classic card. Uid should be a byte array with the UID of the card, block number should be the block to authenticate, key number should be the key type (like MIFARE_CMD_AUTH_A or MIFARE_CMD_AUTH_B), and key should be a byte array with the key data. Returns True if the block was authenticated, or False if not authenticated. """ # Build parameters for InDataExchange command to authenticate MiFare card. uidlen = len(uid) keylen = len(key) params = bytearray(3+uidlen+keylen) params[0] = 0x01 # Max card numbers params[1] = key_number & 0xFF params[2] = block_number & 0xFF params[3:3+keylen] = key params[3+keylen:] = uid # Send InDataExchange request and verify response is 0x00. response = self.call_function(PN532_COMMAND_INDATAEXCHANGE, params=params, response_length=1) return response[0] == 0x00 def mifare_classic_read_block(self, block_number): """Read a block of data from the card. Block number should be the block to read. If the block is successfully read a bytearray of length 16 with data starting at the specified block will be returned. If the block is not read then None will be returned. """ # Send InDataExchange request to read block of MiFare data. response = self.call_function(PN532_COMMAND_INDATAEXCHANGE, params=[0x01, MIFARE_CMD_READ, block_number & 0xFF], response_length=17) # Check first response is 0x00 to show success. if response[0] != 0x00: return None # Return first 4 bytes since 16 bytes are always returned. return response[1:] def mifare_classic_write_block(self, block_number, data): """Write a block of data to the card. Block number should be the block to write and data should be a byte array of length 16 with the data to write. If the data is successfully written then True is returned, otherwise False is returned. """ assert data is not None and len(data) == 16, 'Data must be an array of 16 bytes!' # Build parameters for InDataExchange command to do MiFare classic write. params = bytearray(19) params[0] = 0x01 # Max card numbers params[1] = MIFARE_CMD_WRITE params[2] = block_number & 0xFF params[3:] = data # Send InDataExchange request. response = self.call_function(PN532_COMMAND_INDATAEXCHANGE, params=params, response_length=1) return response[0] == 0x00
Adafruit-PN532
/Adafruit_PN532-1.2.1.tar.gz/Adafruit_PN532-1.2.1/Adafruit_PN532/PN532.py
PN532.py
Introduction ============ .. image:: https://readthedocs.org/projects/adafruit-platformdetect/badge/?version=latest :target: https://circuitpython.readthedocs.io/projects/platformdetect/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/discord/327254708534116352.svg :target: https://adafru.it/discord :alt: Discord .. image:: https://github.com/adafruit/Adafruit_Python_PlatformDetect/workflows/Build%20CI/badge.svg :target: https://github.com/adafruit/Adafruit_Python_PlatformDetect/actions :alt: Build Status .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/psf/black :alt: Code Style: Black This library provides best-guess platform detection for a range of single-board computers and (potentially) other platforms. It was written primarily for use in `Adafruit_Blinka <https://github.com/adafruit/Adafruit_Blinka>`_, but may be useful in other contexts. Platform detection is divided into "chip" and "board" detection, with the latter generally dependent on the former. Platform info is gathered from: - Python's `sys.platform` - Various files on Linux systems: - /proc/cpuinfo (for processor info, Raspberry Pi hardware revisions, etc.) - /proc/device-tree/compatible (for 96Boards info) - Beaglebone EEPROM board IDs - Distribution-specific files such as /etc/armbian-release. Dependencies ============= This driver depends on: * Python 3.7 or higher Installing from PyPI ===================== On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from PyPI <https://pypi.org/project/Adafruit-PlatformDetect/>`_. To install for current user: .. code-block:: shell pip3 install Adafruit-PlatformDetect To install system-wide (this may be required in some cases): .. code-block:: shell sudo pip3 install Adafruit-PlatformDetect To install in a virtual environment in your current project: .. code-block:: shell mkdir project-name && cd project-name python3 -m venv .env source .env/bin/activate pip3 install Adafruit-PlatformDetect Usage Example ============= .. code-block:: python from adafruit_platformdetect import Detector detector = Detector() print("Chip id: ", detector.chip.id) print("Board id: ", detector.board.id) # Check for specific board models: print("Pi 3B+? ", detector.board.RASPBERRY_PI_3B_PLUS) print("BBB? ", detector.board.BEAGLEBONE_BLACK) print("Orange Pi PC? ", detector.board.ORANGE_PI_PC) print("generic Linux PC? ", detector.board.GENERIC_LINUX_PC) Contributing ============ Contributions are welcome! Please read our `Code of Conduct <https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/master/CODE_OF_CONDUCT.md>`_ before contributing to help this project stay welcoming. Documentation ============= For information on building library documentation, please check out `this guide <https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/sharing-our-docs-on-readthedocs#sphinx-5-1>`_.
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/README.rst
README.rst
<!-- SPDX-FileCopyrightText: 2014 Coraline Ada Ehmke SPDX-FileCopyrightText: 2019 Kattni Rembor for Adafruit Industries SPDX-License-Identifier: CC-BY-4.0 --> # Adafruit Community Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and leaders pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level or type of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards We are committed to providing a friendly, safe and welcoming environment for all. Examples of behavior that contributes to creating a positive environment include: * Be kind and courteous to others * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Collaborating with other community members * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and sexual attention or advances * The use of inappropriate images, including in a community member's avatar * The use of inappropriate language, including in a community member's nickname * Any spamming, flaming, baiting or other attention-stealing behavior * Excessive or unwelcome helping; answering outside the scope of the question asked * Trolling, insulting/derogatory comments, and personal or political attacks * Promoting or spreading disinformation, lies, or conspiracy theories against a person, group, organisation, project, or community * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate The goal of the standards and moderation guidelines outlined here is to build and maintain a respectful community. We ask that you don’t just aim to be "technically unimpeachable", but rather try to be your best self. We value many things beyond technical expertise, including collaboration and supporting others within our community. Providing a positive experience for other community members can have a much more significant impact than simply providing the correct answer. ## Our Responsibilities Project leaders are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project leaders have the right and responsibility to remove, edit, or reject messages, comments, commits, code, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any community member for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Moderation Instances of behaviors that violate the Adafruit Community Code of Conduct may be reported by any member of the community. Community members are encouraged to report these situations, including situations they witness involving other community members. You may report in the following ways: In any situation, you may send an email to <[email protected]>. On the Adafruit Discord, you may send an open message from any channel to all Community Moderators by tagging @community moderators. You may also send an open message from any channel, or a direct message to @kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. Email and direct message reports will be kept confidential. In situations on Discord where the issue is particularly egregious, possibly illegal, requires immediate action, or violates the Discord terms of service, you should also report the message directly to Discord. These are the steps for upholding our community’s standards of conduct. 1. Any member of the community may report any situation that violates the Adafruit Community Code of Conduct. All reports will be reviewed and investigated. 2. If the behavior is an egregious violation, the community member who committed the violation may be banned immediately, without warning. 3. Otherwise, moderators will first respond to such behavior with a warning. 4. Moderators follow a soft "three strikes" policy - the community member may be given another chance, if they are receptive to the warning and change their behavior. 5. If the community member is unreceptive or unreasonable when warned by a moderator, or the warning goes unheeded, they may be banned for a first or second offense. Repeated offenses will result in the community member being banned. ## Scope This Code of Conduct and the enforcement policies listed above apply to all Adafruit Community venues. This includes but is not limited to any community spaces (both public and private), the entire Adafruit Discord server, and Adafruit GitHub repositories. Examples of Adafruit Community spaces include but are not limited to meet-ups, audio chats on the Adafruit Discord, or interaction at a conference. This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. As a community member, you are representing our community, and are expected to behave accordingly. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at <https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>, and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). For other projects adopting the Adafruit Community Code of Conduct, please contact the maintainers of those projects for enforcement. If you wish to use this code of conduct for your own project, consider explicitly mentioning your moderation policy or making a copy with your own moderation policy so as to avoid confusion.
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/CODE_OF_CONDUCT.md
CODE_OF_CONDUCT.md
.. include:: ../README.rst Table of Contents ================= .. toctree:: :maxdepth: 4 :hidden: self .. toctree:: :caption: API Reference :maxdepth: 3 api .. toctree:: :caption: Tutorials Adding a Single Board Computer to PlatformDetect for Blinka <https://learn.adafruit.com/adding-a-single-board-computer-to-platformdetect-for-blinka> .. toctree:: :caption: Related Products .. toctree:: :caption: Other Links Download <https://github.com/adafruit/Adafruit_Python_PlatformDetect/releases/latest> CircuitPython Reference Documentation <https://circuitpython.readthedocs.io> CircuitPython Support Forum <https://forums.adafruit.com/viewforum.php?f=60> Discord Chat <https://adafru.it/discord> Adafruit Learning System <https://learn.adafruit.com> Adafruit Blog <https://blog.adafruit.com> Adafruit Store <https://www.adafruit.com> Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/docs/index.rst
index.rst
import os import sys try: from typing import Optional except ImportError: pass from adafruit_platformdetect.constants import chips __version__ = "3.49.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PlatformDetect.git" class Chip: """Attempt detection of current chip / CPU.""" def __init__(self, detector) -> None: self.detector = detector self._chip_id = None # pylint: disable=invalid-name,too-many-branches,too-many-return-statements @property def id( self, ) -> Optional[str]: """Return a unique id for the detected chip, if any.""" # There are some times we want to trick the platform detection # say if a raspberry pi doesn't have the right ID, or for testing # Caching if self._chip_id: return self._chip_id if getattr(os, "environ", None) is not None: try: return os.environ["BLINKA_FORCECHIP"] except KeyError: # no forced chip, continue with testing! pass # Special cases controlled by environment var if os.environ.get("BLINKA_FT232H"): from pyftdi.usbtools import UsbTools # look for it based on PID/VID count = len(UsbTools.find_all([(0x0403, 0x6014)])) if count == 0: raise RuntimeError( "BLINKA_FT232H environment variable " + "set, but no FT232H device found" ) self._chip_id = chips.FT232H return self._chip_id if os.environ.get("BLINKA_FT2232H"): from pyftdi.usbtools import UsbTools # look for it based on PID/VID count = len(UsbTools.find_all([(0x0403, 0x6010)])) if count == 0: raise RuntimeError( "BLINKA_FT2232H environment variable " + "set, but no FT2232H device found" ) self._chip_id = chips.FT2232H return self._chip_id if os.environ.get("BLINKA_MCP2221"): import hid # look for it based on PID/VID for dev in hid.enumerate(): if dev["vendor_id"] == 0x04D8 and dev["product_id"] == 0x00DD: self._chip_id = chips.MCP2221 return self._chip_id raise RuntimeError( "BLINKA_MCP2221 environment variable " + "set, but no MCP2221 device found" ) if os.environ.get("BLINKA_U2IF"): import hid # look for it based on PID/VID for dev in hid.enumerate(): vendor = dev["vendor_id"] product = dev["product_id"] # NOTE: If any products are added here, they need added # to _rp2040_u2if_id() in board.py as well. if ( # Raspberry Pi Pico vendor == 0xCAFE and product == 0x4005 ) or ( # Feather RP2040 # Itsy Bitsy RP2040 # QT Py RP2040 # QT2040 Trinkey # MacroPad RP2040 # Feather RP2040 ThinkInk # Feather RP2040 RFM # Feather RP2040 CAN Bus vendor == 0x239A and product in ( 0x00F1, 0x00FD, 0x00F7, 0x0109, 0x0107, 0x812C, 0x812E, 0x8130, 0x0105, ) ): self._chip_id = chips.RP2040_U2IF return self._chip_id raise RuntimeError( "BLINKA_U2IF environment variable " + "set, but no compatible device found" ) if os.environ.get("BLINKA_GREATFET"): import usb if usb.core.find(idVendor=0x1D50, idProduct=0x60E6) is not None: self._chip_id = chips.LPC4330 return self._chip_id raise RuntimeError( "BLINKA_GREATFET environment variable " + "set, but no GreatFET device found" ) if os.environ.get("BLINKA_NOVA"): self._chip_id = chips.BINHO return self._chip_id platform = sys.platform if platform in ("linux", "linux2"): self._chip_id = self._linux_id() return self._chip_id if platform == "esp8266": self._chip_id = chips.ESP8266 return self._chip_id if platform == "samd21": self._chip_id = chips.SAMD21 return self._chip_id if platform == "pyboard": self._chip_id = chips.STM32F405 return self._chip_id if platform == "rp2": self._chip_id = chips.RP2040 return self._chip_id # nothing found! return None # pylint: enable=invalid-name def _linux_id(self) -> Optional[str]: # pylint: disable=too-many-branches,too-many-statements # pylint: disable=too-many-return-statements """Attempt to detect the CPU on a computer running the Linux kernel.""" if self.detector.check_dt_compatible_value("ti,am625"): return chips.AM625X if self.detector.check_dt_compatible_value("ti,am654"): return chips.AM65XX if self.detector.check_dt_compatible_value("ti,am652"): return chips.AM65XX if self.detector.check_dt_compatible_value("sun4i-a10"): return chips.A10 if self.detector.check_dt_compatible_value("sun7i-a20"): return chips.A20 if self.detector.check_dt_compatible_value("amlogic,g12a"): return chips.S905Y2 if self.detector.check_dt_compatible_value("amlogic, g12a"): return chips.S905X3 if self.detector.check_dt_compatible_value("sun8i-h3"): return chips.H3 if self.detector.check_dt_compatible_value("qcom,apq8016"): return chips.APQ8016 if self.detector.check_dt_compatible_value("fu500"): return chips.HFU540 if self.detector.check_dt_compatible_value("sun20iw1p1"): return chips.C906 # Older Builds if self.detector.check_dt_compatible_value("sifive"): return chips.JH71x0 # Newer Builds if self.detector.check_dt_compatible_value("jh7100"): return chips.JH71x0 if self.detector.check_dt_compatible_value("sun8i-a33"): return chips.A33 if self.detector.check_dt_compatible_value("rockchip,rk3308"): return chips.RK3308 if self.detector.check_dt_compatible_value("radxa,rock-4c-plus"): return chips.RK3399_T if self.detector.check_dt_compatible_value("rockchip,rk3399pro"): return chips.RK3399PRO if self.detector.check_dt_compatible_value("rockchip,rk3399"): return chips.RK3399 if self.detector.check_dt_compatible_value("rockchip,rk3288"): return chips.RK3288 if self.detector.check_dt_compatible_value("rockchip,rk3328"): return chips.RK3328 if self.detector.check_dt_compatible_value("rockchip,rk3566"): return chips.RK3566 if self.detector.check_dt_compatible_value("rockchip,rk3568"): return chips.RK3568 if self.detector.check_dt_compatible_value("rockchip,rk3568b2"): return chips.RK3568B2 if self.detector.check_dt_compatible_value("rockchip,rk3588"): return chips.RK3588 if self.detector.check_dt_compatible_value("amlogic,a311d"): return chips.A311D if self.detector.check_dt_compatible_value("st,stm32mp157"): return chips.STM32MP157 if self.detector.check_dt_compatible_value("st,stm32mp153"): return chips.STM32MP157DAA1 if self.detector.check_dt_compatible_value("sun50i-a64"): return chips.A64 if self.detector.check_dt_compatible_value("sun50i-h5"): return chips.H5 if self.detector.check_dt_compatible_value("sun50i-h616"): return chips.H616 if self.detector.check_dt_compatible_value("sun50iw9"): return chips.H616 if self.detector.check_dt_compatible_value("sun50i-h6"): return chips.H6 if self.detector.check_dt_compatible_value("mediatek,mt8167"): return chips.MT8167 if self.detector.check_dt_compatible_value("imx6ull"): return chips.IMX6ULL if self.detector.check_dt_compatible_value("ti,j721e"): return chips.TDA4VM if self.detector.check_dt_compatible_value("sun20i-d1"): return chips.D1_RISCV if self.detector.check_dt_compatible_value("imx8mp"): return chips.IMX8MP if self.detector.check_dt_compatible_value("libretech,aml-s905x-cc"): return chips.S905X linux_id = None hardware = self.detector.get_cpuinfo_field("Hardware") if hardware is None: vendor_id = self.detector.get_cpuinfo_field("vendor_id") if vendor_id == "AuthenticAMD": model_name = self.detector.get_cpuinfo_field("model name").upper() if "RYZEN EMBEDDED V1202B" in model_name: linux_id = chips.RYZEN_V1202B if "RYZEN EMBEDDED V1605B" in model_name: linux_id = chips.RYZEN_V1605B else: linux_id = chips.GENERIC_X86 ## print("linux_id = ", linux_id) elif vendor_id == "GenuineIntel": model_name = self.detector.get_cpuinfo_field("model name").upper() ## print('model_name =', model_name) if "N3710" in model_name: linux_id = chips.PENTIUM_N3710 if "N5105" in model_name: linux_id = chips.CELERON_N5105 elif "X5-Z8350" in model_name: linux_id = chips.ATOM_X5_Z8350 elif "J4105" in model_name: linux_id = chips.ATOM_J4105 else: linux_id = chips.GENERIC_X86 ## print("linux_id = ", linux_id) compatible = self.detector.get_device_compatible() if compatible and "tegra" in compatible: compats = compatible.split("\x00") if "nvidia,tegra210" in compats: linux_id = chips.T210 elif "nvidia,tegra186" in compats: linux_id = chips.T186 elif "nvidia,tegra194" in compats: linux_id = chips.T194 elif "nvidia,tegra234" in compats: linux_id = chips.T234 if compatible and "imx8m" in compatible: linux_id = chips.IMX8MX if compatible and "odroid-c2" in compatible: linux_id = chips.S905 if compatible and "amlogic" in compatible: compatible_list = ( compatible.replace("\x00", ",").replace(" ", "").split(",") ) if "g12a" in compatible_list: # 'sm1' is correct for S905X3, but some kernels use 'g12a' return chips.S905X3 if "g12b" in compatible_list: return chips.S922X if "sm1" in compatible_list: return chips.S905X3 if "vim3amlogic" in compatible_list: return chips.A311D if compatible and "sun50i-a64" in compatible: linux_id = chips.A64 if compatible and "sun50i-h6" in compatible: linux_id = chips.H6 if compatible and "sun50i-h5" in compatible: linux_id = chips.H5 if compatible and "odroid-xu4" in compatible: linux_id = chips.EXYNOS5422 cpu_model = self.detector.get_cpuinfo_field("cpu model") if cpu_model is not None: if "MIPS 24Kc" in cpu_model: linux_id = chips.MIPS24KC elif "MIPS 24KEc" in cpu_model: linux_id = chips.MIPS24KEC # we still haven't identified the hardware, so # convert it to a list and let the remaining # conditions attempt. if not linux_id: hardware = [ entry.replace("\x00", "") for entry in compatible.split(",") ] if not linux_id: if "AM33XX" in hardware: linux_id = chips.AM33XX elif "DRA74X" in hardware: linux_id = chips.DRA74X elif "sun4i" in hardware: linux_id = chips.A10 elif "sun7i" in hardware: linux_id = chips.A20 elif "sun8i" in hardware: linux_id = chips.SUN8I elif "ODROIDC" in hardware: linux_id = chips.S805 elif "ODROID-C2" in hardware: linux_id = chips.S905 elif "ODROID-N2" in hardware: linux_id = chips.S922X elif "ODROID-C4" in hardware: linux_id = chips.S905X3 elif "ODROID-XU4" in hardware: linux_id = chips.EXYNOS5422 elif "KHADAS-VIM3" in hardware: linux_id = chips.A311D elif "SAMA5" in hardware: linux_id = chips.SAMA5 elif "Pinebook" in hardware: linux_id = chips.A64 elif "ASUS_TINKER_BOARD" in hardware: linux_id = chips.RK3288 elif "Xilinx Zynq" in hardware: compatible = self.detector.get_device_compatible() if compatible and "xlnx,zynq-7000" in compatible: linux_id = chips.ZYNQ7000 else: if isinstance(hardware, str): if hardware.upper() in chips.BCM_RANGE: linux_id = chips.BCM2XXX elif isinstance(hardware, list): if {model.upper() for model in hardware} & chips.BCM_RANGE: linux_id = chips.BCM2XXX return linux_id def __getattr__(self, attr: str) -> bool: """ Detect whether the given attribute is the currently-detected chip. See list of constants at the top of this module for available options. """ if self.id == attr: return True return False
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/adafruit_platformdetect/chip.py
chip.py
import os import re try: from typing import Optional except ImportError: pass from adafruit_platformdetect.constants import boards, chips __version__ = "3.49.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PlatformDetect.git" class Board: """Attempt to detect specific boards.""" def __init__(self, detector) -> None: self.detector = detector self._board_id = None # pylint: disable=invalid-name, protected-access, too-many-return-statements @property def id(self) -> Optional[str]: """Return a unique id for the detected board, if any.""" # There are some times we want to trick the platform detection # say if a raspberry pi doesn't have the right ID, or for testing # Caching if self._board_id: return self._board_id try: return os.environ["BLINKA_FORCEBOARD"] except (AttributeError, KeyError): # no forced board, continue with testing! pass chip_id = self.detector.chip.id board_id = None if chip_id == chips.H3: board_id = self._armbian_id() or self._allwinner_variants_id() elif chip_id == chips.BCM2XXX: board_id = self._pi_id() elif chip_id == chips.AM625X: board_id = self._beaglebone_id() elif chip_id == chips.AM33XX: board_id = self._beaglebone_id() elif chip_id == chips.AM65XX: board_id = self._siemens_simatic_iot2000_id() elif chip_id == chips.DRA74X: board_id = self._bbai_id() elif chip_id == chips.SUN4I: board_id = self._armbian_id() elif chip_id == chips.SUN7I: board_id = self._armbian_id() elif chip_id == chips.SUN8I: board_id = self._armbian_id() or self._allwinner_variants_id() elif chip_id == chips.SAMA5: board_id = self._sama5_id() elif chip_id == chips.IMX8MX: board_id = self._imx8mx_id() elif chip_id == chips.IMX8MP: board_id = self._imx8mp_id() elif chip_id == chips.IMX6ULL: board_id = self._imx6ull_id() elif chip_id == chips.S905Y2: board_id = boards.RADXA_ZERO elif chip_id == chips.ESP8266: board_id = boards.FEATHER_HUZZAH elif chip_id == chips.SAMD21: board_id = boards.FEATHER_M0_EXPRESS elif chip_id == chips.STM32F405: board_id = boards.PYBOARD elif chip_id == chips.RP2040: board_id = boards.RASPBERRY_PI_PICO elif chip_id == chips.S805: board_id = boards.ODROID_C1 elif chip_id == chips.RK3568B2: board_id = boards.ODROID_M1 elif chip_id == chips.S905: board_id = boards.ODROID_C2 elif chip_id == chips.S905X3: board_id = self._s905x3_id() elif chip_id == chips.S922X: board_id = boards.ODROID_N2 elif chip_id == chips.A311D: board_id = boards.KHADAS_VIM3 elif chip_id == chips.EXYNOS5422: board_id = boards.ODROID_XU4 elif chip_id == chips.FT232H: board_id = boards.FTDI_FT232H elif chip_id == chips.FT2232H: board_id = boards.FTDI_FT2232H elif chip_id == chips.APQ8016: board_id = boards.DRAGONBOARD_410C elif chip_id in (chips.T210, chips.T186, chips.T194, chips.T234): board_id = self._tegra_id() elif chip_id == chips.HFU540: board_id = self._sifive_id() elif chip_id == chips.C906: board_id = self._allwinner_id() elif chip_id == chips.JH71x0: board_id = self._beaglebone_id() elif chip_id == chips.MCP2221: board_id = boards.MICROCHIP_MCP2221 elif chip_id == chips.BINHO: board_id = boards.BINHO_NOVA elif chip_id == chips.LPC4330: board_id = boards.GREATFET_ONE elif chip_id == chips.MIPS24KC: board_id = boards.ONION_OMEGA elif chip_id == chips.MIPS24KEC: board_id = boards.ONION_OMEGA2 elif chip_id == chips.ZYNQ7000: board_id = self._pynq_id() elif chip_id == chips.A10: board_id = self._armbian_id() elif chip_id == chips.A20: board_id = self._armbian_id() elif chip_id == chips.A64: board_id = self._pine64_id() elif chip_id == chips.H6: board_id = self._pine64_id() or self._armbian_id() elif chip_id == chips.H5: board_id = self._armbian_id() or self._allwinner_variants_id() elif chip_id == chips.H616: board_id = self._armbian_id() or self._allwinner_variants_id() elif chip_id == chips.A33: board_id = self._clockwork_pi_id() elif chip_id == chips.RK3308: board_id = self._rock_pi_id() elif chip_id == chips.RK3399: board_id = ( self._rock_pi_id() or self._armbian_id() or self._diet_pi_id() or self._asus_tinker_board_id() ) elif chip_id == chips.RK3399PRO: board_id = self._asus_tinker_board_id() elif chip_id == chips.RK3399_T: board_id = self._rock_pi_id() or self._armbian_id() elif chip_id == chips.ATOM_X5_Z8350: board_id = self._rock_pi_id() elif chip_id == chips.ATOM_J4105: board_id = self._j4105_id() elif chip_id == chips.RK3288: board_id = self._asus_tinker_board_id() elif chip_id == chips.RK3328: board_id = self._rock_pi_id() or self._libre_id() elif chip_id == chips.RK3566: board_id = self._rk3566_id() elif chip_id == chips.RK3568: board_id = self._rk3568_id() elif chip_id == chips.RK3588: board_id = self._rock_pi_id() or self._orange_pi_id() or self._armbian_id() elif chip_id == chips.RYZEN_V1605B: board_id = self._udoo_id() elif chip_id == chips.PENTIUM_N3710: board_id = self._udoo_id() elif chip_id == chips.CELERON_N5105: board_id = self._intel_n_series_id() elif chip_id == chips.STM32MP157: board_id = self._stm32mp1_id() elif chip_id == chips.STM32MP157DAA1: board_id = self._stm32mp1_id() elif chip_id == chips.MT8167: board_id = boards.CORAL_EDGE_TPU_DEV_MINI elif chip_id == chips.RP2040_U2IF: board_id = self._rp2040_u2if_id() elif chip_id == chips.GENERIC_X86: board_id = boards.GENERIC_LINUX_PC elif chip_id == chips.TDA4VM: board_id = self._beaglebone_id() or self._tisk_id() elif chip_id == chips.D1_RISCV: board_id = self._armbian_id() elif chip_id == chips.S905X: board_id = boards.AML_S905X_CC self._board_id = board_id return board_id # pylint: enable=invalid-name def _pi_id(self) -> Optional[str]: """Try to detect id of a Raspberry Pi.""" # Check for Pi boards: pi_rev_code = self._pi_rev_code() if pi_rev_code: from adafruit_platformdetect.revcodes import PiDecoder try: decoder = PiDecoder(pi_rev_code) model = boards._PI_MODELS[decoder.type_raw] if isinstance(model, dict): model = model[decoder.revision] return model except ValueError: pass # We may be on a non-Raspbian OS, so try to lazily determine # the version based on `get_device_model` else: pi_model = self.detector.get_device_model() if pi_model: pi_model = pi_model.upper().replace(" ", "_") if "PLUS" in pi_model: re_model = re.search(r"(RASPBERRY_PI_\d).*([AB]_*)(PLUS)", pi_model) elif "CM" in pi_model: # untested for Compute Module re_model = re.search(r"(RASPBERRY_PI_CM)(\d)", pi_model) else: # untested for non-plus models re_model = re.search(r"(RASPBERRY_PI_\d).*([AB])", pi_model) if re_model: pi_model = "".join(re_model.groups()) available_models = boards._PI_REV_CODES.keys() for model in available_models: if model == pi_model: return model return None def _pi_rev_code(self) -> Optional[str]: """Attempt to find a Raspberry Pi revision code for this board.""" # 2708 is Pi 1 # 2709 is Pi 2 # 2835 is Pi 3 (or greater) on 4.9.x kernel # Anything else is not a Pi. if self.detector.chip.id != chips.BCM2XXX: # Something else, not a Pi. return None rev = self.detector.get_cpuinfo_field("Revision") if rev is not None: return rev try: with open("/proc/device-tree/system/linux,revision", "rb") as revision: rev_bytes = revision.read() if rev_bytes[:1] == b"\x00": rev_bytes = rev_bytes[1:] return rev_bytes.hex() except FileNotFoundError: return None # pylint: disable=no-self-use def _beaglebone_id(self) -> Optional[str]: """Try to detect id of a Beaglebone.""" board_value = self.detector.get_device_compatible() # Older Builds if "freedom-u74-arty" in board_value: return boards.BEAGLEV_STARLIGHT # Newer Builds if "beaglev-starlight" in board_value: return boards.BEAGLEV_STARLIGHT try: with open("/sys/bus/nvmem/devices/0-00500/nvmem", "rb") as eeprom: eeprom_bytes = eeprom.read(16) except FileNotFoundError: try: with open("/sys/bus/nvmem/devices/0-00501/nvmem", "rb") as eeprom: eeprom_bytes = eeprom.read(16) except FileNotFoundError: try: # Special Case for AI64 with open("/sys/bus/nvmem/devices/2-00500/nvmem", "rb") as eeprom: eeprom_bytes = eeprom.read(16) except FileNotFoundError: return None if eeprom_bytes[:4] != b"\xaaU3\xee": return None # special condition for BeagleBone Green rev. 1A # refer to GitHub issue #57 in this repo for more info if eeprom_bytes == b"\xaaU3\xeeA335BNLT\x1a\x00\x00\x00": return boards.BEAGLEBONE_GREEN # BeaglePlay Special Condition # new Beagle EEPROM IDs are 24 Bit, so we need to verify full range if eeprom_bytes == b"\xaaU3\xee\x017\x00\x10.\x00BEAGLE": with open("/sys/bus/nvmem/devices/0-00500/nvmem", "rb") as eeprom: eeprom_bytes = eeprom.read(24) if eeprom_bytes == b"\xaaU3\xee\x017\x00\x10.\x00BEAGLEPLAY-A0-": return boards.BEAGLE_PLAY id_string = eeprom_bytes[4:].decode("ascii") for model, bb_ids in boards._BEAGLEBONE_BOARD_IDS.items(): for bb_id in bb_ids: if id_string == bb_id[1]: return model board_value = self.detector.get_armbian_release_field("BOARD") return None # pylint: enable=no-self-use def _bbai_id(self) -> Optional[str]: """Try to detect id of a Beaglebone AI related board.""" board_value = self.detector.get_device_model() if "BeagleBone AI" in board_value: return boards.BEAGLEBONE_AI return None def _tisk_id(self) -> Optional[str]: """Try to detect the id of aarch64 board.""" compatible = self.detector.get_device_compatible() print(compatible) if not compatible: return None compats = compatible.split("\x00") for board_id, board_compats in boards._TI_SK_BOARD_IDS: if any(v in compats for v in board_compats): return board_id return None # pylint: disable=too-many-return-statements def _armbian_id(self) -> Optional[str]: """Get the current board via the ARMBIAN release field.""" board_value = self.detector.get_armbian_release_field("BOARD") board = None if board_value == "orangepipc": board = boards.ORANGE_PI_PC elif board_value == "orangepi-r1": board = boards.ORANGE_PI_R1 elif board_value == "orangepizero": board = boards.ORANGE_PI_ZERO elif board_value == "orangepione": board = boards.ORANGE_PI_ONE elif board_value == "orangepilite": board = boards.ORANGE_PI_LITE elif board_value == "orangepiplus2e": board = boards.ORANGE_PI_PLUS_2E elif board_value == "orangepipcplus": board = boards.ORANGE_PI_PC_PLUS elif board_value == "pinebook-a64": board = boards.PINEBOOK elif board_value == "pineH64": board = boards.PINEH64 elif board_value == "orangepi2": board = boards.ORANGE_PI_2 elif board_value == "orangepi3": board = boards.ORANGE_PI_3 elif board_value == "orangepi3-lts": board = boards.ORANGE_PI_3_LTS elif board_value == "orangepi4": board = boards.ORANGE_PI_4 elif board_value == "orangepi4-lts": board = boards.ORANGE_PI_4_LTS elif board_value == "orangepi5": board = boards.ORANGE_PI_5 elif board_value == "bananapim2zero": board = boards.BANANA_PI_M2_ZERO elif board_value == "bananapim2plus": board = boards.BANANA_PI_M2_PLUS elif board_value == "bananapim2berry": board = boards.BANANA_PI_M2_BERRY elif board_value == "bananapim5": board = boards.BANANA_PI_M5 elif board_value == "bananapipro": board = boards.LEMAKER_BANANA_PRO elif board_value == "orangepizeroplus2-h5": board = boards.ORANGE_PI_ZERO_PLUS_2H5 elif board_value == "orangepizeroplus": board = boards.ORANGE_PI_ZERO_PLUS elif board_value == "orangepizero2": board = boards.ORANGE_PI_ZERO_2 elif board_value == "nanopiair": board = boards.NANOPI_NEO_AIR elif board_value == "nanopiduo2": board = boards.NANOPI_DUO2 elif board_value == "nanopineo": board = boards.NANOPI_NEO elif board_value == "nanopineo2": board = boards.NANOPI_NEO_2 elif board_value == "nezha": board = boards.LICHEE_RV elif board_value == "pcduino2": board = boards.PCDUINO2 elif board_value == "pcduino3": board = boards.PCDUINO3 elif board_value == "rock-3a": board = boards.ROCK_PI_3A return board # pylint: enable=too-many-return-statements def _diet_pi_id(self) -> Optional[str]: board_value = self.detector.get_device_model() if "OrangePi 4" in board_value: return boards.ORANGE_PI_4 return None def _orange_pi_id(self) -> Optional[str]: board_value = self.detector.get_device_model() if "Orange Pi 5" in board_value: return boards.ORANGE_PI_5 return None def _sama5_id(self) -> Optional[str]: """Check what type sama5 board.""" board_value = self.detector.get_device_model() if "Giant Board" in board_value: return boards.GIANT_BOARD return None def _s905x3_id(self) -> Optional[str]: """Check what type S905X3 board.""" board_value = self.detector.get_device_model() if "Bananapi BPI-M5" in board_value: return boards.BANANA_PI_M5 return boards.ODROID_C4 def _stm32mp1_id(self) -> Optional[str]: """Check what type stm32mp1 board.""" board_value = self.detector.get_device_model() if "STM32MP157C-DK2" in board_value: return boards.STM32MP157C_DK2 if "LubanCat" in board_value: return boards.LUBANCAT_STM32MP157 if "OSD32MP1-BRK" in board_value: return boards.OSD32MP1_BRK if "OSD32MP1-RED" in board_value: return boards.OSD32MP1_RED if "STM32MP1XX OLinuXino" in board_value: return boards.STMP157_OLINUXINO_LIME2 return None def _imx8mx_id(self) -> Optional[str]: """Check what type iMX8M board.""" board_value = self.detector.get_device_model() if "FSL i.MX8MM DDR4 EVK" in board_value: return boards.MAAXBOARD_MINI if "Freescale i.MX8MQ EVK" in board_value: return boards.MAAXBOARD if "Phanbell" in board_value: return boards.CORAL_EDGE_TPU_DEV return None def _imx8mp_id(self) -> Optional[str]: """Check what type iMX8M board.""" board_value = self.detector.get_device_model() if "NXP i.MX8MPlus SOM" in board_value: return boards.NXP_IMX8MPLUS_SOM return None def _imx6ull_id(self) -> Optional[str]: """Check what type iMX6ULL board.""" board_value = self.detector.get_device_model() if "LubanCat" in board_value or "Embedfire" in board_value: return boards.LUBANCAT_IMX6ULL return None def _tegra_id(self) -> Optional[str]: """Try to detect the id of aarch64 board.""" compatible = self.detector.get_device_compatible() if not compatible: return None compats = compatible.split("\x00") for board_id, board_compats in boards._JETSON_IDS: if any(v in compats for v in board_compats): return board_id return None def _sifive_id(self) -> Optional[str]: """Try to detect the id for Sifive RISCV64 board.""" board_value = self.detector.get_device_model() if "hifive-unleashed-a00" in board_value: return boards.SIFIVE_UNLEASHED return None def _allwinner_id(self) -> Optional[str]: """Try to detect the id for Allwiner D1 board.""" board_value = self.detector.get_device_model() if "sun20iw1p1" in board_value: return boards.ALLWINER_D1 return None def _pine64_id(self) -> Optional[str]: """Try to detect the id for Pine64 board or device.""" board_value = self.detector.get_device_model() board = None if "pinephone" in board_value.lower(): board = boards.PINEPHONE elif "pine64" in board_value.lower(): board = boards.PINE64 elif "pine h64" in board_value.lower(): board = boards.PINEH64 elif "pinebook" in board_value.lower(): board = boards.PINEBOOK elif "sopine" in board_value.lower(): board = boards.SOPINE return board # pylint: disable=no-self-use def _pynq_id(self) -> Optional[str]: """Try to detect the id for Xilinx PYNQ boards.""" try: with open( "/proc/device-tree/chosen/pynq_board", "r", encoding="utf-8" ) as board_file: board_model = board_file.read() match = board_model.upper().replace("-", "_").rstrip("\x00") for model in boards._PYNQ_IDS: if model == match: return model return None except FileNotFoundError: return None def _rk3566_id(self) -> Optional[str]: """Check what type of rk3566 board.""" board_value = self.detector.get_device_model() board = None if board_value and "LubanCat-Zero" in board_value: board = boards.LUBANCAT_ZERO if board_value and any(x in board_value for x in ("LubanCat1", "LubanCat-1")): board = boards.LUBANCAT1 if board_value and "Radxa CM3 IO" in board_value: board = boards.RADXA_CM3 return board def _rk3568_id(self) -> Optional[str]: """Check what type of rk3568 board.""" board_value = self.detector.get_device_model() board = None if board_value and any(x in board_value for x in ("LubanCat2", "LubanCat-2")): board = boards.LUBANCAT2 if board_value and "ROCK3 Model A" in board_value: board = boards.ROCK_PI_3A return board def _rock_pi_id(self) -> Optional[str]: """Check what type of Rock Pi board.""" board_value = self.detector.get_device_model() board = None if board_value and "ROCK Pi S" in board_value: board = boards.ROCK_PI_S if board_value and "ROCK PI 4" in board_value.upper(): board = boards.ROCK_PI_4 if board_value and "ROCK PI E" in board_value.upper(): board = boards.ROCK_PI_E if self.detector.check_board_name_value() == "ROCK Pi X": board = boards.ROCK_PI_X if board_value and "ROCK 5" in board_value.upper(): board = boards.ROCK_PI_5 if board_value and "RADXA ROCK 4C+" in board_value.upper(): board = boards.ROCK_PI_4_C_PLUS if board_value and "ROCK3 Model A" in board_value: board = boards.ROCK_PI_3A return board def _libre_id(self) -> Optional[str]: """Check what type of Libre Computer board.""" board_value = self.detector.get_device_model() board = None if board_value and "Libre Computer ROC-RK3328-CC" in board_value: board = boards.ROC_RK3328_CC return board def _clockwork_pi_id(self) -> Optional[str]: """Check what type of Clockwork Pi board.""" board_value = self.detector.get_device_model() board = None if board_value and "Clockwork CPI3" in board_value: board = boards.CLOCKWORK_CPI3 return board def _udoo_id(self) -> Optional[str]: """Try to detect the id of udoo board.""" board_asset_tag = self.detector.check_board_asset_tag_value() for board_id, board_tags in boards._UDOO_BOARD_IDS.items(): if any(v == board_asset_tag for v in board_tags): return board_id if self.detector.check_board_name_value() == "UDOO x86": return boards.UDOO_X86 return None def _intel_n_series_id(self) -> Optional[str]: """Try to detect the id of an Intel N-Series board.""" if self.detector.check_board_name_value() == "ODROID-H3": return boards.ODROID_H3 return None def _j4105_id(self) -> Optional[str]: """Try to detect the id of J4105 board.""" try: with open( "/sys/devices/virtual/dmi/id/board_name", "r", encoding="utf-8" ) as board_name: board_value = board_name.read().rstrip() if board_value in ("ODYSSEY-X86J41X5", "ODYSSEY-X86J41O5"): return boards.ODYSSEY_X86J41X5 return None except FileNotFoundError: return None def _asus_tinker_board_id(self) -> Optional[str]: """Check what type of Tinker Board.""" board_value = self.detector.get_device_model() board = None if board_value and "ASUS Tinker Board" in board_value: board = boards.ASUS_TINKER_BOARD if board_value and "ASUS TINKER BOARD 2" in board_value: board = boards.ASUS_TINKER_BOARD_2 if board_value and "ASUS_TINKER_EDGE_R" in board_value: board = boards.ASUS_TINKER_EDGE_R return board def _pcduino_board_id(self) -> Optional[str]: """Check on the type of Pcduino""" board_value = self.detector.get_device_model() board = None if "pcduino2" in board_value.lower(): board = boards.PCDUINO2 if "pcduino3" in board_value.lower(): board = boards.PCDUINO3 return board def _allwinner_variants_id(self) -> Optional[str]: """Try to detect the id of allwinner based board. (orangepi, nanopi)""" board_value = self.detector.get_device_model() board = None if not board_value: return board board_value = board_value.lower() chip_id = self.detector.chip.id if "banana pi m2 berry" in board_value: board = boards.BANANA_PI_M2_BERRY if "nanopi" in board_value: if "neo" in board_value and "SUN8I" in chip_id: board = boards.NANOPI_NEO_AIR elif "neo2" in board_value and "H5" in chip_id: board = boards.NANOPI_NEO_2 elif any(x in board_value for x in ("orange pi", "orangepi")): if "zero" in board_value: if "H5" in chip_id: board = boards.ORANGE_PI_ZERO_PLUS_2H5 elif "H616" in chip_id: board = boards.ORANGE_PI_ZERO_2 # TODO: Add other specifc board contexts here return board # pylint: disable=too-many-return-statements def _rp2040_u2if_id(self) -> Optional[str]: import hid # look for it based on PID/VID for dev in hid.enumerate(): # Raspberry Pi Pico vendor = dev["vendor_id"] product = dev["product_id"] if vendor == 0xCAFE and product == 0x4005: return boards.PICO_U2IF if vendor == 0x239A: # Feather RP2040 if product == 0x00F1: return boards.FEATHER_U2IF # Itsy Bitsy RP2040 if product == 0x00FD: return boards.ITSYBITSY_U2IF # QT Py RP2040 if product == 0x00F7: return boards.QTPY_U2IF # QT2040 Trinkey if product == 0x0109: return boards.QT2040_TRINKEY_U2IF # MacroPad RP2040 if product == 0x0107: return boards.MACROPAD_U2IF # Feather RP2040 ThinkInk if product == 0x812C: return boards.FEATHER_EPD_U2IF # Feather RP2040 RFM if product == 0x812E: return boards.FEATHER_RFM_U2IF # Feather RP2040 CAN if product == 0x8130: return boards.FEATHER_CAN_U2IF # KB2040 Kee Board if product == 0x0105: return boards.KB2040_U2IF # Will only reach here if a device was added in chip.py but here. raise RuntimeError("RP2040_U2IF device was added to chip but not board.") # pylint: enable=too-many-return-statements def _siemens_simatic_iot2000_id(self) -> Optional[str]: """Try to detect if this is a IOT2050 Gateway.""" board_value = self.detector.get_device_model() board = None if board_value and "SIMATIC IOT2050 Advanced" in board_value: board = boards.SIEMENS_SIMATIC_IOT2050_ADV elif board_value and "SIMATIC IOT2050 Basic" in board_value: board = boards.SIEMENS_SIMATIC_IOT2050_BASIC return board @property def any_siemens_simatic_iot2000(self) -> bool: """Check whether the current board is a SIEMENS SIMATIC IOT2000 Gateway.""" return self.id in boards._SIEMENS_SIMATIC_IOT2000_IDS @property def any_nanopi(self) -> bool: """Check whether the current board is any defined Nano Pi.""" return self.id in boards._NANOPI_IDS @property def any_96boards(self) -> bool: """Check whether the current board is any 96boards board.""" return self.id in boards._LINARO_96BOARDS_IDS @property def any_raspberry_pi(self) -> bool: """Check whether the current board is any Raspberry Pi.""" return self._pi_rev_code() is not None @property def any_raspberry_pi_40_pin(self) -> bool: """Check whether the current board is any 40-pin Raspberry Pi.""" return self.id in boards._RASPBERRY_PI_40_PIN_IDS @property def any_raspberry_pi_cm(self) -> bool: """Check whether the current board is any Compute Module Raspberry Pi.""" return self.id in boards._RASPBERRY_PI_CM_IDS @property def any_beaglebone(self) -> bool: """Check whether the current board is any Beaglebone-family system.""" return self.id in boards._BEAGLEBONE_IDS @property def any_orange_pi(self) -> bool: """Check whether the current board is any defined Orange Pi.""" return self.id in boards._ORANGE_PI_IDS @property def any_lubancat(self) -> bool: """Check whether the current board is any defined lubancat.""" return self.id in boards._LUBANCAT_IDS @property def any_coral_board(self) -> bool: """Check whether the current board is any defined Coral.""" return self.id in boards._CORAL_IDS @property def any_pynq_board(self) -> bool: """Check whether the current board is any defined PYNQ Board.""" return self.id in boards._PYNQ_IDS @property def any_giant_board(self) -> bool: """Check whether the current board is any defined Giant Board.""" return self.GIANT_BOARD @property def any_odroid_40_pin(self) -> bool: """Check whether the current board is any defined 40-pin Odroid.""" return self.id in boards._ODROID_40_PIN_IDS @property def any_odroid_mini_pc(self) -> bool: """Check whether the current board is any defined Odroid Mini PC.""" return self.id in boards._ODROID_MINI_PC_IDS @property def khadas_vim3_40_pin(self) -> bool: """Check whether the current board is any defined 40-pin Khadas VIM3.""" return self.id in boards._KHADAS_40_PIN_IDS @property def any_jetson_board(self) -> bool: """Check whether the current board is any defined Jetson Board.""" return self.id in [v[0] for v in boards._JETSON_IDS] @property def any_sifive_board(self) -> bool: """Check whether the current board is any defined Jetson Board.""" return self.id in boards._SIFIVE_IDS @property def any_onion_omega_board(self) -> bool: """Check whether the current board is any defined OpenWRT board.""" return self.id in boards._ONION_OMEGA_BOARD_IDS @property def any_pine64_board(self) -> bool: """Check whether the current board is any Pine64 device.""" return self.id in boards._PINE64_DEV_IDS @property def any_rock_pi_board(self) -> bool: """Check whether the current board is any Rock Pi device.""" return self.id in boards._ROCK_PI_IDS @property def any_clockwork_pi_board(self) -> bool: """Check whether the current board is any Clockwork Pi device.""" return self.CLOCKWORK_CPI3 @property def any_udoo_board(self) -> bool: """Check to see if the current board is an UDOO board""" return self.id in boards._UDOO_BOARD_IDS @property def any_seeed_board(self) -> bool: """Check to see if the current board is an SEEED board""" return self.id in boards._SEEED_BOARD_IDS @property def any_asus_tinker_board(self) -> bool: """Check to see if the current board is an ASUS Tinker Board""" return self.id in boards._ASUS_TINKER_BOARD_IDS @property def any_pcduino_board(self) -> bool: """Check whether the current board is any Pcduino board""" return self.id in boards._PCDUINO_DEV_IDS @property def any_stm32mp1(self) -> bool: """Check whether the current board is any stm32mp1 board.""" return self.id in boards._STM32MP1_IDS @property def any_bananapi(self) -> bool: """Check whether the current board is any BananaPi-family system.""" return self.id in boards._BANANA_PI_IDS @property def any_lemaker(self) -> bool: """Check whether the current board is any LeMaker board.""" return self.id in boards._LEMAKER_IDS @property def any_maaxboard(self) -> bool: """Check whether the current board is any BananaPi-family system.""" return self.id in boards._MAAXBOARD_IDS @property def any_tisk_board(self) -> bool: """Check whether the current board is any defined TI SK Board.""" return self.id in [v[0] for v in boards._TI_SK_BOARD_IDS] @property def any_lichee_riscv_board(self) -> bool: """Check whether the current board is any defined Lichee RISC-V.""" return self.id in boards._LICHEE_RISCV_IDS @property def any_libre_computer_board(self) -> bool: """Check whether the current board is any defined Libre Computer board.""" return self.id in boards._LIBRE_COMPUTER_IDS @property def any_nxp_navq_board(self) -> bool: """Check whether the current board is any NXP NavQ board""" return self.id in boards._NXP_SOM_IDS @property def os_environ_board(self) -> bool: """Check whether the current board is an OS environment variable special case.""" def lazily_generate_conditions(): yield self.board.FTDI_FT232H yield self.board.FTDI_FT2232H yield self.board.MICROCHIP_MCP2221 yield self.board.BINHO_NOVA yield self.board.GREATFET_ONE yield self.board.PICO_U2IF yield self.board.FEATHER_U2IF yield self.board.FEATHER_CAN_U2IF yield self.board.FEATHER_EPD_U2IF yield self.board.FEATHER_RFM_U2IF yield self.board.ITSYBITY_U2IF yield self.board.MACROPAD_U2IF yield self.board.QTPY_U2IF yield self.board.QT2040_TRINKEY_U2IF yield self.board.KB2040_U2IF return any(condition for condition in lazily_generate_conditions()) @property def any_embedded_linux(self) -> bool: """Check whether the current board is any embedded Linux device.""" def lazily_generate_conditions(): yield self.any_raspberry_pi_40_pin yield self.any_raspberry_pi yield self.any_beaglebone yield self.any_orange_pi yield self.any_nanopi yield self.any_giant_board yield self.any_jetson_board yield self.any_coral_board yield self.any_odroid_40_pin yield self.any_odroid_mini_pc yield self.khadas_vim3_40_pin yield self.any_96boards yield self.any_sifive_board yield self.any_onion_omega_board yield self.any_pine64_board yield self.any_pynq_board yield self.any_rock_pi_board yield self.any_clockwork_pi_board yield self.any_udoo_board yield self.any_seeed_board yield self.any_asus_tinker_board yield self.any_stm32mp1 yield self.any_lubancat yield self.any_bananapi yield self.any_lemaker yield self.any_maaxboard yield self.any_tisk_board yield self.any_siemens_simatic_iot2000 yield self.any_lichee_riscv_board yield self.any_pcduino_board yield self.any_libre_computer_board yield self.generic_linux yield self.any_nxp_navq_board return any(condition for condition in lazily_generate_conditions()) @property def generic_linux(self) -> bool: """Check whether the current board is an Generic Linux System.""" return self.id == boards.GENERIC_LINUX_PC @property def ftdi_ft232h(self) -> bool: """Check whether the current board is an FTDI FT232H.""" return self.id == boards.FTDI_FT232H @property def ftdi_ft2232h(self) -> bool: """Check whether the current board is an FTDI FT2232H.""" return self.id == boards.FTDI_FT2232H @property def microchip_mcp2221(self) -> bool: """Check whether the current board is a Microchip MCP2221.""" return self.id == boards.MICROCHIP_MCP2221 @property def pico_u2if(self) -> bool: """Check whether the current board is a RPi Pico w/ u2if.""" return self.id == boards.PICO_U2IF @property def feather_u2if(self) -> bool: """Check whether the current board is a Feather RP2040 w/ u2if.""" return self.id == boards.FEATHER_U2IF @property def feather_can_u2if(self) -> bool: """Check whether the current board is a Feather CAN Bus RP2040 w/ u2if.""" return self.id == boards.FEATHER_CAN_U2IF @property def feather_epd_u2if(self) -> bool: """Check whether the current board is a Feather ThinkInk RP2040 w/ u2if.""" return self.id == boards.FEATHER_EPD_U2IF @property def feather_rfm_u2if(self) -> bool: """Check whether the current board is a Feather RFM RP2040 w/ u2if.""" return self.id == boards.FEATHER_RFM_U2IF @property def itsybitsy_u2if(self) -> bool: """Check whether the current board is a Itsy Bitsy w/ u2if.""" return self.id == boards.ITSYBITSY_U2IF @property def macropad_u2if(self) -> bool: """Check whether the current board is a MacroPad w/ u2if.""" return self.id == boards.MACROPAD_U2IF @property def qtpy_u2if(self) -> bool: """Check whether the current board is a QT Py w/ u2if.""" return self.id == boards.QTPY_U2IF @property def qt2040_trinkey_u2if(self) -> bool: """Check whether the current board is a QT Py w/ u2if.""" return self.id == boards.QT2040_TRINKEY_U2IF @property def kb2040_u2if(self) -> bool: """Check whether the current board is a KB2040 w/ u2if.""" return self.id == boards.KB2040_U2IF @property def binho_nova(self) -> bool: """Check whether the current board is an BINHO NOVA.""" return self.id == boards.BINHO_NOVA @property def greatfet_one(self) -> bool: """Check whether the current board is a GreatFET One.""" return self.id == boards.GREATFET_ONE def __getattr__(self, attr: str) -> bool: """ Detect whether the given attribute is the currently-detected board. See list of constants at the top of this module for available options. """ if self.id == attr: return True return False
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/adafruit_platformdetect/board.py
board.py
import os import re import sys try: from typing import Optional except ImportError: pass from adafruit_platformdetect.board import Board from adafruit_platformdetect.chip import Chip # Needed to find libs (like libusb) installed by homebrew on Apple Silicon if sys.platform == "darwin": os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/opt/homebrew/lib/" # Various methods here may retain state in future, so tell pylint not to worry # that they don't use self right now: # pylint: disable=no-self-use class Detector: """Wrap various platform detection functions.""" def __init__(self) -> None: self.board = Board(self) self.chip = Chip(self) def get_cpuinfo_field(self, field: str) -> Optional[str]: """ Search /proc/cpuinfo for a field and return its value, if found, otherwise None. """ # Match a line like 'Hardware : BCM2709': pattern = r"^" + field + r"\s+:\s+(.*)$" with open("/proc/cpuinfo", "r", encoding="utf-8") as infile: cpuinfo = infile.read().split("\n") for line in cpuinfo: match = re.search(pattern, line, flags=re.IGNORECASE) if match: return match.group(1) return None def check_dt_compatible_value(self, value: str) -> bool: """ Search /proc/device-tree/compatible for a value and return True, if found, otherwise False. """ # Match a value like 'qcom,apq8016-sbc': dt_compatible = self.get_device_compatible() if dt_compatible and value in dt_compatible: return True return False def get_armbian_release_field(self, field: str) -> Optional[str]: """ Search /etc/armbian-release, if it exists, for a field and return its value, if found, otherwise None. """ field_value = None pattern = r"^" + field + r"=(.*)" try: with open("/etc/armbian-release", "r", encoding="utf-8") as release_file: armbian = release_file.read().split("\n") for line in armbian: match = re.search(pattern, line) if match: field_value = match.group(1) except FileNotFoundError: pass return field_value def get_device_model(self) -> Optional[str]: """ Search /proc/device-tree/model for the device model and return its value, if found, otherwise None. """ try: with open("/proc/device-tree/model", "r", encoding="utf-8") as model_file: return model_file.read() except FileNotFoundError: pass return None def get_device_compatible(self) -> Optional[str]: """ Search /proc/device-tree/compatible for the compatible chip name. """ try: with open( "/proc/device-tree/compatible", "r", encoding="utf-8" ) as model_file: return model_file.read() except FileNotFoundError: pass return None def check_board_asset_tag_value(self) -> Optional[str]: """ Search /sys/devices/virtual/dmi/id for the device model and return its value, if found, otherwise None. """ try: with open( "/sys/devices/virtual/dmi/id/board_asset_tag", "r", encoding="utf-8" ) as tag_file: return tag_file.read().strip() except FileNotFoundError: pass return None def check_board_name_value(self) -> Optional[str]: """ Search /sys/devices/virtual/dmi/id for the board name and return its value, if found, otherwise None. Debian/ubuntu based """ try: with open( "/sys/devices/virtual/dmi/id/board_name", "r", encoding="utf-8" ) as board_name_file: return board_name_file.read().strip() except FileNotFoundError: pass return None
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/adafruit_platformdetect/__init__.py
__init__.py
NEW_OVERVOLTAGE = ( "Overvoltage allowed", "Overvoltage disallowed", ) NEW_OTP_PROGRAM = ( "OTP programming is allowed", "OTP programming is disallowed", ) NEW_OTP_READ = ( "OTP reading is allowed", "OTP reading is disallowed", ) NEW_WARRANTY_BIT = ( "Warranty is intact", "Warranty has been voided by overclocking", ) NEW_REV_STYLE = ( "Old-style revision", "New-style revision", ) NEW_MEMORY_SIZE = ( "256MB", "512MB", "1GB", "2GB", "4GB", "8GB", ) NEW_MANUFACTURER = ( "Sony UK", "Egoman", "Embest", "Sony Japan", "Embest", "Stadium", ) NEW_PROCESSOR = ( "BCM2835", "BCM2836", "BCM2837", "BCM2711", ) PI_TYPE = { 0x00: "A", 0x01: "B", 0x02: "A+", 0x03: "B+", 0x04: "2B", 0x05: "Alpha (early prototype)", 0x06: "CM1", 0x08: "3B", 0x09: "Zero", 0x0A: "CM3", 0x0B: "Custom", 0x0C: "Zero W", 0x0D: "3B+", 0x0E: "3A+", 0x0F: "Internal use only", 0x10: "CM3+", 0x11: "4B", 0x12: "Zero 2 W", 0x13: "400", 0x14: "CM4", 0x15: "CM4S", } OLD_MANUFACTURER = ( "Sony UK", "Egoman", "Embest", "Qisda", ) OLD_MEMORY_SIZE = ("256MB", "512MB", "256MB/512MB") NEW_REV_STRUCTURE = { "overvoltage": (31, 1, NEW_OVERVOLTAGE), "otp_program": (30, 1, NEW_OTP_PROGRAM), "otp_read": (29, 1, NEW_OTP_READ), "warranty": (25, 1, NEW_WARRANTY_BIT), "rev_style": (23, 1, NEW_REV_STYLE), "memory_size": (20, 3, NEW_MEMORY_SIZE), "manufacturer": (16, 4, NEW_MANUFACTURER), "processor": (12, 4, NEW_PROCESSOR), "type": (4, 8, PI_TYPE), "revision": (0, 4, int), } OLD_REV_STRUCTURE = { "type": (0, PI_TYPE), "revision": (1, float), "memory_size": (2, OLD_MEMORY_SIZE), "manufacturer": (3, OLD_MANUFACTURER), } OLD_REV_EXTRA_PROPS = { "warranty": (24, 1, NEW_WARRANTY_BIT), } OLD_REV_LUT = { 0x02: (1, 1.0, 0, 1), 0x03: (1, 1.0, 0, 1), 0x04: (1, 2.0, 0, 0), 0x05: (1, 2.0, 0, 3), 0x06: (1, 2.0, 0, 1), 0x07: (0, 2.0, 0, 1), 0x08: (0, 2.0, 0, 0), 0x09: (0, 2.0, 0, 3), 0x0D: (1, 2.0, 1, 1), 0x0E: (1, 2.0, 1, 0), 0x0F: (1, 2.0, 1, 1), 0x10: (3, 1.2, 1, 0), 0x11: (6, 1.0, 1, 0), 0x12: (2, 1.1, 0, 0), 0x13: (3, 1.2, 1, 2), 0x14: (6, 1.0, 1, 2), 0x15: (2, 1.1, 2, 2), } class PiDecoder: """Raspberry Pi Revision Code Decoder""" def __init__(self, rev_code): try: self.rev_code = int(rev_code, 16) & 0xFFFFFFFF except ValueError: print("Invalid revision code. It should be a hexadecimal value.") def is_valid_code(self): """Quickly check the validity of a code""" if self.is_new_format(): for code_format in NEW_REV_STRUCTURE.values(): lower_bit, bit_size, values = code_format prop_value = (self.rev_code >> lower_bit) & ((1 << bit_size) - 1) if not self._valid_value(prop_value, values): return False else: if (self.rev_code & 0xFFFF) not in OLD_REV_LUT.keys(): return False for code_format in OLD_REV_STRUCTURE.values(): index, values = code_format code_format = OLD_REV_LUT[self.rev_code & 0xFFFF] if index >= len(code_format): return False if not self._valid_value(code_format[index], values): return False return True def _get_rev_prop_value(self, name, structure=None, raw=False): if structure is None: structure = NEW_REV_STRUCTURE if name not in structure.keys(): raise ValueError(f"Unknown property {name}") lower_bit, bit_size, values = structure[name] prop_value = self._get_bits_value(lower_bit, bit_size) if not self._valid_value(prop_value, values): raise ValueError(f"Invalid value {prop_value} for property {name}") if raw: return prop_value return self._format_value(prop_value, values) def _get_bits_value(self, lower_bit, bit_size): return (self.rev_code >> lower_bit) & ((1 << bit_size) - 1) def _get_old_rev_prop_value(self, name, raw=False): if name not in OLD_REV_STRUCTURE.keys(): raise ValueError(f"Unknown property {name}") index, values = OLD_REV_STRUCTURE[name] data = OLD_REV_LUT[self.rev_code & 0xFFFF] if index >= len(data): raise IndexError(f"Index {index} out of range for property {name}") if not self._valid_value(data[index], values): raise ValueError(f"Invalid value {data[index]} for property {name}") if raw: return data[index] return self._format_value(data[index], values) @staticmethod def _format_value(value, valid_values): if valid_values is float or valid_values is int: return valid_values(value) return valid_values[value] @staticmethod def _valid_value(value, valid_values): if valid_values is float or valid_values is int: return isinstance(value, valid_values) if isinstance(valid_values, (tuple, list)) and 0 <= value < len(valid_values): return True if isinstance(valid_values, dict) and value in valid_values.keys(): return True return False def _get_property(self, name, raw=False): if name not in NEW_REV_STRUCTURE: raise ValueError(f"Unknown property {name}") if self.is_new_format(): return self._get_rev_prop_value(name, raw=raw) if name in OLD_REV_EXTRA_PROPS: return self._get_rev_prop_value( name, structure=OLD_REV_EXTRA_PROPS, raw=raw ) return self._get_old_rev_prop_value(name, raw=raw) def is_new_format(self): """Check if the code is in the new format""" return self._get_rev_prop_value("rev_style", raw=True) == 1 @property def overvoltage(self): """Overvoltage allowed/disallowed""" return self._get_property("overvoltage") @property def warranty_bit(self): """Warranty bit""" return self._get_property("warranty") @property def otp_program(self): """OTP programming allowed/disallowed""" return self._get_property("otp_program") @property def otp_read(self): """OTP reading allowed/disallowed""" return self._get_property("otp_read") @property def rev_style(self): """Revision Code style""" # Force new style for Rev Style return self._get_rev_prop_value("rev_style") @property def memory_size(self): """Memory size""" return self._get_property("memory_size") @property def manufacturer(self): """Manufacturer""" return self._get_property("manufacturer") @property def processor(self): """Processor""" return self._get_property("processor") @property def type(self): """Specific Model""" return self._get_property("type") @property def type_raw(self): """Raw Value of Specific Model""" return self._get_property("type", raw=True) @property def revision(self): """Revision Number""" return self._get_property("revision")
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/adafruit_platformdetect/revcodes.py
revcodes.py
"""Definition of boards and/or ids""" # Allow for aligned constant definitions: BEAGLE_PLAY = "BEAGLE_PLAY" BEAGLEBONE_AI64 = "BEAGLEBONE_AI64" BEAGLEBONE = "BEAGLEBONE" BEAGLEBONE_BLACK = "BEAGLEBONE_BLACK" BEAGLEBONE_BLUE = "BEAGLEBONE_BLUE" BEAGLEBONE_BLACK_WIRELESS = "BEAGLEBONE_BLACK_WIRELESS" BEAGLEBONE_POCKETBEAGLE = "BEAGLEBONE_POCKETBEAGLE" BEAGLEBONE_GREEN = "BEAGLEBONE_GREEN" BEAGLEBONE_GREEN_WIRELESS = "BEAGLEBONE_GREEN_WIRELESS" BEAGLEBONE_GREEN_GATEWAY = "BEAGLEBONE_GREEN_GATEWAY" BEAGLEBONE_BLACK_INDUSTRIAL = "BEAGLEBONE_BLACK_INDUSTRIAL" BEAGLEBONE_ENHANCED = "BEAGLEBONE_ENHANCED" BEAGLEBONE_USOMIQ = "BEAGLEBONE_USOMIQ" BEAGLEBONE_AIR = "BEAGLEBONE_AIR" BEAGLEBONE_AI = "BEAGLEBONE_AI" BEAGLEBONE_POCKETBONE = "BEAGLEBONE_POCKETBONE" BEAGLEV_STARLIGHT = "BEAGLEV_STARLIGHT" BEAGLELOGIC_STANDALONE = "BEAGLELOGIC_STANDALONE" OSD3358_DEV_BOARD = "OSD3358_DEV_BOARD" OSD3358_SM_RED = "OSD3358_SM_RED" FEATHER_HUZZAH = "FEATHER_HUZZAH" FEATHER_M0_EXPRESS = "FEATHER_M0_EXPRESS" GENERIC_LINUX_PC = "GENERIC_LINUX_PC" PYBOARD = "PYBOARD" NODEMCU = "NODEMCU" RASPBERRY_PI_PICO = "RASPBERRY_PI_PICO" GIANT_BOARD = "GIANT_BOARD" # ASUS Tinker Boards ASUS_TINKER_BOARD = "ASUS_TINKER_BOARD" ASUS_TINKER_BOARD_2 = "ASUS_TINKER_BOARD_2" ASUS_TINKER_EDGE_R = "ASUS_TINKER_EDGE_R" # Clockwork Pi boards CLOCKWORK_CPI3 = "CLOCKWORK_CPI3" # Orange Pi boards ORANGE_PI_PC = "ORANGE_PI_PC" ORANGE_PI_R1 = "ORANGE_PI_R1" ORANGE_PI_ZERO = "ORANGE_PI_ZERO" ORANGE_PI_ONE = "ORANGE_PI_ONE" ORANGE_PI_LITE = "ORANGE_PI_LITE" ORANGE_PI_PC_PLUS = "ORANGE_PI_PC_PLUS" ORANGE_PI_PLUS_2E = "ORANGE_PI_PLUS_2E" ORANGE_PI_2 = "ORANGE_PI_2" ORANGE_PI_ZERO_PLUS_2H5 = "ORANGE_PI_ZERO_PLUS_2H5" ORANGE_PI_ZERO_PLUS = "ORANGE_PI_ZERO_PLUS" ORANGE_PI_ZERO_2 = "ORANGE_PI_ZERO_2" ORANGE_PI_3 = "ORANGE_PI_3" ORANGE_PI_3_LTS = "ORANGE_PI_3_LTS" ORANGE_PI_4 = "ORANGE_PI_4" ORANGE_PI_4_LTS = "ORANGE_PI_4_LTS" ORANGE_PI_5 = "ORANGE_PI_5" # Nano Pi boards NANOPI_NEO_AIR = "NANOPI_NEO_AIR" NANOPI_DUO2 = "NANOPI_DUO2" NANOPI_NEO = "NANOPI_NEO" NANOPI_NEO_2 = "NANOPI_NEO_2" # Banana Pi boards BANANA_PI_M2_ZERO = "BANANA_PI_M2_ZERO" BANANA_PI_M2_PLUS = "BANANA_PI_M2_PLUS" BANANA_PI_M2_BERRY = "BANANA_PI_M2_BERRY" BANANA_PI_M5 = "BANANA_PI_M5" # LeMaker boards LEMAKER_BANANA_PRO = "LEMAKER_BANANA_PRO" # NVIDIA Jetson boards JETSON_TX1 = "JETSON_TX1" JETSON_TX2 = "JETSON_TX2" JETSON_TX2_NX = "JETSON_TX2_NX" CLARA_AGX_XAVIER = "CLARA_AGX_XAVIER" JETSON_XAVIER = "JETSON_XAVIER" JETSON_AGX_ORIN = "JETSON_ORIN" JETSON_NANO = "JETSON_NANO" JETSON_NX = "JETSON_NX" JETSON_ORIN_NANO = "JETSON_ORIN_NANO" JETSON_ORIN_NX = "JETSON_ORIN_NX" # Texas Instruments SK boards TI_J721E_SK = "TI_J721E_SK" # Google Coral dev board CORAL_EDGE_TPU_DEV = "CORAL_EDGE_TPU_DEV" CORAL_EDGE_TPU_DEV_MINI = "CORAL_EDGE_TPU_DEV_MINI" # Xilinx PYNQ FPGA dev boards PYNQ_Z1 = "PYNQ_Z1" PYNQ_Z2 = "PYNQ_Z2" # STM32 MPU boards STM32MP157C_DK2 = "STM32MP157C_DK2" OSD32MP1_BRK = "OSD32MP1_BRK" OSD32MP1_RED = "OSD32MP1_RED" STMP157_OLINUXINO_LIME2 = "STMP157_OLINUXINO_LIME2" # Embedfire LubanCat board LUBANCAT_IMX6ULL = "LUBANCAT_IMX6ULL" LUBANCAT_STM32MP157 = "LUBANCAT_STM32MP157" LUBANCAT_ZERO = "LUBANCAT_ZERO" LUBANCAT1 = "LUBANCAT1" LUBANCAT2 = "LUBANCAT2" # Various Raspberry Pi models RASPBERRY_PI_B_REV1 = "RASPBERRY_PI_B_REV1" RASPBERRY_PI_B_REV2 = "RASPBERRY_PI_B_REV2" RASPBERRY_PI_B_PLUS = "RASPBERRY_PI_B_PLUS" RASPBERRY_PI_A = "RASPBERRY_PI_A" RASPBERRY_PI_A_PLUS = "RASPBERRY_PI_A_PLUS" RASPBERRY_PI_CM1 = "RASPBERRY_PI_CM1" RASPBERRY_PI_ZERO = "RASPBERRY_PI_ZERO" RASPBERRY_PI_ZERO_W = "RASPBERRY_PI_ZERO_W" RASPBERRY_PI_ZERO_2_W = "RASPBERRY_PI_ZERO_2_W" RASPBERRY_PI_2B = "RASPBERRY_PI_2B" RASPBERRY_PI_3B = "RASPBERRY_PI_3B" RASPBERRY_PI_3B_PLUS = "RASPBERRY_PI_3B_PLUS" RASPBERRY_PI_CM3 = "RASPBERRY_PI_CM3" RASPBERRY_PI_3A_PLUS = "RASPBERRY_PI_3A_PLUS" RASPBERRY_PI_CM3_PLUS = "RASPBERRY_PI_CM3_PLUS" RASPBERRY_PI_4B = "RASPBERRY_PI_4B" RASPBERRY_PI_AVNET_IIOT_GW = "RASPBERY_PI_AVNET_IIOT_GW" RASPBERRY_PI_400 = "RASPBERRY_PI_400" RASPBERRY_PI_CM4 = "RASPBERRY_PI_CM4" RASPBERRY_PI_CM4S = "RASPBERRY_PI_CM4S" ODROID_C1 = "ODROID_C1" ODROID_C1_PLUS = "ODROID_C1_PLUS" ODROID_C2 = "ODROID_C2" ODROID_C4 = "ODROID_C4" ODROID_H3 = "ODROID_H3" ODROID_N2 = "ODROID_N2" ODROID_XU4 = "ODROID_XU4" ODROID_M1 = "ODROID_M1" FTDI_FT232H = "FTDI_FT232H" FTDI_FT2232H = "FTDI_FT2232H" DRAGONBOARD_410C = "DRAGONBOARD_410C" SIFIVE_UNLEASHED = "SIFIVE_UNLEASHED" ALLWINER_D1 = "ALLWINER_D1" LICHEE_RV = "LICHEE_RV" MICROCHIP_MCP2221 = "MICROCHIP_MCP2221" # Linkspirte Pcduino based boards PCDUINO2 = "PCDUINO2" PCDUINO3 = "PCDUINO3" # Boards with u2if firmware # https://github.com/execuc/u2if PICO_U2IF = "PICO_U2IF" FEATHER_U2IF = "FEATHER_U2IF" FEATHER_CAN_U2IF = "FEATHER_CAN_U2IF" FEATHER_EPD_U2IF = "FEATHER_EPD_U2IF" FEATHER_RFM_U2IF = "FEATHER_RFM_U2IF" ITSYBITSY_U2IF = "ITSYBITSY_U2IF" MACROPAD_U2IF = "MACROPAD_U2IF" QTPY_U2IF = "QTPY_U2IF" QT2040_TRINKEY_U2IF = "QT2040_TRINKEY_U2IF" KB2040_U2IF = "KB2040_U2IF" BINHO_NOVA = "BINHO_NOVA" ONION_OMEGA = "ONION_OMEGA" ONION_OMEGA2 = "ONION_OMEGA2" PINE64 = "PINE64" PINEH64 = "PINEH64" PINEBOOK = "PINEBOOK" PINEPHONE = "PINEPHONE" SOPINE = "SOPINE" RADXA_ZERO = "RADXA_ZERO" RADXA_CM3 = "RADXA_CM3" ROCK_PI_3A = "ROCK_PI_3A" ROCK_PI_S = "ROCK_PI_S" ROCK_PI_4 = "ROCK_PI_4" ROCK_PI_4_C_PLUS = "ROCK_PI_4C+" ROCK_PI_X = "ROCK_PI_X" ROCK_PI_E = "ROCK_PI_E" ROCK_PI_5 = "ROCK_PI_5" GREATFET_ONE = "GREATFET_ONE" # SeeedStudio boards ODYSSEY_X86J41X5 = "ODYSSEY_X86J41X5" # Udoo boards UDOO_BOLT_V3 = "UDOO_BOLT_V3" UDOO_BOLT_V8 = "UDOO_BOLT_V8" UDOO_X86 = "UDOO_X86" # MaaXBoard MAAXBOARD = "MAAXBOARD" MAAXBOARD_MINI = "MAAXBOARD_MINI" # Khadas VIM3 KHADAS_VIM3 = "KHADAS_VIM3" _KHADAS_40_PIN_IDS = (KHADAS_VIM3,) # Asus Tinkerboard _ASUS_TINKER_BOARD_IDS = ( ASUS_TINKER_BOARD, ASUS_TINKER_BOARD_2, ASUS_TINKER_EDGE_R, ) # STM32MP1 _STM32MP1_IDS = ( STM32MP157C_DK2, LUBANCAT_STM32MP157, OSD32MP1_BRK, OSD32MP1_RED, STMP157_OLINUXINO_LIME2, ) # OrangePI _ORANGE_PI_IDS = ( ORANGE_PI_PC, ORANGE_PI_R1, ORANGE_PI_ZERO, ORANGE_PI_ONE, ORANGE_PI_LITE, ORANGE_PI_PC_PLUS, ORANGE_PI_PLUS_2E, ORANGE_PI_2, ORANGE_PI_ZERO_PLUS_2H5, ORANGE_PI_ZERO_PLUS, ORANGE_PI_ZERO_2, ORANGE_PI_3, ORANGE_PI_3_LTS, ORANGE_PI_4, ORANGE_PI_4_LTS, ORANGE_PI_5, ) # NanoPi _NANOPI_IDS = ( NANOPI_NEO_AIR, NANOPI_DUO2, NANOPI_NEO, NANOPI_NEO_2, ) # BananaPI _BANANA_PI_IDS = ( BANANA_PI_M2_ZERO, BANANA_PI_M2_PLUS, BANANA_PI_M2_BERRY, BANANA_PI_M5, ) # LeMaker _LEMAKER_IDS = (LEMAKER_BANANA_PRO,) # LubanCat _LUBANCAT_IDS = ( LUBANCAT_IMX6ULL, LUBANCAT_STM32MP157, LUBANCAT_ZERO, LUBANCAT1, LUBANCAT2, ) # Coral boards _CORAL_IDS = (CORAL_EDGE_TPU_DEV, CORAL_EDGE_TPU_DEV_MINI) _PYNQ_IDS = (PYNQ_Z1, PYNQ_Z2) _JETSON_IDS = ( (JETSON_TX1, ("nvidia,p2371-2180", "nvidia,jetson-cv")), ( JETSON_TX2, ( "nvidia,p2771-0000", "nvidia,p2771-0888", "nvidia,p3489-0000", "nvidia,lightning", "nvidia,quill", "nvidia,storm", ), ), (JETSON_TX2_NX, ("nvidia,p3509-0000+p3636-0001",)), (CLARA_AGX_XAVIER, ("nvidia,e3900-0000+p2888-0004",)), ( JETSON_XAVIER, ( "nvidia,p2972-0000", "nvidia,p2972-0006", "nvidia,jetson-xavier", "nvidia,jetson-xavier-industrial", "nvidia,galen-industrial", ), ), (JETSON_NANO, ("nvidia,p3450-0000", "nvidia,p3450-0002", "nvidia,jetson-nano")), ( JETSON_NX, ( "nvidia,p3509-0000+p3668-0000", "nvidia,p3509-0000+p3668-0001", "nvidia,p3509-0000-a00+p3668-0000-a01", "nvidia,p3509-0000-a00+p3668-0001-a01", "nvidia,p3449-0000+p3668-0000", "nvidia,p3449-0000+p3668-0001", "nvidia,p3449-0000+p3668-0003", ), ), ( JETSON_AGX_ORIN, ( "nvidia,p3737-0000+p3701-0000", "nvidia,p3737-0000+p3701-0004", ), ), ( JETSON_ORIN_NX, ( "nvidia,p3509-0000+p3767-0000", "nvidia,p3768-0000+p3767-0000", "nvidia,p3509-0000+p3767-0001", "nvidia,p3768-0000+p3767-0001", ), ), ( JETSON_ORIN_NANO, ( "nvidia,p3509-0000+p3767-0003", "nvidia,p3768-0000+p3767-0003", "nvidia,p3509-0000+p3767-0004", "nvidia,p3768-0000+p3767-0004", "nvidia,p3509-0000+p3767-0005", "nvidia,p3768-0000+p3767-0005", ), ), ) _TI_SK_BOARD_IDS = ((TI_J721E_SK, ("ti,j721e-sk", "ti,j721e")),) _RASPBERRY_PI_40_PIN_IDS = ( RASPBERRY_PI_B_PLUS, RASPBERRY_PI_A_PLUS, RASPBERRY_PI_ZERO, RASPBERRY_PI_ZERO_W, RASPBERRY_PI_ZERO_2_W, RASPBERRY_PI_2B, RASPBERRY_PI_3B, RASPBERRY_PI_3B_PLUS, RASPBERRY_PI_3A_PLUS, RASPBERRY_PI_4B, RASPBERRY_PI_AVNET_IIOT_GW, RASPBERRY_PI_400, ) _RASPBERRY_PI_CM_IDS = ( RASPBERRY_PI_CM1, RASPBERRY_PI_CM3, RASPBERRY_PI_CM3_PLUS, RASPBERRY_PI_CM4, RASPBERRY_PI_CM4S, ) _ODROID_40_PIN_IDS = ( ODROID_C1, ODROID_C1_PLUS, ODROID_C2, ODROID_C4, ODROID_N2, ODROID_XU4, ODROID_M1, ) _ODROID_MINI_PC_IDS = (ODROID_H3,) _BEAGLEBONE_IDS = ( BEAGLE_PLAY, BEAGLEBONE_AI64, BEAGLEBONE, BEAGLEBONE_BLACK, BEAGLEBONE_BLUE, BEAGLEBONE_BLACK_WIRELESS, BEAGLEBONE_POCKETBEAGLE, BEAGLEBONE_GREEN, BEAGLEBONE_GREEN_WIRELESS, BEAGLEBONE_GREEN_GATEWAY, BEAGLEBONE_BLACK_INDUSTRIAL, BEAGLEBONE_ENHANCED, BEAGLEBONE_USOMIQ, BEAGLEBONE_AIR, BEAGLEBONE_AI, BEAGLEBONE_POCKETBONE, BEAGLELOGIC_STANDALONE, BEAGLEV_STARLIGHT, OSD3358_DEV_BOARD, OSD3358_SM_RED, ) _LINARO_96BOARDS_IDS = (DRAGONBOARD_410C,) _SIFIVE_IDS = (SIFIVE_UNLEASHED,) # BeagleBone eeprom board ids from: # https://github.com/beagleboard/image-builder # Thanks to zmatt on freenode #beagle for pointers. _BEAGLEBONE_BOARD_IDS = { BEAGLE_PLAY: (("A0", "7.BEAGLE")), BEAGLEBONE_AI64: (("B0", "7.BBONEA")), # Original bone/white: BEAGLEBONE: ( ("A4", "A335BONE00A4"), ("A5", "A335BONE00A5"), ("A6", "A335BONE00A6"), ("A6A", "A335BONE0A6A"), ("A6B", "A335BONE0A6B"), ("B", "A335BONE000B"), ), BEAGLEBONE_BLACK: ( ("A5", "A335BNLT00A5"), ("A5A", "A335BNLT0A5A"), ("A5B", "A335BNLT0A5B"), ("A5C", "A335BNLT0A5C"), ("A6", "A335BNLT00A6"), ("A6A", "A335BNLT0A6A"), ("B", "A335BNLT000B"), ("C", "A335BNLT000C"), ("C", "A335BNLT00C0"), ), BEAGLEBONE_BLUE: (("A2", "A335BNLTBLA2"),), BEAGLEBONE_BLACK_WIRELESS: (("A5", "A335BNLTBWA5"),), BEAGLEBONE_POCKETBEAGLE: (("A2", "A335PBGL00A2"),), BEAGLEBONE_GREEN: (("1A", "A335BNLT...."), ("UNKNOWN", "A335BNLTBBG1")), BEAGLEBONE_GREEN_WIRELESS: (("W1A", "A335BNLTGW1A"),), BEAGLEBONE_GREEN_GATEWAY: (("GA1", "A335BNLTGG1A"),), BEAGLEBONE_BLACK_INDUSTRIAL: ( ("A0", "A335BNLTAIA0"), # Arrow ("A0", "A335BNLTEIA0"), # Element14 ), BEAGLEBONE_ENHANCED: (("A", "A335BNLTSE0A"),), BEAGLEBONE_USOMIQ: (("6", "A335BNLTME06"),), BEAGLEBONE_AIR: (("A0", "A335BNLTNAD0"),), BEAGLEBONE_POCKETBONE: (("0", "A335BNLTBP00"),), OSD3358_DEV_BOARD: (("0.1", "A335BNLTGH01"),), OSD3358_SM_RED: (("0", "A335BNLTOS00"),), BEAGLELOGIC_STANDALONE: (("A", "A335BLGC000A"),), } # Pi revision codes from: # https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md # Each tuple here contains both the base codes, and the versions that indicate # the Pi is overvolted / overclocked - for 4-digit codes, this will be prefixed # with 1000, and for 6-digit codes it'll be prefixed with 1. These are placed # on separate lines. _PI_REV_CODES = { RASPBERRY_PI_B_REV1: ( # Regular codes: "0002", "0003", # Overvolted/clocked versions: "1000002", "1000003", ), RASPBERRY_PI_B_REV2: ( "0004", "0005", "0006", "000d", "000e", "000f", "1000005", "1000006", "100000d", "100000e", "100000f", ), RASPBERRY_PI_B_PLUS: ("0010", "0013", "900032", "1000010", "1000013", "1900032"), RASPBERRY_PI_A: ("0007", "0008", "0009", "1000007", "1000008", "1000009"), RASPBERRY_PI_A_PLUS: ("0012", "0015", "900021", "1000012", "1000015", "1900021"), RASPBERRY_PI_CM1: ("0011", "0014", "10000011", "10000014"), RASPBERRY_PI_ZERO: ( "900092", "920092", "900093", "920093", "1900092", "1920092", "1900093", "1920093", # warranty bit 24 "2900092", "2920092", "2900093", "2920093", # warranty bit 25 ), RASPBERRY_PI_ZERO_W: ("9000c1", "19000c1", "29000c1"), # warranty bits RASPBERRY_PI_2B: ( "a01040", "a01041", "a02042", "a21041", "a22042", "1a01040", "1a01041", "1a02042", "1a21041", "1a22042", # warranty bit 24 "2a01040", "2a01041", "2a02042", "2a21041", "2a22042", # warranty bit 25 "3a01040", "3a01041", "3a02042", "3a21041", "3a22042", ), RASPBERRY_PI_3B: ( "a02082", "a22082", "a32082", "a52082", "1a02082", "1a22082", "1a32082", "1a52082", # warranty bit 24 "2a02082", "2a22082", "2a32082", "2a52082", # warranty bit 25 ), RASPBERRY_PI_3B_PLUS: ("a020d3", "1a020d3", "2a020d3", "a020d4"), # warranty bits RASPBERRY_PI_AVNET_IIOT_GW: ("60a220b0",), RASPBERRY_PI_CM3: ( "a020a0", "a220a0", "1a020a0", "2a020a0", # warranty bits "1a220a0", "2a220a0", ), RASPBERRY_PI_3A_PLUS: ("9020e0", "19020e0", "29020e0"), # warranty bits RASPBERRY_PI_CM3_PLUS: ("a02100", "1a02100", "2a02100"), # warranty bits RASPBERRY_PI_4B: ( "a03111", "b03111", "c03111", "a03112", "b03112", "c03112", "b03114", "c03114", "d03114", "a03115", "b03115", "c03115", "d03115", "1a03111", "2a03111", "1b03111", "2b03111", # warranty bits "1c03111", "2c03111", "1a03112", "2a03112", "1b03112", "2b03112", "1c03112", "2c03112", "80c03114", ), RASPBERRY_PI_400: ("c03130", "c03131"), RASPBERRY_PI_CM4: ( "a03140", "a03141", "b03140", "b03141", "c03140", "c03141", "d03140", "d03141", ), RASPBERRY_PI_ZERO_2_W: ("902120", "2902120"), } _PI_MODELS = { 0x00: RASPBERRY_PI_A, 0x01: { 1.0: RASPBERRY_PI_B_REV1, 2.0: RASPBERRY_PI_B_REV2, }, 0x02: RASPBERRY_PI_A_PLUS, 0x03: RASPBERRY_PI_B_PLUS, 0x04: RASPBERRY_PI_2B, 0x06: RASPBERRY_PI_CM1, 0x08: RASPBERRY_PI_3B, 0x09: RASPBERRY_PI_ZERO, 0x0A: RASPBERRY_PI_CM3, 0x0B: RASPBERRY_PI_AVNET_IIOT_GW, 0x0C: RASPBERRY_PI_ZERO_W, 0x0D: RASPBERRY_PI_3B_PLUS, 0x0E: RASPBERRY_PI_3A_PLUS, 0x10: RASPBERRY_PI_CM3_PLUS, 0x11: RASPBERRY_PI_4B, 0x12: RASPBERRY_PI_ZERO_2_W, 0x13: RASPBERRY_PI_400, 0x14: RASPBERRY_PI_CM4, 0x15: RASPBERRY_PI_CM4S, } # Onion omega boards _ONION_OMEGA_BOARD_IDS = (ONION_OMEGA, ONION_OMEGA2) # Pine64 boards and devices _PINE64_DEV_IDS = (PINE64, PINEH64, PINEBOOK, PINEPHONE, SOPINE) # Pcduino baords _PCDUINO_DEV_IDS = (PCDUINO2, PCDUINO3) # RockPi boards and devices _ROCK_PI_IDS = ( ROCK_PI_S, ROCK_PI_4, ROCK_PI_4_C_PLUS, ROCK_PI_X, ROCK_PI_E, RADXA_ZERO, ROCK_PI_5, RADXA_CM3, ROCK_PI_3A, ) # UDOO _UDOO_BOARD_IDS = {UDOO_BOLT_V8: ("SC40-2000-0000-C0|C",), UDOO_X86: ("dummy",)} # SeeedStudio boards _SEEED_BOARD_IDS = (ODYSSEY_X86J41X5,) # MaaXBoard boards _MAAXBOARD_IDS = ("MAAXBOARD", "MAAXBOARD_MINI") # Lichee RISC-V boards _LICHEE_RISCV_IDS = (LICHEE_RV,) # Siemens Simatic IOT2000 Gateways SIEMENS_SIMATIC_IOT2050_ADV = "SIEMENS_SIMATIC_IOT2050_ADVANCED" SIEMENS_SIMATIC_IOT2050_BASIC = "SIEMENS_SIMATIC_IOT2050_BASIC" # Siemens Simatic IOT2000 Gateways _SIEMENS_SIMATIC_IOT2000_IDS = ( SIEMENS_SIMATIC_IOT2050_ADV, SIEMENS_SIMATIC_IOT2050_BASIC, ) # Libre Computer Boards AML_S905X_CC = "AML-S905X-CC" ROC_RK3328_CC = "ROC-RK3328-CC" # Libre Computer Boards _LIBRE_COMPUTER_IDS = ( AML_S905X_CC, ROC_RK3328_CC, ) # NXP System on Module Computer boards NXP_IMX8MPLUS_SOM = "NXP_IMX8MPLUS_SOM" _NXP_SOM_IDS = (NXP_IMX8MPLUS_SOM,)
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/adafruit_platformdetect/constants/boards.py
boards.py
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries # # SPDX-License-Identifier: MIT """ `bin.detect` ================================================================================ Board detection and determination script * Author(s): Melissa LeBlanc-Williams Implementation Notes -------------------- **Software and Dependencies:** * Linux and Python 3.7 or Higher """ import adafruit_platformdetect detector = adafruit_platformdetect.Detector() print("Board Detection Test") print() print("Check that the Chip and Board IDs match your board and that this it is") print("correctly detecting whether or not it is a Linux board.") print() print("Chip id: ", detector.chip.id) print("Board id: ", detector.board.id) print() print("Linux Detection") print("---------------") print("Is this an embedded Linux system?", detector.board.any_embedded_linux) print() print("Raspberry Pi Boards") print("-------------------") if detector.board.any_raspberry_pi: print("Raspberry Pi detected.") print("Is this a Pi 3B+?", detector.board.RASPBERRY_PI_3B_PLUS) print("Is this a Pi 4B?", detector.board.RASPBERRY_PI_4B) print("Is this a 40-pin Raspberry Pi?", detector.board.any_raspberry_pi_40_pin) print("Is this a Raspberry Pi Compute Module?", detector.board.any_raspberry_pi_cm) print() print("Other Boards") print("-------------------") print( "Is this a Siemens Simatic IOT2000 Gateway?", detector.board.any_siemens_simatic_iot2000, ) print("Is this a 96boards board?", detector.board.any_96boards) print("Is this a BeagleBone board?", detector.board.any_beaglebone) print("Is this a Giant board?", detector.board.any_giant_board) print("Is this a Coral Dev board?", detector.board.any_coral_board) print("Is this a MaaXBoard?", detector.board.any_maaxboard) print("Is this a SiFive board? ", detector.board.any_sifive_board) print("Is this a PYNQ board?", detector.board.any_pynq_board) print("Is this a Rock Pi board?", detector.board.any_rock_pi_board) print("Is this a NanoPi board?", detector.board.any_nanopi) print("Is this a Khadas VIM3 board?", detector.board.khadas_vim3_40_pin) print("Is this a Clockwork Pi board?", detector.board.any_clockwork_pi_board) print("Is this a Seeed Board?", detector.board.any_seeed_board) print("Is this a UDOO board?", detector.board.any_udoo_board) print("Is this an ASUS Tinker board?", detector.board.any_asus_tinker_board) print("Is this an STM32MP1 board?", detector.board.any_stm32mp1) print("Is this a generic Linux PC?", detector.board.generic_linux) print( "Is this an OS environment variable special case?", detector.board.os_environ_board ) if detector.board.any_jetson_board: print("Jetson platform detected.") if detector.board.any_tisk_board: print("TI platform detected.") if detector.board.any_pynq_board: print("PYNQ platform detected.") if detector.board.any_orange_pi: print("Orange Pi detected.") if detector.board.any_lemaker: print("LeMaker board detected.") if detector.board.any_odroid_40_pin: print("Odroid detected.") if detector.board.any_onion_omega_board: print("Onion Omega detected.") if detector.board.any_pine64_board: print("Pine64 device detected.") if detector.board.any_rock_pi_board: print("Rock Pi device detected.") if detector.board.any_clockwork_pi_board: print("Clockwork Pi device detected.") if detector.board.any_asus_tinker_board: print("ASUS Tinker Board device detected.") if detector.board.any_coral_board: print("Coral device detected.") if detector.board.any_lubancat: print("LubanCat detected.") if detector.board.any_siemens_simatic_iot2000: print("Siemens Simatic IOT2000 Gateway detected.") if detector.board.any_nxp_navq_board: print("NXP NavQ board detected.")
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/bin/detect.py
detect.py
# SPDX-FileCopyrightText: 2023 Melissa LeBlanc-Williams for Adafruit Industries # # SPDX-License-Identifier: MIT """ `bin.rpi_info` ================================================================================ Interactive mode will prompt for the revision code Otherwise it will be detected automatically * Author(s): Melissa LeBlanc-Williams Implementation Notes -------------------- **Software and Dependencies:** * Linux and Python 3.7 or Higher """ import sys import adafruit_platformdetect from adafruit_platformdetect.revcodes import PiDecoder pi_rev_code = None detector = adafruit_platformdetect.Detector() pi_rev_code = detector.board._pi_rev_code() # pylint: disable=protected-access if pi_rev_code is None: print("Raspberry Pi not detected. Using interactive mode") pi_rev_code = input("Enter a Raspberry Pi revision code (e.g. d03114 or 000f): ") try: decoder = PiDecoder(pi_rev_code) except ValueError as e: print("Invalid revision code. It should be a hexadecimal value.") sys.exit(1) if not decoder.is_valid_code(): print( "Code is invalid. This rev code includes at least one " "value that is outside of the expected range." ) sys.exit(1) def print_property(label, value): "Format and print a property" print(f"{label}: {value}") if decoder.is_new_format(): print_property("Overvoltage", decoder.overvoltage) print_property("OTP Program", decoder.otp_program) print_property("OTP Read", decoder.otp_read) print_property("Warranty bit", decoder.warranty_bit) print_property("New flag", decoder.rev_style) print_property("Memory size", decoder.memory_size) print_property("Manufacturer", decoder.manufacturer) print_property("Processor", decoder.processor) print_property("Type", decoder.type) print_property("Revision", decoder.revision) else: print_property("Warranty bit", decoder.warranty_bit) print_property("Model", decoder.type) print_property("Revision", decoder.revision) print_property("RAM", decoder.memory_size) print_property("Manufacturer", decoder.manufacturer)
Adafruit-PlatformDetect
/Adafruit-PlatformDetect-3.49.0.tar.gz/Adafruit-PlatformDetect-3.49.0/bin/rpi_info.py
rpi_info.py
Introduction ============ .. image:: https://readthedocs.org/projects/adafruit-pureio/badge/?version=latest :target: https://adafruit-pureio.readthedocs.io/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/discord/327254708534116352.svg :target: https://adafru.it/discord :alt: Discord .. image:: https://github.com/adafruit/Adafruit_Python_PureIO/workflows/Build%20CI/badge.svg :target: https://github.com/adafruit/Adafruit_Python_PureIO/actions :alt: Build Status .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/psf/black :alt: Code Style: Black Pure python (i.e. no native extensions) access to Linux IO including I2C and SPI. Drop in replacement for smbus and spidev modules. Dependencies ============= This driver depends on: * Python 3.5 or higher Installing from PyPI ===================== On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from PyPI <https://pypi.org/project/Adafruit-PureIO/>`_. To install for current user: .. code-block:: shell pip3 install Adafruit-PureIO To install system-wide (this may be required in some cases): .. code-block:: shell sudo pip3 install Adafruit-PureIO To install in a virtual environment in your current project: .. code-block:: shell mkdir project-name && cd project-name python3 -m venv .env source .env/bin/activate pip3 install Adafruit-PureIO Contributing ============ Contributions are welcome! Please read our `Code of Conduct <https://github.com/adafruit/Adafruit_Python_PureIO/blob/master/CODE_OF_CONDUCT.md>`_ before contributing to help this project stay welcoming. Documentation ============= For information on building library documentation, please check out `this guide <https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/sharing-our-docs-on-readthedocs#sphinx-5-1>`_.
Adafruit-PureIO
/Adafruit_PureIO-1.1.11.tar.gz/Adafruit_PureIO-1.1.11/README.rst
README.rst
<!-- SPDX-FileCopyrightText: 2014 Coraline Ada Ehmke SPDX-FileCopyrightText: 2019 Kattni Rembor for Adafruit Industries SPDX-License-Identifier: CC-BY-4.0 --> # Adafruit Community Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and leaders pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level or type of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards We are committed to providing a friendly, safe and welcoming environment for all. Examples of behavior that contributes to creating a positive environment include: * Be kind and courteous to others * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Collaborating with other community members * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and sexual attention or advances * The use of inappropriate images, including in a community member's avatar * The use of inappropriate language, including in a community member's nickname * Any spamming, flaming, baiting or other attention-stealing behavior * Excessive or unwelcome helping; answering outside the scope of the question asked * Trolling, insulting/derogatory comments, and personal or political attacks * Promoting or spreading disinformation, lies, or conspiracy theories against a person, group, organisation, project, or community * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate The goal of the standards and moderation guidelines outlined here is to build and maintain a respectful community. We ask that you don’t just aim to be "technically unimpeachable", but rather try to be your best self. We value many things beyond technical expertise, including collaboration and supporting others within our community. Providing a positive experience for other community members can have a much more significant impact than simply providing the correct answer. ## Our Responsibilities Project leaders are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project leaders have the right and responsibility to remove, edit, or reject messages, comments, commits, code, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any community member for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Moderation Instances of behaviors that violate the Adafruit Community Code of Conduct may be reported by any member of the community. Community members are encouraged to report these situations, including situations they witness involving other community members. You may report in the following ways: In any situation, you may send an email to <[email protected]>. On the Adafruit Discord, you may send an open message from any channel to all Community Moderators by tagging @community moderators. You may also send an open message from any channel, or a direct message to @kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. Email and direct message reports will be kept confidential. In situations on Discord where the issue is particularly egregious, possibly illegal, requires immediate action, or violates the Discord terms of service, you should also report the message directly to Discord. These are the steps for upholding our community’s standards of conduct. 1. Any member of the community may report any situation that violates the Adafruit Community Code of Conduct. All reports will be reviewed and investigated. 2. If the behavior is an egregious violation, the community member who committed the violation may be banned immediately, without warning. 3. Otherwise, moderators will first respond to such behavior with a warning. 4. Moderators follow a soft "three strikes" policy - the community member may be given another chance, if they are receptive to the warning and change their behavior. 5. If the community member is unreceptive or unreasonable when warned by a moderator, or the warning goes unheeded, they may be banned for a first or second offense. Repeated offenses will result in the community member being banned. ## Scope This Code of Conduct and the enforcement policies listed above apply to all Adafruit Community venues. This includes but is not limited to any community spaces (both public and private), the entire Adafruit Discord server, and Adafruit GitHub repositories. Examples of Adafruit Community spaces include but are not limited to meet-ups, audio chats on the Adafruit Discord, or interaction at a conference. This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. As a community member, you are representing our community, and are expected to behave accordingly. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at <https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>, and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). For other projects adopting the Adafruit Community Code of Conduct, please contact the maintainers of those projects for enforcement. If you wish to use this code of conduct for your own project, consider explicitly mentioning your moderation policy or making a copy with your own moderation policy so as to avoid confusion.
Adafruit-PureIO
/Adafruit_PureIO-1.1.11.tar.gz/Adafruit_PureIO-1.1.11/CODE_OF_CONDUCT.md
CODE_OF_CONDUCT.md
.. include:: ../README.rst Table of Contents ================= .. toctree:: :maxdepth: 4 :hidden: self .. toctree:: :caption: API Reference :maxdepth: 3 api .. toctree:: :caption: Tutorials .. toctree:: :caption: Related Products .. toctree:: :caption: Other Links Download <https://github.com/adafruit/Adafruit_Python_PureIO/releases/latest> CircuitPython Reference Documentation <https://circuitpython.readthedocs.io> CircuitPython Support Forum <https://forums.adafruit.com/viewforum.php?f=60> Discord Chat <https://adafru.it/discord> Adafruit Learning System <https://learn.adafruit.com> Adafruit Blog <https://blog.adafruit.com> Adafruit Store <https://www.adafruit.com> Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
Adafruit-PureIO
/Adafruit_PureIO-1.1.11.tar.gz/Adafruit_PureIO-1.1.11/docs/index.rst
index.rst
# imports from ctypes import create_string_buffer, string_at, addressof from fcntl import ioctl import struct import platform import os.path from os import environ import array __version__ = "1.1.11" __repo__ = "https://github.com/adafruit/Adafruit_Python_PureIO.git" # SPI C API constants (from linux kernel headers) SPI_CPHA = 0x01 SPI_CPOL = 0x02 SPI_CS_HIGH = 0x04 SPI_LSB_FIRST = 0x08 SPI_THREE_WIRE = 0x10 SPI_LOOP = 0x20 SPI_NO_CS = 0x40 SPI_READY = 0x80 SPI_TX_DUAL = 0x100 SPI_TX_QUAD = 0x200 SPI_RX_DUAL = 0x400 SPI_RX_QUAD = 0x800 SPI_MODE_0 = 0 SPI_MODE_1 = SPI_CPHA SPI_MODE_2 = SPI_CPOL SPI_MODE_3 = SPI_CPHA | SPI_CPOL SPI_DEFAULT_CHUNK_SIZE = 4096 def _ioc_encode(direction, number, structure): """ ioctl command encoding helper function Calculates the appropriate spidev ioctl op argument given the direction, command number, and argument structure in python's struct.pack format. Returns a tuple of the calculated op and the struct.pack format See Linux kernel source file /include/uapi/asm/ioctl.h """ ioc_magic = ord("k") ioc_nrbits = 8 ioc_typebits = 8 if platform.machine() == "mips": ioc_sizebits = 13 else: ioc_sizebits = 14 ioc_nrshift = 0 ioc_typeshift = ioc_nrshift + ioc_nrbits ioc_sizeshift = ioc_typeshift + ioc_typebits ioc_dirshift = ioc_sizeshift + ioc_sizebits size = struct.calcsize(structure) operation = ( (direction << ioc_dirshift) | (ioc_magic << ioc_typeshift) | (number << ioc_nrshift) | (size << ioc_sizeshift) ) return direction, operation, structure # pylint: disable=too-many-instance-attributes, too-many-branches class SPI: """ This class is similar to SpiDev, but instead of opening and closing for each call, it is set up on initialization making it fast. """ _IOC_TRANSFER_FORMAT = "QQIIHBBBBH" if platform.machine() == "mips": # Direction is 3 bits _IOC_READ = 2 _IOC_WRITE = 4 else: # Direction is 2 bits _IOC_WRITE = 1 _IOC_READ = 2 # _IOC_MESSAGE is a special case, so we ony need the ioctl operation _IOC_MESSAGE = _ioc_encode(_IOC_WRITE, 0, _IOC_TRANSFER_FORMAT)[1] _IOC_RD_MODE = _ioc_encode(_IOC_READ, 1, "B") _IOC_WR_MODE = _ioc_encode(_IOC_WRITE, 1, "B") _IOC_RD_LSB_FIRST = _ioc_encode(_IOC_READ, 2, "B") _IOC_WR_LSB_FIRST = _ioc_encode(_IOC_WRITE, 2, "B") _IOC_RD_BITS_PER_WORD = _ioc_encode(_IOC_READ, 3, "B") _IOC_WR_BITS_PER_WORD = _ioc_encode(_IOC_WRITE, 3, "B") _IOC_RD_MAX_SPEED_HZ = _ioc_encode(_IOC_READ, 4, "I") _IOC_WR_MAX_SPEED_HZ = _ioc_encode(_IOC_WRITE, 4, "I") _IOC_RD_MODE32 = _ioc_encode(_IOC_READ, 5, "I") _IOC_WR_MODE32 = _ioc_encode(_IOC_WRITE, 5, "I") # pylint: disable=too-many-arguments def __init__( self, device, max_speed_hz=None, bits_per_word=None, phase=None, polarity=None, cs_high=None, lsb_first=None, three_wire=None, loop=None, no_cs=None, ready=None, ): """ Create spidev interface object. """ if isinstance(device, tuple): (bus, dev) = device device = f"/dev/spidev{bus:d}.{dev:d}" if not os.path.exists(device): raise IOError(f"{device} does not exist") self.handle = os.open(device, os.O_RDWR) self.chunk_size = SPI_DEFAULT_CHUNK_SIZE if environ.get("SPI_BUFSIZE") is not None: try: self.chunk_size = int(os.environ.get("SPI_BUFSIZE")) except ValueError: self.chunk_size = SPI_DEFAULT_CHUNK_SIZE if max_speed_hz is not None: self.max_speed_hz = max_speed_hz if bits_per_word is not None: self.bits_per_word = bits_per_word if phase is not None: self.phase = phase if polarity is not None: self.polarity = polarity if cs_high is not None: self.cs_high = cs_high if lsb_first is not None: self.lsb_first = lsb_first if three_wire is not None: self.three_wire = three_wire if loop is not None: self.loop = loop if no_cs is not None: self.no_cs = no_cs if ready is not None: self.ready = ready # pylint: enable=too-many-arguments def _ioctl(self, ioctl_data, data=None): """ ioctl helper function. Performs an ioctl on self.handle. If the ioctl is an SPI read type ioctl, returns the result value. """ (direction, ioctl_bytes, structure) = ioctl_data if direction == SPI._IOC_READ: arg = array.array(structure, [0]) ioctl(self.handle, ioctl_bytes, arg, True) return arg[0] arg = struct.pack("=" + structure, data) ioctl(self.handle, ioctl_bytes, arg) return None def _get_mode_field(self, field): """Helper function to get specific spidev mode bits""" return bool(self._ioctl(SPI._IOC_RD_MODE) & field) def _set_mode_field(self, field, value): """Helper function to set a spidev mode bit""" mode = self._ioctl(SPI._IOC_RD_MODE) if value: mode |= field else: mode &= ~field self._ioctl(SPI._IOC_WR_MODE, mode) @property def phase(self): """SPI clock phase bit""" return self._get_mode_field(SPI_CPHA) @phase.setter def phase(self, phase): self._set_mode_field(SPI_CPHA, phase) @property def polarity(self): """SPI polarity bit""" return self._get_mode_field(SPI_CPOL) @polarity.setter def polarity(self, polarity): self._set_mode_field(SPI_CPOL, polarity) @property def cs_high(self): """SPI chip select active level""" return self._get_mode_field(SPI_CS_HIGH) @cs_high.setter def cs_high(self, cs_high): self._set_mode_field(SPI_CS_HIGH, cs_high) @property def lsb_first(self): """Bit order of SPI word transfers""" return self._get_mode_field(SPI_LSB_FIRST) @lsb_first.setter def lsb_first(self, lsb_first): self._set_mode_field(SPI_LSB_FIRST, lsb_first) @property def three_wire(self): """SPI 3-wire mode""" return self._get_mode_field(SPI_THREE_WIRE) @three_wire.setter def three_wire(self, three_wire): self._set_mode_field(SPI_THREE_WIRE, three_wire) @property def loop(self): """SPI loopback mode""" return self._get_mode_field(SPI_LOOP) @loop.setter def loop(self, loop): self._set_mode_field(SPI_LOOP, loop) @property def no_cs(self): """No chipselect. Single device on bus.""" return self._get_mode_field(SPI_NO_CS) @no_cs.setter def no_cs(self, no_cs): self._set_mode_field(SPI_NO_CS, no_cs) @property def ready(self): """Slave pulls low to pause""" return self._get_mode_field(SPI_READY) @ready.setter def ready(self, ready): self._set_mode_field(SPI_READY, ready) @property def max_speed_hz(self): """Maximum SPI transfer speed in Hz. Note that the controller cannot necessarily assign the requested speed. """ return self._ioctl(SPI._IOC_RD_MAX_SPEED_HZ) @max_speed_hz.setter def max_speed_hz(self, max_speed_hz): self._ioctl(SPI._IOC_WR_MAX_SPEED_HZ, max_speed_hz) @property def bits_per_word(self): """Number of bits per word of SPI transfer. A value of 0 is equivalent to 8 bits per word """ return self._ioctl(SPI._IOC_RD_BITS_PER_WORD) @bits_per_word.setter def bits_per_word(self, bits_per_word): self._ioctl(SPI._IOC_WR_BITS_PER_WORD, bits_per_word) @property def mode(self): """Mode that SPI is currently running in""" return self._ioctl(SPI._IOC_RD_MODE) @mode.setter def mode(self, mode): self._ioctl(SPI._IOC_WR_MODE, mode) def writebytes(self, data, max_speed_hz=0, bits_per_word=0, delay=0): """Perform half-duplex SPI write.""" data = array.array("B", data).tobytes() # length = len(data) chunks = [ data[i : i + self.chunk_size] for i in range(0, len(data), self.chunk_size) ] for chunk in chunks: length = len(chunk) transmit_buffer = create_string_buffer(chunk) spi_ioc_transfer = struct.pack( SPI._IOC_TRANSFER_FORMAT, addressof(transmit_buffer), 0, length, max_speed_hz, delay, bits_per_word, 0, 0, 0, 0, ) try: ioctl(self.handle, SPI._IOC_MESSAGE, spi_ioc_transfer) except TimeoutError as err: raise Exception( # pylint: disable=broad-exception-raised "ioctl timeout. Please try a different SPI frequency or less data." ) from err def readbytes(self, length, max_speed_hz=0, bits_per_word=0, delay=0): """Perform half-duplex SPI read as a binary string""" receive_buffer = create_string_buffer(length) spi_ioc_transfer = struct.pack( SPI._IOC_TRANSFER_FORMAT, 0, addressof(receive_buffer), length, max_speed_hz, delay, bits_per_word, 0, 0, 0, 0, ) ioctl(self.handle, SPI._IOC_MESSAGE, spi_ioc_transfer) return string_at(receive_buffer, length) def transfer(self, data, max_speed_hz=0, bits_per_word=0, delay=0): """Perform full-duplex SPI transfer""" data = array.array("B", data).tobytes() receive_data = [] chunks = [ data[i : i + self.chunk_size] for i in range(0, len(data), self.chunk_size) ] for chunk in chunks: length = len(chunk) receive_buffer = create_string_buffer(length) transmit_buffer = create_string_buffer(chunk) spi_ioc_transfer = struct.pack( SPI._IOC_TRANSFER_FORMAT, addressof(transmit_buffer), addressof(receive_buffer), length, max_speed_hz, delay, bits_per_word, 0, 0, 0, 0, ) ioctl(self.handle, SPI._IOC_MESSAGE, spi_ioc_transfer) receive_data += string_at(receive_buffer, length) return receive_data
Adafruit-PureIO
/Adafruit_PureIO-1.1.11.tar.gz/Adafruit_PureIO-1.1.11/Adafruit_PureIO/spi.py
spi.py
from ctypes import c_uint8, c_uint16, c_uint32, cast, pointer, POINTER from ctypes import create_string_buffer, Structure from fcntl import ioctl import struct # pylint: disable=fixme # I2C C API constants (from linux kernel headers) I2C_M_TEN = 0x0010 # this is a ten bit chip address I2C_M_RD = 0x0001 # read data, from slave to master I2C_M_STOP = 0x8000 # if I2C_FUNC_PROTOCOL_MANGLING I2C_M_NOSTART = 0x4000 # if I2C_FUNC_NOSTART I2C_M_REV_DIR_ADDR = 0x2000 # if I2C_FUNC_PROTOCOL_MANGLING I2C_M_IGNORE_NAK = 0x1000 # if I2C_FUNC_PROTOCOL_MANGLING I2C_M_NO_RD_ACK = 0x0800 # if I2C_FUNC_PROTOCOL_MANGLING I2C_M_RECV_LEN = 0x0400 # length will be first received byte I2C_SLAVE = 0x0703 # Use this slave address I2C_SLAVE_FORCE = 0x0706 # Use this slave address, even if # is already in use by a driver! I2C_TENBIT = 0x0704 # 0 for 7 bit addrs, != 0 for 10 bit I2C_FUNCS = 0x0705 # Get the adapter functionality mask I2C_RDWR = 0x0707 # Combined R/W transfer (one STOP only) I2C_PEC = 0x0708 # != 0 to use PEC with SMBus I2C_SMBUS = 0x0720 # SMBus transfer # ctypes versions of I2C structs defined by kernel. # Tone down pylint for the Python classes that mirror C structs. # pylint: disable=invalid-name,too-few-public-methods class i2c_msg(Structure): """Linux i2c_msg struct.""" _fields_ = [ ("addr", c_uint16), ("flags", c_uint16), ("len", c_uint16), ("buf", POINTER(c_uint8)), ] class i2c_rdwr_ioctl_data(Structure): # pylint: disable=invalid-name """Linux i2c data struct.""" _fields_ = [("msgs", POINTER(i2c_msg)), ("nmsgs", c_uint32)] # pylint: enable=invalid-name,too-few-public-methods # pylint: disable=attribute-defined-outside-init def make_i2c_rdwr_data(messages): """Utility function to create and return an i2c_rdwr_ioctl_data structure populated with a list of specified I2C messages. The messages parameter should be a list of tuples which represent the individual I2C messages to send in this transaction. Tuples should contain 4 elements: address value, flags value, buffer length, ctypes c_uint8 pointer to buffer. """ # Create message array and populate with provided data. msg_data_type = i2c_msg * len(messages) msg_data = msg_data_type() for i, message in enumerate(messages): msg_data[i].addr = message[0] & 0x7F msg_data[i].flags = message[1] msg_data[i].len = message[2] msg_data[i].buf = message[3] # Now build the data structure. data = i2c_rdwr_ioctl_data() data.msgs = msg_data data.nmsgs = len(messages) return data # pylint: enable=attribute-defined-outside-init # Create an interface that mimics the Python SMBus API. class SMBus: """I2C interface that mimics the Python SMBus API but is implemented with pure Python calls to ioctl and direct /dev/i2c device access. """ def __init__(self, bus=None): """Create a new smbus instance. Bus is an optional parameter that specifies the I2C bus number to use, for example 1 would use device /dev/i2c-1. If bus is not specified then the open function should be called to open the bus. """ self._device = None if bus is not None: self.open(bus) def __del__(self): """Clean up any resources used by the SMBus instance.""" self.close() def __enter__(self): """Context manager enter function.""" # Just return this object so it can be used in a with statement, like # with SMBus(1) as bus: # # do stuff! return self def __exit__(self, exc_type, exc_val, exc_tb): """Context manager exit function, ensures resources are cleaned up.""" self.close() return False # Don't suppress exceptions. def open(self, bus): """Open the smbus interface on the specified bus.""" # Close the device if it's already open. if self._device is not None: self.close() # Try to open the file for the specified bus. Must turn off buffering # or else Python 3 fails (see: https://bugs.python.org/issue20074) # pylint: disable=consider-using-with self._device = open(f"/dev/i2c-{bus}", "r+b", buffering=0) # pylint: enable=consider-using-with # TODO: Catch IOError and throw a better error message that describes # what's wrong (i.e. I2C may not be enabled or the bus doesn't exist). def close(self): """Close the smbus connection. You cannot make any other function calls on the bus unless open is called!""" if self._device is not None: self._device.close() self._device = None def _select_device(self, addr): """Set the address of the device to communicate with on the I2C bus.""" ioctl(self._device.fileno(), I2C_SLAVE, addr & 0x7F) def read_byte(self, addr): """Read a single byte from the specified device.""" assert ( self._device is not None ), "Bus must be opened before operations are made against it!" self._select_device(addr) return ord(self._device.read(1)) def read_bytes(self, addr, number): """Read many bytes from the specified device.""" assert ( self._device is not None ), "Bus must be opened before operations are made against it!" self._select_device(addr) return self._device.read(number) def read_byte_data(self, addr, cmd): """Read a single byte from the specified cmd register of the device.""" assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Build ctypes values to marshall between ioctl and Python. reg = c_uint8(cmd) result = c_uint8() # Build ioctl request. request = make_i2c_rdwr_data( [ (addr, 0, 1, pointer(reg)), # Write cmd register. (addr, I2C_M_RD, 1, pointer(result)), # Read 1 byte as result. ] ) # Make ioctl call and return result data. ioctl(self._device.fileno(), I2C_RDWR, request) return result.value def read_word_data(self, addr, cmd): """Read a word (2 bytes) from the specified cmd register of the device. Note that this will interpret data using the endianness of the processor running Python (typically little endian)! """ assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Build ctypes values to marshall between ioctl and Python. reg = c_uint8(cmd) result = c_uint16() # Build ioctl request. request = make_i2c_rdwr_data( [ (addr, 0, 1, pointer(reg)), # Write cmd register. ( addr, I2C_M_RD, 2, cast(pointer(result), POINTER(c_uint8)), ), # Read word (2 bytes). ] ) # Make ioctl call and return result data. ioctl(self._device.fileno(), I2C_RDWR, request) return result.value def read_block_data(self, addr, cmd): """Perform a block read from the specified cmd register of the device. The amount of data read is determined by the first byte send back by the device. Data is returned as a bytearray. """ # TODO: Unfortunately this will require calling the low level I2C # access ioctl to trigger a proper read_block_data. The amount of data # returned isn't known until the device starts responding so an I2C_RDWR # ioctl won't work. raise NotImplementedError() def read_i2c_block_data(self, addr, cmd, length=32): """Perform a read from the specified cmd register of device. Length number of bytes (default of 32) will be read and returned as a bytearray. """ assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Build ctypes values to marshall between ioctl and Python. # convert register into bytearray if not isinstance(cmd, (bytes, bytearray)): reg = cmd # backup cmd = bytearray(1) cmd[0] = reg cmdstring = create_string_buffer(len(cmd)) for i, val in enumerate(cmd): cmdstring[i] = val result = create_string_buffer(length) # Build ioctl request. request = make_i2c_rdwr_data( [ ( addr, 0, len(cmd), cast(cmdstring, POINTER(c_uint8)), ), # Write cmd register. (addr, I2C_M_RD, length, cast(result, POINTER(c_uint8))), # Read data. ] ) # Make ioctl call and return result data. ioctl(self._device.fileno(), I2C_RDWR, request) return bytearray( result.raw ) # Use .raw instead of .value which will stop at a null byte! def write_quick(self, addr): """Write a single byte to the specified device.""" # What a strange function, from the python-smbus source this appears to # just write a single byte that initiates a write to the specified device # address (but writes no data!). The functionality is duplicated below # but the actual use case for this is unknown. assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Build ioctl request. request = make_i2c_rdwr_data( [ (addr, 0, 0, None), ] ) # Write with no data. # Make ioctl call and return result data. ioctl(self._device.fileno(), I2C_RDWR, request) def write_byte(self, addr, val): """Write a single byte to the specified device.""" assert ( self._device is not None ), "Bus must be opened before operations are made against it!" self._select_device(addr) data = bytearray(1) data[0] = val & 0xFF self._device.write(data) def write_bytes(self, addr, buf): """Write many bytes to the specified device. buf is a bytearray""" assert ( self._device is not None ), "Bus must be opened before operations are made against it!" self._select_device(addr) self._device.write(buf) def write_byte_data(self, addr, cmd, val): """Write a byte of data to the specified cmd register of the device.""" assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Construct a string of data to send with the command register and byte value. data = bytearray(2) data[0] = cmd & 0xFF data[1] = val & 0xFF # Send the data to the device. self._select_device(addr) self._device.write(data) def write_word_data(self, addr, cmd, val): """Write a word (2 bytes) of data to the specified cmd register of the device. Note that this will write the data in the endianness of the processor running Python (typically little endian)! """ assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Construct a string of data to send with the command register and word value. data = struct.pack("=BH", cmd & 0xFF, val & 0xFFFF) # Send the data to the device. self._select_device(addr) self._device.write(data) def write_block_data(self, addr, cmd, vals): """Write a block of data to the specified cmd register of the device. The amount of data to write should be the first byte inside the vals string/bytearray and that count of bytes of data to write should follow it. """ # Just use the I2C block data write to write the provided values and # their length as the first byte. data = bytearray(len(vals) + 1) data[0] = len(vals) & 0xFF data[1:] = vals[0:] self.write_i2c_block_data(addr, cmd, data) def write_i2c_block_data(self, addr, cmd, vals): """Write a buffer of data to the specified cmd register of the device.""" assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Construct a string of data to send, including room for the command register. data = bytearray(len(vals) + 1) data[0] = cmd & 0xFF # Command register at the start. data[1:] = vals[0:] # Copy in the block data (ugly but necessary to ensure # the entire write happens in one transaction). # Send the data to the device. self._select_device(addr) self._device.write(data) def process_call(self, addr, cmd, val): """Perform a smbus process call by writing a word (2 byte) value to the specified register of the device, and then reading a word of response data (which is returned). """ assert ( self._device is not None ), "Bus must be opened before operations are made against it!" # Build ctypes values to marshall between ioctl and Python. data = create_string_buffer(struct.pack("=BH", cmd, val)) result = c_uint16() # Build ioctl request. request = make_i2c_rdwr_data( [ (addr, 0, 3, cast(pointer(data), POINTER(c_uint8))), # Write data. ( addr, I2C_M_RD, 2, cast(pointer(result), POINTER(c_uint8)), ), # Read word (2 bytes). ] ) # Make ioctl call and return result data. ioctl(self._device.fileno(), I2C_RDWR, request) # Note the python-smbus code appears to have a rather serious bug and # does not return the result value! This is fixed below by returning it. return result.value
Adafruit-PureIO
/Adafruit_PureIO-1.1.11.tar.gz/Adafruit_PureIO-1.1.11/Adafruit_PureIO/smbus.py
smbus.py
<!-- SPDX-FileCopyrightText: 2021 Adafruit Industries SPDX-License-Identifier: MIT --> Thank you for opening an issue on an Adafruit Python library repository. To improve the speed of resolution please review the following guidelines and common troubleshooting steps below before creating the issue: - **Do not use GitHub issues for troubleshooting projects and issues.** Instead use the forums at http://forums.adafruit.com to ask questions and troubleshoot why something isn't working as expected. In many cases the problem is a common issue that you will more quickly receive help from the forum community. GitHub issues are meant for known defects in the code. If you don't know if there is a defect in the code then start with troubleshooting on the forum first. - **If following a tutorial or guide be sure you didn't miss a step.** Carefully check all of the steps and commands to run have been followed. Consult the forum if you're unsure or have questions about steps in a guide/tutorial. - **For Python/Raspberry Pi projects check these very common issues to ensure they don't apply**: - If you are receiving an **ImportError: No module named...** error then a library the code depends on is not installed. Check the tutorial/guide or README to ensure you have installed the necessary libraries. Usually the missing library can be installed with the `pip` tool, but check the tutorial/guide for the exact command. - **Be sure you are supplying adequate power to the board.** Check the specs of your board and power in an external power supply. In many cases just plugging a board into your computer is not enough to power it and other peripherals. - **Double check all soldering joints and connections.** Flakey connections cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints. If you're sure this issue is a defect in the code and checked the steps above please fill in the following fields to provide enough troubleshooting information. You may delete the guideline and text above to just leave the following details: - Platform/operating system (i.e. Raspberry Pi with Raspbian operating system, Windows 32-bit, Windows 64-bit, Mac OSX 64-bit, etc.): **INSERT PLATFORM/OPERATING SYSTEM HERE** - Python version (run `python -version` or `python3 -version`): **INSERT PYTHON VERSION HERE** - Error message you are receiving, including any Python exception traces: **INSERT ERROR MESAGE/EXCEPTION TRACES HERE*** - List the steps to reproduce the problem below (if possible attach code or commands to run): **LIST REPRO STEPS BELOW**
Adafruit-PureIO
/Adafruit_PureIO-1.1.11.tar.gz/Adafruit_PureIO-1.1.11/.github/ISSUE_TEMPLATE.md
ISSUE_TEMPLATE.md
<!-- SPDX-FileCopyrightText: 2021 Adafruit Industries SPDX-License-Identifier: MIT --> Thank you for creating a pull request to contribute to Adafruit's GitHub code! Before you open the request please review the following guidelines and tips to help it be more easily integrated: - **Describe the scope of your change--i.e. what the change does and what parts of the code were modified.** This will help us understand any risks of integrating the code. - **Describe any known limitations with your change.** For example if the change doesn't apply to a supported platform of the library please mention it. - **Please run any tests or examples that can exercise your modified code.** We strive to not break users of the code and running tests/examples helps with this process. Thank you again for contributing! We will try to test and integrate the change as soon as we can, but be aware we have many GitHub repositories to manage and can't immediately respond to every request. There is no need to bump or check in on a pull request (it will clutter the discussion of the request). Also don't be worried if the request is closed or not integrated--sometimes the priorities of Adafruit's GitHub code (education, ease of use) might not match the priorities of the pull request. Don't fret, the open source community thrives on forks and GitHub makes it easy to keep your changes in a forked repo. After reviewing the guidelines above you can delete this text from the pull request.
Adafruit-PureIO
/Adafruit_PureIO-1.1.11.tar.gz/Adafruit_PureIO-1.1.11/.github/PULL_REQUEST_TEMPLATE.md
PULL_REQUEST_TEMPLATE.md
# Adafruit_Python_SHT31 This Python driver allows you to read data from the [Adafruit SHT31D Breakout](https://www.adafruit.com/products/2857) on a Raspberry Pi, Pi2 or similar device. ## Requirements This driver requires that you have previously installed the [Adafruit_Python_GPIO](https://github.com/adafruit/Adafruit_Python_GPIO) package. On Raspbian, you can install this package with the following commands: ``` sudo apt-get update sudo apt-get install build-essential python-pip python-dev python-smbus git git clone https://github.com/adafruit/Adafruit_Python_GPIO.git cd Adafruit_Python_GPIO sudo python setup.py install ``` ## Usage To read a single set of data points from the SHT31, connect your Pi or Pi2 to the SHT31D breakout using I2C (connect SCL0/1 to the SCK pin and SCL0/1 to the SDI pin), and run the following command from this folder: ``` python Adafruit_SHT31_Example.py ``` ## Credits This driver is based on the [Adafruit_BME280](https://github.com/adafruit/Adafruit_Python_BME280) driver by Tony DiCola (Adafruit Industries), with BME280 additions kindly provided by David J. Taylor (www.satsignal.eu). Modified for use with SHT31D by Ralf Mueller, (www.bj-ig.de) # MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Adafruit-SHT31
/Adafruit_SHT31-1.0.2.tar.gz/Adafruit_SHT31-1.0.2/README.md
README.md
import logging import time # SHT31D default address. SHT31_I2CADDR = 0x44 # SHT31D Registers SHT31_MEAS_HIGHREP_STRETCH = 0x2C06 SHT31_MEAS_MEDREP_STRETCH = 0x2C0D SHT31_MEAS_LOWREP_STRETCH = 0x2C10 SHT31_MEAS_HIGHREP = 0x2400 SHT31_MEAS_MEDREP = 0x240B SHT31_MEAS_LOWREP = 0x2416 SHT31_READSTATUS = 0xF32D SHT31_CLEARSTATUS = 0x3041 SHT31_SOFTRESET = 0x30A2 SHT31_HEATER_ON = 0x306D SHT31_HEATER_OFF = 0x3066 SHT31_STATUS_DATA_CRC_ERROR = 0x0001 SHT31_STATUS_COMMAND_ERROR = 0x0002 SHT31_STATUS_RESET_DETECTED = 0x0010 SHT31_STATUS_TEMPERATURE_ALERT = 0x0400 SHT31_STATUS_HUMIDITY_ALERT = 0x0800 SHT31_STATUS_HEATER_ACTIVE = 0x2000 SHT31_STATUS_ALERT_PENDING = 0x8000 class SHT31(object): def __init__(self, address=SHT31_I2CADDR, i2c=None, **kwargs): self._logger = logging.getLogger('Adafruit_SHT.SHT31D') # Create I2C device. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._device = i2c.get_i2c_device(address, **kwargs) time.sleep(0.05) # Wait the required time def _writeCommand(self, cmd): self._device.write8(cmd >> 8, cmd & 0xFF) def reset(self): self._writeCommand(SHT31_SOFTRESET) time.sleep(0.01) # Wait the required time def clear_status(self): self._writeCommand(SHT31_CLEARSTATUS); def read_status(self): self._writeCommand(SHT31_READSTATUS); buffer = self._device.readList(0, 3) stat = buffer[0] << 8 | buffer[1] if buffer[2] != self._crc8(buffer[0:2]): return None return stat def is_data_crc_error(self): return bool(self.read_status() & SHT31_STATUS_DATA_CRC_ERROR) def is_command_error(self): return bool(self.read_status() & SHT31_STATUS_COMMAND_ERROR) def is_reset_detected(self): return bool(self.read_status() & SHT31_STATUS_RESET_DETECTED) def is_tracking_temperature_alert(self): return bool(self.read_status() & SHT31_STATUS_TEMPERATURE_ALERT) def is_tracking_humidity_alert(self): return bool(self.read_status() & SHT31_STATUS_HUMIDITY_ALERT) def is_heater_active(self): return bool(self.read_status() & SHT31_STATUS_HEATER_ACTIVE) def is_alert_pending(self): return bool(self.read_status() & SHT31_STATUS_ALERT_PENDING) def set_heater(self, doEnable = True): if doEnable: self._writeCommand(SHT31_HEATER_ON) else: self._writeCommand(SHT31_HEATER_OFF) def read_temperature_humidity(self): self._writeCommand(SHT31_MEAS_HIGHREP) time.sleep(0.015) buffer = self._device.readList(0, 6) if buffer[2] != self._crc8(buffer[0:2]): return (float("nan"), float("nan")) rawTemperature = buffer[0] << 8 | buffer[1] temperature = 175.0 * rawTemperature / 0xFFFF - 45.0 if buffer[5] != self._crc8(buffer[3:5]): return (float("nan"), float("nan")) rawHumidity = buffer[3] << 8 | buffer[4] humidity = 100.0 * rawHumidity / 0xFFFF return (temperature, humidity) def read_temperature(self): (temperature, humidity) = self.read_temperature_humidity() return temperature def read_humidity(self): (temperature, humidity) = self.read_temperature_humidity() return humidity def _crc8(self, buffer): """ Polynomial 0x31 (x8 + x5 +x4 +1) """ polynomial = 0x31; crc = 0xFF; index = 0 for index in range(0, len(buffer)): crc ^= buffer[index] for i in range(8, 0, -1): if crc & 0x80: crc = (crc << 1) ^ polynomial else: crc = (crc << 1) return crc & 0xFF
Adafruit-SHT31
/Adafruit_SHT31-1.0.2.tar.gz/Adafruit_SHT31-1.0.2/Adafruit_SHT31.py
Adafruit_SHT31.py
Adafruit Python SSD1306 ======================= Python library to use SSD1306-based 128x64 or 128x32 pixel OLED displays with a Raspberry Pi or Beaglebone Black. Designed specifically to work with the Adafruit SSD1306-based OLED displays ----> https://www.adafruit.com/categories/98 Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Installing ---------- ``` sudo python -m pip install --upgrade pip setuptools wheel sudo pip install Adafruit-SSD1306 ``` Or alternatively: ``` sudo python -m pip install --upgrade pip setuptools wheel git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git cd Adafruit_Python_SSD1306 sudo python setup.py install ``` Copying ------- Written by Tony DiCola for Adafruit Industries. MIT license, all text above must be included in any redistribution
Adafruit-SSD1306
/Adafruit_SSD1306-1.6.2.tar.gz/Adafruit_SSD1306-1.6.2/README.md
README.md
from __future__ import division import logging import time import Adafruit_GPIO as GPIO import Adafruit_GPIO.SPI as SPI # Constants SSD1306_I2C_ADDRESS = 0x3C # 011110+SA0+RW - 0x3C or 0x3D SSD1306_SETCONTRAST = 0x81 SSD1306_DISPLAYALLON_RESUME = 0xA4 SSD1306_DISPLAYALLON = 0xA5 SSD1306_NORMALDISPLAY = 0xA6 SSD1306_INVERTDISPLAY = 0xA7 SSD1306_DISPLAYOFF = 0xAE SSD1306_DISPLAYON = 0xAF SSD1306_SETDISPLAYOFFSET = 0xD3 SSD1306_SETCOMPINS = 0xDA SSD1306_SETVCOMDETECT = 0xDB SSD1306_SETDISPLAYCLOCKDIV = 0xD5 SSD1306_SETPRECHARGE = 0xD9 SSD1306_SETMULTIPLEX = 0xA8 SSD1306_SETLOWCOLUMN = 0x00 SSD1306_SETHIGHCOLUMN = 0x10 SSD1306_SETSTARTLINE = 0x40 SSD1306_MEMORYMODE = 0x20 SSD1306_COLUMNADDR = 0x21 SSD1306_PAGEADDR = 0x22 SSD1306_COMSCANINC = 0xC0 SSD1306_COMSCANDEC = 0xC8 SSD1306_SEGREMAP = 0xA0 SSD1306_CHARGEPUMP = 0x8D SSD1306_EXTERNALVCC = 0x1 SSD1306_SWITCHCAPVCC = 0x2 # Scrolling constants SSD1306_ACTIVATE_SCROLL = 0x2F SSD1306_DEACTIVATE_SCROLL = 0x2E SSD1306_SET_VERTICAL_SCROLL_AREA = 0xA3 SSD1306_RIGHT_HORIZONTAL_SCROLL = 0x26 SSD1306_LEFT_HORIZONTAL_SCROLL = 0x27 SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29 SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A class SSD1306Base(object): """Base class for SSD1306-based OLED displays. Implementors should subclass and provide an implementation for the _initialize function. """ def __init__(self, width, height, rst, dc=None, sclk=None, din=None, cs=None, gpio=None, spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS, i2c=None): self._log = logging.getLogger('Adafruit_SSD1306.SSD1306Base') self._spi = None self._i2c = None self.width = width self.height = height self._pages = height//8 self._buffer = [0]*(width*self._pages) # Default to platform GPIO if not provided. self._gpio = gpio if self._gpio is None: self._gpio = GPIO.get_platform_gpio() # Setup reset pin. self._rst = rst if not self._rst is None: self._gpio.setup(self._rst, GPIO.OUT) # Handle hardware SPI if spi is not None: self._log.debug('Using hardware SPI') self._spi = spi self._spi.set_clock_hz(8000000) # Handle software SPI elif sclk is not None and din is not None and cs is not None: self._log.debug('Using software SPI') self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs) # Handle hardware I2C elif i2c is not None: self._log.debug('Using hardware I2C with custom I2C provider.') self._i2c = i2c.get_i2c_device(i2c_address) else: self._log.debug('Using hardware I2C with platform I2C provider.') import Adafruit_GPIO.I2C as I2C if i2c_bus is None: self._i2c = I2C.get_i2c_device(i2c_address) else: self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus) # Initialize DC pin if using SPI. if self._spi is not None: if dc is None: raise ValueError('DC pin must be provided when using SPI.') self._dc = dc self._gpio.setup(self._dc, GPIO.OUT) def _initialize(self): raise NotImplementedError def command(self, c): """Send command byte to display.""" if self._spi is not None: # SPI write. self._gpio.set_low(self._dc) self._spi.write([c]) else: # I2C write. control = 0x00 # Co = 0, DC = 0 self._i2c.write8(control, c) def data(self, c): """Send byte of data to display.""" if self._spi is not None: # SPI write. self._gpio.set_high(self._dc) self._spi.write([c]) else: # I2C write. control = 0x40 # Co = 0, DC = 0 self._i2c.write8(control, c) def begin(self, vccstate=SSD1306_SWITCHCAPVCC): """Initialize display.""" # Save vcc state. self._vccstate = vccstate # Reset and initialize display. self.reset() self._initialize() # Turn on the display. self.command(SSD1306_DISPLAYON) def reset(self): """Reset the display.""" if self._rst is None: return # Set reset high for a millisecond. self._gpio.set_high(self._rst) time.sleep(0.001) # Set reset low for 10 milliseconds. self._gpio.set_low(self._rst) time.sleep(0.010) # Set reset high again. self._gpio.set_high(self._rst) def display(self): """Write display buffer to physical display.""" self.command(SSD1306_COLUMNADDR) self.command(0) # Column start address. (0 = reset) self.command(self.width-1) # Column end address. self.command(SSD1306_PAGEADDR) self.command(0) # Page start address. (0 = reset) self.command(self._pages-1) # Page end address. # Write buffer data. if self._spi is not None: # Set DC high for data. self._gpio.set_high(self._dc) # Write buffer. self._spi.write(self._buffer) else: for i in range(0, len(self._buffer), 16): control = 0x40 # Co = 0, DC = 0 self._i2c.writeList(control, self._buffer[i:i+16]) def image(self, image): """Set buffer to value of Python Imaging Library image. The image should be in 1 bit mode and a size equal to the display size. """ if image.mode != '1': raise ValueError('Image must be in mode 1.') imwidth, imheight = image.size if imwidth != self.width or imheight != self.height: raise ValueError('Image must be same dimensions as display ({0}x{1}).' \ .format(self.width, self.height)) # Grab all the pixels from the image, faster than getpixel. pix = image.load() # Iterate through the memory pages index = 0 for page in range(self._pages): # Iterate through all x axis columns. for x in range(self.width): # Set the bits for the column of pixels at the current position. bits = 0 # Don't use range here as it's a bit slow for bit in [0, 1, 2, 3, 4, 5, 6, 7]: bits = bits << 1 bits |= 0 if pix[(x, page*8+7-bit)] == 0 else 1 # Update buffer byte and increment to next byte. self._buffer[index] = bits index += 1 def clear(self): """Clear contents of image buffer.""" self._buffer = [0]*(self.width*self._pages) def set_contrast(self, contrast): """Sets the contrast of the display. Contrast should be a value between 0 and 255.""" if contrast < 0 or contrast > 255: raise ValueError('Contrast must be a value from 0 to 255 (inclusive).') self.command(SSD1306_SETCONTRAST) self.command(contrast) def dim(self, dim): """Adjusts contrast to dim the display if dim is True, otherwise sets the contrast to normal brightness if dim is False. """ # Assume dim display. contrast = 0 # Adjust contrast based on VCC if not dimming. if not dim: if self._vccstate == SSD1306_EXTERNALVCC: contrast = 0x9F else: contrast = 0xCF class SSD1306_128_64(SSD1306Base): def __init__(self, rst, dc=None, sclk=None, din=None, cs=None, gpio=None, spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS, i2c=None): # Call base class constructor. super(SSD1306_128_64, self).__init__(128, 64, rst, dc, sclk, din, cs, gpio, spi, i2c_bus, i2c_address, i2c) def _initialize(self): # 128x64 pixel specific initialization. self.command(SSD1306_DISPLAYOFF) # 0xAE self.command(SSD1306_SETDISPLAYCLOCKDIV) # 0xD5 self.command(0x80) # the suggested ratio 0x80 self.command(SSD1306_SETMULTIPLEX) # 0xA8 self.command(0x3F) self.command(SSD1306_SETDISPLAYOFFSET) # 0xD3 self.command(0x0) # no offset self.command(SSD1306_SETSTARTLINE | 0x0) # line #0 self.command(SSD1306_CHARGEPUMP) # 0x8D if self._vccstate == SSD1306_EXTERNALVCC: self.command(0x10) else: self.command(0x14) self.command(SSD1306_MEMORYMODE) # 0x20 self.command(0x00) # 0x0 act like ks0108 self.command(SSD1306_SEGREMAP | 0x1) self.command(SSD1306_COMSCANDEC) self.command(SSD1306_SETCOMPINS) # 0xDA self.command(0x12) self.command(SSD1306_SETCONTRAST) # 0x81 if self._vccstate == SSD1306_EXTERNALVCC: self.command(0x9F) else: self.command(0xCF) self.command(SSD1306_SETPRECHARGE) # 0xd9 if self._vccstate == SSD1306_EXTERNALVCC: self.command(0x22) else: self.command(0xF1) self.command(SSD1306_SETVCOMDETECT) # 0xDB self.command(0x40) self.command(SSD1306_DISPLAYALLON_RESUME) # 0xA4 self.command(SSD1306_NORMALDISPLAY) # 0xA6 class SSD1306_128_32(SSD1306Base): def __init__(self, rst, dc=None, sclk=None, din=None, cs=None, gpio=None, spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS, i2c=None): # Call base class constructor. super(SSD1306_128_32, self).__init__(128, 32, rst, dc, sclk, din, cs, gpio, spi, i2c_bus, i2c_address, i2c) def _initialize(self): # 128x32 pixel specific initialization. self.command(SSD1306_DISPLAYOFF) # 0xAE self.command(SSD1306_SETDISPLAYCLOCKDIV) # 0xD5 self.command(0x80) # the suggested ratio 0x80 self.command(SSD1306_SETMULTIPLEX) # 0xA8 self.command(0x1F) self.command(SSD1306_SETDISPLAYOFFSET) # 0xD3 self.command(0x0) # no offset self.command(SSD1306_SETSTARTLINE | 0x0) # line #0 self.command(SSD1306_CHARGEPUMP) # 0x8D if self._vccstate == SSD1306_EXTERNALVCC: self.command(0x10) else: self.command(0x14) self.command(SSD1306_MEMORYMODE) # 0x20 self.command(0x00) # 0x0 act like ks0108 self.command(SSD1306_SEGREMAP | 0x1) self.command(SSD1306_COMSCANDEC) self.command(SSD1306_SETCOMPINS) # 0xDA self.command(0x02) self.command(SSD1306_SETCONTRAST) # 0x81 self.command(0x8F) self.command(SSD1306_SETPRECHARGE) # 0xd9 if self._vccstate == SSD1306_EXTERNALVCC: self.command(0x22) else: self.command(0xF1) self.command(SSD1306_SETVCOMDETECT) # 0xDB self.command(0x40) self.command(SSD1306_DISPLAYALLON_RESUME) # 0xA4 self.command(SSD1306_NORMALDISPLAY) # 0xA6 class SSD1306_96_16(SSD1306Base): def __init__(self, rst, dc=None, sclk=None, din=None, cs=None, gpio=None, spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS, i2c=None): # Call base class constructor. super(SSD1306_96_16, self).__init__(96, 16, rst, dc, sclk, din, cs, gpio, spi, i2c_bus, i2c_address, i2c) def _initialize(self): # 128x32 pixel specific initialization. self.command(SSD1306_DISPLAYOFF) # 0xAE self.command(SSD1306_SETDISPLAYCLOCKDIV) # 0xD5 self.command(0x60) # the suggested ratio 0x60 self.command(SSD1306_SETMULTIPLEX) # 0xA8 self.command(0x0F) self.command(SSD1306_SETDISPLAYOFFSET) # 0xD3 self.command(0x0) # no offset self.command(SSD1306_SETSTARTLINE | 0x0) # line #0 self.command(SSD1306_CHARGEPUMP) # 0x8D if self._vccstate == SSD1306_EXTERNALVCC: self.command(0x10) else: self.command(0x14) self.command(SSD1306_MEMORYMODE) # 0x20 self.command(0x00) # 0x0 act like ks0108 self.command(SSD1306_SEGREMAP | 0x1) self.command(SSD1306_COMSCANDEC) self.command(SSD1306_SETCOMPINS) # 0xDA self.command(0x02) self.command(SSD1306_SETCONTRAST) # 0x81 self.command(0x8F) self.command(SSD1306_SETPRECHARGE) # 0xd9 if self._vccstate == SSD1306_EXTERNALVCC: self.command(0x22) else: self.command(0xF1) self.command(SSD1306_SETVCOMDETECT) # 0xDB self.command(0x40) self.command(SSD1306_DISPLAYALLON_RESUME) # 0xA4 self.command(SSD1306_NORMALDISPLAY) # 0xA6
Adafruit-SSD1306
/Adafruit_SSD1306-1.6.2.tar.gz/Adafruit_SSD1306-1.6.2/Adafruit_SSD1306/SSD1306.py
SSD1306.py
# DEPRECATED LIBRARY Adafruit Python TCS34725 This library has been deprecated! We are now only using our CircuitPython sensor libraries in Python. We are leaving the code up for historical/research purposes but archiving the repository. Check out this guide for using the TCS34725 with Python! https://learn.adafruit.com/adafruit-color-sensors/python-circuitpython ---- Python code to use the TCS34725 color sensor with the Raspberry Pi &amp; BeagleBone Black. ## Installation To install the library from source (recommended) run the following commands on a Raspberry Pi or other Debian-based OS system: sudo apt-get install git build-essential python-dev cd ~ git clone https://github.com/adafruit/Adafruit_Python_TCS34725.git cd Adafruit_Python_TCS34725 sudo python setup.py install Alternatively you can install from pip with: sudo pip install adafruit-tcs34725 Note that the pip install method **won't** install the example code.
Adafruit-TCS34725
/Adafruit_TCS34725-1.0.3.tar.gz/Adafruit_TCS34725-1.0.3/README.md
README.md
import time TCS34725_ADDRESS = 0x29 TCS34725_ID = 0x12 # 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 TCS34725_COMMAND_BIT = 0x80 TCS34725_ENABLE = 0x00 TCS34725_ENABLE_AIEN = 0x10 # RGBC Interrupt Enable TCS34725_ENABLE_WEN = 0x08 # Wait enable - Writing 1 activates the wait timer TCS34725_ENABLE_AEN = 0x02 # RGBC Enable - Writing 1 actives the ADC, 0 disables it TCS34725_ENABLE_PON = 0x01 # Power on - Writing 1 activates the internal oscillator, 0 disables it TCS34725_ATIME = 0x01 # Integration time TCS34725_WTIME = 0x03 # Wait time (if TCS34725_ENABLE_WEN is asserted) TCS34725_WTIME_2_4MS = 0xFF # WLONG0 = 2.4ms WLONG1 = 0.029s TCS34725_WTIME_204MS = 0xAB # WLONG0 = 204ms WLONG1 = 2.45s TCS34725_WTIME_614MS = 0x00 # WLONG0 = 614ms WLONG1 = 7.4s TCS34725_AILTL = 0x04 # Clear channel lower interrupt threshold TCS34725_AILTH = 0x05 TCS34725_AIHTL = 0x06 # Clear channel upper interrupt threshold TCS34725_AIHTH = 0x07 TCS34725_PERS = 0x0C # Persistence register - basic SW filtering mechanism for interrupts TCS34725_PERS_NONE = 0b0000 # Every RGBC cycle generates an interrupt TCS34725_PERS_1_CYCLE = 0b0001 # 1 clean channel value outside threshold range generates an interrupt TCS34725_PERS_2_CYCLE = 0b0010 # 2 clean channel values outside threshold range generates an interrupt TCS34725_PERS_3_CYCLE = 0b0011 # 3 clean channel values outside threshold range generates an interrupt TCS34725_PERS_5_CYCLE = 0b0100 # 5 clean channel values outside threshold range generates an interrupt TCS34725_PERS_10_CYCLE = 0b0101 # 10 clean channel values outside threshold range generates an interrupt TCS34725_PERS_15_CYCLE = 0b0110 # 15 clean channel values outside threshold range generates an interrupt TCS34725_PERS_20_CYCLE = 0b0111 # 20 clean channel values outside threshold range generates an interrupt TCS34725_PERS_25_CYCLE = 0b1000 # 25 clean channel values outside threshold range generates an interrupt TCS34725_PERS_30_CYCLE = 0b1001 # 30 clean channel values outside threshold range generates an interrupt TCS34725_PERS_35_CYCLE = 0b1010 # 35 clean channel values outside threshold range generates an interrupt TCS34725_PERS_40_CYCLE = 0b1011 # 40 clean channel values outside threshold range generates an interrupt TCS34725_PERS_45_CYCLE = 0b1100 # 45 clean channel values outside threshold range generates an interrupt TCS34725_PERS_50_CYCLE = 0b1101 # 50 clean channel values outside threshold range generates an interrupt TCS34725_PERS_55_CYCLE = 0b1110 # 55 clean channel values outside threshold range generates an interrupt TCS34725_PERS_60_CYCLE = 0b1111 # 60 clean channel values outside threshold range generates an interrupt TCS34725_CONFIG = 0x0D TCS34725_CONFIG_WLONG = 0x02 # Choose between short and long (12x) wait times via TCS34725_WTIME TCS34725_CONTROL = 0x0F # Set the gain level for the sensor TCS34725_ID = 0x12 # 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 TCS34725_STATUS = 0x13 TCS34725_STATUS_AINT = 0x10 # RGBC Clean channel interrupt TCS34725_STATUS_AVALID = 0x01 # Indicates that the RGBC channels have completed an integration cycle TCS34725_CDATAL = 0x14 # Clear channel data TCS34725_CDATAH = 0x15 TCS34725_RDATAL = 0x16 # Red channel data TCS34725_RDATAH = 0x17 TCS34725_GDATAL = 0x18 # Green channel data TCS34725_GDATAH = 0x19 TCS34725_BDATAL = 0x1A # Blue channel data TCS34725_BDATAH = 0x1B TCS34725_INTEGRATIONTIME_2_4MS = 0xFF # 2.4ms - 1 cycle - Max Count: 1024 TCS34725_INTEGRATIONTIME_24MS = 0xF6 # 24ms - 10 cycles - Max Count: 10240 TCS34725_INTEGRATIONTIME_50MS = 0xEB # 50ms - 20 cycles - Max Count: 20480 TCS34725_INTEGRATIONTIME_101MS = 0xD5 # 101ms - 42 cycles - Max Count: 43008 TCS34725_INTEGRATIONTIME_154MS = 0xC0 # 154ms - 64 cycles - Max Count: 65535 TCS34725_INTEGRATIONTIME_700MS = 0x00 # 700ms - 256 cycles - Max Count: 65535 TCS34725_GAIN_1X = 0x00 # No gain TCS34725_GAIN_4X = 0x01 # 2x gain TCS34725_GAIN_16X = 0x02 # 16x gain TCS34725_GAIN_60X = 0x03 # 60x gain # Lookup table for integration time delays. INTEGRATION_TIME_DELAY = { 0xFF: 0.0024, # 2.4ms - 1 cycle - Max Count: 1024 0xF6: 0.024, # 24ms - 10 cycles - Max Count: 10240 0xEB: 0.050, # 50ms - 20 cycles - Max Count: 20480 0xD5: 0.101, # 101ms - 42 cycles - Max Count: 43008 0xC0: 0.154, # 154ms - 64 cycles - Max Count: 65535 0x00: 0.700 # 700ms - 256 cycles - Max Count: 65535 } # Utility methods: def calculate_color_temperature(r, g, b): """Converts the raw R/G/B values to color temperature in degrees Kelvin.""" # 1. Map RGB values to their XYZ counterparts. # Based on 6500K fluorescent, 3000K fluorescent # and 60W incandescent values for a wide range. # Note: Y = Illuminance or lux X = (-0.14282 * r) + (1.54924 * g) + (-0.95641 * b) Y = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b) Z = (-0.68202 * r) + (0.77073 * g) + ( 0.56332 * b) # Check for divide by 0 (total darkness) and return None. if (X + Y + Z) == 0: return None # 2. Calculate the chromaticity co-ordinates xc = (X) / (X + Y + Z) yc = (Y) / (X + Y + Z) # Check for divide by 0 again and return None. if (0.1858 - yc) == 0: return None # 3. Use McCamy's formula to determine the CCT n = (xc - 0.3320) / (0.1858 - yc) # Calculate the final CCT cct = (449.0 * (n ** 3.0)) + (3525.0 *(n ** 2.0)) + (6823.3 * n) + 5520.33 return int(cct) def calculate_lux(r, g, b): """Converts the raw R/G/B values to luminosity in lux.""" illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b) return int(illuminance) class TCS34725(object): """TCS34725 color sensor.""" def __init__(self, integration_time=TCS34725_INTEGRATIONTIME_2_4MS, gain=TCS34725_GAIN_4X, address=TCS34725_ADDRESS, i2c=None, **kwargs): """Initialize the TCS34725 sensor.""" # Setup I2C interface for the device. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._device = i2c.get_i2c_device(address, **kwargs) # Make sure we're connected to the sensor. chip_id = self._readU8(TCS34725_ID) if chip_id != 0x44: raise RuntimeError('Failed to read TCS34725 chip ID, check your wiring.') # Set default integration time and gain. self.set_integration_time(integration_time) self.set_gain(gain) # Enable the device (by default, the device is in power down mode on bootup). self.enable() def _readU8(self, reg): """Read an unsigned 8-bit register.""" return self._device.readU8(TCS34725_COMMAND_BIT | reg) def _readU16LE(self, reg): """Read a 16-bit little endian register.""" return self._device.readU16LE(TCS34725_COMMAND_BIT | reg) def _write8(self, reg, value): """Write a 8-bit value to a register.""" self._device.write8(TCS34725_COMMAND_BIT | reg, value) def enable(self): """Enable the chip.""" # Flip on the power and enable bits. self._write8(TCS34725_ENABLE, TCS34725_ENABLE_PON) time.sleep(0.01) self._write8(TCS34725_ENABLE, (TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN)) def disable(self): """Disable the chip (power down).""" # Flip off the power on and enable bits. reg = self._readU8(TCS34725_ENABLE) reg &= ~(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN) self._write8(TCS34725_ENABLE, reg) def set_integration_time(self, integration_time): """Sets the integration time for the TC34725. Provide one of these constants: - TCS34725_INTEGRATIONTIME_2_4MS = 2.4ms - 1 cycle - Max Count: 1024 - TCS34725_INTEGRATIONTIME_24MS = 24ms - 10 cycles - Max Count: 10240 - TCS34725_INTEGRATIONTIME_50MS = 50ms - 20 cycles - Max Count: 20480 - TCS34725_INTEGRATIONTIME_101MS = 101ms - 42 cycles - Max Count: 43008 - TCS34725_INTEGRATIONTIME_154MS = 154ms - 64 cycles - Max Count: 65535 - TCS34725_INTEGRATIONTIME_700MS = 700ms - 256 cycles - Max Count: 65535 """ self._integration_time = integration_time self._write8(TCS34725_ATIME, integration_time) def get_integration_time(self): """Return the current integration time value. This will be one of the constants specified in the set_integration_time doc string. """ return self._readU8(TCS34725_ATIME) def set_gain(self, gain): """Adjusts the gain on the TCS34725 (adjusts the sensitivity to light). Use one of the following constants: - TCS34725_GAIN_1X = No gain - TCS34725_GAIN_4X = 2x gain - TCS34725_GAIN_16X = 16x gain - TCS34725_GAIN_60X = 60x gain """ self._write8(TCS34725_CONTROL, gain) def get_gain(self): """Return the current gain value. This will be one of the constants specified in the set_gain doc string. """ return self._readU8(TCS34725_CONTROL) def get_raw_data(self): """Reads the raw red, green, blue and clear channel values. Will return a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit numbers). """ # Read each color register. r = self._readU16LE(TCS34725_RDATAL) g = self._readU16LE(TCS34725_GDATAL) b = self._readU16LE(TCS34725_BDATAL) c = self._readU16LE(TCS34725_CDATAL) # Delay for the integration time to allow for next reading immediately. time.sleep(INTEGRATION_TIME_DELAY[self._integration_time]) return (r, g, b, c) def set_interrupt(self, enabled): """Enable or disable interrupts by setting enabled to True or False.""" enable_reg = self._readU8(TCS34725_ENABLE) if enabled: enable_reg |= TCS34725_ENABLE_AIEN else: enable_reg &= ~TCS34725_ENABLE_AIEN self._write8(TCS34725_ENABLE, enable_reg) time.sleep(1) def clear_interrupt(self): """Clear interrupt.""" self._device.write8(0x66 & 0xff) def set_interrupt_limits(self, low, high): """Set the interrupt limits to provied unsigned 16-bit threshold values. """ self._device.write8(0x04, low & 0xFF) self._device.write8(0x05, low >> 8) self._device.write8(0x06, high & 0xFF) self._device.write8(0x07, high >> 8)
Adafruit-TCS34725
/Adafruit_TCS34725-1.0.3.tar.gz/Adafruit_TCS34725-1.0.3/Adafruit_TCS34725/TCS34725.py
TCS34725.py
DEPRECATED LIBRARY Adafruit Python TMP006 =================== This library has been deprecated! the tmp006 and tmp007 are no longer made, and we are now only using our circuitpython sensor libraries in python we are leaving the code up for historical/research purposes but archiving the repository. if you happen to have one, check out this guide for using the tmp007 with python! https://learn.adafruit.com/adafruit-tmp007-sensor-breakout # Python library for accessing the TMP006 & TMP007 non-contact temperature sensor on a Raspberry Pi or Beaglebone Black. Designed specifically to work with the Adafruit TMP006 sensor ----> https://www.adafruit.com/products/1296 To install, first make sure some dependencies are available by running the following commands (on a Raspbian or Beaglebone Black Debian install): ```` sudo apt-get update sudo apt-get install build-essential python-dev python-smbus ```` Then download the library by clicking the download zip link to the right and unzip the archive somewhere on your Raspberry Pi or Beaglebone Black. Then execute the following command in the directory of the library: ```` sudo python setup.py install ```` Make sure you have internet access on the device so it can download the required dependencies. See examples of usage in the examples folder. Note that the example code and classes use the TMP006 name but will work fine with a TMP007 sensor too. Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Tony DiCola for Adafruit Industries. MIT license, all text above must be included in any redistribution
Adafruit-TMP
/Adafruit_TMP-1.6.3.tar.gz/Adafruit_TMP-1.6.3/README.md
README.md
import logging import math # Coefficient values, found from this whitepaper: # http://www.ti.com/lit/ug/sbou107/sbou107.pdf TMP006_B0 = -0.0000294 TMP006_B1 = -0.00000057 TMP006_B2 = 0.00000000463 TMP006_C2 = 13.4 TMP006_TREF = 298.15 TMP006_A2 = -0.00001678 TMP006_A1 = 0.00175 TMP006_S0 = 6.4 # * 10^-14 # Default device I2C address. TMP006_I2CADDR = 0x40 # Register addresses. TMP006_CONFIG = 0x02 TMP006_MANID = 0xFE TMP006_DEVID = 0xFF TMP006_VOBJ = 0x0 TMP006_TAMB = 0x01 # Config register values. TMP006_CFG_RESET = 0x8000 TMP006_CFG_MODEON = 0x7000 CFG_1SAMPLE = 0x0000 CFG_2SAMPLE = 0x0200 CFG_4SAMPLE = 0x0400 CFG_8SAMPLE = 0x0600 CFG_16SAMPLE = 0x0800 TMP006_CFG_DRDYEN = 0x0100 TMP006_CFG_DRDY = 0x0080 class TMP006(object): """Class to represent an Adafruit TMP006 non-contact temperature measurement board. """ def __init__(self, address=TMP006_I2CADDR, i2c=None, **kwargs): """Initialize TMP006 device on the specified I2C address and bus number. Address defaults to 0x40 and bus number defaults to the appropriate bus for the hardware. """ self._logger = logging.getLogger('Adafruit_TMP.TMP006') if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._device = i2c.get_i2c_device(address, **kwargs) def begin(self, samplerate=CFG_16SAMPLE): """Start taking temperature measurements. Samplerate can be one of TMP006_CFG_1SAMPLE, TMP006_CFG_2SAMPLE, TMP006_CFG_4SAMPLE, TMP006_CFG_8SAMPLE, or TMP006_CFG_16SAMPLE. The default is 16 samples for the highest resolution. Returns True if the device is intialized, False otherwise. """ if samplerate not in (CFG_1SAMPLE, CFG_2SAMPLE, CFG_4SAMPLE, CFG_8SAMPLE, CFG_16SAMPLE): raise ValueError('Unexpected samplerate value! Must be one of: ' \ 'CFG_1SAMPLE, CFG_2SAMPLE, CFG_4SAMPLE, CFG_8SAMPLE, or CFG_16SAMPLE') self._logger.debug('Using samplerate value: {0:04X}'.format(samplerate)) # Set configuration register to turn on chip, enable data ready output, # and start sampling at the specified rate. config = TMP006_CFG_MODEON | TMP006_CFG_DRDYEN | samplerate # Flip byte order of config value because write16 uses little endian but we # need big endian here. This is an ugly hack for now, better to add support # in write16 for explicit endians. config = ((config & 0xFF) << 8) | (config >> 8) self._device.write16(TMP006_CONFIG, config) # Check manufacturer and device ID match expected values. mid = self._device.readU16BE(TMP006_MANID) did = self._device.readU16BE(TMP006_DEVID) self._logger.debug('Read manufacturer ID: {0:04X}'.format(mid)) self._logger.debug('Read device ID: {0:04X}'.format(did)) return mid == 0x5449 and did == 0x0067 def sleep(self): """Put TMP006 into low power sleep mode. No measurement data will be updated while in sleep mode. """ control = self._device.readU16BE(TMP006_CONFIG) control &= ~(TMP006_CFG_MODEON) self._device.write16(TMP006_CONFIG, control) self._logger.debug('TMP006 entered sleep mode.') def wake(self): """Wake up TMP006 from low power sleep mode.""" control = self._device.readU16BE(TMP006_CONFIG) control |= TMP006_CFG_MODEON self._device.write16(TMP006_CONFIG, control) self._logger.debug('TMP006 woke from sleep mode.') def readRawVoltage(self): """Read raw voltage from TMP006 sensor. Meant to be used in the calculation of temperature values. """ raw = self._device.readS16BE(TMP006_VOBJ) self._logger.debug('Raw voltage: 0x{0:04X} ({1:0.4F} uV)'.format(raw & 0xFFFF, raw * 156.25 / 1000.0)) return raw def readRawDieTemperature(self): """Read raw die temperature from TMP006 sensor. Meant to be used in the calculation of temperature values. """ raw = self._device.readS16BE(TMP006_TAMB) self._logger.debug('Raw temperature: 0x{0:04X} ({1:0.4F} *C)'.format(raw & 0xFFFF, raw / 4.0 * 0.03125)) return raw >> 2 def readDieTempC(self): """Read sensor die temperature and return its value in degrees celsius.""" Tdie = self.readRawDieTemperature() return Tdie * 0.03125 def readObjTempC(self): """Read sensor object temperature (i.e. temperature of item in front of the sensor) and return its value in degrees celsius.""" # Read raw values and scale them to required units. Tdie = self.readRawDieTemperature() Vobj = self.readRawVoltage() Vobj *= 156.25 # 156.25 nV per bit self._logger.debug('Vobj = {0:0.4} nV'.format(Vobj)) Vobj /= 1000000000.0 # Convert nV to volts Tdie *= 0.03125 # Convert to celsius Tdie += 273.14 # Convert to kelvin self._logger.debug('Tdie = {0:0.4} K'.format(Tdie)) # Compute object temperature following equations from: # http://www.ti.com/lit/ug/sbou107/sbou107.pdf Tdie_ref = Tdie - TMP006_TREF S = 1.0 + TMP006_A1*Tdie_ref + TMP006_A2*math.pow(Tdie_ref, 2.0) S *= TMP006_S0 S /= 10000000.0 S /= 10000000.0 Vos = TMP006_B0 + TMP006_B1*Tdie_ref + TMP006_B2*math.pow(Tdie_ref, 2.0) fVobj = (Vobj - Vos) + TMP006_C2*math.pow((Vobj - Vos), 2.0) Tobj = math.sqrt(math.sqrt(math.pow(Tdie, 4.0) + (fVobj/S))) return Tobj - 273.15
Adafruit-TMP
/Adafruit_TMP-1.6.3.tar.gz/Adafruit_TMP-1.6.3/Adafruit_TMP/TMP006.py
TMP006.py
# This is pretty much a 1:1 direct Python port of the Adafruit_Thermal # library for Arduino. All methods use the same naming conventions as the # Arduino library, with only slight changes in parameter behavior where # needed. This should simplify porting existing Adafruit_Thermal-based # printer projects to Raspberry Pi, BeagleBone, etc. See printertest.py # for an example. # # One significant change is the addition of the printImage() function, # which ties this to the Python Imaging Library and opens the door to a # lot of cool graphical stuff! # # TO DO: # - Might use standard ConfigParser library to put thermal calibration # settings in a global configuration file (rather than in the library). # - Make this use proper Python library installation procedure. # - Trap errors properly. Some stuff just falls through right now. # - Add docstrings throughout! # Python 2.X code using the library usu. needs to include the next line: from __future__ import print_function from serial import Serial import time import sys class Adafruit_Thermal(Serial): resumeTime = 0.0 byteTime = 0.0 dotPrintTime = 0.0 dotFeedTime = 0.0 prevByte = '\n' column = 0 maxColumn = 32 charHeight = 24 lineSpacing = 8 barcodeHeight = 50 printMode = 0 defaultHeatTime = 120 firmwareVersion = 268 writeToStdout = False def __init__(self, *args, **kwargs): # NEW BEHAVIOR: if no parameters given, output is written # to stdout, to be piped through 'lp -o raw' (old behavior # was to use default port & baud rate). baudrate = 19200 if len(args) == 0: self.writeToStdout = True if len(args) == 1: # If only port is passed, use default baud rate. args = [ args[0], baudrate ] elif len(args) == 2: # If both passed, use those values. baudrate = args[1] # Firmware is assumed version 2.68. Can override this # with the 'firmware=X' argument, where X is the major # version number * 100 + the minor version number (e.g. # pass "firmware=264" for version 2.64. self.firmwareVersion = kwargs.get('firmware', 268) if self.writeToStdout is False: # Calculate time to issue one byte to the printer. # 11 bits (not 8) to accommodate idle, start and # stop bits. Idle time might be unnecessary, but # erring on side of caution here. self.byteTime = 11.0 / float(baudrate) Serial.__init__(self, *args, **kwargs) # Remainder of this method was previously in begin() # The printer can't start receiving data immediately # upon power up -- it needs a moment to cold boot # and initialize. Allow at least 1/2 sec of uptime # before printer can receive data. self.timeoutSet(0.5) self.wake() self.reset() # Description of print settings from p. 23 of manual: # ESC 7 n1 n2 n3 Setting Control Parameter Command # Decimal: 27 55 n1 n2 n3 # max heating dots, heating time, heating interval # n1 = 0-255 Max heat dots, Unit (8dots), Default: 7 (64 dots) # n2 = 3-255 Heating time, Unit (10us), Default: 80 (800us) # n3 = 0-255 Heating interval, Unit (10us), Default: 2 (20us) # The more max heating dots, the more peak current # will cost when printing, the faster printing speed. # The max heating dots is 8*(n1+1). The more heating # time, the more density, but the slower printing # speed. If heating time is too short, blank page # may occur. The more heating interval, the more # clear, but the slower printing speed. heatTime = kwargs.get('heattime', self.defaultHeatTime) self.writeBytes( 27, # Esc 55, # 7 (print settings) 11, # Heat dots heatTime, # Lib default 40) # Heat interval # Description of print density from p. 23 of manual: # DC2 # n Set printing density # Decimal: 18 35 n # D4..D0 of n is used to set the printing density. # Density is 50% + 5% * n(D4-D0) printing density. # D7..D5 of n is used to set the printing break time. # Break time is n(D7-D5)*250us. # (Unsure of default values -- not documented) printDensity = 10 # 100% printBreakTime = 2 # 500 uS self.writeBytes( 18, # DC2 35, # Print density (printBreakTime << 5) | printDensity) self.dotPrintTime = 0.03 self.dotFeedTime = 0.0021 else: self.reset() # Inits some vars # Because there's no flow control between the printer and computer, # special care must be taken to avoid overrunning the printer's # buffer. Serial output is throttled based on serial speed as well # as an estimate of the device's print and feed rates (relatively # slow, being bound to moving parts and physical reality). After # an operation is issued to the printer (e.g. bitmap print), a # timeout is set before which any other printer operations will be # suspended. This is generally more efficient than using a delay # in that it allows the calling code to continue with other duties # (e.g. receiving or decoding an image) while the printer # physically completes the task. # Sets estimated completion time for a just-issued task. def timeoutSet(self, x): self.resumeTime = time.time() + x # Waits (if necessary) for the prior task to complete. def timeoutWait(self): if self.writeToStdout is False: while (time.time() - self.resumeTime) < 0: pass # Printer performance may vary based on the power supply voltage, # thickness of paper, phase of the moon and other seemingly random # variables. This method sets the times (in microseconds) for the # paper to advance one vertical 'dot' when printing and feeding. # For example, in the default initialized state, normal-sized text # is 24 dots tall and the line spacing is 32 dots, so the time for # one line to be issued is approximately 24 * print time + 8 * feed # time. The default print and feed times are based on a random # test unit, but as stated above your reality may be influenced by # many factors. This lets you tweak the timing to avoid excessive # delays and/or overrunning the printer buffer. def setTimes(self, p, f): # Units are in microseconds for # compatibility with Arduino library self.dotPrintTime = p / 1000000.0 self.dotFeedTime = f / 1000000.0 # 'Raw' byte-writing method def writeBytes(self, *args): if self.writeToStdout: for arg in args: sys.stdout.write(chr(arg)) else: self.timeoutWait() self.timeoutSet(len(args) * self.byteTime) for arg in args: super(Adafruit_Thermal, self).write(chr(arg)) # Override write() method to keep track of paper feed. def write(self, *data): for i in range(len(data)): c = data[i] if self.writeToStdout: sys.stdout.write(c) continue if c != 0x13: self.timeoutWait() super(Adafruit_Thermal, self).write(c) d = self.byteTime if ((c == '\n') or (self.column == self.maxColumn)): # Newline or wrap if self.prevByte == '\n': # Feed line (blank) d += ((self.charHeight + self.lineSpacing) * self.dotFeedTime) else: # Text line d += ((self.charHeight * self.dotPrintTime) + (self.lineSpacing * self.dotFeedTime)) self.column = 0 # Treat wrap as newline # on next pass c = '\n' else: self.column += 1 self.timeoutSet(d) self.prevByte = c # The bulk of this method was moved into __init__, # but this is left here for compatibility with older # code that might get ported directly from Arduino. def begin(self, heatTime=defaultHeatTime): self.writeBytes( 27, # Esc 55, # 7 (print settings) 11, # Heat dots heatTime, 40) # Heat interval def reset(self): self.writeBytes(27, 64) # Esc @ = init command self.prevByte = '\n' # Treat as if prior line is blank self.column = 0 self.maxColumn = 32 self.charHeight = 24 self.lineSpacing = 6 self.barcodeHeight = 50 if self.firmwareVersion >= 264: # Configure tab stops on recent printers self.writeBytes(27, 68) # Set tab stops self.writeBytes( 4, 8, 12, 16) # every 4 columns, self.writeBytes(20, 24, 28, 0) # 0 is end-of-list. # Reset text formatting parameters. def setDefault(self): self.online() self.justify('L') self.inverseOff() self.doubleHeightOff() self.setLineHeight(30) self.boldOff() self.underlineOff() self.setBarcodeHeight(50) self.setSize('s') self.setCharset() self.setCodePage() def test(self): self.write("Hello world!") self.feed(2) def testPage(self): self.writeBytes(18, 84) self.timeoutSet( self.dotPrintTime * 24 * 26 + self.dotFeedTime * (6 * 26 + 30)) def setBarcodeHeight(self, val=50): if val < 1: val = 1 self.barcodeHeight = val self.writeBytes(29, 104, val) UPC_A = 0 UPC_E = 1 EAN13 = 2 EAN8 = 3 CODE39 = 4 I25 = 5 CODEBAR = 6 CODE93 = 7 CODE128 = 8 CODE11 = 9 MSI = 10 ITF = 11 CODABAR = 12 def printBarcode(self, text, type): newDict = { # UPC codes & values for firmwareVersion >= 264 self.UPC_A : 65, self.UPC_E : 66, self.EAN13 : 67, self.EAN8 : 68, self.CODE39 : 69, self.ITF : 70, self.CODABAR : 71, self.CODE93 : 72, self.CODE128 : 73, self.I25 : -1, # NOT IN NEW FIRMWARE self.CODEBAR : -1, self.CODE11 : -1, self.MSI : -1 } oldDict = { # UPC codes & values for firmwareVersion < 264 self.UPC_A : 0, self.UPC_E : 1, self.EAN13 : 2, self.EAN8 : 3, self.CODE39 : 4, self.I25 : 5, self.CODEBAR : 6, self.CODE93 : 7, self.CODE128 : 8, self.CODE11 : 9, self.MSI : 10, self.ITF : -1, # NOT IN OLD FIRMWARE self.CODABAR : -1 } if self.firmwareVersion >= 264: n = newDict[type] else: n = oldDict[type] if n == -1: return self.feed(1) # Recent firmware requires this? self.writeBytes( 29, 72, 2, # Print label below barcode 29, 119, 3, # Barcode width 29, 107, n) # Barcode type self.timeoutWait() self.timeoutSet((self.barcodeHeight + 40) * self.dotPrintTime) # Print string if self.firmwareVersion >= 264: # Recent firmware: write length byte + string sans NUL n = len(text) if n > 255: n = 255 if self.writeToStdout: sys.stdout.write(chr(n)) for i in range(n): sys.stdout.write(text[i]) else: super(Adafruit_Thermal, self).write(chr(n)) for i in range(n): super(Adafruit_Thermal, self).write(text[i]) else: # Older firmware: write string + NUL if self.writeToStdout: sys.stdout.write(text) else: super(Adafruit_Thermal, self).write(text) self.prevByte = '\n' # === Character commands === INVERSE_MASK = (1 << 1) # Not in 2.6.8 firmware (see inverseOn()) UPDOWN_MASK = (1 << 2) BOLD_MASK = (1 << 3) DOUBLE_HEIGHT_MASK = (1 << 4) DOUBLE_WIDTH_MASK = (1 << 5) STRIKE_MASK = (1 << 6) def setPrintMode(self, mask): self.printMode |= mask self.writePrintMode() if self.printMode & self.DOUBLE_HEIGHT_MASK: self.charHeight = 48 else: self.charHeight = 24 if self.printMode & self.DOUBLE_WIDTH_MASK: self.maxColumn = 16 else: self.maxColumn = 32 def unsetPrintMode(self, mask): self.printMode &= ~mask self.writePrintMode() if self.printMode & self.DOUBLE_HEIGHT_MASK: self.charHeight = 48 else: self.charHeight = 24 if self.printMode & self.DOUBLE_WIDTH_MASK: self.maxColumn = 16 else: self.maxColumn = 32 def writePrintMode(self): self.writeBytes(27, 33, self.printMode) def normal(self): self.printMode = 0 self.writePrintMode() def inverseOn(self): if self.firmwareVersion >= 268: self.writeBytes(29, 66, 1) else: self.setPrintMode(self.INVERSE_MASK) def inverseOff(self): if self.firmwareVersion >= 268: self.writeBytes(29, 66, 0) else: self.unsetPrintMode(self.INVERSE_MASK) def upsideDownOn(self): self.setPrintMode(self.UPDOWN_MASK) def upsideDownOff(self): self.unsetPrintMode(self.UPDOWN_MASK) def doubleHeightOn(self): self.setPrintMode(self.DOUBLE_HEIGHT_MASK) def doubleHeightOff(self): self.unsetPrintMode(self.DOUBLE_HEIGHT_MASK) def doubleWidthOn(self): self.setPrintMode(self.DOUBLE_WIDTH_MASK) def doubleWidthOff(self): self.unsetPrintMode(self.DOUBLE_WIDTH_MASK) def strikeOn(self): self.setPrintMode(self.STRIKE_MASK) def strikeOff(self): self.unsetPrintMode(self.STRIKE_MASK) def boldOn(self): self.setPrintMode(self.BOLD_MASK) def boldOff(self): self.unsetPrintMode(self.BOLD_MASK) def justify(self, value): c = value.upper() if c == 'C': pos = 1 elif c == 'R': pos = 2 else: pos = 0 self.writeBytes(0x1B, 0x61, pos) # Feeds by the specified number of lines def feed(self, x=1): if self.firmwareVersion >= 264: self.writeBytes(27, 100, x) self.timeoutSet(self.dotFeedTime * self.charHeight) self.prevByte = '\n' self.column = 0 else: # datasheet claims sending bytes 27, 100, <x> works, # but it feeds much more than that. So, manually: while x > 0: self.write('\n') x -= 1 # Feeds by the specified number of individual pixel rows def feedRows(self, rows): self.writeBytes(27, 74, rows) self.timeoutSet(rows * dotFeedTime) self.prevByte = '\n' self.column = 0 def flush(self): self.writeBytes(12) # ASCII FF def setSize(self, value): c = value.upper() if c == 'L': # Large: double width and height size = 0x11 self.charHeight = 48 self.maxColumn = 16 elif c == 'M': # Medium: double height size = 0x01 self.charHeight = 48 self.maxColumn = 32 else: # Small: standard width and height size = 0x00 self.charHeight = 24 self.maxColumn = 32 self.writeBytes(29, 33, size) prevByte = '\n' # Setting the size adds a linefeed # Underlines of different weights can be produced: # 0 - no underline # 1 - normal underline # 2 - thick underline def underlineOn(self, weight=1): if weight > 2: weight = 2 self.writeBytes(27, 45, weight) def underlineOff(self): self.writeBytes(27, 45, 0) def printBitmap(self, w, h, bitmap, LaaT=False): rowBytes = (w + 7) / 8 # Round up to next byte boundary if rowBytes >= 48: rowBytesClipped = 48 # 384 pixels max width else: rowBytesClipped = rowBytes # if LaaT (line-at-a-time) is True, print bitmaps # scanline-at-a-time (rather than in chunks). # This tends to make for much cleaner printing # (no feed gaps) on large images...but has the # opposite effect on small images that would fit # in a single 'chunk', so use carefully! if LaaT: maxChunkHeight = 1 else: maxChunkHeight = 255 i = 0 for rowStart in range(0, h, maxChunkHeight): chunkHeight = h - rowStart if chunkHeight > maxChunkHeight: chunkHeight = maxChunkHeight # Timeout wait happens here self.writeBytes(18, 42, chunkHeight, rowBytesClipped) for y in range(chunkHeight): for x in range(rowBytesClipped): if self.writeToStdout: sys.stdout.write( chr(bitmap[i])) else: super(Adafruit_Thermal, self).write(chr(bitmap[i])) i += 1 i += rowBytes - rowBytesClipped self.timeoutSet(chunkHeight * self.dotPrintTime) self.prevByte = '\n' # Print Image. Requires Python Imaging Library. This is # specific to the Python port and not present in the Arduino # library. Image will be cropped to 384 pixels width if # necessary, and converted to 1-bit w/diffusion dithering. # For any other behavior (scale, B&W threshold, etc.), use # the Imaging Library to perform such operations before # passing the result to this function. def printImage(self, image, LaaT=False): from PIL import Image if image.mode != '1': image = image.convert('1') width = image.size[0] height = image.size[1] if width > 384: width = 384 rowBytes = (width + 7) / 8 bitmap = bytearray(rowBytes * height) pixels = image.load() for y in range(height): n = y * rowBytes x = 0 for b in range(rowBytes): sum = 0 bit = 128 while bit > 0: if x >= width: break if pixels[x, y] == 0: sum |= bit x += 1 bit >>= 1 bitmap[n + b] = sum self.printBitmap(width, height, bitmap, LaaT) # Take the printer offline. Print commands sent after this # will be ignored until 'online' is called. def offline(self): self.writeBytes(27, 61, 0) # Take the printer online. Subsequent print commands will be obeyed. def online(self): self.writeBytes(27, 61, 1) # Put the printer into a low-energy state immediately. def sleep(self): self.sleepAfter(1) # Can't be 0, that means "don't sleep" # Put the printer into a low-energy state after # the given number of seconds. def sleepAfter(self, seconds): if self.firmwareVersion >= 264: self.writeBytes(27, 56, seconds & 0xFF, seconds >> 8) else: self.writeBytes(27, 56, seconds) def wake(self): self.timeoutSet(0) self.writeBytes(255) if self.firmwareVersion >= 264: time.sleep(0.05) # 50 ms self.writeBytes(27, 118, 0) # Sleep off (important!) else: for i in range(10): self.writeBytes(27) self.timeoutSet(0.1) # Empty method, included for compatibility # with existing code ported from Arduino. def listen(self): pass # Check the status of the paper using the printers self reporting # ability. Doesn't match the datasheet... # Returns True for paper, False for no paper. def hasPaper(self): if self.firmwareVersion >= 264: self.writeBytes(27, 118, 0) else: self.writeBytes(29, 114, 0) # Bit 2 of response seems to be paper status stat = ord(self.read(1)) & 0b00000100 # If set, we have paper; if clear, no paper return stat == 0 def setLineHeight(self, val=32): if val < 24: val = 24 self.lineSpacing = val - 24 # The printer doesn't take into account the current text # height when setting line height, making this more akin # to inter-line spacing. Default line spacing is 32 # (char height of 24, line spacing of 8). self.writeBytes(27, 51, val) CHARSET_USA = 0 CHARSET_FRANCE = 1 CHARSET_GERMANY = 2 CHARSET_UK = 3 CHARSET_DENMARK1 = 4 CHARSET_SWEDEN = 5 CHARSET_ITALY = 6 CHARSET_SPAIN1 = 7 CHARSET_JAPAN = 8 CHARSET_NORWAY = 9 CHARSET_DENMARK2 = 10 CHARSET_SPAIN2 = 11 CHARSET_LATINAMERICA = 12 CHARSET_KOREA = 13 CHARSET_SLOVENIA = 14 CHARSET_CROATIA = 14 CHARSET_CHINA = 15 # Alters some chars in ASCII 0x23-0x7E range; see datasheet def setCharset(self, val=0): if val > 15: val = 15 self.writeBytes(27, 82, val) CODEPAGE_CP437 = 0 # USA, Standard Europe CODEPAGE_KATAKANA = 1 CODEPAGE_CP850 = 2 # Multilingual CODEPAGE_CP860 = 3 # Portuguese CODEPAGE_CP863 = 4 # Canadian-French CODEPAGE_CP865 = 5 # Nordic CODEPAGE_WCP1251 = 6 # Cyrillic CODEPAGE_CP866 = 7 # Cyrillic #2 CODEPAGE_MIK = 8 # Cyrillic/Bulgarian CODEPAGE_CP755 = 9 # East Europe, Latvian 2 CODEPAGE_IRAN = 10 CODEPAGE_CP862 = 15 # Hebrew CODEPAGE_WCP1252 = 16 # Latin 1 CODEPAGE_WCP1253 = 17 # Greek CODEPAGE_CP852 = 18 # Latin 2 CODEPAGE_CP858 = 19 # Multilingual Latin 1 + Euro CODEPAGE_IRAN2 = 20 CODEPAGE_LATVIAN = 21 CODEPAGE_CP864 = 22 # Arabic CODEPAGE_ISO_8859_1 = 23 # West Europe CODEPAGE_CP737 = 24 # Greek CODEPAGE_WCP1257 = 25 # Baltic CODEPAGE_THAI = 26 CODEPAGE_CP720 = 27 # Arabic CODEPAGE_CP855 = 28 CODEPAGE_CP857 = 29 # Turkish CODEPAGE_WCP1250 = 30 # Central Europe CODEPAGE_CP775 = 31 CODEPAGE_WCP1254 = 32 # Turkish CODEPAGE_WCP1255 = 33 # Hebrew CODEPAGE_WCP1256 = 34 # Arabic CODEPAGE_WCP1258 = 35 # Vietnam CODEPAGE_ISO_8859_2 = 36 # Latin 2 CODEPAGE_ISO_8859_3 = 37 # Latin 3 CODEPAGE_ISO_8859_4 = 38 # Baltic CODEPAGE_ISO_8859_5 = 39 # Cyrillic CODEPAGE_ISO_8859_6 = 40 # Arabic CODEPAGE_ISO_8859_7 = 41 # Greek CODEPAGE_ISO_8859_8 = 42 # Hebrew CODEPAGE_ISO_8859_9 = 43 # Turkish CODEPAGE_ISO_8859_15 = 44 # Latin 3 CODEPAGE_THAI2 = 45 CODEPAGE_CP856 = 46 CODEPAGE_CP874 = 47 # Selects alt symbols for 'upper' ASCII values 0x80-0xFF def setCodePage(self, val=0): if val > 47: val = 47 self.writeBytes(27, 116, val) # Copied from Arduino lib for parity; may not work on all printers def tab(self): self.writeBytes(9) self.column = (self.column + 4) & 0xFC # Copied from Arduino lib for parity; may not work on all printers def setCharSpacing(self, spacing): self.writeBytes(27, 32, spacing) # Overloading print() in Python pre-3.0 is dirty pool, # but these are here to provide more direct compatibility # with existing code written for the Arduino library. def print(self, *args, **kwargs): for arg in args: self.write(str(arg)) # For Arduino code compatibility again def println(self, *args, **kwargs): for arg in args: self.write(str(arg)) self.write('\n')
Adafruit-Thermal
/Adafruit_Thermal-1.1.0.tar.gz/Adafruit_Thermal-1.1.0/Adafruit_Thermal/Adafruit_Thermal.py
Adafruit_Thermal.py
DEPRECATED LIBRARY Adafruit Python VCNL40xx =================== This library has been deprecated! we are now only using our circuitpython sensor libraries in python, they work great and are easier to maintain we are leaving the code up for historical/research purposes but archiving the repository. check out this guide for using the vcnl4010 with python! https://learn.adafruit.com/using-vcnl4010-proximity-sensor ## Python code to use the VCNL4000 &amp; VCNL4010 proximity sensors with the Raspberry Pi &amp; BeagleBone Black. ## Installation To install the library from source (recommended) run the following commands on a Raspberry Pi or other Debian-based OS system: sudo apt-get install git build-essential python-dev cd ~ git clone https://github.com/adafruit/Adafruit_Python_VCNL40xx.git cd Adafruit_Python_VCNL40xx sudo python setup.py install Alternatively you can install from pip with: sudo pip install adafruit-vcnl40xx Note that the pip install method **won't** install the example code.
Adafruit-VCNL40xx
/Adafruit_VCNL40xx-1.0.4.tar.gz/Adafruit_VCNL40xx-1.0.4/README.md
README.md
import time # Common VCNL40xx constants: VCNL40xx_ADDRESS = 0x13 VCNL40xx_COMMAND = 0x80 VCNL40xx_PRODUCTID = 0x81 VCNL40xx_IRLED = 0x83 VCNL40xx_AMBIENTPARAMETER = 0x84 VCNL40xx_AMBIENTDATA = 0x85 VCNL40xx_PROXIMITYDATA = 0x87 VCNL40xx_PROXIMITYADJUST = 0x8A VCNL40xx_3M125 = 0 VCNL40xx_1M5625 = 1 VCNL40xx_781K25 = 2 VCNL40xx_390K625 = 3 VCNL40xx_MEASUREAMBIENT = 0x10 VCNL40xx_MEASUREPROXIMITY = 0x08 VCNL40xx_AMBIENTREADY = 0x40 VCNL40xx_PROXIMITYREADY = 0x20 # VCBL4000 constants: VCNL4000_SIGNALFREQ = 0x89 # VCNL4010 constants: VCNL4010_PROXRATE = 0x82 VCNL4010_INTCONTROL = 0x89 VCNL4010_INTSTAT = 0x8E VCNL4010_MODTIMING = 0x8F VCNL4010_INT_PROX_READY = 0x80 VCNL4010_INT_ALS_READY = 0x40 class VCNL40xxBase(object): """Base class for VCNL40xx proximity sensors.""" def __init__(self, address=VCNL40xx_ADDRESS, i2c=None, **kwargs): """Initialize the VCNL40xx sensor.""" # Setup I2C interface for the device. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._device = i2c.get_i2c_device(address, **kwargs) def _wait_response(self, ready, timeout_sec): """Wait for a response to be ready (the provided ready bits are set). If the specified timeout (in seconds) is exceeded and error will be thrown. """ # Wait for the measurement to be ready (or a timeout elapses). start = time.time() while True: # Check if the timeout has elapsed. if (time.time() - start) >= timeout_sec: raise RuntimeError('Exceeded timeout waiting for VCNL40xx response, check your wiring.') # Check if result is ready and return it. result = self._device.readU8(VCNL40xx_COMMAND) if (result & ready) > 0: return # Otherwise delay for a bit and try reading again. time.sleep(0.001) def read_proximity(self, timeout_sec=1): """Read the sensor proximity and return it as an unsigned 16-bit value. The larger the value the closer an object is to the sensor. """ # Ask for a proximity measurement and wait for the response. self._device.write8(VCNL40xx_COMMAND, VCNL40xx_MEASUREPROXIMITY) self._wait_response(VCNL40xx_PROXIMITYREADY, timeout_sec) # Return the proximity response. return self._device.readU16BE(VCNL40xx_PROXIMITYDATA) def read_ambient(self, timeout_sec=1): """Read the ambient light sensor and return it as an unsigned 16-bit value. """ # Ask for an ambient measurement and wait for the response. self._device.write8(VCNL40xx_COMMAND, VCNL40xx_MEASUREAMBIENT) self._wait_response(VCNL40xx_AMBIENTREADY, timeout_sec) # Return the ambient response. return self._device.readU16BE(VCNL40xx_AMBIENTDATA) class VCNL4000(VCNL40xxBase): """VCNL4000 proximity sensor.""" def __init__(self, **kwargs): """Initialize the VCNL4000 sensor.""" super(VCNL4000, self).__init__(**kwargs) # Write proximity adjustement register. self._device.write8(VCNL40xx_PROXIMITYADJUST, 0x81) class VCNL4010(VCNL40xxBase): """VCNL4010 proximity sensor.""" def __init__(self, **kwargs): """Initialize the VCNL4010 sensor.""" super(VCNL4010, self).__init__(**kwargs) # Enable interrupt for proximity data ready. self._device.write8(VCNL4010_INTCONTROL, 0x08) def _clear_interrupt(self, intbit): """Clear the specified interrupt bit in the interrupt status register. """ int_status = self._device.readU8(VCNL4010_INTSTAT); int_status &= ~intbit; self._device.write8(VCNL4010_INTSTAT, int_status); def read_proximity(self, timeout_sec=1): """Read the sensor proximity and return it as an unsigned 16-bit value. The larger the value the closer an object is to the sensor. """ # Clear any interrupts. self._clear_interrupt(VCNL4010_INT_PROX_READY) # Call base class read_proximity and return result. return super(VCNL4010, self).read_proximity(timeout_sec) def read_ambient(self, timeout_sec=1): """Read the ambient light sensor and return it as an unsigned 16-bit value. """ # Clear any interrupts. self._clear_interrupt(VCNL4010_INT_ALS_READY) # Call base class read_ambient and return result. return super(VCNL4010, self).read_ambient(timeout_sec)
Adafruit-VCNL40xx
/Adafruit_VCNL40xx-1.0.4.tar.gz/Adafruit_VCNL40xx-1.0.4/Adafruit_VCNL40xx/VCNL40xx.py
VCNL40xx.py
import time import Adafruit_GPIO.SPI as SPI def RGB_to_color(r, g, b): """Convert three 8-bit red, green, blue component values to a single 24-bit color value. """ return ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF) def color_to_RGB(color): """Convert a 24-bit color value to 8-bit red, green, blue components. Will return a 3-tuple with the color component values. """ return ((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF) class WS2801Pixels(object): """WS2801/SPI interface addressable RGB LED lights.""" def __init__(self, count, clk=None, do=None, spi=None, gpio=None): """Initialize set of WS2801/SPI-like addressable RGB LEDs. Must specify the count of pixels, and either an explicit clk (clokc) and do (data output) line for software SPI or a spi instance for hardware SPI. """ self._spi = None if spi is not None: # Handle hardware SPI. self._spi = spi elif clk is not None and do is not None: # Handle software SPI. # Default to platform GPIO if not provided. if gpio is None: import Adafruit_GPIO as GPIO gpio = GPIO.get_platform_gpio() self._spi = SPI.BitBang(gpio, clk, do, None, None) else: raise ValueError('Must specify either spi for for hardware SPI or clk, and do for softwrare SPI!') # Setup SPI interface with up to 20mhz speed. self._spi.set_clock_hz(1000000) self._spi.set_mode(0) self._spi.set_bit_order(SPI.MSBFIRST) # Setup buffer for pixel RGB data. self._count = count self._pixels = [0]*(count*3) def show(self): """Push the current pixel values out to the hardware. Must be called to actually change the pixel colors. """ self._spi.write(self._pixels) time.sleep(0.002) def count(self): """Return the count of pixels.""" return self._count def set_pixel(self, n, color): """Set the specified pixel n to the provided 24-bit RGB color. Note you MUST call show() after setting pixels to see the LEDs change color!""" r = color >> 16 g = color >> 8 b = color # Note the color components will be truncated to 8-bits in the # set_pixel_rgb function call. self.set_pixel_rgb(n, r, g, b) def set_pixel_rgb(self, n, r, g, b): """Set the specified pixel n to the provided 8-bit red, green, blue component values. Note you MUST call show() after setting pixels to see the LEDs change color! """ assert n >= 0 and n < self._count, 'Pixel n outside the count of pixels!' self._pixels[n*3] = r & 0xFF self._pixels[n*3+1] = g & 0xFF self._pixels[n*3+2] = b & 0xFF def get_pixel(self, n): """Retrieve the 24-bit RGB color of the specified pixel n.""" r, g, b = self.get_pixel_rgb(n) return (r << 16) | (g << 8) | b def get_pixel_rgb(self, n): """Retrieve the 8-bit red, green, blue component color values of the specified pixel n. Will return a 3-tuple of red, green, blue data. """ assert n >= 0 and n < self._count, 'Pixel n outside the count of pixels!' return (self._pixels[n*3], self._pixels[n*3+1], self._pixels[n*3+2]) def set_pixels(self, color=0): """Set all pixels to the provided 24-bit RGB color value. Note you MUST call show() after setting pixels to see the LEDs change!""" for i in range(self._count): self.set_pixel(i, color) def set_pixels_rgb(self, r, g, b): """Set all pixels to the provided 8-bit red, green, blue component color value. Note you MUST call show() after setting pixels to see the LEDs change! """ for i in range(self._count): self.set_pixel(i, r, g, b) def clear(self): """Clear all the pixels to black/off. Note you MUST call show() after clearing pixels to see the LEDs change! """ self.set_pixels(0) # # def colorwipe(pixels, c, delay): # for i in range(len(pixels)): # setpixelcolor(pixels, i, c) # writestrip(pixels) # time.sleep(delay) # # def Wheel(WheelPos): # if (WheelPos < 85): # return Color(WheelPos * 3, 255 - WheelPos * 3, 0) # elif (WheelPos < 170): # WheelPos -= 85; # return Color(255 - WheelPos * 3, 0, WheelPos * 3) # else: # WheelPos -= 170; # return Color(0, WheelPos * 3, 255 - WheelPos * 3) # # def rainbowCycle(pixels, wait): # for j in range(256): # one cycle of all 256 colors in the wheel # for i in range(len(pixels)): # # tricky math! we use each pixel as a fraction of the full 96-color wheel # # (thats the i / strip.numPixels() part) # # Then add in j which makes the colors go around per pixel # # the % 96 is to make the wheel cycle around # setpixelcolor(pixels, i, Wheel( ((i * 256 / len(pixels)) + j) % 256) ) # writestrip(pixels) # time.sleep(wait) # # colorwipe(ledpixels, Color(255, 0, 0), 0.05) # colorwipe(ledpixels, Color(0, 255, 0), 0.05) # colorwipe(ledpixels, Color(0, 0, 255), 0.05) # while True: # rainbowCycle(ledpixels, 0.00)
Adafruit-WS2801
/Adafruit_WS2801-1.0.1.tar.gz/Adafruit_WS2801-1.0.1/Adafruit_WS2801/WS2801.py
WS2801.py
Adafruit's Raspberry-Pi Python Code Library ============ Here is a growing collection of libraries and example python scripts for controlling a variety of Adafruit electronics with a Raspberry Pi In progress! Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries. BSD license, all text above and below must be included in any redistribution To download, we suggest logging into your Pi with Internet accessibility and typing: git clone https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git cd Adafruit-Raspberry-Pi-Python-Code python setup.py install ============ Copyright (c) 2012-2013 Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/README.md
README.md
# Copyright 2012 Daniel Berlin (with some changes by Adafruit Industries/Limor Fried) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal MCP230XX_GPIO(1, 0xin # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from Adafruit.I2C import Adafruit_I2C import smbus import time MCP23017_IODIRA = 0x00 MCP23017_IODIRB = 0x01 MCP23017_GPIOA = 0x12 MCP23017_GPIOB = 0x13 MCP23017_GPPUA = 0x0C MCP23017_GPPUB = 0x0D MCP23017_OLATA = 0x14 MCP23017_OLATB = 0x15 MCP23008_GPIOA = 0x09 MCP23008_GPPUA = 0x06 MCP23008_OLATA = 0x0A class Adafruit_MCP230XX(object): OUTPUT = 0 INPUT = 1 def __init__(self, address, num_gpios): assert num_gpios >= 0 and num_gpios <= 16, "Number of GPIOs must be between 0 and 16" self.i2c = Adafruit_I2C(address=address) self.address = address self.num_gpios = num_gpios # set defaults if num_gpios <= 8: self.i2c.write8(MCP23017_IODIRA, 0xFF) # all inputs on port A self.direction = self.i2c.readU8(MCP23017_IODIRA) self.i2c.write8(MCP23008_GPPUA, 0x00) elif num_gpios > 8 and num_gpios <= 16: self.i2c.write8(MCP23017_IODIRA, 0xFF) # all inputs on port A self.i2c.write8(MCP23017_IODIRB, 0xFF) # all inputs on port B self.direction = self.i2c.readU8(MCP23017_IODIRA) self.direction |= self.i2c.readU8(MCP23017_IODIRB) << 8 self.i2c.write8(MCP23017_GPPUA, 0x00) self.i2c.write8(MCP23017_GPPUB, 0x00) def _changebit(self, bitmap, bit, value): assert value == 1 or value == 0, "Value is %s must be 1 or 0" % value if value == 0: return bitmap & ~(1 << bit) elif value == 1: return bitmap | (1 << bit) def _readandchangepin(self, port, pin, value, currvalue = None): assert pin >= 0 and pin < self.num_gpios, "Pin number %s is invalid, only 0-%s are valid" % (pin, self.num_gpios) #assert self.direction & (1 << pin) == 0, "Pin %s not set to output" % pin if not currvalue: currvalue = self.i2c.readU8(port) newvalue = self._changebit(currvalue, pin, value) self.i2c.write8(port, newvalue) return newvalue def pullup(self, pin, value): if self.num_gpios <= 8: return self._readandchangepin(MCP23008_GPPUA, pin, value) if self.num_gpios <= 16: lvalue = self._readandchangepin(MCP23017_GPPUA, pin, value) if (pin < 8): return else: return self._readandchangepin(MCP23017_GPPUB, pin-8, value) << 8 # Set pin to either input or output mode def config(self, pin, mode): if self.num_gpios <= 8: self.direction = self._readandchangepin(MCP23017_IODIRA, pin, mode) if self.num_gpios <= 16: if (pin < 8): self.direction = self._readandchangepin(MCP23017_IODIRA, pin, mode) else: self.direction |= self._readandchangepin(MCP23017_IODIRB, pin-8, mode) << 8 return self.direction def output(self, pin, value): # assert self.direction & (1 << pin) == 0, "Pin %s not set to output" % pin if self.num_gpios <= 8: self.outputvalue = self._readandchangepin(MCP23008_GPIOA, pin, value, self.i2c.readU8(MCP23008_OLATA)) if self.num_gpios <= 16: if (pin < 8): self.outputvalue = self._readandchangepin(MCP23017_GPIOA, pin, value, self.i2c.readU8(MCP23017_OLATA)) else: self.outputvalue = self._readandchangepin(MCP23017_GPIOB, pin-8, value, self.i2c.readU8(MCP23017_OLATB)) << 8 return self.outputvalue self.outputvalue = self._readandchangepin(MCP23017_IODIRA, pin, value, self.outputvalue) return self.outputvalue def input(self, pin): assert pin >= 0 and pin < self.num_gpios, "Pin number %s is invalid, only 0-%s are valid" % (pin, self.num_gpios) assert self.direction & (1 << pin) != 0, "Pin %s not set to input" % pin if self.num_gpios <= 8: value = self.i2c.readU8(MCP23008_GPIOA) elif self.num_gpios > 8 and self.num_gpios <= 16: value = self.i2c.readU8(MCP23017_GPIOA) value |= self.i2c.readU8(MCP23017_GPIOB) << 8 return value & (1 << pin) def readU8(self): result = self.i2c.readU8(MCP23008_OLATA) return(result) def readS8(self): result = self.i2c.readU8(MCP23008_OLATA) if (result > 127): result -= 256 return result def readU16(self): assert self.num_gpios >= 16, "16bits required" lo = self.i2c.readU8(MCP23017_OLATA) hi = self.i2c.readU8(MCP23017_OLATB) return((hi << 8) | lo) def readS16(self): assert self.num_gpios >= 16, "16bits required" lo = self.i2c.readU8(MCP23017_OLATA) hi = self.i2c.readU8(MCP23017_OLATB) if (hi > 127): hi -= 256 return((hi << 8) | lo) def write8(self, value): self.i2c.write8(MCP23008_OLATA, value) def write16(self, value): assert self.num_gpios >= 16, "16bits required" self.i2c.write8(MCP23017_OLATA, value & 0xFF) self.i2c.write8(MCP23017_OLATB, (value >> 8) & 0xFF) # RPi.GPIO compatible interface for MCP23017 and MCP23008 class MCP230XX_GPIO(object): OUT = 0 IN = 1 BCM = 0 BOARD = 0 def __init__(self, busnum, address, num_gpios): self.chip = Adafruit_MCP230XX(busnum, address, num_gpios) def setmode(self, mode): # do nothing pass def setup(self, pin, mode): self.chip.config(pin, mode) def input(self, pin): return self.chip.input(pin) def output(self, pin, value): self.chip.output(pin, value) def pullup(self, pin, value): self.chip.pullup(pin, value) if __name__ == '__main__': # *************************************************** # Set num_gpios to 8 for MCP23008 or 16 for MCP23017! # *************************************************** mcp = Adafruit_MCP230XX(address = 0x20, num_gpios = 8) # MCP23008 # mcp = Adafruit_MCP230XX(address = 0x20, num_gpios = 16) # MCP23017 # Set pins 0, 1 and 2 to output (you can set pins 0..15 this way) mcp.config(0, mcp.OUTPUT) mcp.config(1, mcp.OUTPUT) mcp.config(2, mcp.OUTPUT) # Set pin 3 to input with the pullup resistor enabled mcp.config(3, mcp.INPUT) mcp.pullup(3, 1) # Read input pin and display the results print "Pin 3 = %d" % (mcp.input(3) >> 3) # Python speed test on output 0 toggling at max speed print "Starting blinky on pin 0 (CTRL+C to quit)" while (True): mcp.output(0, 1) # Pin 0 High time.sleep(1); mcp.output(0, 0) # Pin 0 Low time.sleep(1);
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/MCP230xx/Adafruit_MCP230xx.py
Adafruit_MCP230xx.py
import time import smbus from Adafruit.I2C import Adafruit_I2C # =========================================================================== # ADS1x15 Class # # Originally written by K. Townsend, Adafruit (https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_ADS1x15) # Updates and new functions implementation by Pedro Villanueva, 03/2013. # The only error in the original code was in line 57: # __ADS1015_REG_CONFIG_DR_920SPS = 0x0050 # should be # __ADS1015_REG_CONFIG_DR_920SPS = 0x0060 # # NOT IMPLEMENTED: Conversion ready pin, page 15 datasheet. # =========================================================================== class ADS1x15: i2c = None # IC Identifiers __IC_ADS1015 = 0x00 __IC_ADS1115 = 0x01 # Pointer Register __ADS1015_REG_POINTER_MASK = 0x03 __ADS1015_REG_POINTER_CONVERT = 0x00 __ADS1015_REG_POINTER_CONFIG = 0x01 __ADS1015_REG_POINTER_LOWTHRESH = 0x02 __ADS1015_REG_POINTER_HITHRESH = 0x03 # Config Register __ADS1015_REG_CONFIG_OS_MASK = 0x8000 __ADS1015_REG_CONFIG_OS_SINGLE = 0x8000 # Write: Set to start a single-conversion __ADS1015_REG_CONFIG_OS_BUSY = 0x0000 # Read: Bit = 0 when conversion is in progress __ADS1015_REG_CONFIG_OS_NOTBUSY = 0x8000 # Read: Bit = 1 when device is not performing a conversion __ADS1015_REG_CONFIG_MUX_MASK = 0x7000 __ADS1015_REG_CONFIG_MUX_DIFF_0_1 = 0x0000 # Differential P = AIN0, N = AIN1 (default) __ADS1015_REG_CONFIG_MUX_DIFF_0_3 = 0x1000 # Differential P = AIN0, N = AIN3 __ADS1015_REG_CONFIG_MUX_DIFF_1_3 = 0x2000 # Differential P = AIN1, N = AIN3 __ADS1015_REG_CONFIG_MUX_DIFF_2_3 = 0x3000 # Differential P = AIN2, N = AIN3 __ADS1015_REG_CONFIG_MUX_SINGLE_0 = 0x4000 # Single-ended AIN0 __ADS1015_REG_CONFIG_MUX_SINGLE_1 = 0x5000 # Single-ended AIN1 __ADS1015_REG_CONFIG_MUX_SINGLE_2 = 0x6000 # Single-ended AIN2 __ADS1015_REG_CONFIG_MUX_SINGLE_3 = 0x7000 # Single-ended AIN3 __ADS1015_REG_CONFIG_PGA_MASK = 0x0E00 __ADS1015_REG_CONFIG_PGA_6_144V = 0x0000 # +/-6.144V range __ADS1015_REG_CONFIG_PGA_4_096V = 0x0200 # +/-4.096V range __ADS1015_REG_CONFIG_PGA_2_048V = 0x0400 # +/-2.048V range (default) __ADS1015_REG_CONFIG_PGA_1_024V = 0x0600 # +/-1.024V range __ADS1015_REG_CONFIG_PGA_0_512V = 0x0800 # +/-0.512V range __ADS1015_REG_CONFIG_PGA_0_256V = 0x0A00 # +/-0.256V range __ADS1015_REG_CONFIG_MODE_MASK = 0x0100 __ADS1015_REG_CONFIG_MODE_CONTIN = 0x0000 # Continuous conversion mode __ADS1015_REG_CONFIG_MODE_SINGLE = 0x0100 # Power-down single-shot mode (default) __ADS1015_REG_CONFIG_DR_MASK = 0x00E0 __ADS1015_REG_CONFIG_DR_128SPS = 0x0000 # 128 samples per second __ADS1015_REG_CONFIG_DR_250SPS = 0x0020 # 250 samples per second __ADS1015_REG_CONFIG_DR_490SPS = 0x0040 # 490 samples per second __ADS1015_REG_CONFIG_DR_920SPS = 0x0060 # 920 samples per second __ADS1015_REG_CONFIG_DR_1600SPS = 0x0080 # 1600 samples per second (default) __ADS1015_REG_CONFIG_DR_2400SPS = 0x00A0 # 2400 samples per second __ADS1015_REG_CONFIG_DR_3300SPS = 0x00C0 # 3300 samples per second (also 0x00E0) __ADS1115_REG_CONFIG_DR_8SPS = 0x0000 # 8 samples per second __ADS1115_REG_CONFIG_DR_16SPS = 0x0020 # 16 samples per second __ADS1115_REG_CONFIG_DR_32SPS = 0x0040 # 32 samples per second __ADS1115_REG_CONFIG_DR_64SPS = 0x0060 # 64 samples per second __ADS1115_REG_CONFIG_DR_128SPS = 0x0080 # 128 samples per second __ADS1115_REG_CONFIG_DR_250SPS = 0x00A0 # 250 samples per second (default) __ADS1115_REG_CONFIG_DR_475SPS = 0x00C0 # 475 samples per second __ADS1115_REG_CONFIG_DR_860SPS = 0x00E0 # 860 samples per second __ADS1015_REG_CONFIG_CMODE_MASK = 0x0010 __ADS1015_REG_CONFIG_CMODE_TRAD = 0x0000 # Traditional comparator with hysteresis (default) __ADS1015_REG_CONFIG_CMODE_WINDOW = 0x0010 # Window comparator __ADS1015_REG_CONFIG_CPOL_MASK = 0x0008 __ADS1015_REG_CONFIG_CPOL_ACTVLOW = 0x0000 # ALERT/RDY pin is low when active (default) __ADS1015_REG_CONFIG_CPOL_ACTVHI = 0x0008 # ALERT/RDY pin is high when active __ADS1015_REG_CONFIG_CLAT_MASK = 0x0004 # Determines if ALERT/RDY pin latches once asserted __ADS1015_REG_CONFIG_CLAT_NONLAT = 0x0000 # Non-latching comparator (default) __ADS1015_REG_CONFIG_CLAT_LATCH = 0x0004 # Latching comparator __ADS1015_REG_CONFIG_CQUE_MASK = 0x0003 __ADS1015_REG_CONFIG_CQUE_1CONV = 0x0000 # Assert ALERT/RDY after one conversions __ADS1015_REG_CONFIG_CQUE_2CONV = 0x0001 # Assert ALERT/RDY after two conversions __ADS1015_REG_CONFIG_CQUE_4CONV = 0x0002 # Assert ALERT/RDY after four conversions __ADS1015_REG_CONFIG_CQUE_NONE = 0x0003 # Disable the comparator and put ALERT/RDY in high state (default) # Dictionaries with the sampling speed values # These simplify and clean the code (avoid the abuse of if/elif/else clauses) spsADS1115 = { 8:__ADS1115_REG_CONFIG_DR_8SPS, 16:__ADS1115_REG_CONFIG_DR_16SPS, 32:__ADS1115_REG_CONFIG_DR_32SPS, 64:__ADS1115_REG_CONFIG_DR_64SPS, 128:__ADS1115_REG_CONFIG_DR_128SPS, 250:__ADS1115_REG_CONFIG_DR_250SPS, 475:__ADS1115_REG_CONFIG_DR_475SPS, 860:__ADS1115_REG_CONFIG_DR_860SPS } spsADS1015 = { 128:__ADS1015_REG_CONFIG_DR_128SPS, 250:__ADS1015_REG_CONFIG_DR_250SPS, 490:__ADS1015_REG_CONFIG_DR_490SPS, 920:__ADS1015_REG_CONFIG_DR_920SPS, 1600:__ADS1015_REG_CONFIG_DR_1600SPS, 2400:__ADS1015_REG_CONFIG_DR_2400SPS, 3300:__ADS1015_REG_CONFIG_DR_3300SPS } # Dictionariy with the programable gains pgaADS1x15 = { 6144:__ADS1015_REG_CONFIG_PGA_6_144V, 4096:__ADS1015_REG_CONFIG_PGA_4_096V, 2048:__ADS1015_REG_CONFIG_PGA_2_048V, 1024:__ADS1015_REG_CONFIG_PGA_1_024V, 512:__ADS1015_REG_CONFIG_PGA_0_512V, 256:__ADS1015_REG_CONFIG_PGA_0_256V } # Constructor def __init__(self, address=0x48, ic=__IC_ADS1015, debug=False): # Depending on if you have an old or a new Raspberry Pi, you # may need to change the I2C bus. Older Pis use SMBus 0, # whereas new Pis use SMBus 1. If you see an error like: # 'Error accessing 0x48: Check your I2C address ' # change the SMBus number in the initializer below! self.i2c = Adafruit_I2C(address) self.address = address self.debug = debug # Make sure the IC specified is valid if ((ic < self.__IC_ADS1015) | (ic > self.__IC_ADS1115)): if (self.debug): print "ADS1x15: Invalid IC specfied: %h" % ic return -1 else: self.ic = ic # Set pga value, so that getLastConversionResult() can use it, # any function that accepts a pga value must update this. self.pga = 6144 def readADCSingleEnded(self, channel=0, pga=6144, sps=250): "Gets a single-ended ADC reading from the specified channel in mV. \ The sample rate for this mode (single-shot) can be used to lower the noise \ (low sps) or to lower the power consumption (high sps) by duty cycling, \ see datasheet page 14 for more info. \ The pga must be given in mV, see page 13 for the supported values." # With invalid channel return -1 if (channel > 3): if (self.debug): print "ADS1x15: Invalid channel specified: %d" % channel return -1 # Disable comparator, Non-latching, Alert/Rdy active low # traditional comparator, single-shot mode config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \ self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \ self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \ self.__ADS1015_REG_CONFIG_CMODE_TRAD | \ self.__ADS1015_REG_CONFIG_MODE_SINGLE # Set sample per seconds, defaults to 250sps # If sps is in the dictionary (defined in init) it returns the value of the constant # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! if (self.ic == self.__IC_ADS1015): config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) else: if ( (sps not in self.spsADS1115) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) # Set PGA/voltage range, defaults to +-6.144V if ( (pga not in self.pgaADS1x15) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) self.pga = pga # Set the channel to be converted if channel == 3: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_3 elif channel == 2: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_2 elif channel == 1: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_1 else: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_0 # Set 'start single-conversion' bit config |= self.__ADS1015_REG_CONFIG_OS_SINGLE # Write config register to the ADC bytes = [(config >> 8) & 0xFF, config & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) # Wait for the ADC conversion to complete # The minimum delay depends on the sps: delay >= 1/sps # We add 0.1ms to be sure delay = 1.0/sps+0.0001 time.sleep(delay) # Read the conversion results result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) if (self.ic == self.__IC_ADS1015): # Shift right 4 bits for the 12-bit ADS1015 and convert to mV return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0 else: # Return a mV value for the ADS1115 # (Take signed values into account as well) val = (result[0] << 8) | (result[1]) if val > 0x7FFF: return (val - 0xFFFF)*pga/32768.0 else: return ( (result[0] << 8) | (result[1]) )*pga/32768.0 def readADCDifferential(self, chP=0, chN=1, pga=6144, sps=250): "Gets a differential ADC reading from channels chP and chN in mV. \ The sample rate for this mode (single-shot) can be used to lower the noise \ (low sps) or to lower the power consumption (high sps) by duty cycling, \ see data sheet page 14 for more info. \ The pga must be given in mV, see page 13 for the supported values." # Disable comparator, Non-latching, Alert/Rdy active low # traditional comparator, single-shot mode config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \ self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \ self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \ self.__ADS1015_REG_CONFIG_CMODE_TRAD | \ self.__ADS1015_REG_CONFIG_MODE_SINGLE # Set channels if ( (chP == 0) & (chN == 1) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_1 elif ( (chP == 0) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_3 elif ( (chP == 2) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_2_3 elif ( (chP == 1) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_1_3 else: if (self.debug): print "ADS1x15: Invalid channels specified: %d, %d" % (chP, chN) return -1 # Set sample per seconds, defaults to 250sps # If sps is in the dictionary (defined in init()) it returns the value of the constant # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! if (self.ic == self.__IC_ADS1015): config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) else: if ( (sps not in self.spsADS1115) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) # Set PGA/voltage range, defaults to +-6.144V if ( (pga not in self.pgaADS1x15) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) self.pga = pga # Set 'start single-conversion' bit config |= self.__ADS1015_REG_CONFIG_OS_SINGLE # Write config register to the ADC bytes = [(config >> 8) & 0xFF, config & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) # Wait for the ADC conversion to complete # The minimum delay depends on the sps: delay >= 1/sps # We add 0.1ms to be sure delay = 1.0/sps+0.0001 time.sleep(delay) # Read the conversion results result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) if (self.ic == self.__IC_ADS1015): # Shift right 4 bits for the 12-bit ADS1015 and convert to mV return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0 else: # Return a mV value for the ADS1115 # (Take signed values into account as well) val = (result[0] << 8) | (result[1]) if val > 0x7FFF: return (val - 0xFFFF)*pga/32768.0 else: return ( (result[0] << 8) | (result[1]) )*pga/32768.0 def readADCDifferential01(self, pga=6144, sps=250): "Gets a differential ADC reading from channels 0 and 1 in mV\ The sample rate for this mode (single-shot) can be used to lower the noise \ (low sps) or to lower the power consumption (high sps) by duty cycling, \ see data sheet page 14 for more info. \ The pga must be given in mV, see page 13 for the supported values." return self.readADCDifferential(0, 1, pga, sps) def readADCDifferential03(self, pga=6144, sps=250): "Gets a differential ADC reading from channels 0 and 3 in mV \ The sample rate for this mode (single-shot) can be used to lower the noise \ (low sps) or to lower the power consumption (high sps) by duty cycling, \ see data sheet page 14 for more info. \ The pga must be given in mV, see page 13 for the supported values." return self.readADCDifferential(0, 3, pga, sps) def readADCDifferential13(self, pga=6144, sps=250): "Gets a differential ADC reading from channels 1 and 3 in mV \ The sample rate for this mode (single-shot) can be used to lower the noise \ (low sps) or to lower the power consumption (high sps) by duty cycling, \ see data sheet page 14 for more info. \ The pga must be given in mV, see page 13 for the supported values." return self.__readADCDifferential(1, 3, pga, sps) def readADCDifferential23(self, pga=6144, sps=250): "Gets a differential ADC reading from channels 2 and 3 in mV \ The sample rate for this mode (single-shot) can be used to lower the noise \ (low sps) or to lower the power consumption (high sps) by duty cycling, \ see data sheet page 14 for more info. \ The pga must be given in mV, see page 13 for the supported values." return self.readADCDifferential(2, 3, pga, sps) def startContinuousConversion(self, channel=0, pga=6144, sps=250): "Starts the continuous conversion mode and returns the first ADC reading \ in mV from the specified channel. \ The sps controls the sample rate. \ The pga must be given in mV, see datasheet page 13 for the supported values. \ Use getLastConversionResults() to read the next values and \ stopContinuousConversion() to stop converting." # Default to channel 0 with invalid channel, or return -1? if (channel > 3): if (self.debug): print "ADS1x15: Invalid channel specified: %d" % channel return -1 # Disable comparator, Non-latching, Alert/Rdy active low # traditional comparator, continuous mode # The last flag is the only change we need, page 11 datasheet config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \ self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \ self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \ self.__ADS1015_REG_CONFIG_CMODE_TRAD | \ self.__ADS1015_REG_CONFIG_MODE_CONTIN # Set sample per seconds, defaults to 250sps # If sps is in the dictionary (defined in init()) it returns the value of the constant # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! if (self.ic == self.__IC_ADS1015): config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) else: if ( (sps not in self.spsADS1115) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) # Set PGA/voltage range, defaults to +-6.144V if ( (pga not in self.pgaADS1x15) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) self.pga = pga # Set the channel to be converted if channel == 3: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_3 elif channel == 2: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_2 elif channel == 1: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_1 else: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_0 # Set 'start single-conversion' bit to begin conversions # No need to change this for continuous mode! config |= self.__ADS1015_REG_CONFIG_OS_SINGLE # Write config register to the ADC # Once we write the ADC will convert continously # we can read the next values using getLastConversionResult bytes = [(config >> 8) & 0xFF, config & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) # Wait for the ADC conversion to complete # The minimum delay depends on the sps: delay >= 1/sps # We add 0.5ms to be sure delay = 1.0/sps+0.0005 time.sleep(delay) # Read the conversion results result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) if (self.ic == self.__IC_ADS1015): # Shift right 4 bits for the 12-bit ADS1015 and convert to mV return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0 else: # Return a mV value for the ADS1115 # (Take signed values into account as well) val = (result[0] << 8) | (result[1]) if val > 0x7FFF: return (val - 0xFFFF)*pga/32768.0 else: return ( (result[0] << 8) | (result[1]) )*pga/32768.0 def startContinuousDifferentialConversion(self, chP=0, chN=1, pga=6144, sps=250): "Starts the continuous differential conversion mode and returns the first ADC reading \ in mV as the difference from the specified channels. \ The sps controls the sample rate. \ The pga must be given in mV, see datasheet page 13 for the supported values. \ Use getLastConversionResults() to read the next values and \ stopContinuousConversion() to stop converting." # Disable comparator, Non-latching, Alert/Rdy active low # traditional comparator, continuous mode # The last flag is the only change we need, page 11 datasheet config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \ self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \ self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \ self.__ADS1015_REG_CONFIG_CMODE_TRAD | \ self.__ADS1015_REG_CONFIG_MODE_CONTIN # Set sample per seconds, defaults to 250sps # If sps is in the dictionary (defined in init()) it returns the value of the constant # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! if (self.ic == self.__IC_ADS1015): config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) else: if ( (sps not in self.spsADS1115) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) # Set PGA/voltage range, defaults to +-6.144V if ( (pga not in self.pgaADS1x15) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) self.pga = pga # Set channels if ( (chP == 0) & (chN == 1) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_1 elif ( (chP == 0) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_3 elif ( (chP == 2) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_2_3 elif ( (chP == 1) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_1_3 else: if (self.debug): print "ADS1x15: Invalid channels specified: %d, %d" % (chP, chN) return -1 # Set 'start single-conversion' bit to begin conversions # No need to change this for continuous mode! config |= self.__ADS1015_REG_CONFIG_OS_SINGLE # Write config register to the ADC # Once we write the ADC will convert continously # we can read the next values using getLastConversionResult bytes = [(config >> 8) & 0xFF, config & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) # Wait for the ADC conversion to complete # The minimum delay depends on the sps: delay >= 1/sps # We add 0.5ms to be sure delay = 1.0/sps+0.0005 time.sleep(delay) # Read the conversion results result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) if (self.ic == self.__IC_ADS1015): # Shift right 4 bits for the 12-bit ADS1015 and convert to mV return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0 else: # Return a mV value for the ADS1115 # (Take signed values into account as well) val = (result[0] << 8) | (result[1]) if val > 0x7FFF: return (val - 0xFFFF)*pga/32768.0 else: return ( (result[0] << 8) | (result[1]) )*pga/32768.0 def stopContinuousConversion(self): "Stops the ADC's conversions when in continuous mode \ and resets the configuration to its default value." # Write the default config register to the ADC # Once we write, the ADC will do a single conversion and # enter power-off mode. config = 0x8583 # Page 18 datasheet. bytes = [(config >> 8) & 0xFF, config & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) return True def getLastConversionResults(self): "Returns the last ADC conversion result in mV" # Read the conversion results result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) if (self.ic == self.__IC_ADS1015): # Shift right 4 bits for the 12-bit ADS1015 and convert to mV return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*self.pga/2048.0 else: # Return a mV value for the ADS1115 # (Take signed values into account as well) val = (result[0] << 8) | (result[1]) if val > 0x7FFF: return (val - 0xFFFF)*self.pga/32768.0 else: return ( (result[0] << 8) | (result[1]) )*self.pga/32768.0 def startSingleEndedComparator(self, channel, thresholdHigh, thresholdLow, \ pga=6144, sps=250, \ activeLow=True, traditionalMode=True, latching=False, \ numReadings=1): "Starts the comparator mode on the specified channel, see datasheet pg. 15. \ In traditional mode it alerts (ALERT pin will go low) when voltage exceeds \ thresholdHigh until it falls below thresholdLow (both given in mV). \ In window mode (traditionalMode=False) it alerts when voltage doesn't lie\ between both thresholds.\ In latching mode the alert will continue until the conversion value is read. \ numReadings controls how many readings are necessary to trigger an alert: 1, 2 or 4.\ Use getLastConversionResults() to read the current value (which may differ \ from the one that triggered the alert) and clear the alert pin in latching mode. \ This function starts the continuous conversion mode. The sps controls \ the sample rate and the pga the gain, see datasheet page 13. " # With invalid channel return -1 if (channel > 3): if (self.debug): print "ADS1x15: Invalid channel specified: %d" % channel return -1 # Continuous mode config = self.__ADS1015_REG_CONFIG_MODE_CONTIN if (activeLow==False): config |= self.__ADS1015_REG_CONFIG_CPOL_ACTVHI else: config |= self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW if (traditionalMode==False): config |= self.__ADS1015_REG_CONFIG_CMODE_WINDOW else: config |= self.__ADS1015_REG_CONFIG_CMODE_TRAD if (latching==True): config |= self.__ADS1015_REG_CONFIG_CLAT_LATCH else: config |= self.__ADS1015_REG_CONFIG_CLAT_NONLAT if (numReadings==4): config |= self.__ADS1015_REG_CONFIG_CQUE_4CONV elif (numReadings==2): config |= self.__ADS1015_REG_CONFIG_CQUE_2CONV else: config |= self.__ADS1015_REG_CONFIG_CQUE_1CONV # Set sample per seconds, defaults to 250sps # If sps is in the dictionary (defined in init()) it returns the value of the constant # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! if (self.ic == self.__IC_ADS1015): if ( (sps not in self.spsADS1015) & self.debug): print "ADS1x15: Invalid sps specified: %d, using 1600sps" % sps config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) else: if ( (sps not in self.spsADS1115) & self.debug): print "ADS1x15: Invalid sps specified: %d, using 250sps" % sps config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) # Set PGA/voltage range, defaults to +-6.144V if ( (pga not in self.pgaADS1x15) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % pga config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) self.pga = pga # Set the channel to be converted if channel == 3: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_3 elif channel == 2: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_2 elif channel == 1: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_1 else: config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_0 # Set 'start single-conversion' bit to begin conversions config |= self.__ADS1015_REG_CONFIG_OS_SINGLE # Write threshold high and low registers to the ADC # V_digital = (2^(n-1)-1)/pga*V_analog if (self.ic == self.__IC_ADS1015): thresholdHighWORD = int(thresholdHigh*(2048.0/pga)) else: thresholdHighWORD = int(thresholdHigh*(32767.0/pga)) bytes = [(thresholdHighWORD >> 8) & 0xFF, thresholdHighWORD & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_HITHRESH, bytes) if (self.ic == self.__IC_ADS1015): thresholdLowWORD = int(thresholdLow*(2048.0/pga)) else: thresholdLowWORD = int(thresholdLow*(32767.0/pga)) bytes = [(thresholdLowWORD >> 8) & 0xFF, thresholdLowWORD & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_LOWTHRESH, bytes) # Write config register to the ADC # Once we write the ADC will convert continously and alert when things happen, # we can read the converted values using getLastConversionResult bytes = [(config >> 8) & 0xFF, config & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) def startDifferentialComparator(self, chP, chN, thresholdHigh, thresholdLow, \ pga=6144, sps=250, \ activeLow=True, traditionalMode=True, latching=False, \ numReadings=1): "Starts the comparator mode on the specified channel, see datasheet pg. 15. \ In traditional mode it alerts (ALERT pin will go low) when voltage exceeds \ thresholdHigh until it falls below thresholdLow (both given in mV). \ In window mode (traditionalMode=False) it alerts when voltage doesn't lie\ between both thresholds.\ In latching mode the alert will continue until the conversion value is read. \ numReadings controls how many readings are necessary to trigger an alert: 1, 2 or 4.\ Use getLastConversionResults() to read the current value (which may differ \ from the one that triggered the alert) and clear the alert pin in latching mode. \ This function starts the continuous conversion mode. The sps controls \ the sample rate and the pga the gain, see datasheet page 13. " # Continuous mode config = self.__ADS1015_REG_CONFIG_MODE_CONTIN if (activeLow==False): config |= self.__ADS1015_REG_CONFIG_CPOL_ACTVHI else: config |= self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW if (traditionalMode==False): config |= self.__ADS1015_REG_CONFIG_CMODE_WINDOW else: config |= self.__ADS1015_REG_CONFIG_CMODE_TRAD if (latching==True): config |= self.__ADS1015_REG_CONFIG_CLAT_LATCH else: config |= self.__ADS1015_REG_CONFIG_CLAT_NONLAT if (numReadings==4): config |= self.__ADS1015_REG_CONFIG_CQUE_4CONV elif (numReadings==2): config |= self.__ADS1015_REG_CONFIG_CQUE_2CONV else: config |= self.__ADS1015_REG_CONFIG_CQUE_1CONV # Set sample per seconds, defaults to 250sps # If sps is in the dictionary (defined in init()) it returns the value of the constant # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! if (self.ic == self.__IC_ADS1015): if ( (sps not in self.spsADS1015) & self.debug): print "ADS1x15: Invalid sps specified: %d, using 1600sps" % sps config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) else: if ( (sps not in self.spsADS1115) & self.debug): print "ADS1x15: Invalid sps specified: %d, using 250sps" % sps config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) # Set PGA/voltage range, defaults to +-6.144V if ( (pga not in self.pgaADS1x15) & self.debug): print "ADS1x15: Invalid pga specified: %d, using 6144mV" % pga config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) self.pga = pga # Set channels if ( (chP == 0) & (chN == 1) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_1 elif ( (chP == 0) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_3 elif ( (chP == 2) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_2_3 elif ( (chP == 1) & (chN == 3) ): config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_1_3 else: if (self.debug): print "ADS1x15: Invalid channels specified: %d, %d" % (chP, chN) return -1 # Set 'start single-conversion' bit to begin conversions config |= self.__ADS1015_REG_CONFIG_OS_SINGLE # Write threshold high and low registers to the ADC # V_digital = (2^(n-1)-1)/pga*V_analog if (self.ic == self.__IC_ADS1015): thresholdHighWORD = int(thresholdHigh*(2048.0/pga)) else: thresholdHighWORD = int(thresholdHigh*(32767.0/pga)) bytes = [(thresholdHighWORD >> 8) & 0xFF, thresholdHighWORD & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_HITHRESH, bytes) if (self.ic == self.__IC_ADS1015): thresholdLowWORD = int(thresholdLow*(2048.0/pga)) else: thresholdLowWORD = int(thresholdLow*(32767.0/pga)) bytes = [(thresholdLowWORD >> 8) & 0xFF, thresholdLowWORD & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_LOWTHRESH, bytes) # Write config register to the ADC # Once we write the ADC will convert continously and alert when things happen, # we can read the converted values using getLastConversionResult bytes = [(config >> 8) & 0xFF, config & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes)
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/ADS1x15/Adafruit_ADS1x15.py
Adafruit_ADS1x15.py
import smbus # =========================================================================== # Adafruit_I2C Class # =========================================================================== class Adafruit_I2C : @staticmethod def getPiRevision(): "Gets the version number of the Raspberry Pi board" # Courtesy quick2wire-python-api # https://github.com/quick2wire/quick2wire-python-api try: with open('/proc/cpuinfo','r') as f: for line in f: if line.startswith('Revision'): return 1 if line.rstrip()[-1] in ['1','2'] else 2 except: return 0 @staticmethod def getPiI2CBusNumber(): # Gets the I2C bus number /dev/i2c# return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 def __init__(self, address, busnum=-1, debug=False): self.address = address # By default, the correct I2C bus is auto-detected using /proc/cpuinfo # Alternatively, you can hard-code the bus version below: # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) self.bus = smbus.SMBus( busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) self.debug = debug def reverseByteOrder(self, data): "Reverses the byte order of an int (16-bit) or long (32-bit) value" # Courtesy Vishal Sapre byteCount = len(hex(data)[2:].replace('L','')[::2]) val = 0 for i in range(byteCount): val = (val << 8) | (data & 0xff) data >>= 8 return val def errMsg(self): print "Error accessing 0x%02X: Check your I2C address" % self.address return -1 def write8(self, reg, value): "Writes an 8-bit value to the specified register/address" try: self.bus.write_byte_data(self.address, reg, value) if self.debug: print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg) except IOError, err: return self.errMsg() def write16(self, reg, value): "Writes a 16-bit value to the specified register/address pair" try: self.bus.write_word_data(self.address, reg, value) if self.debug: print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % (value, reg, reg+1)) except IOError, err: return self.errMsg() def writeList(self, reg, list): "Writes an array of bytes using I2C format" try: if self.debug: print "I2C: Writing list to register 0x%02X:" % reg print list self.bus.write_i2c_block_data(self.address, reg, list) except IOError, err: return self.errMsg() def readList(self, reg, length): "Read a list of bytes from the I2C device" try: results = self.bus.read_i2c_block_data(self.address, reg, length) if self.debug: print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % (self.address, reg)) print results return results except IOError, err: return self.errMsg() def readU8(self, reg): "Read an unsigned byte from the I2C device" try: result = self.bus.read_byte_data(self.address, reg) if self.debug: print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % (self.address, result & 0xFF, reg)) return result except IOError, err: return self.errMsg() def readS8(self, reg): "Reads a signed byte from the I2C device" try: result = self.bus.read_byte_data(self.address, reg) if result > 127: result -= 256 if self.debug: print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % (self.address, result & 0xFF, reg)) return result except IOError, err: return self.errMsg() def readU16(self, reg): "Reads an unsigned 16-bit value from the I2C device" try: result = self.bus.read_word_data(self.address,reg) if (self.debug): print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) return result except IOError, err: return self.errMsg() def readS16(self, reg): "Reads a signed 16-bit value from the I2C device" try: result = self.bus.read_word_data(self.address,reg) if (self.debug): print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) return result except IOError, err: return self.errMsg() if __name__ == '__main__': try: bus = Adafruit_I2C(address=0) print "Default I2C bus is accessible" except: print "Error accessing default I2C bus"
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/I2C/Adafruit_I2C.py
Adafruit_I2C.py
from Adafruit_MCP4725 import MCP4725 import time # Set this value to 9, 8, 7, 6 or 5 to adjust the resolution DAC_RESOLUTION = 9 # 9-Bit Lookup Table (512 values) DACLookup_FullSine_9Bit = \ [ 2048, 2073, 2098, 2123, 2148, 2174, 2199, 2224, 2249, 2274, 2299, 2324, 2349, 2373, 2398, 2423, 2448, 2472, 2497, 2521, 2546, 2570, 2594, 2618, 2643, 2667, 2690, 2714, 2738, 2762, 2785, 2808, 2832, 2855, 2878, 2901, 2924, 2946, 2969, 2991, 3013, 3036, 3057, 3079, 3101, 3122, 3144, 3165, 3186, 3207, 3227, 3248, 3268, 3288, 3308, 3328, 3347, 3367, 3386, 3405, 3423, 3442, 3460, 3478, 3496, 3514, 3531, 3548, 3565, 3582, 3599, 3615, 3631, 3647, 3663, 3678, 3693, 3708, 3722, 3737, 3751, 3765, 3778, 3792, 3805, 3817, 3830, 3842, 3854, 3866, 3877, 3888, 3899, 3910, 3920, 3930, 3940, 3950, 3959, 3968, 3976, 3985, 3993, 4000, 4008, 4015, 4022, 4028, 4035, 4041, 4046, 4052, 4057, 4061, 4066, 4070, 4074, 4077, 4081, 4084, 4086, 4088, 4090, 4092, 4094, 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4094, 4092, 4090, 4088, 4086, 4084, 4081, 4077, 4074, 4070, 4066, 4061, 4057, 4052, 4046, 4041, 4035, 4028, 4022, 4015, 4008, 4000, 3993, 3985, 3976, 3968, 3959, 3950, 3940, 3930, 3920, 3910, 3899, 3888, 3877, 3866, 3854, 3842, 3830, 3817, 3805, 3792, 3778, 3765, 3751, 3737, 3722, 3708, 3693, 3678, 3663, 3647, 3631, 3615, 3599, 3582, 3565, 3548, 3531, 3514, 3496, 3478, 3460, 3442, 3423, 3405, 3386, 3367, 3347, 3328, 3308, 3288, 3268, 3248, 3227, 3207, 3186, 3165, 3144, 3122, 3101, 3079, 3057, 3036, 3013, 2991, 2969, 2946, 2924, 2901, 2878, 2855, 2832, 2808, 2785, 2762, 2738, 2714, 2690, 2667, 2643, 2618, 2594, 2570, 2546, 2521, 2497, 2472, 2448, 2423, 2398, 2373, 2349, 2324, 2299, 2274, 2249, 2224, 2199, 2174, 2148, 2123, 2098, 2073, 2048, 2023, 1998, 1973, 1948, 1922, 1897, 1872, 1847, 1822, 1797, 1772, 1747, 1723, 1698, 1673, 1648, 1624, 1599, 1575, 1550, 1526, 1502, 1478, 1453, 1429, 1406, 1382, 1358, 1334, 1311, 1288, 1264, 1241, 1218, 1195, 1172, 1150, 1127, 1105, 1083, 1060, 1039, 1017, 995, 974, 952, 931, 910, 889, 869, 848, 828, 808, 788, 768, 749, 729, 710, 691, 673, 654, 636, 618, 600, 582, 565, 548, 531, 514, 497, 481, 465, 449, 433, 418, 403, 388, 374, 359, 345, 331, 318, 304, 291, 279, 266, 254, 242, 230, 219, 208, 197, 186, 176, 166, 156, 146, 137, 128, 120, 111, 103, 96, 88, 81, 74, 68, 61, 55, 50, 44, 39, 35, 30, 26, 22, 19, 15, 12, 10, 8, 6, 4, 2, 1, 1, 0, 0, 0, 1, 1, 2, 4, 6, 8, 10, 12, 15, 19, 22, 26, 30, 35, 39, 44, 50, 55, 61, 68, 74, 81, 88, 96, 103, 111, 120, 128, 137, 146, 156, 166, 176, 186, 197, 208, 219, 230, 242, 254, 266, 279, 291, 304, 318, 331, 345, 359, 374, 388, 403, 418, 433, 449, 465, 481, 497, 514, 531, 548, 565, 582, 600, 618, 636, 654, 673, 691, 710, 729, 749, 768, 788, 808, 828, 848, 869, 889, 910, 931, 952, 974, 995, 1017, 1039, 1060, 1083, 1105, 1127, 1150, 1172, 1195, 1218, 1241, 1264, 1288, 1311, 1334, 1358, 1382, 1406, 1429, 1453, 1478, 1502, 1526, 1550, 1575, 1599, 1624, 1648, 1673, 1698, 1723, 1747, 1772, 1797, 1822, 1847, 1872, 1897, 1922, 1948, 1973, 1998, 2023 ] # 8-bit Lookup Table (256 values) DACLookup_FullSine_8Bit = \ [ 2048, 2098, 2148, 2198, 2248, 2298, 2348, 2398, 2447, 2496, 2545, 2594, 2642, 2690, 2737, 2784, 2831, 2877, 2923, 2968, 3013, 3057, 3100, 3143, 3185, 3226, 3267, 3307, 3346, 3385, 3423, 3459, 3495, 3530, 3565, 3598, 3630, 3662, 3692, 3722, 3750, 3777, 3804, 3829, 3853, 3876, 3898, 3919, 3939, 3958, 3975, 3992, 4007, 4021, 4034, 4045, 4056, 4065, 4073, 4080, 4085, 4089, 4093, 4094, 4095, 4094, 4093, 4089, 4085, 4080, 4073, 4065, 4056, 4045, 4034, 4021, 4007, 3992, 3975, 3958, 3939, 3919, 3898, 3876, 3853, 3829, 3804, 3777, 3750, 3722, 3692, 3662, 3630, 3598, 3565, 3530, 3495, 3459, 3423, 3385, 3346, 3307, 3267, 3226, 3185, 3143, 3100, 3057, 3013, 2968, 2923, 2877, 2831, 2784, 2737, 2690, 2642, 2594, 2545, 2496, 2447, 2398, 2348, 2298, 2248, 2198, 2148, 2098, 2048, 1997, 1947, 1897, 1847, 1797, 1747, 1697, 1648, 1599, 1550, 1501, 1453, 1405, 1358, 1311, 1264, 1218, 1172, 1127, 1082, 1038, 995, 952, 910, 869, 828, 788, 749, 710, 672, 636, 600, 565, 530, 497, 465, 433, 403, 373, 345, 318, 291, 266, 242, 219, 197, 176, 156, 137, 120, 103, 88, 74, 61, 50, 39, 30, 22, 15, 10, 6, 2, 1, 0, 1, 2, 6, 10, 15, 22, 30, 39, 50, 61, 74, 88, 103, 120, 137, 156, 176, 197, 219, 242, 266, 291, 318, 345, 373, 403, 433, 465, 497, 530, 565, 600, 636, 672, 710, 749, 788, 828, 869, 910, 952, 995, 1038, 1082, 1127, 1172, 1218, 1264, 1311, 1358, 1405, 1453, 1501, 1550, 1599, 1648, 1697, 1747, 1797, 1847, 1897, 1947, 1997 ] # 7-bit Lookup Table (128 values) DACLookup_FullSine_7Bit = \ [ 2048, 2148, 2248, 2348, 2447, 2545, 2642, 2737, 2831, 2923, 3013, 3100, 3185, 3267, 3346, 3423, 3495, 3565, 3630, 3692, 3750, 3804, 3853, 3898, 3939, 3975, 4007, 4034, 4056, 4073, 4085, 4093, 4095, 4093, 4085, 4073, 4056, 4034, 4007, 3975, 3939, 3898, 3853, 3804, 3750, 3692, 3630, 3565, 3495, 3423, 3346, 3267, 3185, 3100, 3013, 2923, 2831, 2737, 2642, 2545, 2447, 2348, 2248, 2148, 2048, 1947, 1847, 1747, 1648, 1550, 1453, 1358, 1264, 1172, 1082, 995, 910, 828, 749, 672, 600, 530, 465, 403, 345, 291, 242, 197, 156, 120, 88, 61, 39, 22, 10, 2, 0, 2, 10, 22, 39, 61, 88, 120, 156, 197, 242, 291, 345, 403, 465, 530, 600, 672, 749, 828, 910, 995, 1082, 1172, 1264, 1358, 1453, 1550, 1648, 1747, 1847, 1947 ] # 6-bit Lookup Table (64 values) DACLookup_FullSine_6Bit = \ [ 2048, 2248, 2447, 2642, 2831, 3013, 3185, 3346, 3495, 3630, 3750, 3853, 3939, 4007, 4056, 4085, 4095, 4085, 4056, 4007, 3939, 3853, 3750, 3630, 3495, 3346, 3185, 3013, 2831, 2642, 2447, 2248, 2048, 1847, 1648, 1453, 1264, 1082, 910, 749, 600, 465, 345, 242, 156, 88, 39, 10, 0, 10, 39, 88, 156, 242, 345, 465, 600, 749, 910, 1082, 1264, 1453, 1648, 1847 ] # 5-bit Lookup Table (32 values) DACLookup_FullSine_5Bit = \ [ 2048, 2447, 2831, 3185, 3495, 3750, 3939, 4056, 4095, 4056, 3939, 3750, 3495, 3185, 2831, 2447, 2048, 1648, 1264, 910, 600, 345, 156, 39, 0, 39, 156, 345, 600, 910, 1264, 1648 ] # Initialise the DAC using the default address dac = MCP4725(0x62) if (DAC_RESOLUTION < 5) | (DAC_RESOLUTION > 9): print "Invalid DAC resolution: Set DAC_RESOLUTION from 5..9" else: print "Generating a sine wave with %d-bit resolution" % DAC_RESOLUTION print "Press CTRL+C to stop" while(True): if (DAC_RESOLUTION == 9): for val in DACLookup_FullSine_9Bit: dac.setVoltage(val) if (DAC_RESOLUTION == 8): for val in DACLookup_FullSine_8Bit: dac.setVoltage(val) if (DAC_RESOLUTION == 7): for val in DACLookup_FullSine_7Bit: dac.setVoltage(val) if (DAC_RESOLUTION == 6): for val in DACLookup_FullSine_6Bit: dac.setVoltage(val) if (DAC_RESOLUTION == 5): for val in DACLookup_FullSine_5Bit: dac.setVoltage(val)
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/MCP4725/sinewave.py
sinewave.py
# Python library for Adafruit Flora Accelerometer/Compass Sensor (LSM303). # This is pretty much a direct port of the current Arduino library and is # similarly incomplete (e.g. no orientation value returned from read() # method). This does add optional high resolution mode to accelerometer # though. # Copyright 2013 Adafruit Industries # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from Adafruit.I2C import Adafruit_I2C class Adafruit_LSM303(Adafruit_I2C): # Minimal constants carried over from Arduino library LSM303_ADDRESS_ACCEL = (0x32 >> 1) # 0011001x LSM303_ADDRESS_MAG = (0x3C >> 1) # 0011110x # Default Type LSM303_REGISTER_ACCEL_CTRL_REG1_A = 0x20 # 00000111 rw LSM303_REGISTER_ACCEL_CTRL_REG4_A = 0x23 # 00000000 rw LSM303_REGISTER_ACCEL_OUT_X_L_A = 0x28 LSM303_REGISTER_MAG_CRB_REG_M = 0x01 LSM303_REGISTER_MAG_MR_REG_M = 0x02 LSM303_REGISTER_MAG_OUT_X_H_M = 0x03 # Gain settings for setMagGain() LSM303_MAGGAIN_1_3 = 0x20 # +/- 1.3 LSM303_MAGGAIN_1_9 = 0x40 # +/- 1.9 LSM303_MAGGAIN_2_5 = 0x60 # +/- 2.5 LSM303_MAGGAIN_4_0 = 0x80 # +/- 4.0 LSM303_MAGGAIN_4_7 = 0xA0 # +/- 4.7 LSM303_MAGGAIN_5_6 = 0xC0 # +/- 5.6 LSM303_MAGGAIN_8_1 = 0xE0 # +/- 8.1 def __init__(self, busnum=-1, debug=False, hires=False): # Accelerometer and magnetometer are at different I2C # addresses, so invoke a separate I2C instance for each self.accel = Adafruit_I2C(self.LSM303_ADDRESS_ACCEL, busnum, debug) self.mag = Adafruit_I2C(self.LSM303_ADDRESS_MAG , busnum, debug) # Enable the accelerometer self.accel.write8(self.LSM303_REGISTER_ACCEL_CTRL_REG1_A, 0x27) # Select hi-res (12-bit) or low-res (10-bit) output mode. # Low-res mode uses less power and sustains a higher update rate, # output is padded to compatible 12-bit units. if hires: self.accel.write8(self.LSM303_REGISTER_ACCEL_CTRL_REG4_A, 0b00001000) else: self.accel.write8(self.LSM303_REGISTER_ACCEL_CTRL_REG4_A, 0) # Enable the magnetometer self.mag.write8(self.LSM303_REGISTER_MAG_MR_REG_M, 0x00) # Interpret signed 12-bit acceleration component from list def accel12(self, list, idx): n = list[idx] | (list[idx+1] << 8) # Low, high bytes if n > 32767: n -= 65536 # 2's complement signed return n >> 4 # 12-bit resolution # Interpret signed 16-bit magnetometer component from list def mag16(self, list, idx): n = (list[idx] << 8) | list[idx+1] # High, low bytes return n if n < 32768 else n - 65536 # 2's complement signed def read(self): # Read the accelerometer list = self.accel.readList( self.LSM303_REGISTER_ACCEL_OUT_X_L_A | 0x80, 6) res = [( self.accel12(list, 0), self.accel12(list, 2), self.accel12(list, 4) )] # Read the magnetometer list = self.mag.readList(self.LSM303_REGISTER_MAG_OUT_X_H_M, 6) res.append((self.mag16(list, 0), self.mag16(list, 2), self.mag16(list, 4), 0.0 )) # ToDo: Calculate orientation return res def setMagGain(gain=LSM303_MAGGAIN_1_3): self.mag.write8( LSM303_REGISTER_MAG_CRB_REG_M, gain) # Simple example prints accel/mag data once per second: if __name__ == '__main__': from time import sleep lsm = Adafruit_LSM303() print '[(Accelerometer X, Y, Z), (Magnetometer X, Y, Z, orientation)]' while True: print lsm.read() sleep(1) # Output is fun to watch if this is commented out
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/LSM303/Adafruit_LSM303.py
Adafruit_LSM303.py
# Test code for Adafruit LED Pixels, uses hardware SPI import RPi.GPIO as GPIO, time, os DEBUG = 1 GPIO.setmode(GPIO.BCM) def slowspiwrite(clockpin, datapin, byteout): GPIO.setup(clockpin, GPIO.OUT) GPIO.setup(datapin, GPIO.OUT) for i in range(8): if (byteout & 0x80): GPIO.output(datapin, True) else: GPIO.output(clockpin, False) byteout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) SPICLK = 18 SPIDO = 17 ledpixels = [0] * 25 def writestrip(pixels): spidev = file("/dev/spidev0.0", "w") for i in range(len(pixels)): spidev.write(chr((pixels[i]>>16) & 0xFF)) spidev.write(chr((pixels[i]>>8) & 0xFF)) spidev.write(chr(pixels[i] & 0xFF)) spidev.close() time.sleep(0.002) def Color(r, g, b): return ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF) def setpixelcolor(pixels, n, r, g, b): if (n >= len(pixels)): return pixels[n] = Color(r,g,b) def setpixelcolor(pixels, n, c): if (n >= len(pixels)): return pixels[n] = c def colorwipe(pixels, c, delay): for i in range(len(pixels)): setpixelcolor(pixels, i, c) writestrip(pixels) time.sleep(delay) def Wheel(WheelPos): if (WheelPos < 85): return Color(WheelPos * 3, 255 - WheelPos * 3, 0) elif (WheelPos < 170): WheelPos -= 85; return Color(255 - WheelPos * 3, 0, WheelPos * 3) else: WheelPos -= 170; return Color(0, WheelPos * 3, 255 - WheelPos * 3) def rainbowCycle(pixels, wait): for j in range(256): # one cycle of all 256 colors in the wheel for i in range(len(pixels)): # tricky math! we use each pixel as a fraction of the full 96-color wheel # (thats the i / strip.numPixels() part) # Then add in j which makes the colors go around per pixel # the % 96 is to make the wheel cycle around setpixelcolor(pixels, i, Wheel( ((i * 256 / len(pixels)) + j) % 256) ) writestrip(pixels) time.sleep(wait) colorwipe(ledpixels, Color(255, 0, 0), 0.05) colorwipe(ledpixels, Color(0, 255, 0), 0.05) colorwipe(ledpixels, Color(0, 0, 255), 0.05) while True: rainbowCycle(ledpixels, 0.00)
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/LEDpixels/Adafruit_LEDpixels.py
Adafruit_LEDpixels.py
# just some bitbang code for testing all 8 channels import RPi.GPIO as GPIO, time, os DEBUG = 1 GPIO.setmode(GPIO.BCM) # this function is not used, its for future reference! def slowspiwrite(clockpin, datapin, byteout): GPIO.setup(clockpin, GPIO.OUT) GPIO.setup(datapin, GPIO.OUT) for i in range(8): if (byteout & 0x80): GPIO.output(datapin, True) else: GPIO.output(datapin, False) byteout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) # this function is not used, its for future reference! def slowspiread(clockpin, datapin): GPIO.setup(clockpin, GPIO.OUT) GPIO.setup(datapin, GPIO.IN) byteout = 0 for i in range(8): GPIO.output(clockpin, False) GPIO.output(clockpin, True) byteout <<= 1 if (GPIO.input(datapin)): byteout = byteout | 0x1 return byteout # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7) def readadc(adcnum, clockpin, mosipin, misopin, cspin): if ((adcnum > 7) or (adcnum < 0)): return -1 GPIO.output(cspin, True) GPIO.output(clockpin, False) # start clock low GPIO.output(cspin, False) # bring CS low commandout = adcnum commandout |= 0x18 # start bit + single-ended bit commandout <<= 3 # we only need to send 5 bits here for i in range(5): if (commandout & 0x80): GPIO.output(mosipin, True) else: GPIO.output(mosipin, False) commandout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout = 0 # read in one empty bit, one null bit and 10 ADC bits for i in range(12): GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout <<= 1 if (GPIO.input(misopin)): adcout |= 0x1 GPIO.output(cspin, True) adcout /= 2 # first bit is 'null' so drop it return adcout # change these as desired SPICLK = 18 SPIMOSI = 17 SPIMISO = 21 SPICS = 22 # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) # Note that bitbanging SPI is incredibly slow on the Pi as its not # a RTOS - reading the ADC takes about 30 ms (~30 samples per second) # which is awful for a microcontroller but better-than-nothing for Linux print "| #0 \t #1 \t #2 \t #3 \t #4 \t #5 \t #6 \t #7\t|" print "-----------------------------------------------------------------" while True: print "|", for adcnum in range(8): ret = readadc(adcnum, SPICLK, SPIMOSI, SPIMISO, SPICS) print ret,"\t", print "|"
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/MCP3008/mcp3008.py
mcp3008.py
import time import math from Adafruit.I2C import Adafruit_I2C # ============================================================================ # Adafruit PCA9685 16-Channel PWM Servo Driver # ============================================================================ class PWM : i2c = None # Registers/etc. __SUBADR1 = 0x02 __SUBADR2 = 0x03 __SUBADR3 = 0x04 __MODE1 = 0x00 __PRESCALE = 0xFE __LED0_ON_L = 0x06 __LED0_ON_H = 0x07 __LED0_OFF_L = 0x08 __LED0_OFF_H = 0x09 __ALLLED_ON_L = 0xFA __ALLLED_ON_H = 0xFB __ALLLED_OFF_L = 0xFC __ALLLED_OFF_H = 0xFD def __init__(self, address=0x40, debug=False): self.i2c = Adafruit_I2C(address) self.address = address self.debug = debug if (self.debug): print "Reseting PCA9685" self.i2c.write8(self.__MODE1, 0x00) def setPWMFreq(self, freq): "Sets the PWM frequency" prescaleval = 25000000.0 # 25MHz prescaleval /= 4096.0 # 12-bit prescaleval /= float(freq) prescaleval -= 1.0 if (self.debug): print "Setting PWM frequency to %d Hz" % freq print "Estimated pre-scale: %d" % prescaleval prescale = math.floor(prescaleval + 0.5) if (self.debug): print "Final pre-scale: %d" % prescale oldmode = self.i2c.readU8(self.__MODE1); newmode = (oldmode & 0x7F) | 0x10 # sleep self.i2c.write8(self.__MODE1, newmode) # go to sleep self.i2c.write8(self.__PRESCALE, int(math.floor(prescale))) self.i2c.write8(self.__MODE1, oldmode) time.sleep(0.005) self.i2c.write8(self.__MODE1, oldmode | 0x80) def setPWM(self, channel, on, off): "Sets a single PWM channel" self.i2c.write8(self.__LED0_ON_L+4*channel, on & 0xFF) self.i2c.write8(self.__LED0_ON_H+4*channel, on >> 8) self.i2c.write8(self.__LED0_OFF_L+4*channel, off & 0xFF) self.i2c.write8(self.__LED0_OFF_H+4*channel, off >> 8)
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/PWM_Servo_Driver/Adafruit_PWM_Servo_Driver.py
Adafruit_PWM_Servo_Driver.py
import sys import time import datetime import gspread from Adafruit_BMP085 import BMP085 # =========================================================================== # Google Account Details # =========================================================================== # Account details for google docs email = '[email protected]' password = '$hhh!' spreadsheet = 'SpreadsheetName' # =========================================================================== # Example Code # =========================================================================== # Initialise the BMP085 and use STANDARD mode (default value) # bmp = BMP085(0x77, debug=True) bmp = BMP085(0x77) # To specify a different operating mode, uncomment one of the following: # bmp = BMP085(0x77, 0) # ULTRALOWPOWER Mode # bmp = BMP085(0x77, 1) # STANDARD Mode # bmp = BMP085(0x77, 2) # HIRES Mode # bmp = BMP085(0x77, 3) # ULTRAHIRES Mode # Login with your Google account try: gc = gspread.login(email, password) except: print "Unable to log in. Check your email address/password" sys.exit() # Open a worksheet from your spreadsheet using the filename try: worksheet = gc.open(spreadsheet).sheet1 # Alternatively, open a spreadsheet using the spreadsheet's key # worksheet = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') except: print "Unable to open the spreadsheet. Check your filename: %s" % spreadsheet sys.exit() # Continuously append data while(True): temp = bmp.readTemperature() pressure = bmp.readPressure() altitude = bmp.readAltitude() print "Temperature: %.2f C" % temp print "Pressure: %.2f hPa" % (pressure / 100.0) print "Altitude: %.2f" % altitude # Append the data in the spreadsheet, including a timestamp try: values = [datetime.datetime.now(), temp, pressure, altitude] worksheet.append_row(values) except: print "Unable to append data. Check your connection?" sys.exit() # Wait 5 seconds before continuing print "Wrote a row to %s" % spreadsheet time.sleep(5)
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/BMP085/Adafruit_BMP085_googledocs_ex.py
Adafruit_BMP085_googledocs_ex.py
import time from Adafruit.I2C import Adafruit_I2C # =========================================================================== # BMP085 Class # =========================================================================== class BMP085 : i2c = None # Operating Modes __BMP085_ULTRALOWPOWER = 0 __BMP085_STANDARD = 1 __BMP085_HIGHRES = 2 __BMP085_ULTRAHIGHRES = 3 # BMP085 Registers __BMP085_CAL_AC1 = 0xAA # R Calibration data (16 bits) __BMP085_CAL_AC2 = 0xAC # R Calibration data (16 bits) __BMP085_CAL_AC3 = 0xAE # R Calibration data (16 bits) __BMP085_CAL_AC4 = 0xB0 # R Calibration data (16 bits) __BMP085_CAL_AC5 = 0xB2 # R Calibration data (16 bits) __BMP085_CAL_AC6 = 0xB4 # R Calibration data (16 bits) __BMP085_CAL_B1 = 0xB6 # R Calibration data (16 bits) __BMP085_CAL_B2 = 0xB8 # R Calibration data (16 bits) __BMP085_CAL_MB = 0xBA # R Calibration data (16 bits) __BMP085_CAL_MC = 0xBC # R Calibration data (16 bits) __BMP085_CAL_MD = 0xBE # R Calibration data (16 bits) __BMP085_CONTROL = 0xF4 __BMP085_TEMPDATA = 0xF6 __BMP085_PRESSUREDATA = 0xF6 __BMP085_READTEMPCMD = 0x2E __BMP085_READPRESSURECMD = 0x34 # Private Fields _cal_AC1 = 0 _cal_AC2 = 0 _cal_AC3 = 0 _cal_AC4 = 0 _cal_AC5 = 0 _cal_AC6 = 0 _cal_B1 = 0 _cal_B2 = 0 _cal_MB = 0 _cal_MC = 0 _cal_MD = 0 # Constructor def __init__(self, address=0x77, mode=1, debug=False): self.i2c = Adafruit_I2C(address) self.address = address self.debug = debug # Make sure the specified mode is in the appropriate range if ((mode < 0) | (mode > 3)): if (self.debug): print "Invalid Mode: Using STANDARD by default" self.mode = self.__BMP085_STANDARD else: self.mode = mode # Read the calibration data self.readCalibrationData() def readS16(self, register): "Reads a signed 16-bit value" hi = self.i2c.readS8(register) lo = self.i2c.readU8(register+1) return (hi << 8) + lo def readU16(self, register): "Reads an unsigned 16-bit value" hi = self.i2c.readU8(register) lo = self.i2c.readU8(register+1) return (hi << 8) + lo def readCalibrationData(self): "Reads the calibration data from the IC" self._cal_AC1 = self.readS16(self.__BMP085_CAL_AC1) # INT16 self._cal_AC2 = self.readS16(self.__BMP085_CAL_AC2) # INT16 self._cal_AC3 = self.readS16(self.__BMP085_CAL_AC3) # INT16 self._cal_AC4 = self.readU16(self.__BMP085_CAL_AC4) # UINT16 self._cal_AC5 = self.readU16(self.__BMP085_CAL_AC5) # UINT16 self._cal_AC6 = self.readU16(self.__BMP085_CAL_AC6) # UINT16 self._cal_B1 = self.readS16(self.__BMP085_CAL_B1) # INT16 self._cal_B2 = self.readS16(self.__BMP085_CAL_B2) # INT16 self._cal_MB = self.readS16(self.__BMP085_CAL_MB) # INT16 self._cal_MC = self.readS16(self.__BMP085_CAL_MC) # INT16 self._cal_MD = self.readS16(self.__BMP085_CAL_MD) # INT16 if (self.debug): self.showCalibrationData() def showCalibrationData(self): "Displays the calibration values for debugging purposes" print "DBG: AC1 = %6d" % (self._cal_AC1) print "DBG: AC2 = %6d" % (self._cal_AC2) print "DBG: AC3 = %6d" % (self._cal_AC3) print "DBG: AC4 = %6d" % (self._cal_AC4) print "DBG: AC5 = %6d" % (self._cal_AC5) print "DBG: AC6 = %6d" % (self._cal_AC6) print "DBG: B1 = %6d" % (self._cal_B1) print "DBG: B2 = %6d" % (self._cal_B2) print "DBG: MB = %6d" % (self._cal_MB) print "DBG: MC = %6d" % (self._cal_MC) print "DBG: MD = %6d" % (self._cal_MD) def readRawTemp(self): "Reads the raw (uncompensated) temperature from the sensor" self.i2c.write8(self.__BMP085_CONTROL, self.__BMP085_READTEMPCMD) time.sleep(0.005) # Wait 5ms raw = self.readU16(self.__BMP085_TEMPDATA) if (self.debug): print "DBG: Raw Temp: 0x%04X (%d)" % (raw & 0xFFFF, raw) return raw def readRawPressure(self): "Reads the raw (uncompensated) pressure level from the sensor" self.i2c.write8(self.__BMP085_CONTROL, self.__BMP085_READPRESSURECMD + (self.mode << 6)) if (self.mode == self.__BMP085_ULTRALOWPOWER): time.sleep(0.005) elif (self.mode == self.__BMP085_HIGHRES): time.sleep(0.014) elif (self.mode == self.__BMP085_ULTRAHIGHRES): time.sleep(0.026) else: time.sleep(0.008) msb = self.i2c.readU8(self.__BMP085_PRESSUREDATA) lsb = self.i2c.readU8(self.__BMP085_PRESSUREDATA+1) xlsb = self.i2c.readU8(self.__BMP085_PRESSUREDATA+2) raw = ((msb << 16) + (lsb << 8) + xlsb) >> (8 - self.mode) if (self.debug): print "DBG: Raw Pressure: 0x%04X (%d)" % (raw & 0xFFFF, raw) return raw def readTemperature(self): "Gets the compensated temperature in degrees celcius" UT = 0 X1 = 0 X2 = 0 B5 = 0 temp = 0.0 # Read raw temp before aligning it with the calibration values UT = self.readRawTemp() X1 = ((UT - self._cal_AC6) * self._cal_AC5) >> 15 X2 = (self._cal_MC << 11) / (X1 + self._cal_MD) B5 = X1 + X2 temp = ((B5 + 8) >> 4) / 10.0 if (self.debug): print "DBG: Calibrated temperature = %f C" % temp return temp def readPressure(self): "Gets the compensated pressure in pascal" UT = 0 UP = 0 B3 = 0 B5 = 0 B6 = 0 X1 = 0 X2 = 0 X3 = 0 p = 0 B4 = 0 B7 = 0 UT = self.readRawTemp() UP = self.readRawPressure() # You can use the datasheet values to test the conversion results # dsValues = True dsValues = False if (dsValues): UT = 27898 UP = 23843 self._cal_AC6 = 23153 self._cal_AC5 = 32757 self._cal_MB = -32768; self._cal_MC = -8711 self._cal_MD = 2868 self._cal_B1 = 6190 self._cal_B2 = 4 self._cal_AC3 = -14383 self._cal_AC2 = -72 self._cal_AC1 = 408 self._cal_AC4 = 32741 self.mode = self.__BMP085_ULTRALOWPOWER if (self.debug): self.showCalibrationData() # True Temperature Calculations X1 = ((UT - self._cal_AC6) * self._cal_AC5) >> 15 X2 = (self._cal_MC << 11) / (X1 + self._cal_MD) B5 = X1 + X2 if (self.debug): print "DBG: X1 = %d" % (X1) print "DBG: X2 = %d" % (X2) print "DBG: B5 = %d" % (B5) print "DBG: True Temperature = %.2f C" % (((B5 + 8) >> 4) / 10.0) # Pressure Calculations B6 = B5 - 4000 X1 = (self._cal_B2 * (B6 * B6) >> 12) >> 11 X2 = (self._cal_AC2 * B6) >> 11 X3 = X1 + X2 B3 = (((self._cal_AC1 * 4 + X3) << self.mode) + 2) / 4 if (self.debug): print "DBG: B6 = %d" % (B6) print "DBG: X1 = %d" % (X1) print "DBG: X2 = %d" % (X2) print "DBG: X3 = %d" % (X3) print "DBG: B3 = %d" % (B3) X1 = (self._cal_AC3 * B6) >> 13 X2 = (self._cal_B1 * ((B6 * B6) >> 12)) >> 16 X3 = ((X1 + X2) + 2) >> 2 B4 = (self._cal_AC4 * (X3 + 32768)) >> 15 B7 = (UP - B3) * (50000 >> self.mode) if (self.debug): print "DBG: X1 = %d" % (X1) print "DBG: X2 = %d" % (X2) print "DBG: X3 = %d" % (X3) print "DBG: B4 = %d" % (B4) print "DBG: B7 = %d" % (B7) if (B7 < 0x80000000): p = (B7 * 2) / B4 else: p = (B7 / B4) * 2 if (self.debug): print "DBG: X1 = %d" % (X1) X1 = (p >> 8) * (p >> 8) X1 = (X1 * 3038) >> 16 X2 = (-7357 * p) >> 16 if (self.debug): print "DBG: p = %d" % (p) print "DBG: X1 = %d" % (X1) print "DBG: X2 = %d" % (X2) p = p + ((X1 + X2 + 3791) >> 4) if (self.debug): print "DBG: Pressure = %d Pa" % (p) return p def readAltitude(self, seaLevelPressure=101325): "Calculates the altitude in meters" altitude = 0.0 pressure = float(self.readPressure()) altitude = 44330.0 * (1.0 - pow(pressure / seaLevelPressure, 0.1903)) if (self.debug): print "DBG: Altitude = %d" % (altitude) return altitude return 0
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/BMP085/Adafruit_BMP085.py
Adafruit_BMP085.py
# Python library for Adafruit RGB-backlit LCD plate for Raspberry Pi. # Written by Adafruit Industries. MIT license. # This is essentially a complete rewrite, but the calling syntax # and constants are based on code from lrvick and LiquidCrystal. # lrvic - https://github.com/lrvick/raspi-hd44780/blob/master/hd44780.py # LiquidCrystal - https://github.com/arduino/Arduino/blob/master/libraries/LiquidCrystal/LiquidCrystal.cpp from Adafruit.I2C import Adafruit_I2C from time import sleep class Adafruit_CharLCDPlate(Adafruit_I2C): # ---------------------------------------------------------------------- # Constants # Port expander registers MCP23017_IOCON_BANK0 = 0x0A # IOCON when Bank 0 active MCP23017_IOCON_BANK1 = 0x15 # IOCON when Bank 1 active # These are register addresses when in Bank 1 only: MCP23017_GPIOA = 0x09 MCP23017_IODIRB = 0x10 MCP23017_GPIOB = 0x19 # Port expander input pin definitions SELECT = 0 RIGHT = 1 DOWN = 2 UP = 3 LEFT = 4 # LED colors OFF = 0x00 RED = 0x01 GREEN = 0x02 BLUE = 0x04 YELLOW = RED + GREEN TEAL = GREEN + BLUE VIOLET = RED + BLUE WHITE = RED + GREEN + BLUE ON = RED + GREEN + BLUE # LCD Commands LCD_CLEARDISPLAY = 0x01 LCD_RETURNHOME = 0x02 LCD_ENTRYMODESET = 0x04 LCD_DISPLAYCONTROL = 0x08 LCD_CURSORSHIFT = 0x10 LCD_FUNCTIONSET = 0x20 LCD_SETCGRAMADDR = 0x40 LCD_SETDDRAMADDR = 0x80 # Flags for display on/off control LCD_DISPLAYON = 0x04 LCD_DISPLAYOFF = 0x00 LCD_CURSORON = 0x02 LCD_CURSOROFF = 0x00 LCD_BLINKON = 0x01 LCD_BLINKOFF = 0x00 # Flags for display entry mode LCD_ENTRYRIGHT = 0x00 LCD_ENTRYLEFT = 0x02 LCD_ENTRYSHIFTINCREMENT = 0x01 LCD_ENTRYSHIFTDECREMENT = 0x00 # Flags for display/cursor shift LCD_DISPLAYMOVE = 0x08 LCD_CURSORMOVE = 0x00 LCD_MOVERIGHT = 0x04 LCD_MOVELEFT = 0x00 # ---------------------------------------------------------------------- # Constructor def __init__(self, busnum=-1, addr=0x20, debug=False): self.i2c = Adafruit_I2C(addr, busnum, debug) # I2C is relatively slow. MCP output port states are cached # so we don't need to constantly poll-and-change bit states. self.porta, self.portb, self.ddrb = 0, 0, 0b00010000 # Set MCP23017 IOCON register to Bank 0 with sequential operation. # If chip is already set for Bank 0, this will just write to OLATB, # which won't seriously bother anything on the plate right now # (blue backlight LED will come on, but that's done in the next # step anyway). self.i2c.bus.write_byte_data( self.i2c.address, self.MCP23017_IOCON_BANK1, 0) # Brute force reload ALL registers to known state. This also # sets up all the input pins, pull-ups, etc. for the Pi Plate. self.i2c.bus.write_i2c_block_data( self.i2c.address, 0, [ 0b00111111, # IODIRA R+G LEDs=outputs, buttons=inputs self.ddrb , # IODIRB LCD D7=input, Blue LED=output 0b00111111, # IPOLA Invert polarity on button inputs 0b00000000, # IPOLB 0b00000000, # GPINTENA Disable interrupt-on-change 0b00000000, # GPINTENB 0b00000000, # DEFVALA 0b00000000, # DEFVALB 0b00000000, # INTCONA 0b00000000, # INTCONB 0b00000000, # IOCON 0b00000000, # IOCON 0b00111111, # GPPUA Enable pull-ups on buttons 0b00000000, # GPPUB 0b00000000, # INTFA 0b00000000, # INTFB 0b00000000, # INTCAPA 0b00000000, # INTCAPB self.porta, # GPIOA self.portb, # GPIOB self.porta, # OLATA 0 on all outputs; side effect of self.portb ]) # OLATB turning on R+G+B backlight LEDs. # Switch to Bank 1 and disable sequential operation. # From this point forward, the register addresses do NOT match # the list immediately above. Instead, use the constants defined # at the start of the class. Also, the address register will no # longer increment automatically after this -- multi-byte # operations must be broken down into single-byte calls. self.i2c.bus.write_byte_data( self.i2c.address, self.MCP23017_IOCON_BANK0, 0b10100000) self.displayshift = (self.LCD_CURSORMOVE | self.LCD_MOVERIGHT) self.displaymode = (self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT) self.displaycontrol = (self.LCD_DISPLAYON | self.LCD_CURSOROFF | self.LCD_BLINKOFF) self.write(0x33) # Init self.write(0x32) # Init self.write(0x28) # 2 line 5x8 matrix self.write(self.LCD_CLEARDISPLAY) self.write(self.LCD_CURSORSHIFT | self.displayshift) self.write(self.LCD_ENTRYMODESET | self.displaymode) self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) self.write(self.LCD_RETURNHOME) # ---------------------------------------------------------------------- # Write operations # The LCD data pins (D4-D7) connect to MCP pins 12-9 (PORTB4-1), in # that order. Because this sequence is 'reversed,' a direct shift # won't work. This table remaps 4-bit data values to MCP PORTB # outputs, incorporating both the reverse and shift. flip = ( 0b00000000, 0b00010000, 0b00001000, 0b00011000, 0b00000100, 0b00010100, 0b00001100, 0b00011100, 0b00000010, 0b00010010, 0b00001010, 0b00011010, 0b00000110, 0b00010110, 0b00001110, 0b00011110 ) # Low-level 4-bit interface for LCD output. This doesn't actually # write data, just returns a byte array of the PORTB state over time. # Can concatenate the output of multiple calls (up to 8) for more # efficient batch write. def out4(self, bitmask, value): hi = bitmask | self.flip[value >> 4] lo = bitmask | self.flip[value & 0x0F] return [hi | 0b00100000, hi, lo | 0b00100000, lo] # The speed of LCD accesses is inherently limited by I2C through the # port expander. A 'well behaved program' is expected to poll the # LCD to know that a prior instruction completed. But the timing of # most instructions is a known uniform 37 mS. The enable strobe # can't even be twiddled that fast through I2C, so it's a safe bet # with these instructions to not waste time polling (which requires # several I2C transfers for reconfiguring the port direction). # The D7 pin is set as input when a potentially time-consuming # instruction has been issued (e.g. screen clear), as well as on # startup, and polling will then occur before more commands or data # are issued. pollables = ( LCD_CLEARDISPLAY, LCD_RETURNHOME ) # Write byte, list or string value to LCD def write(self, value, char_mode=False): """ Send command/data to LCD """ # If pin D7 is in input state, poll LCD busy flag until clear. if self.ddrb & 0b00010000: lo = (self.portb & 0b00000001) | 0b01000000 hi = lo | 0b00100000 # E=1 (strobe) self.i2c.bus.write_byte_data( self.i2c.address, self.MCP23017_GPIOB, lo) while True: # Strobe high (enable) self.i2c.bus.write_byte(self.i2c.address, hi) # First nybble contains busy state bits = self.i2c.bus.read_byte(self.i2c.address) # Strobe low, high, low. Second nybble (A3) is ignored. self.i2c.bus.write_i2c_block_data( self.i2c.address, self.MCP23017_GPIOB, [lo, hi, lo]) if (bits & 0b00000010) == 0: break # D7=0, not busy self.portb = lo # Polling complete, change D7 pin to output self.ddrb &= 0b11101111 self.i2c.bus.write_byte_data(self.i2c.address, self.MCP23017_IODIRB, self.ddrb) bitmask = self.portb & 0b00000001 # Mask out PORTB LCD control bits if char_mode: bitmask |= 0b10000000 # Set data bit if not a command # If string or list, iterate through multiple write ops if isinstance(value, str): last = len(value) - 1 # Last character in string data = [] # Start with blank list for i, v in enumerate(value): # For each character... # Append 4 bytes to list representing PORTB over time. # First the high 4 data bits with strobe (enable) set # and unset, then same with low 4 data bits (strobe 1/0). data.extend(self.out4(bitmask, ord(v))) # I2C block data write is limited to 32 bytes max. # If limit reached, write data so far and clear. # Also do this on last byte if not otherwise handled. if (len(data) >= 32) or (i == last): self.i2c.bus.write_i2c_block_data( self.i2c.address, self.MCP23017_GPIOB, data) self.portb = data[-1] # Save state of last byte out data = [] # Clear list for next iteration elif isinstance(value, list): # Same as above, but for list instead of string last = len(value) - 1 data = [] for i, v in enumerate(value): data.extend(self.out4(bitmask, v)) if (len(data) >= 32) or (i == last): self.i2c.bus.write_i2c_block_data( self.i2c.address, self.MCP23017_GPIOB, data) self.portb = data[-1] data = [] else: # Single byte data = self.out4(bitmask, value) self.i2c.bus.write_i2c_block_data( self.i2c.address, self.MCP23017_GPIOB, data) self.portb = data[-1] # If a poll-worthy instruction was issued, reconfigure D7 # pin as input to indicate need for polling on next call. if (not char_mode) and (value in self.pollables): self.ddrb |= 0b00010000 self.i2c.bus.write_byte_data(self.i2c.address, self.MCP23017_IODIRB, self.ddrb) # ---------------------------------------------------------------------- # Utility methods def begin(self, cols, lines): self.currline = 0 self.numlines = lines self.clear() # Puts the MCP23017 back in Bank 0 + sequential write mode so # that other code using the 'classic' library can still work. # Any code using this newer version of the library should # consider adding an atexit() handler that calls this. def stop(self): self.porta = 0b11000000 # Turn off LEDs on the way out self.portb = 0b00000001 sleep(0.0015) self.i2c.bus.write_byte_data( self.i2c.address, self.MCP23017_IOCON_BANK1, 0) self.i2c.bus.write_i2c_block_data( self.i2c.address, 0, [ 0b00111111, # IODIRA self.ddrb , # IODIRB 0b00000000, # IPOLA 0b00000000, # IPOLB 0b00000000, # GPINTENA 0b00000000, # GPINTENB 0b00000000, # DEFVALA 0b00000000, # DEFVALB 0b00000000, # INTCONA 0b00000000, # INTCONB 0b00000000, # IOCON 0b00000000, # IOCON 0b00111111, # GPPUA 0b00000000, # GPPUB 0b00000000, # INTFA 0b00000000, # INTFB 0b00000000, # INTCAPA 0b00000000, # INTCAPB self.porta, # GPIOA self.portb, # GPIOB self.porta, # OLATA self.portb ]) # OLATB def clear(self): self.write(self.LCD_CLEARDISPLAY) def home(self): self.write(self.LCD_RETURNHOME) row_offsets = ( 0x00, 0x40, 0x14, 0x54 ) def setCursor(self, col, row): if row > self.numlines: row = self.numlines - 1 elif row < 0: row = 0 self.write(self.LCD_SETDDRAMADDR | (col + self.row_offsets[row])) def display(self): """ Turn the display on (quickly) """ self.displaycontrol |= self.LCD_DISPLAYON self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) def noDisplay(self): """ Turn the display off (quickly) """ self.displaycontrol &= ~self.LCD_DISPLAYON self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) def cursor(self): """ Underline cursor on """ self.displaycontrol |= self.LCD_CURSORON self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) def noCursor(self): """ Underline cursor off """ self.displaycontrol &= ~self.LCD_CURSORON self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) def ToggleCursor(self): """ Toggles the underline cursor On/Off """ self.displaycontrol ^= self.LCD_CURSORON self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) def blink(self): """ Turn on the blinking cursor """ self.displaycontrol |= self.LCD_BLINKON self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) def noBlink(self): """ Turn off the blinking cursor """ self.displaycontrol &= ~self.LCD_BLINKON self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) def ToggleBlink(self): """ Toggles the blinking cursor """ self.displaycontrol ^= self.LCD_BLINKON self.write(self.LCD_DISPLAYCONTROL | self.displaycontrol) def scrollDisplayLeft(self): """ These commands scroll the display without changing the RAM """ self.displayshift = self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT self.write(self.LCD_CURSORSHIFT | self.displayshift) def scrollDisplayRight(self): """ These commands scroll the display without changing the RAM """ self.displayshift = self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT self.write(self.LCD_CURSORSHIFT | self.displayshift) def leftToRight(self): """ This is for text that flows left to right """ self.displaymode |= self.LCD_ENTRYLEFT self.write(self.LCD_ENTRYMODESET | self.displaymode) def rightToLeft(self): """ This is for text that flows right to left """ self.displaymode &= ~self.LCD_ENTRYLEFT self.write(self.LCD_ENTRYMODESET | self.displaymode) def autoscroll(self): """ This will 'right justify' text from the cursor """ self.displaymode |= self.LCD_ENTRYSHIFTINCREMENT self.write(self.LCD_ENTRYMODESET | self.displaymode) def noAutoscroll(self): """ This will 'left justify' text from the cursor """ self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENT self.write(self.LCD_ENTRYMODESET | self.displaymode) def createChar(self, location, bitmap): self.write(self.LCD_SETCGRAMADDR | ((location & 7) << 3)) self.write(bitmap, True) self.write(self.LCD_SETDDRAMADDR) def message(self, text): """ Send string to LCD. Newline wraps to second line""" lines = str(text).split('\n') # Split at newline(s) for i, line in enumerate(lines): # For each substring... if i > 0: # If newline(s), self.write(0xC0) # set DDRAM address to 2nd line self.write(line, True) # Issue substring def backlight(self, color): c = ~color self.porta = (self.porta & 0b00111111) | ((c & 0b011) << 6) self.portb = (self.portb & 0b11111110) | ((c & 0b100) >> 2) # Has to be done as two writes because sequential operation is off. self.i2c.bus.write_byte_data( self.i2c.address, self.MCP23017_GPIOA, self.porta) self.i2c.bus.write_byte_data( self.i2c.address, self.MCP23017_GPIOB, self.portb) # Read state of single button def buttonPressed(self, b): return (self.i2c.readU8(self.MCP23017_GPIOA) >> b) & 1 # Read and return bitmask of combined button state def buttons(self): return self.i2c.readU8(self.MCP23017_GPIOA) & 0b11111 # ---------------------------------------------------------------------- # Test code if __name__ == '__main__': lcd = Adafruit_CharLCDPlate() lcd.begin(16, 2) lcd.clear() lcd.message("Adafruit RGB LCD\nPlate w/Keypad!") sleep(1) col = (('Red' , lcd.RED) , ('Yellow', lcd.YELLOW), ('Green' , lcd.GREEN), ('Teal', lcd.TEAL), ('Blue' , lcd.BLUE) , ('Violet', lcd.VIOLET), ('Off' , lcd.OFF) , ('On' , lcd.ON)) print "Cycle thru backlight colors" for c in col: print c[0] lcd.clear() lcd.message(c[0]) lcd.backlight(c[1]) sleep(0.5) btn = ((lcd.SELECT, 'Select', lcd.ON), (lcd.LEFT , 'Left' , lcd.RED), (lcd.UP , 'Up' , lcd.BLUE), (lcd.DOWN , 'Down' , lcd.GREEN), (lcd.RIGHT , 'Right' , lcd.VIOLET)) print "Try buttons on plate" lcd.clear() lcd.message("Try buttons") prev = -1 while True: for b in btn: if lcd.buttonPressed(b[0]): if b is not prev: print b[1] lcd.clear() lcd.message(b[1]) lcd.backlight(b[2]) prev = b break
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/CharLCDPlate/Adafruit_CharLCDPlate.py
Adafruit_CharLCDPlate.py
import time import datetime from Adafruit_LEDBackpack import LEDBackpack # =========================================================================== # 8x8 Pixel Display # =========================================================================== class EightByEight: disp = None # Constructor def __init__(self, address=0x70, debug=False): if (debug): print "Initializing a new instance of LEDBackpack at 0x%02X" % address self.disp = LEDBackpack(address=address, debug=debug) def writeRowRaw(self, charNumber, value): "Sets a row of pixels using a raw 16-bit value" if (charNumber > 7): return # Set the appropriate row self.disp.setBufferRow(charNumber, value) def clearPixel(self, x, y): "A wrapper function to clear pixels (purely cosmetic)" self.setPixel(x, y, 0) def setPixel(self, x, y, color=1): "Sets a single pixel" if (x >= 8): return if (y >= 8): return x += 7 # ATTN: This might be a bug? On the color matrix, this causes x=0 to draw on the last line instead of the first. x %= 8 # Set the appropriate pixel buffer = self.disp.getBuffer() if (color): self.disp.setBufferRow(y, buffer[y] | 1 << x) else: self.disp.setBufferRow(y, buffer[y] & ~(1 << x)) def clear(self): "Clears the entire display" self.disp.clear() class ColorEightByEight(EightByEight): def setPixel(self, x, y, color=1): "Sets a single pixel" if (x >= 8): return if (y >= 8): return x %= 8 # Set the appropriate pixel buffer = self.disp.getBuffer() # TODO : Named color constants? # ATNN : This code was mostly taken from the arduino code, but with the addition of clearing the other bit when setting red or green. # The arduino code does not do that, and might have the bug where if you draw red or green, then the other color, it actually draws yellow. # The bug doesn't show up in the examples because it's always clearing. if (color == 1): self.disp.setBufferRow(y, (buffer[y] | (1 << x)) & ~(1 << (x+8)) ) elif (color == 2): self.disp.setBufferRow(y, (buffer[y] | 1 << (x+8)) & ~(1 << x) ) elif (color == 3): self.disp.setBufferRow(y, buffer[y] | (1 << (x+8)) | (1 << x) ) else: self.disp.setBufferRow(y, buffer[y] & ~(1 << x) & ~(1 << (x+8)) )
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/LEDBackpack/Adafruit_8x8.py
Adafruit_8x8.py
import time from copy import copy from Adafruit.I2C import Adafruit_I2C # ============================================================================ # LEDBackpack Class # ============================================================================ class LEDBackpack: i2c = None # Registers __HT16K33_REGISTER_DISPLAY_SETUP = 0x80 __HT16K33_REGISTER_SYSTEM_SETUP = 0x20 __HT16K33_REGISTER_DIMMING = 0xE0 # Blink rate __HT16K33_BLINKRATE_OFF = 0x00 __HT16K33_BLINKRATE_2HZ = 0x01 __HT16K33_BLINKRATE_1HZ = 0x02 __HT16K33_BLINKRATE_HALFHZ = 0x03 # Display buffer (8x16-bits) __buffer = [0x0000, 0x0000, 0x0000, 0x0000, \ 0x0000, 0x0000, 0x0000, 0x0000 ] # Constructor def __init__(self, address=0x70, debug=False): self.i2c = Adafruit_I2C(address) self.address = address self.debug = debug # Turn the oscillator on self.i2c.write8(self.__HT16K33_REGISTER_SYSTEM_SETUP | 0x01, 0x00) # Turn blink off self.setBlinkRate(self.__HT16K33_BLINKRATE_OFF) # Set maximum brightness self.setBrightness(15) # Clear the screen self.clear() def setBrightness(self, brightness): "Sets the brightness level from 0..15" if (brightness > 15): brightness = 15 self.i2c.write8(self.__HT16K33_REGISTER_DIMMING | brightness, 0x00) def setBlinkRate(self, blinkRate): "Sets the blink rate" if (blinkRate > self.__HT16K33_BLINKRATE_HALFHZ): blinkRate = self.__HT16K33_BLINKRATE_OFF self.i2c.write8(self.__HT16K33_REGISTER_DISPLAY_SETUP | 0x01 | (blinkRate << 1), 0x00) def setBufferRow(self, row, value, update=True): "Updates a single 16-bit entry in the 8*16-bit buffer" if (row > 7): return # Prevent buffer overflow self.__buffer[row] = value # value # & 0xFFFF if (update): self.writeDisplay() # Update the display def getBuffer(self): "Returns a copy of the raw buffer contents" bufferCopy = copy(self.__buffer) return bufferCopy def writeDisplay(self): "Updates the display memory" bytes = [] for item in self.__buffer: bytes.append(item & 0xFF) bytes.append((item >> 8) & 0xFF) self.i2c.writeList(0x00, bytes) def clear(self, update=True): "Clears the display memory" self.__buffer = [ 0, 0, 0, 0, 0, 0, 0, 0 ] if (update): self.writeDisplay() led = LEDBackpack(0x70)
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/LEDBackpack/Adafruit_LEDBackpack.py
Adafruit_LEDBackpack.py
# # based on code from lrvick and LiquidCrystal # lrvic - https://github.com/lrvick/raspi-hd44780/blob/master/hd44780.py # LiquidCrystal - https://github.com/arduino/Arduino/blob/master/libraries/LiquidCrystal/LiquidCrystal.cpp # from time import sleep class Adafruit_CharLCD: # commands LCD_CLEARDISPLAY = 0x01 LCD_RETURNHOME = 0x02 LCD_ENTRYMODESET = 0x04 LCD_DISPLAYCONTROL = 0x08 LCD_CURSORSHIFT = 0x10 LCD_FUNCTIONSET = 0x20 LCD_SETCGRAMADDR = 0x40 LCD_SETDDRAMADDR = 0x80 # flags for display entry mode LCD_ENTRYRIGHT = 0x00 LCD_ENTRYLEFT = 0x02 LCD_ENTRYSHIFTINCREMENT = 0x01 LCD_ENTRYSHIFTDECREMENT = 0x00 # flags for display on/off control LCD_DISPLAYON = 0x04 LCD_DISPLAYOFF = 0x00 LCD_CURSORON = 0x02 LCD_CURSOROFF = 0x00 LCD_BLINKON = 0x01 LCD_BLINKOFF = 0x00 # flags for display/cursor shift LCD_DISPLAYMOVE = 0x08 LCD_CURSORMOVE = 0x00 # flags for display/cursor shift LCD_DISPLAYMOVE = 0x08 LCD_CURSORMOVE = 0x00 LCD_MOVERIGHT = 0x04 LCD_MOVELEFT = 0x00 # flags for function set LCD_8BITMODE = 0x10 LCD_4BITMODE = 0x00 LCD_2LINE = 0x08 LCD_1LINE = 0x00 LCD_5x10DOTS = 0x04 LCD_5x8DOTS = 0x00 def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 21, 22], GPIO = None): # Emulate the old behavior of using RPi.GPIO if we haven't been given # an explicit GPIO interface to use if not GPIO: import RPi.GPIO as GPIO self.GPIO = GPIO self.pin_rs = pin_rs self.pin_e = pin_e self.pins_db = pins_db self.GPIO.setmode(GPIO.BCM) self.GPIO.setup(self.pin_e, GPIO.OUT) self.GPIO.setup(self.pin_rs, GPIO.OUT) for pin in self.pins_db: self.GPIO.setup(pin, GPIO.OUT) self.write4bits(0x33) # initialization self.write4bits(0x32) # initialization self.write4bits(0x28) # 2 line 5x7 matrix self.write4bits(0x0C) # turn cursor off 0x0E to enable cursor self.write4bits(0x06) # shift cursor right self.displaycontrol = self.LCD_DISPLAYON | self.LCD_CURSOROFF | self.LCD_BLINKOFF self.displayfunction = self.LCD_4BITMODE | self.LCD_1LINE | self.LCD_5x8DOTS self.displayfunction |= self.LCD_2LINE """ Initialize to default text direction (for romance languages) """ self.displaymode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) # set the entry mode self.clear() def begin(self, cols, lines): if (lines > 1): self.numlines = lines self.displayfunction |= self.LCD_2LINE self.currline = 0 def home(self): self.write4bits(self.LCD_RETURNHOME) # set cursor position to zero self.delayMicroseconds(3000) # this command takes a long time! def clear(self): self.write4bits(self.LCD_CLEARDISPLAY) # command to clear display self.delayMicroseconds(3000) # 3000 microsecond sleep, clearing the display takes a long time def setCursor(self, col, row): self.row_offsets = [ 0x00, 0x40, 0x14, 0x54 ] if ( row > self.numlines ): row = self.numlines - 1 # we count rows starting w/0 self.write4bits(self.LCD_SETDDRAMADDR | (col + self.row_offsets[row])) def noDisplay(self): """ Turn the display off (quickly) """ self.displaycontrol &= ~self.LCD_DISPLAYON self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol) def display(self): """ Turn the display on (quickly) """ self.displaycontrol |= self.LCD_DISPLAYON self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol) def noCursor(self): """ Turns the underline cursor on/off """ self.displaycontrol &= ~self.LCD_CURSORON self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol) def cursor(self): """ Cursor On """ self.displaycontrol |= self.LCD_CURSORON self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol) def noBlink(self): """ Turn on and off the blinking cursor """ self.displaycontrol &= ~self.LCD_BLINKON self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol) def noBlink(self): """ Turn on and off the blinking cursor """ self.displaycontrol &= ~self.LCD_BLINKON self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol) def DisplayLeft(self): """ These commands scroll the display without changing the RAM """ self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT) def scrollDisplayRight(self): """ These commands scroll the display without changing the RAM """ self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT); def leftToRight(self): """ This is for text that flows Left to Right """ self.displaymode |= self.LCD_ENTRYLEFT self.write4bits(self.LCD_ENTRYMODESET | self.displaymode); def rightToLeft(self): """ This is for text that flows Right to Left """ self.displaymode &= ~self.LCD_ENTRYLEFT self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) def autoscroll(self): """ This will 'right justify' text from the cursor """ self.displaymode |= self.LCD_ENTRYSHIFTINCREMENT self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) def noAutoscroll(self): """ This will 'left justify' text from the cursor """ self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENT self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) def write4bits(self, bits, char_mode=False): """ Send command to LCD """ self.delayMicroseconds(1000) # 1000 microsecond sleep bits=bin(bits)[2:].zfill(8) self.GPIO.output(self.pin_rs, char_mode) for pin in self.pins_db: self.GPIO.output(pin, False) for i in range(4): if bits[i] == "1": self.GPIO.output(self.pins_db[::-1][i], True) self.pulseEnable() for pin in self.pins_db: self.GPIO.output(pin, False) for i in range(4,8): if bits[i] == "1": self.GPIO.output(self.pins_db[::-1][i-4], True) self.pulseEnable() def delayMicroseconds(self, microseconds): seconds = microseconds / float(1000000) # divide microseconds by 1 million for seconds sleep(seconds) def pulseEnable(self): self.GPIO.output(self.pin_e, False) self.delayMicroseconds(1) # 1 microsecond pause - enable pulse must be > 450ns self.GPIO.output(self.pin_e, True) self.delayMicroseconds(1) # 1 microsecond pause - enable pulse must be > 450ns self.GPIO.output(self.pin_e, False) self.delayMicroseconds(1) # commands need > 37us to settle def message(self, text): """ Send string to LCD. Newline wraps to second line""" for char in text: if char == '\n': self.write4bits(0xC0) # next line else: self.write4bits(ord(char),True) if __name__ == '__main__': lcd = Adafruit_CharLCD() lcd.clear() lcd.message(" Adafruit 16x2\n Standard LCD")
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/CharLCD/Adafruit_CharLCD.py
Adafruit_CharLCD.py
import smbus # =========================================================================== # Adafruit_I2C Class # =========================================================================== class Adafruit_I2C : @staticmethod def getPiRevision(): "Gets the version number of the Raspberry Pi board" # Courtesy quick2wire-python-api # https://github.com/quick2wire/quick2wire-python-api try: with open('/proc/cpuinfo','r') as f: for line in f: if line.startswith('Revision'): return 1 if line.rstrip()[-1] in ['1','2'] else 2 except: return 0 @staticmethod def getPiI2CBusNumber(): # Gets the I2C bus number /dev/i2c# return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 def __init__(self, address, busnum=-1, debug=False): self.address = address # By default, the correct I2C bus is auto-detected using /proc/cpuinfo # Alternatively, you can hard-code the bus version below: # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) self.bus = smbus.SMBus( busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) self.debug = debug def reverseByteOrder(self, data): "Reverses the byte order of an int (16-bit) or long (32-bit) value" # Courtesy Vishal Sapre byteCount = len(hex(data)[2:].replace('L','')[::2]) val = 0 for i in range(byteCount): val = (val << 8) | (data & 0xff) data >>= 8 return val def errMsg(self): print "Error accessing 0x%02X: Check your I2C address" % self.address return -1 def write8(self, reg, value): "Writes an 8-bit value to the specified register/address" try: self.bus.write_byte_data(self.address, reg, value) if self.debug: print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg) except IOError, err: return self.errMsg() def write16(self, reg, value): "Writes a 16-bit value to the specified register/address pair" try: self.bus.write_word_data(self.address, reg, value) if self.debug: print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % (value, reg, reg+1)) except IOError, err: return self.errMsg() def writeList(self, reg, list): "Writes an array of bytes using I2C format" try: if self.debug: print "I2C: Writing list to register 0x%02X:" % reg print list self.bus.write_i2c_block_data(self.address, reg, list) except IOError, err: return self.errMsg() def readList(self, reg, length): "Read a list of bytes from the I2C device" try: results = self.bus.read_i2c_block_data(self.address, reg, length) if self.debug: print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % (self.address, reg)) print results return results except IOError, err: return self.errMsg() def readU8(self, reg): "Read an unsigned byte from the I2C device" try: result = self.bus.read_byte_data(self.address, reg) if self.debug: print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % (self.address, result & 0xFF, reg)) return result except IOError, err: return self.errMsg() def readS8(self, reg): "Reads a signed byte from the I2C device" try: result = self.bus.read_byte_data(self.address, reg) if result > 127: result -= 256 if self.debug: print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % (self.address, result & 0xFF, reg)) return result except IOError, err: return self.errMsg() def readU16(self, reg): "Reads an unsigned 16-bit value from the I2C device" try: hibyte = self.readU8(reg) lobyte = self.readU8(reg+1) result = (hibyte << 8) + lobyte if (self.debug): print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) return result except IOError, err: return self.errMsg() def readS16(self, reg): "Reads a signed 16-bit value from the I2C device" try: hibyte = self.readS8(reg) lobyte = self.readU8(reg+1) result = (hibyte << 8) + lobyte if (self.debug): print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) return result except IOError, err: return self.errMsg() def readU16Rev(self, reg): "Reads an unsigned 16-bit value from the I2C device with rev byte order" try: lobyte = self.readU8(reg) hibyte = self.readU8(reg+1) result = (hibyte << 8) + lobyte if (self.debug): print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) return result except IOError, err: return self.errMsg() def readS16Rev(self, reg): "Reads a signed 16-bit value from the I2C device with rev byte order" try: lobyte = self.readS8(reg) hibyte = self.readU8(reg+1) result = (hibyte << 8) + lobyte if (self.debug): print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) return result except IOError, err: return self.errMsg() if __name__ == '__main__': try: bus = Adafruit_I2C(address=0) print "Default I2C bus is accessible" except: print "Error accessing default I2C bus"
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/TCS34725/Adafruit_I2C.py
Adafruit_I2C.py
import time from Adafruit_I2C import Adafruit_I2C # =========================================================================== # TCS3472 Class # =========================================================================== class TCS34725: i2c = None __TCS34725_ADDRESS = 0x29 __TCS34725_ID = 0x12 # 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 __TCS34725_COMMAND_BIT = 0x80 __TCS34725_ENABLE = 0x00 __TCS34725_ENABLE_AIEN = 0x10 # RGBC Interrupt Enable __TCS34725_ENABLE_WEN = 0x08 # Wait enable - Writing 1 activates the wait timer __TCS34725_ENABLE_AEN = 0x02 # RGBC Enable - Writing 1 actives the ADC, 0 disables it __TCS34725_ENABLE_PON = 0x01 # Power on - Writing 1 activates the internal oscillator, 0 disables it __TCS34725_ATIME = 0x01 # Integration time __TCS34725_WTIME = 0x03 # Wait time (if TCS34725_ENABLE_WEN is asserted) __TCS34725_WTIME_2_4MS = 0xFF # WLONG0 = 2.4ms WLONG1 = 0.029s __TCS34725_WTIME_204MS = 0xAB # WLONG0 = 204ms WLONG1 = 2.45s __TCS34725_WTIME_614MS = 0x00 # WLONG0 = 614ms WLONG1 = 7.4s __TCS34725_AILTL = 0x04 # Clear channel lower interrupt threshold __TCS34725_AILTH = 0x05 __TCS34725_AIHTL = 0x06 # Clear channel upper interrupt threshold __TCS34725_AIHTH = 0x07 __TCS34725_PERS = 0x0C # Persistence register - basic SW filtering mechanism for interrupts __TCS34725_PERS_NONE = 0b0000 # Every RGBC cycle generates an interrupt __TCS34725_PERS_1_CYCLE = 0b0001 # 1 clean channel value outside threshold range generates an interrupt __TCS34725_PERS_2_CYCLE = 0b0010 # 2 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_3_CYCLE = 0b0011 # 3 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_5_CYCLE = 0b0100 # 5 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_10_CYCLE = 0b0101 # 10 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_15_CYCLE = 0b0110 # 15 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_20_CYCLE = 0b0111 # 20 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_25_CYCLE = 0b1000 # 25 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_30_CYCLE = 0b1001 # 30 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_35_CYCLE = 0b1010 # 35 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_40_CYCLE = 0b1011 # 40 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_45_CYCLE = 0b1100 # 45 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_50_CYCLE = 0b1101 # 50 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_55_CYCLE = 0b1110 # 55 clean channel values outside threshold range generates an interrupt __TCS34725_PERS_60_CYCLE = 0b1111 # 60 clean channel values outside threshold range generates an interrupt __TCS34725_CONFIG = 0x0D __TCS34725_CONFIG_WLONG = 0x02 # Choose between short and long (12x) wait times via TCS34725_WTIME __TCS34725_CONTROL = 0x0F # Set the gain level for the sensor __TCS34725_ID = 0x12 # 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 __TCS34725_STATUS = 0x13 __TCS34725_STATUS_AINT = 0x10 # RGBC Clean channel interrupt __TCS34725_STATUS_AVALID = 0x01 # Indicates that the RGBC channels have completed an integration cycle __TCS34725_CDATAL = 0x14 # Clear channel data __TCS34725_CDATAH = 0x15 __TCS34725_RDATAL = 0x16 # Red channel data __TCS34725_RDATAH = 0x17 __TCS34725_GDATAL = 0x18 # Green channel data __TCS34725_GDATAH = 0x19 __TCS34725_BDATAL = 0x1A # Blue channel data __TCS34725_BDATAH = 0x1B __TCS34725_INTEGRATIONTIME_2_4MS = 0xFF # 2.4ms - 1 cycle - Max Count: 1024 __TCS34725_INTEGRATIONTIME_24MS = 0xF6 # 24ms - 10 cycles - Max Count: 10240 __TCS34725_INTEGRATIONTIME_50MS = 0xEB # 50ms - 20 cycles - Max Count: 20480 __TCS34725_INTEGRATIONTIME_101MS = 0xD5 # 101ms - 42 cycles - Max Count: 43008 __TCS34725_INTEGRATIONTIME_154MS = 0xC0 # 154ms - 64 cycles - Max Count: 65535 __TCS34725_INTEGRATIONTIME_700MS = 0x00 # 700ms - 256 cycles - Max Count: 65535 __TCS34725_GAIN_1X = 0x00 # No gain __TCS34725_GAIN_4X = 0x01 # 2x gain __TCS34725_GAIN_16X = 0x02 # 16x gain __TCS34725_GAIN_60X = 0x03 # 60x gain __integrationTimeDelay = { 0xFF: 0.0024, # 2.4ms - 1 cycle - Max Count: 1024 0xF6: 0.024, # 24ms - 10 cycles - Max Count: 10240 0xEB: 0.050, # 50ms - 20 cycles - Max Count: 20480 0xD5: 0.101, # 101ms - 42 cycles - Max Count: 43008 0xC0: 0.154, # 154ms - 64 cycles - Max Count: 65535 0x00: 0.700 # 700ms - 256 cycles - Max Count: 65535 } # Private Methods def __readU8(self, reg): return self.i2c.readU8(self.__TCS34725_COMMAND_BIT | reg) def __readU16Rev(self, reg): return self.i2c.readU16Rev(self.__TCS34725_COMMAND_BIT | reg) def __write8(self, reg, value): self.i2c.write8(self.__TCS34725_COMMAND_BIT | reg, value & 0xff) # Constructor def __init__(self, address=0x29, debug=False, integrationTime=0xFF, gain=0x01): self.i2c = Adafruit_I2C(address) self.address = address self.debug = debug self.integrationTime = integrationTime self.initialize(integrationTime, gain) def initialize(self, integrationTime, gain): "Initializes I2C and configures the sensor (call this function before \ doing anything else)" # Make sure we're actually connected result = self.__readU8(self.__TCS34725_ID) if (result != 0x44): return -1 # Set default integration time and gain self.setIntegrationTime(integrationTime) self.setGain(gain) # Note: by default, the device is in power down mode on bootup self.enable() def enable(self): self.__write8(self.__TCS34725_ENABLE, self.__TCS34725_ENABLE_PON) time.sleep(0.01) self.__write8(self.__TCS34725_ENABLE, (self.__TCS34725_ENABLE_PON | self.__TCS34725_ENABLE_AEN)) def disable(self): reg = 0 reg = self.__readU8(self.__TCS34725_ENABLE) self.__write8(self.__TCS34725_ENABLE, (reg & ~(self.__TCS34725_ENABLE_PON | self.__TCS34725_ENABLE_AEN))) def setIntegrationTime(self, integrationTime): "Sets the integration time for the TC34725" self.integrationTime = integrationTime self.__write8(self.__TCS34725_ATIME, integrationTime) def getIntegrationTime(self): return self.__readU8(self.__TCS34725_ATIME) def setGain(self, gain): "Adjusts the gain on the TCS34725 (adjusts the sensitivity to light)" self.__write8(self.__TCS34725_CONTROL, gain) def getGain(self): return self.__readU8(self.__TCS34725_CONTROL) def getRawData(self): "Reads the raw red, green, blue and clear channel values" color = {} color["r"] = self.__readU16Rev(self.__TCS34725_RDATAL) color["b"] = self.__readU16Rev(self.__TCS34725_BDATAL) color["g"] = self.__readU16Rev(self.__TCS34725_GDATAL) color["c"] = self.__readU16Rev(self.__TCS34725_CDATAL) # Set a delay for the integration time delay = self.__integrationTimeDelay.get(self.integrationTime) time.sleep(delay) return color def setInterrupt(self, int): r = self.__readU8(self.__TCS34725_ENABLE) if (int): r |= self.__TCS34725_ENABLE_AIEN else: r &= ~self.__TCS34725_ENABLE_AIEN self.__write8(self.__TCS34725_ENABLE, r) def clearInterrupt(self): self.i2c.write8(0x66 & 0xff) def setIntLimits(self, low, high): self.i2c.write8(0x04, low & 0xFF) self.i2c.write8(0x05, low >> 8) self.i2c.write8(0x06, high & 0xFF) self.i2c.write8(0x07, high >> 8) #Static Utility Methods @staticmethod def calculateColorTemperature(rgb): "Converts the raw R/G/B values to color temperature in degrees Kelvin" if not isinstance(rgb, dict): raise ValueError('calculateColorTemperature expects dict as parameter') # 1. Map RGB values to their XYZ counterparts. # Based on 6500K fluorescent, 3000K fluorescent # and 60W incandescent values for a wide range. # Note: Y = Illuminance or lux X = (-0.14282 * rgb['r']) + (1.54924 * rgb['g']) + (-0.95641 * rgb['b']) Y = (-0.32466 * rgb['r']) + (1.57837 * rgb['g']) + (-0.73191 * rgb['b']) Z = (-0.68202 * rgb['r']) + (0.77073 * rgb['g']) + ( 0.56332 * rgb['b']) # 2. Calculate the chromaticity co-ordinates xc = (X) / (X + Y + Z) yc = (Y) / (X + Y + Z) # 3. Use McCamy's formula to determine the CCT n = (xc - 0.3320) / (0.1858 - yc) # Calculate the final CCT cct = (449.0 * (n ** 3.0)) + (3525.0 *(n ** 2.0)) + (6823.3 * n) + 5520.33 return int(cct) @staticmethod def calculateLux(rgb): "Converts the raw R/G/B values to color temperature in degrees Kelvin" if not isinstance(rgb, dict): raise ValueError('calculateLux expects dict as parameter') illuminance = (-0.32466 * rgb['r']) + (1.57837 * rgb['g']) + (-0.73191 * rgb['b']) return int(illuminance)
Adafruit_Libraries
/Adafruit_Libraries-0.1.tar.gz/Adafruit_Libraries-0.1/Adafruit/TCS34725/Adafruit_TCS34725.py
Adafruit_TCS34725.py
Adafruit Python DHT Sensor Library ================================== Python library to read the DHT series of humidity and temperature sensors on a Raspberry Pi or Beaglebone Black. Designed specifically to work with the Adafruit DHT series sensors ----> https://www.adafruit.com/products/385 Currently the library is tested with Python 2.6, 2.7, 3.3 and 3.4. It should work with Python greater than 3.4, too. Installing ---------- ### Dependencies For all platforms (Raspberry Pi and Beaglebone Black) make sure your system is able to compile and download Python extensions with **pip**: On Raspbian or Beaglebone Black's Debian/Ubuntu image you can ensure your system is ready by running one or two of the following sets of commands: Python 2: ````sh sudo apt-get update sudo apt-get install python-pip sudo python -m pip install --upgrade pip setuptools wheel ```` Python 3: ````sh sudo apt-get update sudo apt-get install python3-pip sudo python3 -m pip install --upgrade pip setuptools wheel ```` ### Install with pip Use `pip` to install from PyPI. Python 2: ```sh sudo pip install Adafruit_DHT ``` Python 3: ```sh sudo pip3 install Adafruit_DHT ``` ### Compile and install from the repository First download the library source code from the [GitHub releases page](https://github.com/adafruit/Adafruit_Python_DHT/releases), unzipping the archive, and execute: Python 2: ```sh cd Adafruit_Python_DHT sudo python setup.py install ``` Python 3: ```sh cd Adafruit_Python_DHT sudo python3 setup.py install ``` You may also git clone the repository if you want to test an unreleased version: ```sh git clone https://github.com/adafruit/Adafruit_Python_DHT.git ``` Usage ----- See example of usage in the examples folder. Author ------ Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Tony DiCola for Adafruit Industries. MIT license, all text above must be included in any redistribution
Adafruit_Python_DHT
/Adafruit_Python_DHT-1.4.0.tar.gz/Adafruit_Python_DHT-1.4.0/README.md
README.md
# Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import time from . import platform_detect # Define error constants. DHT_SUCCESS = 0 DHT_ERROR_TIMEOUT = -1 DHT_ERROR_CHECKSUM = -2 DHT_ERROR_ARGUMENT = -3 DHT_ERROR_GPIO = -4 TRANSIENT_ERRORS = [DHT_ERROR_CHECKSUM, DHT_ERROR_TIMEOUT] # Define sensor type constants. DHT11 = 11 DHT22 = 22 AM2302 = 22 SENSORS = [DHT11, DHT22, AM2302] def get_platform(): """Return a DHT platform interface for the currently detected platform.""" plat = platform_detect.platform_detect() if plat == platform_detect.RASPBERRY_PI: # Check for version 1 or 2 of the pi. version = platform_detect.pi_version() if version == 1: from . import Raspberry_Pi return Raspberry_Pi elif version == 2: from . import Raspberry_Pi_2 return Raspberry_Pi_2 elif version == 3: """Use Pi 2 driver even though running on Pi 3""" from . import Raspberry_Pi_2 return Raspberry_Pi_2 else: raise RuntimeError('No driver for detected Raspberry Pi version available!') elif plat == platform_detect.BEAGLEBONE_BLACK: from . import Beaglebone_Black return Beaglebone_Black else: raise RuntimeError('Unknown platform.') def read(sensor, pin, platform=None): """Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on specified pin and return a tuple of humidity (as a floating point value in percent) and temperature (as a floating point value in Celsius). Note that because the sensor requires strict timing to read and Linux is not a real time OS, a result is not guaranteed to be returned! In some cases this will return the tuple (None, None) which indicates the function should be retried. Also note the DHT sensor cannot be read faster than about once every 2 seconds. Platform is an optional parameter which allows you to override the detected platform interface--ignore this parameter unless you receive unknown platform errors and want to override the detection. """ if sensor not in SENSORS: raise ValueError('Expected DHT11, DHT22, or AM2302 sensor value.') if platform is None: platform = get_platform() return platform.read(sensor, pin) def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None): """Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on specified pin and return a tuple of humidity (as a floating point value in percent) and temperature (as a floating point value in Celsius). Unlike the read function, this read_retry function will attempt to read multiple times (up to the specified max retries) until a good reading can be found. If a good reading cannot be found after the amount of retries, a tuple of (None, None) is returned. The delay between retries is by default 2 seconds, but can be overridden. """ for i in range(retries): humidity, temperature = read(sensor, pin, platform) if humidity is not None and temperature is not None: return (humidity, temperature) time.sleep(delay_seconds) return (None, None)
Adafruit_Python_DHT
/Adafruit_Python_DHT-1.4.0.tar.gz/Adafruit_Python_DHT-1.4.0/Adafruit_DHT/common.py
common.py
# Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import re from . import common from . import Beaglebone_Black_Driver as driver # Define mapping of pin names to GPIO base and number. # Adapted from Adafruit_BBIO code Beaglebone Black system reference. pin_to_gpio = { "P9_11": (0,30), "P9_12": (1,28), "P9_13": (0,31), "P9_14": (1,18), "P9_15": (1,16), "P9_16": (1,19), "P9_17": (0,5), "P9_18": (0,4), "P9_19": (0,13), "P9_20": (0,12), "P9_21": (0,3), "P9_22": (0,2), "P9_23": (1,17), "P9_24": (0,15), "P9_25": (3,21), "P9_26": (0,14), "P9_27": (3,19), "P9_28": (3,17), "P9_29": (3,15), "P9_30": (3,16), "P9_31": (3,14), "P9_41": (0,20), "P9_42": (0,7), "UART4_RXD": (0,30), "UART4_TXD": (0,31), "EHRPWM1A": (1,18), "EHRPWM1B": (1,19), "I2C1_SCL": (0,5), "I2C1_SDA": (0,4), "I2C2_SCL": (0,13), "I2C2_SDA": (0,12), "UART2_TXD": (0,3), "UART2_RXD": (0,2), "UART1_TXD": (0,15), "UART1_RXD": (0,14), "SPI1_CS0": (3,17), "SPI1_D0": (3,15), "SPI1_D1": (3,16), "SPI1_SCLK": (3,14), "CLKOUT2": (0,20), "30": (0,30), "60": (1,28), "31": (0,31), "50": (1,18), "48": (1,16), "51": (1,19), "5": (0,5), "4": (0,4), "13": (0,13), "12": (0,12), "3": (0,3), "2": (0,2), "49": (1,17), "15": (0,15), "117": (3,21), "14": (0,14), "115": (3,19), "113": (3,17), "111": (3,15), "112": (3,16), "110": (3,14), "20": (0,20), "7": (0,7), "P8_3": (1,6), "P8_4": (1,7), "P8_5": (1,2), "P8_6": (1,3), "P8_7": (2,2), "P8_8": (2,3), "P8_9": (2,5), "P8_10": (2,4), "P8_11": (1,13), "P8_12": (1,12), "P8_13": (0,23), "P8_14": (0,26), "P8_15": (1,15), "P8_16": (1,14), "P8_17": (0,27), "P8_18": (2,1), "P8_19": (0,22), "P8_20": (1,31), "P8_21": (1,30), "P8_22": (1,5), "P8_23": (1,4), "P8_24": (1,1), "P8_25": (1,0), "P8_26": (1,29), "P8_27": (2,22), "P8_28": (2,24), "P8_29": (2,23), "P8_30": (2,25), "P8_31": (0,10), "P8_32": (0,11), "P8_33": (0,9), "P8_34": (2,17), "P8_35": (0,8), "P8_36": (2,16), "P8_37": (2,14), "P8_38": (2,15), "P8_39": (2,12), "P8_40": (2,13), "P8_41": (2,10), "P8_42": (2,11), "P8_43": (2,8), "P8_44": (2,9), "P8_45": (2,6), "P8_46": (2,7), "TIMER4": (2,2), "TIMER7": (2,3), "TIMER5": (2,5), "TIMER6": (2,4), "EHRPWM2B": (0,23), "EHRPWM2A": (0,22), "UART5_CTSN": (0,10), "UART5_RTSN": (0,11), "UART4_RTSN": (0,9), "UART3_RTSN": (2,17), "UART4_CTSN": (0,8), "UART3_CTSN": (2,16), "UART5_TXD": (2,14), "UART5_RXD": (2,15), "38": (1,6), "39": (1,7), "34": (1,2), "35": (1,3), "66": (2,2), "67": (2,3), "69": (2,5), "68": (2,4), "45": (1,13), "44": (1,12), "23": (0,23), "26": (0,26), "47": (1,15), "46": (1,14), "27": (0,27), "65": (2,1), "22": (0,22), "63": (1,31), "62": (1,30), "37": (1,5), "36": (1,4), "33": (1,1), "32": (1,0), "61": (1,29), "86": (2,22), "88": (2,24), "87": (2,23), "89": (2,25), "10": (0,10), "11": (0,11), "9": (0,9), "81": (2,17), "8": (0,8), "80": (2,16), "78": (2,14), "79": (2,15), "76": (2,12), "77": (2,13), "74": (2,10), "75": (2,11), "72": (2,8), "73": (2,9), "70": (2,6), "71": (2,7) } def read(sensor, pin): # Validate GPIO and map it to GPIO base and number. gpio = pin_to_gpio.get(str(pin).upper(), None) if gpio is None: # Couldn't find in mapping, check if pin looks like GPIO<base>_<number> match = re.match('GPIO([0123])_(\d+)', pin, re.IGNORECASE) if match is not None: gpio = (int(match.group(1)), int(match.group(2))) if gpio is None or gpio[0] < 0 or gpio[0] > 3 or gpio[1] < 0 or gpio[1] > 31: raise ValueError('Pin must be a valid GPIO identifier like P9_12 or GPIO1_28.') # Get a reading from C driver code. result, humidity, temp = driver.read(sensor, gpio[0], gpio[1]) if result in common.TRANSIENT_ERRORS: # Signal no result could be obtained, but the caller can retry. return (None, None) elif result == common.DHT_ERROR_GPIO: raise RuntimeError('Error accessing GPIO. Make sure program is run as root with sudo!') elif result != common.DHT_SUCCESS: # Some kind of error occured. raise RuntimeError('Error calling DHT test driver read: {0}'.format(result)) return (humidity, temp)
Adafruit_Python_DHT
/Adafruit_Python_DHT-1.4.0.tar.gz/Adafruit_Python_DHT-1.4.0/Adafruit_DHT/Beaglebone_Black.py
Beaglebone_Black.py
# Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # This is a direct copy of what's in the Adafruit Python GPIO library: # https://raw.githubusercontent.com/adafruit/Adafruit_Python_GPIO/master/Adafruit_GPIO/Platform.py # TODO: Add dependency on Adafruit Python GPIO and use its platform detect # functions. import platform import re # Platform identification constants. UNKNOWN = 0 RASPBERRY_PI = 1 BEAGLEBONE_BLACK = 2 def platform_detect(): """Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.""" # Handle Raspberry Pi pi = pi_version() if pi is not None: return RASPBERRY_PI # Handle Beaglebone Black # TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading # the platform. plat = platform.platform() if plat.lower().find('armv7l-with-debian') > -1: return BEAGLEBONE_BLACK elif plat.lower().find('armv7l-with-ubuntu') > -1: return BEAGLEBONE_BLACK elif plat.lower().find('armv7l-with-glibc2.4') > -1: return BEAGLEBONE_BLACK elif plat.lower().find('armv7l-with-arch') > -1: return BEAGLEBONE_BLACK # Couldn't figure out the platform, just return unknown. return UNKNOWN def pi_revision(): """Detect the revision number of a Raspberry Pi, useful for changing functionality like default I2C bus based on revision.""" # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History with open('/proc/cpuinfo', 'r') as infile: for line in infile: # Match a line of the form "Revision : 0002" while ignoring extra # info in front of the revsion (like 1000 when the Pi was over-volted). match = re.match('Revision\s+:\s+.*(\w{4})$', line, flags=re.IGNORECASE) if match and match.group(1) in ['0000', '0002', '0003']: # Return revision 1 if revision ends with 0000, 0002 or 0003. return 1 elif match: # Assume revision 2 if revision ends with any other 4 chars. return 2 # Couldn't find the revision, throw an exception. raise RuntimeError('Could not determine Raspberry Pi revision.') def pi_version(): """Detect the version of the Raspberry Pi. Returns either 1, 2, 3 or None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+), Raspberry Pi 2 (model B+), Raspberry Pi 3,Raspberry Pi 3 (model B+) or not a Raspberry Pi. """ # Check /proc/cpuinfo for the Hardware field value. # 2708 is pi 1 # 2709 is pi 2 # 2835 is pi 3 # 2837 is pi 3b+ # Anything else is not a pi. with open('/proc/cpuinfo', 'r') as infile: cpuinfo = infile.read() # Match a line like 'Hardware : BCM2709' match = re.search('^Hardware\s+:\s+(\w+)$', cpuinfo, flags=re.MULTILINE | re.IGNORECASE) if not match: # Couldn't find the hardware, assume it isn't a pi. return None if match.group(1) == 'BCM2708': # Pi 1 return 1 elif match.group(1) == 'BCM2709': # Pi 2 return 2 elif match.group(1) == 'BCM2835': # Pi 3 return 3 elif match.group(1) == 'BCM2837': # Pi 3b+ return 3 else: # Something else, not a pi. return None
Adafruit_Python_DHT
/Adafruit_Python_DHT-1.4.0.tar.gz/Adafruit_Python_DHT-1.4.0/Adafruit_DHT/platform_detect.py
platform_detect.py
import logging from Adafruit_bitfield import Adafruit_bitfield import time SEESAW_STATUS_BASE = 0x00 SEESAW_GPIO_BASE = 0x01 SEESAW_SERCOM0_BASE = 0x02 SEESAW_TIMER_BASE = 0x08 SEESAW_ADC_BASE = 0x09 SEESAW_DAC_BASE = 0x0A SEESAW_INTERRUPT_BASE = 0x0B SEESAW_DAP_BASE = 0x0C SEESAW_EEPROM_BASE = 0x0D SEESAW_NEOPIXEL_BASE = 0x0E SEESAW_GPIO_DIRSET_BULK = 0x02 SEESAW_GPIO_DIRCLR_BULK = 0x03 SEESAW_GPIO_BULK = 0x04 SEESAW_GPIO_BULK_SET = 0x05 SEESAW_GPIO_BULK_CLR = 0x06 SEESAW_GPIO_BULK_TOGGLE = 0x07 SEESAW_GPIO_INTENSET = 0x08 SEESAW_GPIO_INTENCLR = 0x09 SEESAW_GPIO_INTFLAG = 0x0A SEESAW_GPIO_PULLENSET = 0x0B SEESAW_GPIO_PULLENCLR = 0x0C SEESAW_STATUS_HW_ID = 0x01 SEESAW_STATUS_VERSION = 0x02 SEESAW_STATUS_OPTIONS = 0x03 SEESAW_STATUS_SWRST = 0x7F SEESAW_TIMER_STATUS = 0x00 SEESAW_TIMER_PWM = 0x01 SEESAW_ADC_STATUS = 0x00 SEESAW_ADC_INTEN = 0x02 SEESAW_ADC_INTENCLR = 0x03 SEESAW_ADC_WINMODE = 0x04 SEESAW_ADC_WINTHRESH = 0x05 SEESAW_ADC_CHANNEL_OFFSET = 0x07 SEESAW_SERCOM_STATUS = 0x00 SEESAW_SERCOM_INTEN = 0x02 SEESAW_SERCOM_INTENCLR = 0x03 SEESAW_SERCOM_BAUD = 0x04 SEESAW_SERCOM_DATA = 0x05 SEESAW_NEOPIXEL_STATUS = 0x00 SEESAW_NEOPIXEL_PIN = 0x01 SEESAW_NEOPIXEL_SPEED = 0x02 SEESAW_NEOPIXEL_BUF_LENGTH = 0x03 SEESAW_NEOPIXEL_BUF = 0x04 SEESAW_NEOPIXEL_SHOW = 0x05 ADC_INPUT_0_PIN = 0x02 ADC_INPUT_1_PIN = 0x03 ADC_INPUT_2_PIN = 0x04 ADC_INPUT_3_PIN = 0x05 PWM_0_PIN = 0x04 PWM_1_PIN = 0x05 PWM_2_PIN = 0x06 PWM_3_PIN = 0x07 class Seesaw(object): INPUT = 0x00 OUTPUT = 0x01 INPUT_PULLUP = 0x02 def __init__(self, addr=0x49, i2c=None, **kwargs): # Create I2C device. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._bus = i2c.get_i2c_device(addr, **kwargs)._bus self.addr = addr self._sercom_status = Adafruit_bitfield([('ERROR', 1), ('DATA_RDY', 1)]) self._sercom_inten = Adafruit_bitfield([('ERROR', 1), ('DATA_RDY', 1)]) self.begin() def begin(self): self.sw_reset() time.sleep(.500) c = self.read8(SEESAW_STATUS_BASE, SEESAW_STATUS_HW_ID) if c != 0x55: print(c) raise RuntimeError("Seesaw hardware ID returned is not correct! Please check your wiring.") def sw_reset(self): self.write8(SEESAW_STATUS_BASE, SEESAW_STATUS_SWRST, 0xFF) def get_options(self): buf = self.read(SEESAW_STATUS_BASE, SEESAW_STATUS_OPTIONS, 4) ret = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3] return ret def get_version(self): buf = self.read(SEESAW_STATUS_BASE, SEESAW_STATUS_VERSION, 4) ret = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3] return ret def pin_mode(self, pin, mode): self.pin_mode_bulk(1 << pin, mode) def digital_write(self, pin, value): self.digital_write_bulk(1 << pin, value) def digital_read(self, pin): return self.digital_read_bulk((1 << pin)) != 0 def digital_read_bulk(self, pins): buf = self.read(SEESAW_GPIO_BASE, SEESAW_GPIO_BULK, 4) ret = ( (buf[0] & 0xF) << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3] #TODO: weird overflow error, fix return ret & pins def set_GPIO_interrupts(self, pins, enabled): cmd = bytearray([(pins >> 24) & 0xFF, (pins >> 16) & 0xFF, (pins >> 8) & 0xFF, pins & 0xFF]) if enabled: self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_INTENSET, cmd) else: self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_INTENCLR, cmd) def analog_read(self, pin): if pin == ADC_INPUT_0_PIN: p = 0 elif pin == ADC_INPUT_1_PIN: p = 1 elif pin == ADC_INPUT_2_PIN: p = 2 elif pin == ADC_INPUT_3_PIN: p = 3 else: return 0 buf = self.read(SEESAW_ADC_BASE, SEESAW_ADC_CHANNEL_OFFSET + p, 2) ret = buf[0] << 8 | buf[1] time.sleep(.001) return ret def pin_mode_bulk(self, pins, mode): cmd = bytearray([(pins >> 24) & 0xFF, (pins >> 16) & 0xFF, (pins >> 8) & 0xFF, pins & 0xFF ]) if mode == self.OUTPUT: self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_DIRSET_BULK, cmd) elif mode == self.INPUT: self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_DIRCLR_BULK, cmd) elif mode == self.INPUT_PULLUP: self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_DIRCLR_BULK, cmd) self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_PULLENSET, cmd) self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_BULK_SET, cmd) def digital_write_bulk(self, pins, value): cmd = bytearray([(pins >> 24) & 0xFF, (pins >> 16) & 0xFF, (pins >> 8) & 0xFF, pins & 0xFF]) if value: self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_BULK_SET, cmd) else: self.write(SEESAW_GPIO_BASE, SEESAW_GPIO_BULK_CLR, cmd) def analog_write(self, pin, value): p = -1 if pin == PWM_0_PIN: p = 0 elif pin == PWM_1_PIN: p = 1 elif pin == PWM_2_PIN: p = 2 elif pin == PWM_3_PIN: p = 3 if p > -1: cmd = bytearray([p, value]) self.write(SEESAW_TIMER_BASE, SEESAW_TIMER_PWM, cmd) def enable_sercom_data_rdy_interrupt(self, sercom): self._sercom_inten.DATA_RDY = 1 self.write8(SEESAW_SERCOM0_BASE + sercom, SEESAW_SERCOM_INTEN, _sercom_inten.get()) def disable_sercom_data_rdy_interrupt(self, sercom): _sercom_inten.DATA_RDY = 0 self.write8(SEESAW_SERCOM0_BASE + sercom, SEESAW_SERCOM_INTEN, _sercom_inten.get()) def read_sercom_data(self, sercom): return self.read8(SEESAW_SERCOM0_BASE + sercom, SEESAW_SERCOM_DATA) def set_i2c_addr(self, addr): self.eeprom_write8(SEESAW_EEPROM_I2C_ADDR, addr) time.sleep(.250) self.begin(addr) #restart w/ the new addr def get_i2c_addr(self,): return self.read8(SEESAW_EEPROM_BASE, SEESAW_EEPROM_I2C_ADDR) def eeprom_write8(self, addr, val): self.eeprom_write(addr, bytearray([val])) def eeprom_write(self, addr, buf): self.write(SEESAW_EEPROM_BASE, addr, buf) def eeprom_read8(self, addr): return self.read8(SEESAW_EEPROM_BASE, addr) def uart_set_baud(self, baud): cmd = bytearray([(baud >> 24) & 0xFF, (baud >> 16) & 0xFF, (baud >> 8) & 0xFF, baud & 0xFF]) self.write(SEESAW_SERCOM0_BASE, SEESAW_SERCOM_BAUD, cmd) def write8(self, regHigh, regLow, value): self.write(regHigh, regLow, bytearray([value])) def read8(self, regHigh, regLow): ret = self.read(regHigh, regLow, 1) return ret[0] def read(self, regHigh, regLow, length, delay=.001): self.write(regHigh, regLow) time.sleep(delay) ret = self._bus._device.read(length) return [ord(x) for x in ret] def write(self, regHigh, regLow, buf = None): c = bytearray([regHigh, regLow]) if not buf == None: c = c + buf self._bus._select_device(self.addr) self._bus._device.write(c)
Adafruit_seesaw
/Adafruit_seesaw-1.0.tar.gz/Adafruit_seesaw-1.0/Adafruit_Seesaw/seesaw.py
seesaw.py
# Serial-for-controller [![old api](https://img.shields.io/badge/old-api-blue?style=for-the-badge&logoColor=white)](https://github.com/Adam-Software) [![Platforms](https://img.shields.io/badge/Raspberry%20Pi-A22846?style=for-the-badge&logo=Raspberry%20Pi&logoColor=white)](https://img.shields.io/badge/Raspberry%20Pi-A22846?style=for-the-badge&logo=Raspberry%20Pi&logoColor=white) [![Language](https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white) [![adam package](https://img.shields.io/badge/adam_package-red?style=for-the-badge&logo=python&logoColor=white)](https://github.com/Adam-Software) [![License](https://img.shields.io/github/license/Adam-Software/Serial-for-controller)](https://img.shields.io/github/license/Adam-Software/Serial-for-controller) [![Activity](https://img.shields.io/github/commit-activity/m/Adam-Software/Serial-for-controller)](https://img.shields.io/github/commit-activity/m/Adam-Software/Serial-for-controller) [![LastStatus](https://img.shields.io/github/last-commit/Adam-Software/Serial-for-controller)](https://img.shields.io/github/last-commit/Adam-Software/Serial-for-controller) [![CodeSize](https://img.shields.io/github/languages/code-size/Adam-Software/Serial-for-controller)](https://img.shields.io/github/languages/code-size/Adam-Software/Serial-for-controller) [![Depencies](https://img.shields.io/librariesio/github/Adam-Software/Serial-for-controller)](https://img.shields.io/librariesio/github/Adam-Software/Serial-for-controller) Python library for data exchange with controller
Adam-Serial-for-controller
/Adam-Serial-for-controller-0.2.1.tar.gz/Adam-Serial-for-controller-0.2.1/README.md
README.md
#!/usr/bin/python3 #-*- coding: utf-8 -*- #https://docs.python.org/3/library/ctypes.html import sys import time import ctypes import struct import os import numpy.ctypeslib as ctl import numpy as np from numpy.ctypeslib import ndpointer # checking the bit depth of the operating system is64bit = struct.calcsize('P') * 8 == 64 # path path = os.path.dirname(os.path.realpath(__file__)) # loading the library depending on the architecture of the operating system if os.name != 'nt': if(is64bit): serial = ctypes.CDLL(os.path.join(path, 'serial_aaarch64.so')) else: serial = ctypes.CDLL(os.path.join(path, 'serial_armv71.so')) if os.name != 'nt': # Указываем, что функция возвращает int serial.serialOpen.restype = ctypes.c_int serial.serialClose.restype = ctypes.c_void_p serial.serialDataAvail.restype = ctypes.c_int serial.send.restype = ctypes.c_void_p # Указываем, что функция возвращает char * serial.readfrom.restype = ctypes.c_char_p serial.readdata.restype = ctypes.c_char_p serial.serialPrint.restype = ctypes.c_void_p # Указываем, что функция принимает аргумент serial.serialOpen.argtypes = [ctypes.POINTER(ctypes.c_char),ctypes.c_int, ] serial.serialClose.argtypes = [ctypes.c_int] serial.serialDataAvail.argtypes = [ctypes.c_int] serial.send.argtypes = [ctypes.c_int,ctypes.POINTER(ctypes.c_ubyte),ctypes.c_uint,] serial.readfrom.argtypes = [ctypes.c_int,ctypes.c_char,ctypes.c_int,] serial.readdata.argtypes = [ctypes.c_int,ctypes.c_char,ctypes.c_int,ctypes.c_int,] serial.serialPrint.argtypes = [ctypes.c_int,ctypes.POINTER(ctypes.c_char) ] class MetaSingleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class SerialU(metaclass=MetaSingleton): _port = None _devicename = None _baudrate = None def __init__(self, devicename: str = '/dev/ttyAMA0', baudrate: int = 115200): self._devicename = devicename self._baudrate = baudrate self._initPort() def _initPort(self): if os.name == 'nt': return if self._port is None: self._port = serial.serialOpen(self._devicename.encode('utf-8'), self._baudrate) def close(self): if os.name == 'nt': return if self._port is not None: serial.serialClose(self._port) self._port = None def read(self, symbol, time, buffer): if os.name == 'nt': return if self._port is not None: return serial.readdata(self._port, symbol.encode('utf-8'), time, buffer).decode('utf-8') self._initPort() return serial.readdata(self._port, symbol.encode('utf-8'), time, buffer).decode('utf-8') def readByte(self, symbol, time, buffer): if os.name == 'nt': return if self._port is not None: return serial.readdata(self._port, symbol.encode('utf-8'), time, buffer) self._initPort() return serial.readdata(self._port, symbol.encode('utf-8'), time, buffer) def readf(self, symbol, time): if os.name == 'nt': return if self._port is not None: return serial.readfrom(self._port, symbol.encode('utf-8'), time).decode('utf-8') self._initPort() return serial.readfrom(self._port, symbol.encode('utf-8'), time).decode('utf-8') def write(self, byted, size): if os.name == 'nt': return if self._port is not None: buffer = (ctypes.c_ubyte * size)() for i in range(size): buffer[i]=byted[i] serial.send(self._port, buffer, size) return self._initPort() self.write(byted, size) return def print(self, byted, size): if os.name == 'nt': return if self._port is not None: serial.serialPrint(self._port, byted, size) return self._initPort() self.print(byted, size) return def avail(self): if os.name == 'nt': return if self._port is not None: return serial.serialDataAvail(self._port) self._initPort() return serial.serialDataAvail(self._port) @staticmethod def CalculateCrc(arr): st_byt = 0 crc = 0 while st_byt < len(arr): dat = arr[st_byt] for i in range(8): fb = crc ^ dat fb &= 1 crc >>= 1 dat >>= 1 if fb == 1: crc ^= 0x8c st_byt += 1 return crc
Adam-Serial-for-controller
/Adam-Serial-for-controller-0.2.1.tar.gz/Adam-Serial-for-controller-0.2.1/Serial/serialPi.py
serialPi.py
import math import torch from torch.optim.optimizer import Optimizer import torch.nn.functional as F import numpy as np import torch.nn as nn # import torch.optim as Optimizer class Adam_tanhx(Optimizer): r"""Implements Adam_tanh_w algorithm. It is modified from the pytorch implementation of Adam. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) """ def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), gama=0.5,eps=1e-8, weight_decay=1e-2): self.gama=gama if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) super(Adam_tanhx, self).__init__(params, defaults) def __setstate__(self, state): super(Adam_tanhx, self).__setstate__(state) @torch.no_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue # Perform stepweight decay p.mul_(1 - group['lr'] * group['weight_decay']) grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam_tanhx does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) # Previous gradient state['previous_grad'] = torch.zeros_like(p.data) exp_avg, exp_avg_sq, previous_grad = state['exp_avg'], state['exp_avg_sq'], state['previous_grad'] beta1, beta2 = group['betas'] state['step'] += 1 # Decay the first and second moment running average coefficient exp_avg.mul_(beta1).add_(grad,alpha = (1 - beta1)) exp_avg_sq.mul_(beta2).addcmul_(grad, grad,value = 1 - beta2) denom = exp_avg_sq.sqrt().add_(group['eps']) bias_correction1 = 1 - beta1 ** state['step'] bias_correction2 = 1 - beta2 ** state['step'] # compute fai fai = abs(previous_grad - grad) fai = self.gama * torch.tanh(fai) + (1-self.gama) state['previous_grad'] = grad.clone() # update momentum with fai exp_avg1 = exp_avg * fai step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1 p.data.addcdiv_(exp_avg1, denom,value = -step_size) return loss def description(): print("There is an optimizer with better performance than Adam in CIFAR-10 and CIFAR-100 dataset.") print("Its name:Adam_tanhx ") print(" ") print("use methods:") print("pip install Adam_tanhx") print("import Adam_tanhx") print("optimizer = Adam_tanx.Adam_tanhx(net.parameters())")
Adam-tanhx
/Adam_tanhx-0.0.5-py3-none-any.whl/Adam_tanhx/Adam_tanhx.py
Adam_tanhx.py
import os import xlrd class ExcelFiles: """ Calling this class automatically loads all the files in the target folder named source """ def __init__(self, source): self.source = source self.makeDataFileList() #self.makeFieldList() def makeDataFileList(self): """ Make a list of all files in the source directory so that each file has its path appended to it. Store that list in datafiles """ self.datafiles = [] self.sourceFolder = os.walk(self.source) for f in self.sourceFolder: filelist = f[2] for fl in filelist: loc = self.source + '/' + str(fl) self.datafiles.append(loc) def makeFieldList(self): self.list_of_fields = [] for d in self.datafiles: try: self.wb = xlrd.open_workbook(d) #Get the first sheet by index self.sh = self.wb.sheet_by_index(0) try: for f in self.sh.row_values(0): self.list_of_fields.append(f) except Exception as exc: sys.exit( "make field list failed; %s" % str(exc) ) # give a error message print('error', f) except Exception as exc: sys.exit( "make field list failed; %s" % str(exc) ) # give a error message print('error', d) self.list_of_fields = set(self.list_of_fields) self.list_of_fields = list(self.list_of_fields) self.list_of_fields.sort() def makeRowDicts(self): self.rowData = [] for d in self.datafiles: try: self.wb = xlrd.open_workbook(d) #Get the first sheet by index self.sheet = self.wb.sheet_by_index(0) self.numRows = self.sheet.nrows for i in range(self.numRows): if i > 0: keys = self.sheet.row_values(0) values = self.sheet.row_values(i) dictionary = dict(list(zip(keys, values))) self.rowData.append(dictionary) except Exception as exc: print(( "make row dicts failed; %s" % str(exc) )) # give a error message print('error', d) def makeSheet(self, fileName): self.wb = xlrd.open_workbook(fileName) #Get the first sheet by index self.sheet = self.wb.sheet_by_index(0)
AdamTools
/AdamTools-0.0.4.tar.gz/AdamTools-0.0.4/Data/ExcelTools.py
ExcelTools.py
__author__ = 'adam' """ These are classes for helping to save statistical data like tables and charts into html, image, and pdf files. They take a dataframe as an input. """ from pandas import DataFrame import codecs import matplotlib from matplotlib.backends.backend_pdf import PdfPages from datetime import date class StatSaver: @staticmethod def save(PATH, FILENAME, dataframe_w_content, table_title=None): """ This will save a dataframe as a formatted table in an html file @param PATH The path to the folder into which the stats will be saved. Should NOT end in '/' @param FILENAME The name to give the saved file. The date will automatically be appended @param dataframe_w_content A pandas dataframe object containing the content to save @param table_title Optional title to add to the table in the file """ today = date.isoformat(date.today()) head = """<html><head> <style type="text/css"> table.nowrap { margin-right: 80px; } table.dataframe { margin-right: 80px; } table{ font-size:24; height:300px; width:500px; } </style></head> <body> <h1>%s</h1> <h1>%s</h1>""" % (table_title, FILENAME) tail = """<h3>%s</h3></body></html>""" % today content = dataframe_w_content.to_html() page = head + content + tail path = '%s/%s_%s' % (PATH, today, FILENAME) outfile = codecs.open(path, mode='w', encoding='utf-8', errors='html_replace') outfile.write(page) outfile.close() class ChartSaver: """ This is used to save chart data """ @staticmethod def pdf(PATH, CHARTNAME, chartsize=(18.5,10.5)): """ This saves a chart as a pdf. It is called after a chart has been plotted @param PATH The path to the folder into which the stats will be saved. Should NOT end in '/' @param CHARTNAME The name to give the saved file. The date will automatically be appended """ today = date.isoformat(date.today()) filepath = '%s/%s_%s' % (PATH, today, CHARTNAME) pp = PdfPages(filepath) fig = matplotlib.pyplot.gcf() fig.set_size_inches(chartsize[0], chartsize[1]) pp.savefig(fig) pp.close()
AdamTools
/AdamTools-0.0.4.tar.gz/AdamTools-0.0.4/Data/DataSaving.py
DataSaving.py
import bisect def Mean(t): """Computes the mean of a sequence of numbers. Args: t: sequence of numbers Returns: float """ return float(sum(t)) / len(t) def MeanVar(t): """Computes the mean and variance of a sequence of numbers. Args: t: sequence of numbers Returns: tuple of two floats """ mu = Mean(t) var = Var(t, mu) return mu, var def Trim(t, p=0.01): """Trims the largest and smallest elements of t. Args: t: sequence of numbers p: fraction of values to trim off each end Returns: sequence of values """ t.sort() n = int(p * len(t)) t = t[n:-n] return t def TrimmedMean(t, p=0.01): """Computes the trimmed mean of a sequence of numbers. Side effect: sorts the list. Args: t: sequence of numbers p: fraction of values to trim off each end Returns: float """ t = Trim(t, p) return Mean(t) def TrimmedMeanVar(t, p=0.01): """Computes the trimmed mean and variance of a sequence of numbers. Side effect: sorts the list. Args: t: sequence of numbers p: fraction of values to trim off each end Returns: float """ t = Trim(t, p) mu, var = MeanVar(t) return mu, var def Var(t, mu=None): """Computes the variance of a sequence of numbers. Args: t: sequence of numbers mu: value around which to compute the variance; by default, computes the mean. Returns: float """ if mu is None: mu = Mean(t) # compute the squared deviations and return their mean. dev2 = [(x - mu)**2 for x in t] var = Mean(dev2) return var def Binom(n, k, d={}): """Compute the binomial coefficient "n choose k". Args: n: number of trials k: number of successes d: map from (n,k) tuples to cached results Returns: int """ if k == 0: return 1 if n == 0: return 0 try: return d[n, k] except KeyError: res = Binom(n-1, k) + Binom(n-1, k-1) d[n, k] = res return res class Interpolator(object): """Represents a mapping between sorted sequences; performs linear interp. Attributes: xs: sorted list ys: sorted list """ def __init__(self, xs, ys): self.xs = xs self.ys = ys def Lookup(self, x): """Looks up x and returns the corresponding value of y.""" return self._Bisect(x, self.xs, self.ys) def Reverse(self, y): """Looks up y and returns the corresponding value of x.""" return self._Bisect(y, self.ys, self.xs) def _Bisect(self, x, xs, ys): """Helper function.""" if x <= xs[0]: return ys[0] if x >= xs[-1]: return ys[-1] i = bisect.bisect(xs, x) frac = 1.0 * (x - xs[i-1]) / (xs[i] - xs[i-1]) y = ys[i-1] + frac * 1.0 * (ys[i] - ys[i-1]) return y """This file contains code used in "Think Stats", by Allen B. Downey, available from greenteapress.com Copyright 2010 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ import math import random def Cov(xs, ys, mux=None, muy=None): """Computes Cov(X, Y). Args: xs: sequence of values ys: sequence of values mux: optional float mean of xs muy: optional float mean of ys Returns: Cov(X, Y) """ if mux is None: mux = Mean(xs) if muy is None: muy = Mean(ys) total = 0.0 for x, y in zip(xs, ys): total += (x-mux) * (y-muy) return total / len(xs) def Corr(xs, ys): """Computes Corr(X, Y). Args: xs: sequence of values ys: sequence of values Returns: Corr(X, Y) """ xbar, varx = MeanVar(xs) ybar, vary = MeanVar(ys) corr = Cov(xs, ys, xbar, ybar) / math.sqrt(varx * vary) return corr def SerialCorr(xs): """Computes the serial correlation of a sequence.""" return Corr(xs[:-1], xs[1:]) def SpearmanCorr(xs, ys): """Computes Spearman's rank correlation. Args: xs: sequence of values ys: sequence of values Returns: float Spearman's correlation """ xranks = MapToRanks(xs) yranks = MapToRanks(ys) return Corr(xranks, yranks) def LeastSquares(xs, ys): """Computes a linear least squares fit for ys as a function of xs. Args: xs: sequence of values ys: sequence of values Returns: tuple of (intercept, slope) """ xbar, varx = MeanVar(xs) ybar, vary = MeanVar(ys) slope = Cov(xs, ys, xbar, ybar) / varx inter = ybar - slope * xbar return inter, slope def FitLine(xs, inter, slope): """Returns the fitted line for the range of xs. xs: x values used for the fit slope: estimated slope inter: estimated intercept """ fxs = min(xs), max(xs) fys = [x * slope + inter for x in fxs] return fxs, fys def Residuals(xs, ys, inter, slope): """Computes residuals for a linear fit with parameters inter and slope. Args: xs: independent variable ys: dependent variable inter: float intercept slope: float slope Returns: list of residuals """ res = [y - inter - slope*x for x, y in zip(xs, ys)] return res def CoefDetermination(ys, res): """Computes the coefficient of determination (R^2) for given residuals. Args: ys: dependent variable res: residuals Returns: float coefficient of determination """ ybar, vary = MeanVar(ys) resbar, varres = MeanVar(res) return 1 - varres / vary def MapToRanks(t): """Returns a list of ranks corresponding to the elements in t. Args: t: sequence of numbers Returns: list of integer ranks, starting at 1 """ # pair up each value with its index pairs = enumerate(t) # sort by value sorted_pairs = sorted(pairs, key=lambda pair: pair[1]) # pair up each pair with its rank ranked = enumerate(sorted_pairs) # sort by index resorted = sorted(ranked, key=lambda trip: trip[1][0]) # extract the ranks ranks = [trip[0]+1 for trip in resorted] return ranks def CorrelatedGenerator(rho): """Generates standard normal variates with correlation. rho: target coefficient of correlation Returns: iterable """ x = random.gauss(0, 1) yield x sigma = math.sqrt(1 - rho**2); while True: x = random.gauss(x * rho, sigma) yield x def CorrelatedNormalGenerator(mu, sigma, rho): """Generates normal variates with correlation. mu: mean of variate sigma: standard deviation of variate rho: target coefficient of correlation Returns: iterable """ for x in CorrelatedGenerator(rho): yield x * sigma + mu def main(): pass if __name__ == '__main__': main()
AdamTools
/AdamTools-0.0.4.tar.gz/AdamTools-0.0.4/Data/StatisticsBase.py
StatisticsBase.py
import os as os import sys import xlrd as xlrd from openpyxl import Workbook class ExcelFiles: """ Base class for loading excel data Calling this class automatically loads all the files in the target folder. The source var passed in defines the relevant folder. This is a generic base class to be used in many programs """ def __init__( self, source, quiet=False ): """ @param source string The location of the folder containing files @param quiet string Whether to print messages at every step """ self.quiet = quiet self.source = source self.makeDataFileList() # self.makeFieldList() def makeDataFileList( self ): """ Make a list of all files in the source directory so that each file has its path appended to it. Store that list in datafiles """ self.datafiles = [ ] self.sourceFolder = os.walk( self.source ) for f in self.sourceFolder: filelist = f[ 2 ] for fl in filelist: loc = self.source + '/' + str( fl ) self.datafiles.append( loc ) def makeFieldList( self ): """ Store an alphabetically sorted list of all the fields in self.list_of_fields. Also makes a list of with unique fields in self.list_of_unique_fields self.field_sources list Contains tuples of the field name and datafile is is from """ self.list_of_fields = [ ] self.field_sources = [ ] for d in self.datafiles: try: self.wb = xlrd.open_workbook( d ) # Get the first sheet by index self.sh = self.wb.sheet_by_index( 0 ) try: for f in self.sh.row_values( 0 ): self.list_of_fields.append( f ) self.field_sources.append( (f, d) ) except: print( ('error', f) ) except: print( ('error', d) ) self.list_of_unique_fields = set( self.list_of_fields ) self.list_of_unique_fields = list( self.list_of_fields ) self.list_of_fields.sort() self.list_of_unique_fields.sort() def makeRowDicts( self ): """ Makes a dictionary from the data of each row with the first row's values as keys """ self.rowData = [ ] for d in self.datafiles: try: self.wb = xlrd.open_workbook( d ) # Get the first sheet by index self.sheet = self.wb.sheet_by_index( 0 ) self.numRows = self.sheet.nrows for i in range( self.numRows ): if i > 0: keys = self.sheet.row_values( 0 ) values = self.sheet.row_values( i ) dictionary = dict( list( zip( keys, values ) ) ) self.rowData.append( dictionary ) if self.quiet == False: print( ('Loaded %s' % d) ) except: print( ('error', d) ) def makeSheet( self, fileName ): self.wb = xlrd.open_workbook( fileName ) # Get the first sheet by index self.sheet = self.wb.sheet_by_index( 0 ) class ExcelWriter: """ Makes an excel file out of data held in list of dictionaries """ def __init__( self, dataList, rowHeaderKey, valuesKey ): """ @param dataList list The list of dictionaries @param rowHeaderKey string This should be a string corresponding to the name of the dictionary key which holds the value to be inserted in row0 @param valuesKey string This should be a string corresponding to the name of the dictionary key which holds the list of values """ self.wb = Workbook() self.ws = self.wb.get_active_sheet() self.data = dataList self.rowHeaderKey = rowHeaderKey self.valuesKey = valuesKey def write( self ): numCol = len( self.data ) i = 0 for p in self.data: self.cellFiller( 0, i, p[ self.rowHeaderKey ] ) row_count = 1 for f in p[ self.valuesKey ]: self.cellFiller( row_count, i, f ) row_count = row_count + 1 i = i + 1 def cellFiller( self, rw, col, data ): cell = ws.cell( row=rw, column=col ) cell.value = data def save( self, sourceDir, fileName ): fn = sourceDir + fileName self.wb.save( fn )
AdamTools
/AdamTools-0.0.4.tar.gz/AdamTools-0.0.4/Data/SpreadsheetDAOs.py
SpreadsheetDAOs.py
__author__ = 'adam' from IPython.display import HTML from IPython.display import display, Latex from pandas import DataFrame import io def convertToLaTeX( df, caption=None, label=None, alignment="c" ): """ Convert a pandas dataframe to a LaTeX tabular. Prints labels in bold, does not use math mode """ numColumns = df.shape[ 1 ] numRows = df.shape[ 0 ] output = io.StringIO() colFormat = ("%s|%s" % (alignment, alignment * numColumns)) # Write header output.write( "\\begin{table}[]" ) output.write( "\\caption{%s} " % caption ) if label != None: output.write( "\\label{%s}" % label ) output.write( "\\begin{tabular}{%s}\n" % colFormat ) columnLabels = [ "\\textbf{%s}" % label for label in df.columns ] output.write( "& %s\\\\\\hline\n" % " & ".join( columnLabels ) ) # Write data lines for i in range( numRows ): output.write( "\\textbf{%s} & %s\\\\\n" % (df.index[ i ], " & ".join( [ str( val ) for val in df.ix[ i ] ] )) ) # Write footer output.write( "\\end{tabular}" ) output.write( "\\end{table}" ) return output.getvalue() def dlatex( df, caption=None, label=None ): """ Does the conversion to latex and does the displaying for ipython """ display( Latex( convertToLaTeX( df, caption, label ) ) ) def fix_percentages_in_axis_description_for_latex( frame ): """ When attempting to display the output of pandas describe() as a latex table, the % sign will cause errors. This replaces it with 'th' """ return frame.rename_axis( { '25%': '25th', '50%': '50th', '75%': '75th' } ) def Table( df, caption=None, label=None ): """ Does the conversion to latex and does the displaying for ipython """ display( Latex( convertToLaTeX( df, caption, label ) ) ) def Bold( text ): """ Displays in the ipython way the entered text as latex inside a bold text tag """ display( Latex( '\\textbf{%s}' % text ) ) def StartFigure( caption='', label='' ): """ Displays the LaTex formatting that goes before a figure with caption and label @param caption String of caption text @param label String of label text """ startstring = "\\begin{figure}[]\caption{%s}\label{%s}" % (caption, label) display( Latex( startstring ) ) def StopFigure(): """ Displays the LaTex formatting that goes after a figure. Call in separate cell from table maker """ endstring = "\\end{figure}" display( Latex( endstring ) ) def Chart( chartFunction, caption='', label='' ): startstring = "\\begin{figure}[]\caption{%s}\label{%s}" % (caption, label) endstring = "\\end{figure}" print( (display( Latex( startstring ) )) ) chartFunction() print( (display( Latex( endstring ) )) ) class Table: """ Used for displaying the data as a formatted html table """ @staticmethod def display( data_to_display, title=None ): """ Displays the inputted data as a formatted html table @param data_to_display Data in a format that can be made into a pandas DataFrame """ # HTML( out = """ <style type="text/css"> table.nowrap { margin-right: 80px; } table.dataframe { margin-right: 80px; } </style>""" if title != None: out += title + DataFrame( data_to_display ).to_html() else: out += DataFrame( data_to_display ).to_html() return HTML( out ) @staticmethod def displaymultiple( list_of_data_to_display, titlelist=None ): """ Displays the inputted data as a formatted html table @param data_to_display Data in a format that can be made into a pandas DataFrame """ # # HTML(""" # <style type="text/css"> # table.nowrap { # margin-right: 80px; # } # table.dataframe { # margin-right: 80px; # .datatable{ # float: left; # } # } # </style>""") i = 0 out = """<style type='text/css'> table.nowrap { margin-right: 80px; } table.dataframe { margin-right: 80px; .datatable{ float: left; } } </style><div class='tables'>""" for d in list_of_data_to_display: out += "<div class='datatable'>" if titlelist != None: out += titlelist[ i ] out += DataFrame( d ).to_html() out += "</div>" i += 1 out += '</div>' return HTML( out ) if __name__ == '__main__': pass
AdamTools
/AdamTools-0.0.4.tar.gz/AdamTools-0.0.4/Notebook/LatexTools.py
LatexTools.py
import sys import select import socket import re from struct import * # known searchd commands SEARCHD_COMMAND_SEARCH = 0 SEARCHD_COMMAND_EXCERPT = 1 SEARCHD_COMMAND_UPDATE = 2 SEARCHD_COMMAND_KEYWORDS = 3 SEARCHD_COMMAND_PERSIST = 4 SEARCHD_COMMAND_STATUS = 5 SEARCHD_COMMAND_FLUSHATTRS = 7 # current client-side command implementation versions VER_COMMAND_SEARCH = 0x119 VER_COMMAND_EXCERPT = 0x104 VER_COMMAND_UPDATE = 0x102 VER_COMMAND_KEYWORDS = 0x100 VER_COMMAND_STATUS = 0x100 VER_COMMAND_FLUSHATTRS = 0x100 # known searchd status codes SEARCHD_OK = 0 SEARCHD_ERROR = 1 SEARCHD_RETRY = 2 SEARCHD_WARNING = 3 # known match modes SPH_MATCH_ALL = 0 SPH_MATCH_ANY = 1 SPH_MATCH_PHRASE = 2 SPH_MATCH_BOOLEAN = 3 SPH_MATCH_EXTENDED = 4 SPH_MATCH_FULLSCAN = 5 SPH_MATCH_EXTENDED2 = 6 # known ranking modes (extended2 mode only) SPH_RANK_PROXIMITY_BM25 = 0 # default mode, phrase proximity major factor and BM25 minor one SPH_RANK_BM25 = 1 # statistical mode, BM25 ranking only (faster but worse quality) SPH_RANK_NONE = 2 # no ranking, all matches get a weight of 1 SPH_RANK_WORDCOUNT = 3 # simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts SPH_RANK_PROXIMITY = 4 SPH_RANK_MATCHANY = 5 SPH_RANK_FIELDMASK = 6 SPH_RANK_SPH04 = 7 SPH_RANK_EXPR = 8 SPH_RANK_TOTAL = 9 # known sort modes SPH_SORT_RELEVANCE = 0 SPH_SORT_ATTR_DESC = 1 SPH_SORT_ATTR_ASC = 2 SPH_SORT_TIME_SEGMENTS = 3 SPH_SORT_EXTENDED = 4 SPH_SORT_EXPR = 5 # known filter types SPH_FILTER_VALUES = 0 SPH_FILTER_RANGE = 1 SPH_FILTER_FLOATRANGE = 2 # known attribute types SPH_ATTR_NONE = 0 SPH_ATTR_INTEGER = 1 SPH_ATTR_TIMESTAMP = 2 SPH_ATTR_ORDINAL = 3 SPH_ATTR_BOOL = 4 SPH_ATTR_FLOAT = 5 SPH_ATTR_BIGINT = 6 SPH_ATTR_STRING = 7 SPH_ATTR_MULTI = 0X40000001 SPH_ATTR_MULTI64 = 0X40000002 SPH_ATTR_TYPES = (SPH_ATTR_NONE, SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_ORDINAL, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT, SPH_ATTR_STRING, SPH_ATTR_MULTI, SPH_ATTR_MULTI64) # known grouping functions SPH_GROUPBY_DAY = 0 SPH_GROUPBY_WEEK = 1 SPH_GROUPBY_MONTH = 2 SPH_GROUPBY_YEAR = 3 SPH_GROUPBY_ATTR = 4 SPH_GROUPBY_ATTRPAIR = 5 class SphinxClient: def __init__ (self): """ Create a new client object, and fill defaults. """ self._host = 'localhost' # searchd host (default is "localhost") self._port = 9312 # searchd port (default is 9312) self._path = None # searchd unix-domain socket path self._socket = None self._offset = 0 # how much records to seek from result-set start (default is 0) self._limit = 1000 # how much records to return from result-set starting at offset (default is 20) self._mode = SPH_MATCH_EXTENDED2 # word_map_table_creation_query matching mode (default is SPH_MATCH_ALL) self._weights = [] # per-field weights (default is 1 for all fields) self._sort = SPH_SORT_RELEVANCE # match sorting mode (default is SPH_SORT_RELEVANCE) self._sortby = '' # attribute to sort by (defualt is "") self._min_id = 0 # min ID to match (default is 0) self._max_id = 0 # max ID to match (default is UINT_MAX) self._filters = [] # search filters self._groupby = '' # group-by attribute name self._groupfunc = SPH_GROUPBY_DAY # group-by function (to pre-run group-by attribute value with) self._groupsort = '@group desc' # group-by sorting clause (to sort groups in result set with) self._groupdistinct = '' # group-by count-distinct attribute self._maxmatches = 1000 # max matches to retrieve self._cutoff = 0 # cutoff to stop searching at self._retrycount = 0 # distributed retry count self._retrydelay = 0 # distributed retry delay self._anchor = {} # geographical anchor point self._indexweights = {} # per-index weights self._ranker = SPH_RANK_PROXIMITY_BM25 # ranking mode self._rankexpr = '' # ranking expression for SPH_RANK_EXPR self._maxquerytime = 0 # max word_map_table_creation_query time, milliseconds (default is 0, do not limit) self._timeout = 1.0 # connection timeout self._fieldweights = {} # per-field-name weights self._overrides = {} # per-word_map_table_creation_query attribute values overrides self._select = '*' # select-list (attributes or expressions, with optional aliases) self._error = '' # last error message self._warning = '' # last warning message self._reqs = [] # requests array for multi-word_map_table_creation_query def __del__ (self): if self._socket: self._socket.close() def GetLastError (self): """ Get last error message (string). """ return self._error def GetLastWarning (self): """ Get last warning message (string). """ return self._warning def SetServer (self, host, port = None): """ Set searchd server host and port. """ assert(isinstance(host, str)) if host.startswith('/'): self._path = host return elif host.startswith('unix://'): self._path = host[7:] return assert(isinstance(port, int)) self._host = host self._port = port self._path = None def SetConnectTimeout ( self, timeout ): """ Set connection timeout ( float second ) """ assert (isinstance(timeout, float)) # set timeout to 0 make connaection non-blocking that is wrong so timeout got clipped to reasonable minimum self._timeout = max ( 0.001, timeout ) def _Connect (self): """ INTERNAL METHOD, DO NOT CALL. Connects to searchd server. """ if self._socket: # we have a socket, but is it still alive? sr, sw, _ = select.select ( [self._socket], [self._socket], [], 0 ) # this is how alive socket should look if len(sr)==0 and len(sw)==1: return self._socket # oops, looks like it was closed, lets reopen self._socket.close() self._socket = None try: if self._path: af = socket.AF_UNIX addr = self._path desc = self._path else: af = socket.AF_INET addr = ( self._host, self._port ) desc = '%s;%s' % addr sock = socket.socket ( af, socket.SOCK_STREAM ) sock.settimeout ( self._timeout ) sock.connect ( addr ) except socket.error as msg: if sock: sock.close() self._error = 'connection to %s failed (%s)' % ( desc, msg ) return v = unpack('>L', sock.recv(4)) if v<1: sock.close() self._error = 'expected searchd protocol version, got %s' % v return # all ok, send my version sock.send(pack('>L', 1)) return sock def _GetResponse (self, sock, client_ver): """ INTERNAL METHOD, DO NOT CALL. Gets and checks response packet from searchd server. """ (status, ver, length) = unpack('>2HL', sock.recv(8)) response = '' left = length while left>0: chunk = sock.recv(left) if chunk: response += chunk left -= len(chunk) else: break if not self._socket: sock.close() # check response read = len(response) if not response or read!=length: if length: self._error = 'failed to read searchd response (status=%s, ver=%s, len=%s, read=%s)' \ % (status, ver, length, read) else: self._error = 'received zero-sized searchd response' return None # check status if status==SEARCHD_WARNING: wend = 4 + unpack ( '>L', response[0:4] )[0] self._warning = response[4:wend] return response[wend:] if status==SEARCHD_ERROR: self._error = 'searchd error: '+response[4:] return None if status==SEARCHD_RETRY: self._error = 'temporary searchd error: '+response[4:] return None if status!=SEARCHD_OK: self._error = 'unknown status code %d' % status return None # check version if ver<client_ver: self._warning = 'searchd command v.%d.%d older than client\'s v.%d.%d, some options might not work' \ % (ver>>8, ver&0xff, client_ver>>8, client_ver&0xff) return response def SetLimits (self, offset, limit, maxmatches=0, cutoff=0): """ Set offset and count into result set, and optionally set max-matches and cutoff limits. """ assert ( type(offset) in [int,int] and 0<=offset<16777216 ) assert ( type(limit) in [int,int] and 0<limit<16777216 ) assert(maxmatches>=0) self._offset = offset self._limit = limit if maxmatches>0: self._maxmatches = maxmatches if cutoff>=0: self._cutoff = cutoff def SetMaxQueryTime (self, maxquerytime): """ Set maximum word_map_table_creation_query time, in milliseconds, per-index. 0 means 'do not limit'. """ assert(isinstance(maxquerytime,int) and maxquerytime>0) self._maxquerytime = maxquerytime def SetMatchMode (self, mode): """ Set matching mode. """ assert(mode in [SPH_MATCH_ALL, SPH_MATCH_ANY, SPH_MATCH_PHRASE, SPH_MATCH_BOOLEAN, SPH_MATCH_EXTENDED, SPH_MATCH_FULLSCAN, SPH_MATCH_EXTENDED2]) self._mode = mode def SetRankingMode ( self, ranker, rankexpr='' ): """ Set ranking mode. """ assert(ranker>=0 and ranker<SPH_RANK_TOTAL) self._ranker = ranker self._rankexpr = rankexpr def SetSortMode ( self, mode, clause='' ): """ Set sorting mode. """ assert ( mode in [SPH_SORT_RELEVANCE, SPH_SORT_ATTR_DESC, SPH_SORT_ATTR_ASC, SPH_SORT_TIME_SEGMENTS, SPH_SORT_EXTENDED, SPH_SORT_EXPR] ) assert ( isinstance ( clause, str ) ) self._sort = mode self._sortby = clause def SetWeights (self, weights): """ Set per-field weights. WARNING, DEPRECATED; do not use it! use SetFieldWeights() instead """ assert(isinstance(weights, list)) for w in weights: AssertUInt32 ( w ) self._weights = weights def SetFieldWeights (self, weights): """ Bind per-field weights by name; expects (name,field_weight) dictionary as argument. """ assert(isinstance(weights,dict)) for key,val in list(weights.items()): assert(isinstance(key,str)) AssertUInt32 ( val ) self._fieldweights = weights def SetIndexWeights (self, weights): """ Bind per-index weights by name; expects (name,index_weight) dictionary as argument. """ assert(isinstance(weights,dict)) for key,val in list(weights.items()): assert(isinstance(key,str)) AssertUInt32(val) self._indexweights = weights def SetIDRange (self, minid, maxid): """ Set IDs range to match. Only match records if document ID is beetwen $min and $max (inclusive). """ assert(isinstance(minid, int)) assert(isinstance(maxid, int)) assert(minid<=maxid) self._min_id = minid self._max_id = maxid def SetFilter ( self, attribute, values, exclude=0 ): """ Set values set filter. Only match records where 'attribute' value is in given 'values' set. """ assert(isinstance(attribute, str)) assert iter(values) for value in values: AssertInt32 ( value ) self._filters.append ( { 'type':SPH_FILTER_VALUES, 'attr':attribute, 'exclude':exclude, 'values':values } ) def SetFilterRange (self, attribute, min_, max_, exclude=0 ): """ Set range filter. Only match records if 'attribute' value is beetwen 'min_' and 'max_' (inclusive). """ assert(isinstance(attribute, str)) AssertInt32(min_) AssertInt32(max_) assert(min_<=max_) self._filters.append ( { 'type':SPH_FILTER_RANGE, 'attr':attribute, 'exclude':exclude, 'min':min_, 'max':max_ } ) def SetFilterFloatRange (self, attribute, min_, max_, exclude=0 ): assert(isinstance(attribute,str)) assert(isinstance(min_,float)) assert(isinstance(max_,float)) assert(min_ <= max_) self._filters.append ( {'type':SPH_FILTER_FLOATRANGE, 'attr':attribute, 'exclude':exclude, 'min':min_, 'max':max_} ) def SetGeoAnchor (self, attrlat, attrlong, latitude, longitude): assert(isinstance(attrlat,str)) assert(isinstance(attrlong,str)) assert(isinstance(latitude,float)) assert(isinstance(longitude,float)) self._anchor['attrlat'] = attrlat self._anchor['attrlong'] = attrlong self._anchor['lat'] = latitude self._anchor['long'] = longitude def SetGroupBy ( self, attribute, func, groupsort='@group desc' ): """ Set grouping attribute and function. """ assert(isinstance(attribute, str)) assert(func in [SPH_GROUPBY_DAY, SPH_GROUPBY_WEEK, SPH_GROUPBY_MONTH, SPH_GROUPBY_YEAR, SPH_GROUPBY_ATTR, SPH_GROUPBY_ATTRPAIR] ) assert(isinstance(groupsort, str)) self._groupby = attribute self._groupfunc = func self._groupsort = groupsort def SetGroupDistinct (self, attribute): assert(isinstance(attribute,str)) self._groupdistinct = attribute def SetRetries (self, count, delay=0): assert(isinstance(count,int) and count>=0) assert(isinstance(delay,int) and delay>=0) self._retrycount = count self._retrydelay = delay def SetOverride (self, name, type, values): assert(isinstance(name, str)) assert(type in SPH_ATTR_TYPES) assert(isinstance(values, dict)) self._overrides[name] = {'name': name, 'type': type, 'values': values} def SetSelect (self, select): assert(isinstance(select, str)) self._select = select def ResetOverrides (self): self._overrides = {} def ResetFilters (self): """ Clear all filters (for multi-queries). """ self._filters = [] self._anchor = {} def ResetGroupBy (self): """ Clear groupby settings (for multi-queries). """ self._groupby = '' self._groupfunc = SPH_GROUPBY_DAY self._groupsort = '@group desc' self._groupdistinct = '' def Query (self, query, index='*', comment=''): """ Connect to searchd server and run given search word_map_table_creation_query. Returns None on failure; result set hash on success (see documentation for details). """ assert(len(self._reqs)==0) self.AddQuery(query,index,comment) results = self.RunQueries() self._reqs = [] # we won't re-run erroneous batch self.output = results if not results or len(results)==0: return None self._error = results[0]['error'] self._warning = results[0]['warning'] if results[0]['status'] == SEARCHD_ERROR: return None return results[0] def AddQuery (self, query, index='*', comment=''): """ Add word_map_table_creation_query to batch. """ # build request req = [] req.append(pack('>4L', self._offset, self._limit, self._mode, self._ranker)) if self._ranker==SPH_RANK_EXPR: req.append(pack('>L', len(self._rankexpr))) req.append(self._rankexpr) req.append(pack('>L', self._sort)) req.append(pack('>L', len(self._sortby))) req.append(self._sortby) if isinstance(query,str): query = query.encode('utf-8') assert(isinstance(query,str)) req.append(pack('>L', len(query))) req.append(query) req.append(pack('>L', len(self._weights))) for w in self._weights: req.append(pack('>L', w)) req.append(pack('>L', len(index))) req.append(index) req.append(pack('>L',1)) # id64 range marker req.append(pack('>Q', self._min_id)) req.append(pack('>Q', self._max_id)) # filters req.append ( pack ( '>L', len(self._filters) ) ) for f in self._filters: req.append ( pack ( '>L', len(f['attr'])) + f['attr']) filtertype = f['type'] req.append ( pack ( '>L', filtertype)) if filtertype == SPH_FILTER_VALUES: req.append ( pack ('>L', len(f['values']))) for val in f['values']: req.append ( pack ('>q', val)) elif filtertype == SPH_FILTER_RANGE: req.append ( pack ('>2q', f['min'], f['max'])) elif filtertype == SPH_FILTER_FLOATRANGE: req.append ( pack ('>2f', f['min'], f['max'])) req.append ( pack ( '>L', f['exclude'] ) ) # group-by, max-matches, group-sort req.append ( pack ( '>2L', self._groupfunc, len(self._groupby) ) ) req.append ( self._groupby ) req.append ( pack ( '>2L', self._maxmatches, len(self._groupsort) ) ) req.append ( self._groupsort ) req.append ( pack ( '>LLL', self._cutoff, self._retrycount, self._retrydelay)) req.append ( pack ( '>L', len(self._groupdistinct))) req.append ( self._groupdistinct) # anchor point if len(self._anchor) == 0: req.append ( pack ('>L', 0)) else: attrlat, attrlong = self._anchor['attrlat'], self._anchor['attrlong'] latitude, longitude = self._anchor['lat'], self._anchor['long'] req.append ( pack ('>L', 1)) req.append ( pack ('>L', len(attrlat)) + attrlat) req.append ( pack ('>L', len(attrlong)) + attrlong) req.append ( pack ('>f', latitude) + pack ('>f', longitude)) # per-index weights req.append ( pack ('>L',len(self._indexweights))) for indx,weight in list(self._indexweights.items()): req.append ( pack ('>L',len(indx)) + indx + pack ('>L',weight)) # max word_map_table_creation_query time req.append ( pack ('>L', self._maxquerytime) ) # per-field weights req.append ( pack ('>L',len(self._fieldweights) ) ) for field,weight in list(self._fieldweights.items()): req.append ( pack ('>L',len(field)) + field + pack ('>L',weight) ) # comment req.append ( pack('>L',len(comment)) + comment ) # attribute overrides req.append ( pack('>L', len(self._overrides)) ) for v in list(self._overrides.values()): req.extend ( ( pack('>L', len(v['name'])), v['name'] ) ) req.append ( pack('>LL', v['type'], len(v['values'])) ) for id, value in v['values'].items(): req.append ( pack('>Q', id) ) if v['type'] == SPH_ATTR_FLOAT: req.append ( pack('>f', value) ) elif v['type'] == SPH_ATTR_BIGINT: req.append ( pack('>q', value) ) else: req.append ( pack('>l', value) ) # select-list req.append ( pack('>L', len(self._select)) ) req.append ( self._select ) # send word_map_table_creation_query, get response req = ''.join(req) self._reqs.append(req) return def RunQueries (self): """ Run queries batch. Returns None on network IO failure; or an array of result set hashes on success. """ if len(self._reqs)==0: self._error = 'no queries defined, issue AddQuery() first' return None sock = self._Connect() if not sock: return None req = ''.join(self._reqs) length = len(req)+8 req = pack('>HHLLL', SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, length, 0, len(self._reqs))+req sock.send(req) response = self._GetResponse(sock, VER_COMMAND_SEARCH) if not response: return None nreqs = len(self._reqs) # parse response max_ = len(response) p = 0 results = [] for i in range(0,nreqs,1): result = {} results.append(result) result['error'] = '' result['warning'] = '' status = unpack('>L', response[p:p+4])[0] p += 4 result['status'] = status if status != SEARCHD_OK: length = unpack('>L', response[p:p+4])[0] p += 4 message = response[p:p+length] p += length if status == SEARCHD_WARNING: result['warning'] = message else: result['error'] = message continue # read schema fields = [] attrs = [] nfields = unpack('>L', response[p:p+4])[0] p += 4 while nfields>0 and p<max_: nfields -= 1 length = unpack('>L', response[p:p+4])[0] p += 4 fields.append(response[p:p+length]) p += length result['fields'] = fields nattrs = unpack('>L', response[p:p+4])[0] p += 4 while nattrs>0 and p<max_: nattrs -= 1 length = unpack('>L', response[p:p+4])[0] p += 4 attr = response[p:p+length] p += length type_ = unpack('>L', response[p:p+4])[0] p += 4 attrs.append([attr,type_]) result['attrs'] = attrs # read match count count = unpack('>L', response[p:p+4])[0] p += 4 id64 = unpack('>L', response[p:p+4])[0] p += 4 # read matches result['matches'] = [] while count>0 and p<max_: count -= 1 if id64: doc, weight = unpack('>QL', response[p:p+12]) p += 12 else: doc, weight = unpack('>2L', response[p:p+8]) p += 8 match = { 'id':doc, 'weight':weight, 'attrs':{} } for i in range(len(attrs)): if attrs[i][1] == SPH_ATTR_FLOAT: match['attrs'][attrs[i][0]] = unpack('>f', response[p:p+4])[0] elif attrs[i][1] == SPH_ATTR_BIGINT: match['attrs'][attrs[i][0]] = unpack('>q', response[p:p+8])[0] p += 4 elif attrs[i][1] == SPH_ATTR_STRING: slen = unpack('>L', response[p:p+4])[0] p += 4 match['attrs'][attrs[i][0]] = '' if slen>0: match['attrs'][attrs[i][0]] = response[p:p+slen] p += slen-4 elif attrs[i][1] == SPH_ATTR_MULTI: match['attrs'][attrs[i][0]] = [] nvals = unpack('>L', response[p:p+4])[0] p += 4 for n in range(0,nvals,1): match['attrs'][attrs[i][0]].append(unpack('>L', response[p:p+4])[0]) p += 4 p -= 4 elif attrs[i][1] == SPH_ATTR_MULTI64: match['attrs'][attrs[i][0]] = [] nvals = unpack('>L', response[p:p+4])[0] nvals = nvals/2 p += 4 for n in range(0,nvals,1): match['attrs'][attrs[i][0]].append(unpack('>q', response[p:p+8])[0]) p += 8 p -= 4 else: match['attrs'][attrs[i][0]] = unpack('>L', response[p:p+4])[0] p += 4 result['matches'].append ( match ) result['total'], result['total_found'], result['time'], words = unpack('>4L', response[p:p+16]) result['time'] = '%.3f' % (result['time']/1000.0) p += 16 result['words'] = [] while words>0: words -= 1 length = unpack('>L', response[p:p+4])[0] p += 4 word = response[p:p+length] p += length docs, hits = unpack('>2L', response[p:p+8]) p += 8 result['words'].append({'word':word, 'docs':docs, 'hits':hits}) self._reqs = [] return results def BuildExcerpts (self, docs, index, words, opts=None): """ Connect to searchd server and generate exceprts from given documents. """ if not opts: opts = {} if isinstance(words,str): words = words.encode('utf-8') assert(isinstance(docs, list)) assert(isinstance(index, str)) assert(isinstance(words, str)) assert(isinstance(opts, dict)) sock = self._Connect() if not sock: return None # fixup options opts.setdefault('before_match', '<b>') opts.setdefault('after_match', '</b>') opts.setdefault('chunk_separator', ' ... ') opts.setdefault('html_strip_mode', 'index') opts.setdefault('limit', 256) opts.setdefault('limit_passages', 0) opts.setdefault('limit_words', 0) opts.setdefault('around', 5) opts.setdefault('start_passage_id', 1) opts.setdefault('passage_boundary', 'none') # build request # v.1.0 req flags = 1 # (remove spaces) if opts.get('exact_phrase'): flags |= 2 if opts.get('single_passage'): flags |= 4 if opts.get('use_boundaries'): flags |= 8 if opts.get('weight_order'): flags |= 16 if opts.get('query_mode'): flags |= 32 if opts.get('force_all_words'): flags |= 64 if opts.get('load_files'): flags |= 128 if opts.get('allow_empty'): flags |= 256 if opts.get('emit_zones'): flags |= 512 if opts.get('load_files_scattered'): flags |= 1024 # mode=0, flags req = [pack('>2L', 0, flags)] # req index req.append(pack('>L', len(index))) req.append(index) # req words req.append(pack('>L', len(words))) req.append(words) # options req.append(pack('>L', len(opts['before_match']))) req.append(opts['before_match']) req.append(pack('>L', len(opts['after_match']))) req.append(opts['after_match']) req.append(pack('>L', len(opts['chunk_separator']))) req.append(opts['chunk_separator']) req.append(pack('>L', int(opts['limit']))) req.append(pack('>L', int(opts['around']))) req.append(pack('>L', int(opts['limit_passages']))) req.append(pack('>L', int(opts['limit_words']))) req.append(pack('>L', int(opts['start_passage_id']))) req.append(pack('>L', len(opts['html_strip_mode']))) req.append((opts['html_strip_mode'])) req.append(pack('>L', len(opts['passage_boundary']))) req.append((opts['passage_boundary'])) # documents req.append(pack('>L', len(docs))) for doc in docs: if isinstance(doc,str): doc = doc.encode('utf-8') assert(isinstance(doc, str)) req.append(pack('>L', len(doc))) req.append(doc) req = ''.join(req) # send word_map_table_creation_query, get response length = len(req) # add header req = pack('>2HL', SEARCHD_COMMAND_EXCERPT, VER_COMMAND_EXCERPT, length)+req wrote = sock.send(req) response = self._GetResponse(sock, VER_COMMAND_EXCERPT ) if not response: return [] # parse response pos = 0 res = [] rlen = len(response) for i in range(len(docs)): length = unpack('>L', response[pos:pos+4])[0] pos += 4 if pos+length > rlen: self._error = 'incomplete reply' return [] res.append(response[pos:pos+length]) pos += length return res def UpdateAttributes ( self, index, attrs, values, mva=False ): """ Update given attribute values on given documents in given indexes. Returns amount of updated documents (0 or more) on success, or -1 on failure. 'attrs' must be a list of strings. 'values' must be a dict with int key (document ID) and list of int values (new attribute values). optional boolean parameter 'mva' points that there is update of MVA attributes. In this case the 'values' must be a dict with int key (document ID) and list of lists of int values (new MVA attribute values). Example: res = cl.UpdateAttributes ( 'test1', [ 'group_id', 'date_added' ], { 2:[123,1000000000], 4:[456,1234567890] } ) """ assert ( isinstance ( index, str ) ) assert ( isinstance ( attrs, list ) ) assert ( isinstance ( values, dict ) ) for attr in attrs: assert ( isinstance ( attr, str ) ) for docid, entry in list(values.items()): AssertUInt32(docid) assert ( isinstance ( entry, list ) ) assert ( len(attrs)==len(entry) ) for val in entry: if mva: assert ( isinstance ( val, list ) ) for vals in val: AssertInt32(vals) else: AssertInt32(val) # build request req = [ pack('>L',len(index)), index ] req.append ( pack('>L',len(attrs)) ) mva_attr = 0 if mva: mva_attr = 1 for attr in attrs: req.append ( pack('>L',len(attr)) + attr ) req.append ( pack('>L', mva_attr ) ) req.append ( pack('>L',len(values)) ) for docid, entry in list(values.items()): req.append ( pack('>Q',docid) ) for val in entry: val_len = val if mva: val_len = len ( val ) req.append ( pack('>L',val_len ) ) if mva: for vals in val: req.append ( pack ('>L',vals) ) # connect, send word_map_table_creation_query, get response sock = self._Connect() if not sock: return None req = ''.join(req) length = len(req) req = pack ( '>2HL', SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, length ) + req wrote = sock.send ( req ) response = self._GetResponse ( sock, VER_COMMAND_UPDATE ) if not response: return -1 # parse response updated = unpack ( '>L', response[0:4] )[0] return updated def BuildKeywords ( self, query, index, hits ): """ Connect to searchd server, and generate keywords list for a given word_map_table_creation_query. Returns None on failure, or a list of keywords on success. """ assert ( isinstance ( query, str ) ) assert ( isinstance ( index, str ) ) assert ( isinstance ( hits, int ) ) # build request req = [ pack ( '>L', len(query) ) + query ] req.append ( pack ( '>L', len(index) ) + index ) req.append ( pack ( '>L', hits ) ) # connect, send word_map_table_creation_query, get response sock = self._Connect() if not sock: return None req = ''.join(req) length = len(req) req = pack ( '>2HL', SEARCHD_COMMAND_KEYWORDS, VER_COMMAND_KEYWORDS, length ) + req wrote = sock.send ( req ) response = self._GetResponse ( sock, VER_COMMAND_KEYWORDS ) if not response: return None # parse response res = [] nwords = unpack ( '>L', response[0:4] )[0] p = 4 max_ = len(response) while nwords>0 and p<max_: nwords -= 1 length = unpack ( '>L', response[p:p+4] )[0] p += 4 tokenized = response[p:p+length] p += length length = unpack ( '>L', response[p:p+4] )[0] p += 4 normalized = response[p:p+length] p += length entry = { 'tokenized':tokenized, 'normalized':normalized } if hits: entry['docs'], entry['hits'] = unpack ( '>2L', response[p:p+8] ) p += 8 res.append ( entry ) if nwords>0 or p>max_: self._error = 'incomplete reply' return None return res def Status ( self ): """ Get the status """ # connect, send word_map_table_creation_query, get response sock = self._Connect() if not sock: return None req = pack ( '>2HLL', SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, 1 ) wrote = sock.send ( req ) response = self._GetResponse ( sock, VER_COMMAND_STATUS ) if not response: return None # parse response res = [] p = 8 max_ = len(response) while p<max_: length = unpack ( '>L', response[p:p+4] )[0] k = response[p+4:p+length+4] p += 4+length length = unpack ( '>L', response[p:p+4] )[0] v = response[p+4:p+length+4] p += 4+length res += [[k, v]] return res ### persistent connections def Open(self): if self._socket: self._error = 'already connected' return None server = self._Connect() if not server: return None # command, command version = 0, body length = 4, body = 1 request = pack ( '>hhII', SEARCHD_COMMAND_PERSIST, 0, 4, 1 ) server.send ( request ) self._socket = server return True def Close(self): if not self._socket: self._error = 'not connected' return self._socket.close() self._socket = None def EscapeString(self, string): return re.sub(r"([=\(\)|\-!@~\"&/\\\^\$\=])", r"\\\1", string) def FlushAttributes(self): sock = self._Connect() if not sock: return -1 request = pack ( '>hhI', SEARCHD_COMMAND_FLUSHATTRS, VER_COMMAND_FLUSHATTRS, 0 ) # cmd, ver, bodylen sock.send ( request ) response = self._GetResponse ( sock, VER_COMMAND_FLUSHATTRS ) if not response or len(response)!=4: self._error = 'unexpected response length' return -1 tag = unpack ( '>L', response[0:4] )[0] return tag def AssertInt32 ( value ): assert(isinstance(value, int)) assert(value>=-2**32-1 and value<=2**32-1) def AssertUInt32 ( value ): assert(isinstance(value, int)) assert(value>=0 and value<=2**32-1) # # $Id: sphinxapi.py 3087 2012-01-30 23:07:35Z shodan $ #
AdamTools
/AdamTools-0.0.4.tar.gz/AdamTools-0.0.4/FileSystem/sphinxapi.py
sphinxapi.py
import smtplib import sys from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # from email.MIMEMultipart import MIMEMultipart # from email.MIMEBase import MIMEBase # from email import Encoders # from email.MIMEText import MIMEText class EmailerBase( object ): def __init__( self, password, test=False ): if test: self.SMTPserver = 'mailtrap.io' self.PORT = 2525 self.sender = '[email protected]' self.USERNAME = 'fc415c779e9d12' self.PASSWORD = password self.isTest = True else: self.SMTPserver = 'smtp.office365.com' self.sender = '[email protected]' self.USERNAME = "ars62917" self.PASSWORD = password self.isTest = False self.URL = "smtp.office365.com" self.PORT = 587 self.EXCHANGE_USER = "[email protected]" self.EXCHANGE_PASSWORD = password self.bcc_address = '[email protected]' self.isTest = False # typical values for text_subtype are plain, html, xml self.text_subtype = 'html' if self.isTest: print( "TESTING MODE" ) else: print( "LIVE MODE" ) def _connect( self ): try: self.conn = smtplib.SMTP( self.URL, self.PORT ) self.conn.set_debuglevel( False ) self.conn.starttls() self.conn.login( self.EXCHANGE_USER, self.EXCHANGE_PASSWORD ) except Exception as exc: sys.exit( "connection failed; %s" % str( exc ) ) # give a error message def sendMail( self, destination, message_content, subject, print_status=False ): """ @param destination: should be an email address @type destination: C{str} """ raise NotImplementedError def send_w_attachment( self, destination, message_content, subject, attachment ): """ Sends an email with the specified attachment """ raise NotImplementedError class Emailer( EmailerBase ): """ This is the base class for any emailing function """ def __init__( self, test=False ): EmailerBase.__init__( self, test ) def sendMail( self, destination, message_content, subject, print_status=False ): """ @param destination: should be a list of email addresses @type destination: C{list} """ # this invokes the secure SMTP protocol (port 465, uses SSL) # from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption) self.destination = destination self.content = message_content self.subject = subject try: msg = MIMEText( self.content, self.text_subtype ) msg[ 'To' ] = self.destination msg[ 'Subject' ] = self.subject msg[ 'From' ] = self.sender # some SMTP servers will do this automatically, not all # msg['CC'] = self.sender conn = smtplib.SMTP( self.SMTPserver, self.PORT ) conn.set_debuglevel( False ) conn.starttls() conn.login( self.USERNAME, self.PASSWORD ) try: conn.sendmail( self.sender, self.destination, msg.as_string() ) if (print_status): print( "Sent to: %s \n %s" % (self.destination, msg.as_string()) ) finally: conn.close() except Exception as exc: sys.exit( "mail failed; %s" % str( exc ) ) # give a error message def send_w_attachment( self, destination, message_content, subject, attachment ): """ Sends an email with the specified attachment """ self.destination = destination self.content = message_content self.subject = subject try: msg = MIMEMultipart() msg[ 'Subject' ] = self.subject msg[ 'From' ] = self.sender msg[ 'To' ] = self.destination # msg['To'] = ', '.join(self.destination) part = MIMEBase( 'application', "octet-stream" ) part.set_payload( open( attachment, "rb" ).read() ) Encoders.encode_base64( part ) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % attachment ) msg.attach( part ) conn = self.connect() try: conn.sendmail( self.sender, self.destination, msg.as_string() ) finally: conn.close() except Exception as exc: sys.exit( "mail failed; %s" % str( exc ) ) # give a error message class ExchangeEmailer( EmailerBase ): """ Base class for sending email via exchange """ def __init__( self, password, test=False ): super().__init__( password, test ) def sendMail( self, destination, message_content: str, subject: str, print_status=False ): """ @param destination: an of email address @type destination: C{string} :param print_status: Whether to print status messages :param subject: The subject line :param message_content: The body of the message """ self.destination = destination self.content = message_content self.subject = subject try: msg = MIMEText( self.content, self.text_subtype ) msg[ 'To' ] = self.destination msg[ 'Subject' ] = self.subject msg[ 'From' ] = self.sender # some SMTP servers will do this automatically, not all # msg['CC'] = self.sender self._connect() try: self.conn.sendmail( self.sender, self.destination, msg.as_string() ) self.conn.sendmail( self.sender, self.bcc_address, msg.as_string() ) if print_status: print( "Sent to: %s \n %s" % (self.destination, msg.as_string()) ) finally: self.conn.close() except Exception as exc: sys.exit( "mail failed; %s" % str( exc ) ) # give a error message def send_w_attachment( self, destination, message_content, subject, attachment ): """ Sends an email with the specified attachment Unclear whether this works yet """ self.destination = destination self.content = message_content self.subject = subject try: msg = MIMEMultipart() msg[ 'Subject' ] = self.subject msg[ 'From' ] = self.sender msg[ 'To' ] = self.destination # msg['To'] = ', '.join(self.destination) part = MIMEBase( 'application', "octet-stream" ) part.set_payload( open( attachment, "rb" ).read() ) Encoders.encode_base64( part ) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % attachment ) msg.attach( part ) conn = self.connect() try: conn.sendmail( self.sender, self.destination, msg.as_string() ) finally: conn.close() except Exception as exc: sys.exit( "mail failed; %s" % str( exc ) ) # give a error message
AdamTools
/AdamTools-0.0.4.tar.gz/AdamTools-0.0.4/Email/EmailerBase.py
EmailerBase.py
__author__ = 'adam' import nltk # This idiom is necessary. See https://github.com/nltk/nltk/issues/1516 from nltk.metrics import association class NgramError(BaseException): def __init__(self, processing_step): """ Arguments: :param processing_step: String description of where error arose :return: """ super().__init__() self.kind = 'NgramProcessing' self.identifier_type = 'String content' self.step = processing_step # ProcessingError.__init__(self, processing_step) class NgramGetter(object): """ Abstract parent class for extracting ngrams. Attributes: collocation_finder: One of the nltk's collocation finder tools (e.g., BigramCollocationFinder) top_likelihood_ratio: measurement_tool: One of nltk's measurement tools (e.g., nltk.collocations.BigramAssocMeasures) modifiers: IModifier instantiating tool for modifying the text before calculating ngrams ngrams: List of ngrams raw_freq: Frequency distribution of ngrams sorted_ngrams: List of tuples sorted by self.scored_ngrams top_pmi: Variable number of n-grams with the highest Pointwise Mutual Information (i.e., which occur together more often than would be expected) word_bag: List of text to run """ def __init__(self): self.modifiers = [] self.ngram_filters = [] self.word_bag = [] self.ngrams = [] if not self.measurement_tool: raise NotImplementedError def add_modifier(self, iModifier): assert(isinstance(iModifier, IModifier)) self.modifiers.append(iModifier) def _run_modifiers(self): """ Calls the modifiers in sequence and stores the results back in word_bag """ for modifier in self.modifiers: self.word_bag = [modifier.process(w) for w in self.word_bag] def add_filter(self, iNgramFilter): """ Adds a filter to be run after the ngrams are created :param iNgramFilter: :return: """ self.ngram_filters.append(iNgramFilter) def apply_filters(self): for ftr in self.ngram_filters: self.collocation_finder.apply_ngram_filter(ftr) def process(self, word_bag, min_freq=3, get_top=10, **kwargs): """ Runs any modifiers (stemmers, lemmatizers, etc) on the list of terms and then extracts the ngrams Args: get_top: The cut off for ngrams to get stats for min_freq: Integer of minimum number of appearances of ngram to extract word_bag: List of strings to extract ngrams from. Should already be filtered. """ raise NotImplementedError def _calculate_statistics(self, get_top=10, **kwargs): """ A number of measures are available to score collocations or other associations. The arguments to measure functions are marginals of a contingency table, in the bigram case (n_ii, (n_ix, n_xi), n_xx): w1 ~w1 ------ ------ w2 | n_ii | n_oi | = n_xi ------ ------ ~w2 | n_io | n_oo | ------ ------ = n_ix TOTAL = n_xx We test their calculation using some known values presented in Manning and Schutze's text and other papers. Student's t: examples from Manning and Schutze 5.3.2 Arguments: get_top: The cut off for ngrams to get stats for """ self.topPMI = self.collocation_finder.nbest(self.measurement_tool.pmi, get_top) self.raw_freq = self.collocation_finder.score_ngrams(self.measurement_tool.raw_freq) self.sorted_ngrams = [ngram for ngram, score in self.raw_freq] self.top_likelihood_ratio = self.collocation_finder.nbest(self.measurement_tool.likelihood_ratio, get_top) class BigramGetter(NgramGetter): """ Extracts 2-grams from a word bag and calculates statistics Attributes: top_pmi: Variable number of n-grams with the highest Pointwise Mutual Information (i.e., which occur together more often than would be expected) top_likelihood_ratio: raw_freq: Frequency distribution of ngrams sorted_ngrams: List of tuples sorted by self.scored_ngrams """ def __init__(self): self.measurement_tool = association.BigramAssocMeasures() NgramGetter.__init__(self) def process(self, word_bag, min_freq=3, get_top=10, **kwargs): """ Arguments: word_bag: List of strings """ assert(isinstance(word_bag, list)) self.collocation_finder = nltk.collocations.BigramCollocationFinder.from_words(word_bag) self.collocation_finder.apply_freq_filter(min_freq) self._calculate_statistics(get_top) class TrigramGetter(NgramGetter): """ Extracts 3-grams from a word bag and calculates statistics """ def __init__(self): self.measurement_tool = association.TrigramAssocMeasures() NgramGetter.__init__(self) def process(self, word_bag, min_freq=3, get_top=10, **kwargs): """ Arguments: word_bag: List of strings """ assert(isinstance(word_bag, list)) # try: self._run_modifiers() self.collocation_finder = nltk.collocations.TrigramCollocationFinder.from_words(word_bag) self.collocation_finder.apply_freq_filter(min_freq) self._calculate_statistics(get_top) if __name__ == '__main__': pass
AdamTools
/AdamTools-0.0.4.tar.gz/AdamTools-0.0.4/Text/NGramTools.py
NGramTools.py
import optparse import sys import string from subprocess import call from mercurial import hg, ui from mercurial.error import RepoError class Dumper(object): """ Main class that defines how to store database dumps in version control. Will be subclassed for the different database backends to handle the different methods of doing the actual dump. """ def __init__(self, backend, options): self.backend = backend self.database = options.database self.username = options.username self.password = options.password self.mirror = options.mirror self.import_file = options.import_file if options.repository is not None: self.path = options.repository else: self.path = 'adamanteus_%s_%s_backup' % (self.database, self.backend) print 'Preparing to back up a %s database to repository %s' % (self.backend, self.path) try: self.repo = hg.repository(ui.ui(), path=self.path) except RepoError: self.repo = hg.repository(ui.ui(), path=self.path, create=True) def __call__(self, action='dump'): if action == 'dump': self.dump() self.store() if self.mirror is not None: self.push() elif action == 'load': self.load() def dump(self): raise NotImplementedError("You must subclass Dumper and define " "your own dump() method.") def load(self): raise NotImplementedError("You must subclass Dumper and define " "your own load() method.") def store(self): status = self.repo.status(unknown=True) unknown = status[4] len_unknown = len(unknown) missing = status[3] len_missing = len(missing) workingctx = self.repo[None] if len_unknown: print "Adding %d files to repo..." % len_unknown workingctx.add(unknown) if len_missing: print "Removing %d missing files from repo..." % len_unknown workingctx.remove(missing) if len(self.repo.status()[0]) or len(self.repo.status()[1]): rev = self.repo.commit() def push(self): remote_paths = self.mirror.split(',') for remote_path in remote_paths: remote_repo = hg.repository(ui.ui(), path=remote_path) self.repo.push(remote_repo) class MongoDumper(Dumper): """ Subclass of Dumper for working with MongoDB databases. """ def dump(self): try: from pymongo.connection import Connection connection = Connection() collections = connection[self.database].collection_names() for collection in collections: dump_options = ['mongoexport', '-d%s' % self.database, '-c%s' % collection] if self.username is not None: dump_options.append('-u %s' % self.username) if self.password is not None: dump_options.append('-p %s' % self.password) output_file = "%s/%s.json" % (self.path, collection) dump_options.append('-o%s' % output_file) call(dump_options) except ImportError: # For now we need to use mongodump, will switch to # mongoexport with MongoDB 1.5 dump_options = ['mongodump', '--out=%s' % self.path, '-d%s' % self.database] if self.username is not None: dump_options.append('-u %s' % self.username) if self.password is not None: dump_options.append('-p %s' % self.password) call(dump_options) class MySQLDumper(Dumper): """ Subclass of Dumper for working with MySQL databases. """ def dump(self): # mysqldump -u 'username' -ppassword --skip-extended-insert database > $FILENAME output_file = "%s/%s.sql" % (self.path, self.database) dump_options = ['mysqldump'] if self.username is not None: dump_options.append("-u%s" % string.strip(self.username)) if self.password is not None: dump_options.append('-p%s' % self.password) dump_options.append('--skip-extended-insert') dump_options.append(self.database) dump_options.append('--result-file=%s' % output_file) call(dump_options) class PostgresDumper(Dumper): """ Subclass of Dumper for working with PostgreSQL databases. """ def __init__(self, backend, options): super(PostgresDumper, self).__init__(backend, options) # There's apparently no way to pass in a password at the command line, # so looks like we'll just have to leave that out. Will return an error # if the user tries to give a password for a PostgreSQL database dump. if self.password is not None: password_error = """ PostgreSQL dumper does not support password authentication. Please set up a read-only user for backing up your PostgreSQL database, or use a .pgpass file. Details on using a .pgpass file can be found here: http://www.postgresql.org/docs/current/interactive/libpq-pgpass.html """ raise Exception(password_error) def dump(self): # pg_dump django_influencer -U username -W --file=filename output_file = "%s/%s.out" % (self.path, self.database) dump_options = ['pg_dump', self.database] # options get set here if self.username is not None: dump_options.append('-U%s' % string.strip(self.username)) dump_options.append('--file=%s' % output_file) call(dump_options) def load(self): # psql -U {user-name} -d {desintation_db} -f {dumpfilename.sql} load_options = ['psql', '-q', '-d%s' % self.database] if self.username is not None: load_options.append('-U%s' % string.strip(self.username)) load_options.append('--file=%s' % self.import_file) call(load_options) def main(): usage = "usage: %prog BACKEND [action] -d DATABASE [-r repository] [-u username] [-p password]" p = optparse.OptionParser(description=' Backup a database to a mercurial repository', prog='adamanteus', version='adamanteus 0.6', usage=usage) p.add_option('--database', '-d', default=None, help="The name of the database to be backed up.") p.add_option('--repository', '-r', default=None, help="The mercurial repository to be backed up to.") p.add_option('-u', default=None, dest='username', help="The username to use with the database.") p.add_option('--password', '-p', default=None, help="The password to use with the database.") p.add_option('--mirror', '-m', default=None, help="Remote repository to be used as mirror of backup.") p.add_option('--restore-file', '-f', default=None, dest='import_file', help="Archive file to restore database from.") options, arguments = p.parse_args() DUMPERS = { 'mongodb': MongoDumper, 'mysql': MySQLDumper, 'postgres': PostgresDumper, } ACTIONS = ( 'dump', 'load', ) if len(arguments) not in (1, 2): p.print_usage() print >> sys.stderr, 'You must specify a database backend.' return else: backend = arguments[0] try: action = arguments[1] except IndexError: action = 'dump' if backend not in DUMPERS.keys(): print >> sys.stderr, '%s is not currently a supported database backend.' % backend print >> sys.stderr, 'Supported backends include: %s.' % ', '.join(DUMPERS.keys()) return if options.database is None: print p.print_usage() print >> sys.stderr, 'You must specify a database to be backed up.' return if action not in ACTIONS: print >> sys.stderr, '%s is not currently a supported action.' % action print >> sys.stderr, 'Supported backends include: %s.' % ', '.join(ACTIONS) return if options.database is None: print p.print_usage() print >> sys.stderr, 'You must specify a database to be backed up.' return dumper = DUMPERS[backend](backend, options) dumper(action=action) if __name__ == '__main__': main()
Adamanteus
/Adamanteus-0.7.tar.gz/Adamanteus-0.7/adamanteus.py
adamanteus.py
# Adapter-LoRa for Quantization <div align="center"> <img src="assets/LoRa.png" alt="LoRa-Logo" width="200"> [![Made With Love](https://img.shields.io/badge/Made%20With-Love-orange.svg)](https://github.com/youness-elbrag/AdapterLoRa/) [![GitHub issues](https://img.shields.io/github/issues/kyegomez/Med-Palm)](https://github.com/youness-elbrag/AdapterLoRa/issues) [![GitHub forks](https://img.shields.io/github/forks/kyegomez/Med-Palm)](https://github.com/youness-elbrag/AdapterLoRa/network) [![GitHub stars](https://img.shields.io/github/stars/kyegomez/Med-Palm)](https://github.com/youness-elbrag/AdapterLoRa/stargazers) [![GitHub license](https://img.shields.io/github/license/youness-elbrag/AdapterLoRa)](https://github.com/youness-elbrag/AdapterLoRa/blob/master/LICENSE) </div> ## Comparative Features of "loralib" and "loratorch" Implementations **Distinguishing the "loralib" and "loratorch" Approaches for Implementation** The implementations of "loralib" and "loratorch" exhibit distinct methodologies, particularly when using the example of `nn.Linear`. The underlying mathematical representations are as follows: 1. * **loralib** Approach The computation is defined as: \[ h = x W_0^\top + \frac{\alpha}{r} x(BA)^\top, \] where: - `x` is an input matrix of dimensions \(k \times n\), - `W_0` is a pre-trained weight matrix of dimensions \(m \times n\), - `r` is a predefined LoRA rank, - `B` and `A` are LoRA matrices of dimensions \(m \times r\) and \(r \times n\) respectively, - `\alpha` is a hyper-parameter. 1. For ``loralib``, $h = x W_0^\top + \frac{\alpha}{r} x(BA)^\top,$ where $x\in\mathbb{R}^{k\times n}$ is the input matrix, $W_0\in\mathbb{R}^{m\times n}$ is the pre-trained weight matrix, $r$ is the predefined LoRA rank, $B\in\mathbb{R}^{m\times r}$ and $A\in \mathbb{R}^{r\times n}$ are the LoRA matrixes, and $\alpha$ is a hyper-parameter. 2. For ``loratorch``, $h = x (W_0 + \frac{\alpha}{r} BA)^\top.$ ``loralib`` computes $xW_0^\top$ and $x(BA)^\top$ respectively and then merges the results. While ``loratorch`` merges pre-trained weight $W_0$ and its LoRA weight $BA$ and then computes the results by simply using ``nn.Linear.forward()``. There is no difference between ``loralib`` and ``loratorch`` in the linear layers. But in some no-linear or complex layers, we are no sure whether this layer satisfies $L(x, W_0)+L(x, BA) = L(x, W_0+BA)$. Hence, it is difficult to extend LoRA to some complex layers by using ``loralib``. On the contrary, the idea of merging weights first in ``loratorch`` is more general and extensible. You just call ``merge_lora_param()`` in ``loratorch`` to merge weights and then call ``forward()`` in the original layer to compute the results. With the help of ``loratorch``, you can easily implement LoRA to any type of layer of ``torch.nn``. ## Supported Layers | | ``loralib`` | ``loratorch`` | | | ------------------------- |:--------------:|:--------------:| -------------------------------------------------- | | ``nn.Linear`` | ✓ | ✓ | [linear.ipynb](https://github.com/Baijiong-Lin/LoRA-Torch/blob/main/examples/linear.ipynb) | | ``nn.Embedding`` | ✓ | ✓ | [embedding.ipynb](https://github.com/Baijiong-Lin/LoRA-Torch/blob/main/examples/embedding.ipynb) | | ``nn.Conv1d`` | ✓ | ✓ | | | ``nn.Conv2d`` | ✓ | ✓ | | | ``nn.Conv3d`` | ✓ | ✓ | | | ``nn.MultiheadAttention`` | ✘ | ✓ | | | ``MergedLinear`` | ✓ (Error) | ✓ | [mergedlinear.ipynb](https://github.com/Baijiong-Lin/LoRA-Torch/blob/main/examples/mergedlinear.ipynb) | | $\cdots$ | hard to extend | easy to extend | | *We compare the results of ``loralib`` and ``loratorch`` in [examples](./examples) to demonstrate the correctness of the implementation in ``loratorch``.* ## Quick Start **The usage of ``AdapterLoRa``** 1. Install ``AdapterLoRa``. ```bash pip install git+https://github.com/Baijiong-Lin/LoRA-Torch ``` ```python pip install AdapterLoRa ``` ### Usage Tool AdpaterLoRa ```python import torch.nn as nn import torch from core.Quantized import AdapterLoRa model = nn.TransformerEncoderLayer(d_model=512, nhead=8) Adpate_model = AdapterLoRa(model , method="LoRa", Rank=4) """ adding Linear Layer built Self.attention Replace the layers where you would like to use AdapterLoRa by using add_layer function. """ Adpate_model.add_layer("self_attn") Adpate_model.add_layer("linear1") Adpate_model.add_layer("linear2") # reconstruct model Quantized Adpate_model.reconstruct_model() # Iplmented LoRa Method model = Adpate_model.implement_lora(verbose=True) # Total trainable parameters before LoRA: 3176960 # Total trainable parameters after LoRA: 24576 # This sets requires_grad to False for all parameters without the string "lora_" in their names # Training loop for batch in dataloader: model.train() ``` ### Saving Wieghts model * Save LoRA model (only the LoRA matrixes will be saved). ```python import loralib as lora # ===== Before ===== # torch.save(model.state_dict(), checkpoint_path) # ===== After ===== torch.save(lora.lora_state_dict(model), checkpoint_path) ``` ### Loading the Pre-Trained Model * Load LoRA model (need to load the pre-trained model first). ```python import loralib as lora # Load the pre-trained checkpoint first model.load_state_dict(torch.load('ckpt_pretrained.pt'), strict=False) # Then load the LoRA checkpoint model.load_state_dict(torch.load('ckpt_lora.pt'), strict=False) ``` - <img src="assets/rocket.gif" width="32" height="32"/> Quantized Model <img src="assets/rocket.gif" width="32" height="32"/> - <img src="assets/time.gif" width="32" height="32"/> Time to Train <img src="assets/time.gif" width="32" height="32"/> - <img src="assets/money.gif" width="32" height="32"/> Cost to Train <img src="assets/money.gif" width="32" height="32"/> ## What's in it for you? For each of the above four pillars, we are sharing our codebase and insights to: - Assist you to leverage Transfomer-Based Model for your machines needs and challenges - Boost reproducibility efforts which are becoming increasingly difficult with Transfomers i am providing Tool that are ready-to-use for Quantize the model: - Finetuning Transfomer-Based on your proprietary dataset via PeFT methodologies such as LoRA and QLoRa - Performing hyperparameter optimization to get the maximum performance out of these models ## What's the best way to use this repository? Go over to the Transfomer-Based-specific directory that you are interested in, and open the ```README.md```. We have included details about the LLMs, followed by performance results on open-source datasets! ## Roadmap Our plan is to perform these experiments on all the Transformer-Based model below. To that end, this is a tentative roadmap of the LLMs that we aim to cover: - [x] TransfomerEncoder - [x] TransfomerDecoder - [x] Vision-Transfomer - [x] minGPT - [x] OpenAI GPT-2 - [ ] Inflection Pi **Under Progress** ## Correspondence ## Contributor ``AdapterLoRa`` is developed and maintained by ''Youness ELbrag'' ([Email]([email protected]) | [LinkedIn](https://www.linkedin.com/in/youness-el-brag-b13628203/))
AdapterLoRa
/AdapterLoRa-2.0.0.tar.gz/AdapterLoRa-2.0.0/README.md
README.md
import loratorch as LoraT import torch.nn as nn import loralib as lora from .utils import make_lora_replace class CastOutputToFloat(nn.Module): def forward(self, x): return x.to(torch.float32) class AdapterLoRa(nn.Module): def __init__(self, model: nn.Module, method: str, Rank: int): """ AdapterLoRa constructor. Args: model (nn.Module): The input model to which LoRA adaptation will be applied. method (str): The method to use for LoRA adaptation ("LoRa" or "LoRaTorch"). Rank (int): The rank parameter for LoRA adaptation. """ super(AdapterLoRa, self).__init__() self.methods = {"LoRa": lora, "LoRaTorch": LoraT} self.Rank = Rank self.LORA = True self.model = model self.layer = [] if method in self.methods: self.LoRa = self.methods[method] else: raise ValueError("Invalid method provided") def add_layer(self, layer: str): """ Add a layer to the list of layers to be adapted. Args: layer (str): The name of the layer to add. Returns: list: The updated list of layers. """ self.layer.append(layer) return self.layer def lora_layer(self, layer, Rank): """ Create a LoRA adapted layer. Args: layer (nn.Module): The layer to adapt. Rank (int): The rank parameter for LoRA adaptation. Returns: nn.Module: The adapted layer. """ new_layer = self.LoRa.Linear( in_features=layer.in_features, out_features=layer.out_features, bias=layer.bias is not None, r=Rank ) new_layer.weight = nn.Parameter(layer.weight.detach().clone()) if layer.bias is not None: new_layer.bias = nn.Parameter(layer.bias.detach().clone()) return new_layer def freeze_weights(self, weight_freeze=False): """ Freeze model weights. Args: weight_freeze (bool): Flag to freeze model weights. Returns: None """ for param in self.model.parameters(): param.requires_grad = weight_freeze if param.ndim == 1: param.data = param.data.to(torch.float32) self.model.gradient_checkpointing_enable() self.model.encoder, self.model.decoder = CastOutputToFloat(), CastOutputToFloat() def reconstruct_model(self): """ Reconstruct the model using LoRA-adapted layers. Returns: str: A message indicating the success of the reconstruction or an error message. """ if not isinstance(self.model, nn.Module): return "Please make sure the model is based on Torch nn.Module" if self.LORA: make_lora_replace(self.model, self.lora_layer, self.Rank, self.layer) return "Model successfully reconstructed with LoRA-adapted layers" def implement_lora(self,verbose=False): """ Implement LoRA adaptation on the model. Returns: nn.Module: The model with LoRA adaptation applied. """ total_trainable_params_before = sum(p.numel() for p in self.model.parameters() if p.requires_grad) if verbose == True: print(f"Total trainable parameters before LoRA: {total_trainable_params_before}") self.LoRa.mark_only_lora_as_trainable(self.model) total_trainable_params_after = sum(p.numel() for p in self.model.parameters() if p.requires_grad) if verbose == True: print(f"Total trainable parameters after LoRA: {total_trainable_params_after}") return self.model
AdapterLoRa
/AdapterLoRa-2.0.0.tar.gz/AdapterLoRa-2.0.0/core/Quantized.py
Quantized.py
# Let's Sample Step by Step: Adaptive-Consistency for Efficient Reasoning with LLMs <p align="center"> <a href="http://sample-step-by-step.info/">Website</a> • <a href="https://arxiv.org/abs/2305.11860">Paper</a> </p> <p align="center"> <a href="https://github.com/Pranjal2041/AdaptiveConsistency/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/Pranjal2041/AdaptiveConsistency.svg" alt="GitHub license"> </a> <a href="https://twitter.com/intent/tweet?text=Check%20out%20AdaptiveConsistency%3A%20https%3A%2F%2Fgithub.com%2Fpranjal2041%2FAdaptiveeConsistency"> <img src="https://img.shields.io/twitter/url/https/github.com/Pranjal2041/AdaptiveConsistency.svg?style=social" alt="Twitter"> </a> </p> <!-- <br> --> [Pranjal Aggarwal](https://github.com/Pranjal2041), [Aman Madaan](https://madaan.github.io/), [Yiming Yang](https://www.cs.cmu.edu/~./yiming/), [Mausam](https://www.cse.iitd.ac.in/~mausam/) <!-- <br> --> ## Abstract >A popular approach for improving the correctness of output from large language models (LLMs) is Self-Consistency - poll the LLM multiple times and output the most frequent solution. Existing Self-Consistency techniques always draw a constant number of samples per question, where a better approach will be to non-uniformly distribute the available budget based on the amount of agreement in the samples drawn so far. In response, we introduce Adaptive-Consistency, a cost-efficient, model-agnostic technique that dynamically adjusts the number of samples per question using a lightweight stopping criterion. Our experiments over 13 datasets and two LLMs demonstrate that Adaptive-Consistency reduces sample budget by up to 6.0 times with an average accuracy drop of less than 0.1%. > ![AdaptiveConsistency](docs/static/images/ac_teaser_new.png) # Adaptive Consistency: This repository contains code for: 1. Adaptive-Consistency Library for Running efficient LLM generation using [Adaptive-Consistency](http://sample-step-by-step.info) in your code. 2. Code to reproduce results of [Adaptive-Consistency](https://arxiv.org/abs/2305.11860). ## Installation ### From PyPi ```bash pip install AdaptiveConsistency ``` ### From Source First, clone the repo: ```bash git clone https://github.com/Pranjal2041/AdaptiveConsistency.git ``` Next install the package using: ```bash python setup.py install ``` ## Usage Using Adaptive Consistency in your code requires only 2-3 lines of changes in your existing framework. ### 1. Importing the library ```python from adaptive_consistency import AC, BetaStoppingCriteria ``` ### 2. Initializing the library ```python ac = AC(model, stopping_criteria=BetaStoppingCriteria(0.95), max_gens = 40) ``` ### 3. Using the library You can directly run a whole loop of evaluation using: ```python ac.eval_loop(sampling_function, *args, **kwargs) ``` For example, if using Openai api for sampling, you can use: ```python import openai ac.eval_loop(openai.Completion.create, engine="text-davinci-003", prompt="Solve the questions ahead", max_tokens=5) ``` Or you can check for consistency of answers at each step: ```python answers = [] for i in range(40): answers.append(generate_answer_from_model()) # Example openai.Completion.create if ac.should_stop(answers): break ``` ### 4. Stoppping Criterias You can use one of the following Stopping Criterias: 1. `BetaStoppingCriteria (beta)`: Uses the Beta Distribution to guide the stopping criteria. This is the default stopping criteria. 2. `DirichletStoppingCriteria (dirichlet)`: Uses the Dirichlet Distribution to guide the stopping criteria. 3. `EntropyStoppingCriteria (entropy)`: Uses the Entropy of the distribution to guide the stopping criteria. 4. `MajorityStoppingCriteria (majority)`: Uses the Majority ratio of the top element in the distribution to guide the stopping criteria. 5. `RandomStoppingCriteria (random)`: Randomly stops the sampling process with a pre-defined probability. 6. `CRPStoppingCriteria (crp)`: Uses the Chinese Restaurant Process to guide the stopping criteria. Check out the paper for more details. ## Reproducing Numbers ### 1. Downloading the data Run, ```bash bash download_data.sh ``` ### 2. Downloading Model Outputs We provide the model outputs for all the models used in the paper. You can download them using: ```bash bash download_outputs.sh ``` These model outputs will work for all experiments in the paper. ### 3. Running Generations If you decide to skip the previous step, you can run your generations on your own. You can use the following command: ```bash bash scripts/run_self_consistency.sh bash scripts/run_adaptive_consistency.sh ``` By default, `beta` function will be used for stopping criteria. You can change it by passing the `stopping_criteria` and corresponding Confidence Threshold as arguments. For example, to use `entropy` stopping criteria, with a Confidence Threshold of 0.75, you can use: ```bash bash scripts/run_adaptive_consistency.sh entropy 0.75 ``` This step will print the final accuracy on the terminal. ### 4. Running Eval on Model Outputs You can skip Step 3, and directly run eval on the model outputs. You can use the following command: ```bash python eval_outputs.py --output_file <path_to_output_file> --stop_criteria <stop_criteria> --stop_criteria_thresh <stop_criteria_thresh> ``` This will print the average generations and accuracy on the terminal. ## Citation ```bibtex @misc{aggarwal2023lets, title={Let's Sample Step by Step: Adaptive-Consistency for Efficient Reasoning with LLMs}, author={Pranjal Aggarwal and Aman Madaan and Yiming Yang and Mausam}, year={2023}, eprint={2305.11860}, archivePrefix={arXiv}, primaryClass={cs.CL} } ``` ## LICENSE Adaptive-Consistency is MIT licensed, as found in the [LICENSE](LICENSE) file.
AdaptiveConsistency
/AdaptiveConsistency-1.0.0.tar.gz/AdaptiveConsistency-1.0.0/README.md
README.md
import numpy as np from typing import List, Any import warnings from .stopping_criterias import * class AC: ''' A class for using Adaptive Consistency for your LLM generations. Args: max_gens (int): Maximum number of generations to perform for each question. stop_criteria : StoppingCriterias: The stopping criteria function to use. verbose (bool): Whether to print verbose output. Attributes: max_gens (int): Maximum number of generations to perform. verbose (bool): Whether to print verbose output. stop_criteria: The stopping criteria function to use. ''' def __init__(self, max_gens : int = 40, stop_criteria = BetaStoppingCriteria, verbose : bool = False) -> None: ''' Initializes an instance of the AC class. Args: max_gens (int): Maximum number of generations to perform. stop_criteria (StoppingCriterias): The stopping criteria function to use. verbose (bool): Whether to print verbose output. ''' self.max_gens = max_gens self.verbose = verbose self.set_stop_criteria(stop_criteria) def set_max_gens(self, max_gens : int) -> None: ''' Sets the maximum number of generations per question. Args: max_gens (int): Maximum number of generations to perform. ''' self.max_gens = max_gens def set_stop_criteria(self, stop_criteria : BetaStoppingCriteria) -> None: ''' Sets the stopping criteria function. Args: stop_criteria (StoppingCriterias): The stopping criteria function to use. ''' if isinstance(stop_criteria, str): if stop_criteria == 'beta': self.stop_criteria = BetaStoppingCriteria() elif stop_criteria == 'dirichlet': self.stop_criteria = DirichletStoppingCriteria() elif stop_criteria == 'random': self.stop_criteria = RandomStoppingCriteria() elif stop_criteria == 'majority': self.stop_criteria = MajorityStoppingCriteria() elif stop_criteria == 'entropy': self.stop_criteria = EntropyStoppingCriteria() else: raise ValueError(f"Unknown stopping criteria: {stop_criteria}") elif isinstance(stop_criteria, StoppingCriterias): # The function is already initialized, so we can use it directly self.stop_criteria = stop_criteria elif isinstance(stop_criteria, type): # The function is not initialized, so we need to initialize it self.stop_criteria = stop_criteria() def should_stop(self, answers : List[Any], return_dict : bool = False) -> bool: ''' Checks if the answers are consistent based on Adaptive Consistency Algorithm and corresponding Stopping Criteria. Args: answers (List): A list of answers to check consistency. return_dict (bool): Whether to return the full dictionary of output. Returns: Union[bool, Dict]: Whether the answers are consistent or not. If return_dict is True, returns the full dictionary of output. ''' if len(answers) > self.max_gens: # Raise a warning if self.verbose: warnings.warn(f"Warning: max_gens ({self.max_gens}) reached.") should_stop = self.stop_criteria.should_stop(answers, verbose=self.verbose) if return_dict: return should_stop else: return should_stop['stop'] def eval_loop(self, eval_function, *args, **kwargs): ''' Runs AdaptiveConsistency Algorithm by repeatedly calling the evaluation function until the stopping criteria is met. Args: eval_function: The function to evaluate. *args: Additional positional arguments to pass to the eval_function. **kwargs: Additional keyword arguments to pass to the eval_function. Returns: List: A list of answers generated from evaluation function using AdaptiveConsistency. ''' answers = [] for _ in range(self.max_gens): answer = eval_function(*args, **kwargs) answers.append(answer) if self.is_consistent(answers): return answers stop_criteria_dict = { 'beta' : BetaStoppingCriteria, 'dirichlet' : DirichletStoppingCriteria, 'random' : RandomStoppingCriteria, 'majority' : MajorityStoppingCriteria, 'entropy' : EntropyStoppingCriteria, 'always_false' : AlwaysFalseStoppingCriteria, }
AdaptiveConsistency
/AdaptiveConsistency-1.0.0.tar.gz/AdaptiveConsistency-1.0.0/adaptive_consistency/main.py
main.py
import numpy as np from typing import List, Dict from collections import Counter from scipy import integrate, stats class StoppingCriterias: def __init__(self, *args, **kwargs): ... def should_stop(self, *args, **kwargs) -> Dict: ... class BetaStoppingCriteria(StoppingCriterias): def __init__(self, conf_thresh : float = 0.95) -> None: super().__init__() self.conf_thresh = conf_thresh def should_stop(self, answers : List, conf_thresh : int = None, verbose : bool = False) -> Dict: if conf_thresh is None: conf_thresh = self.conf_thresh most_common = Counter(answers).most_common(2) if len(most_common) == 1: a, b = most_common[0][1], 0 else: a, b= most_common[0][1], most_common[1][1] a = float(a) b = float(b) return_dict = { 'most_common' : most_common[0][0], 'prob' : -1, 'stop' : False, } try: prob = integrate.quad(lambda x : x**(a) * (1-x)**(b), 0.5, 1)[0] / integrate.quad(lambda x : x**(a) * (1-x)**(b), 0, 1)[0] except Exception as e: # print error message print(f"Error during numerical integration: {e}") return_dict['stop'] = False return_dict['prob'] = -1 return return_dict return_dict['prob'] = prob return_dict['stop'] = prob >= conf_thresh return return_dict class RandomStoppingCriteria(StoppingCriterias): def __init__(self, conf_thresh : float = 0.1) -> None: super().__init__() self.conf_thresh = conf_thresh def should_stop(self, answers : List, conf_thresh : int = None, verbose : bool = False) -> Dict: if conf_thresh is None: conf_thresh = self.conf_thresh return_dict = { 'most_common' : Counter(answers).most_common(1)[0][0], 'prob' : 0, 'stop' : np.random.uniform(0,1) < conf_thresh, } return return_dict class EntropyStoppingCriteria(StoppingCriterias): def __init__(self, conf_thresh : float = 0.75) -> None: super().__init__() self.conf_thresh = conf_thresh def should_stop(self, answers : List, conf_thresh : int = None, verbose : bool = False) -> Dict: if conf_thresh is None: conf_thresh = self.conf_thresh counter = dict(Counter(answers)) lis = list(counter.values()) if len(lis) < 2: lis.append(1) entropy = stats.entropy(lis, base = 2) return_dict = { 'most_common' : Counter(answers).most_common(1)[0][0], 'prob' : -1, 'stop' : False, } if len(answers) != 1: return_dict['stop'] = entropy/np.log2(len(lis)) <= conf_thresh return_dict['prob'] = entropy/np.log2(len(lis)) return return_dict class MajorityStoppingCriteria(StoppingCriterias): def __init__(self, conf_thresh : float = 0.8) -> None: super().__init__() self.conf_thresh = conf_thresh def should_stop(self, answers : List, conf_thresh : int = None, verbose : bool = False) -> Dict: if conf_thresh is None: conf_thresh = self.conf_thresh return_dict = { 'most_common' : Counter(answers).most_common(1)[0][0], 'prob' : -1, 'stop' : False, } if len(answers) != 1: return_dict['stop'] = Counter(answers).most_common(1)[0][1]/len(answers) >= conf_thresh return_dict['prob'] = Counter(answers).most_common(1)[0][1]/len(answers) return return_dict class DirichletStoppingCriteria(StoppingCriterias): def __init__(self, conf_thresh : float = 0.95, top_k_elements : int = 5, use_markov : bool = True) -> None: super().__init__() self.conf_thresh = conf_thresh self.top_k_elements = top_k_elements self.use_markov = use_markov def integrate_mcs(self, f, limits, N = 10000): ranges = [] samples = [] for _, funcs in enumerate(limits[::-1]): if len(samples) == 0: ranges.append(funcs()) else: ranges.append(funcs(*samples[::-1])) # TODO: Note, we assume, that the first value is actually a scalar. try: ranges[-1][0] = ranges[-1][0][0] except: ... samples.append(np.random.uniform(*ranges[-1], size=N)) integrand_values = f(*samples) * np.prod([r[1] - r[0] for r in ranges], axis=0) integral_approximation = (1/N) * np.sum(integrand_values) return integral_approximation def should_stop(self, answers : List, conf_thresh : int = None, verbose : bool = False) -> Dict: if conf_thresh is None: conf_thresh = self.conf_thresh counts = dict(Counter(answers)) if len(counts) < 3: return BetaStoppingCriteria(conf_thresh).should_stop(answers, conf_thresh, verbose) most_common = Counter(answers).most_common(2)[0][0] counts = {k: v for k, v in sorted(counts.items(), key=lambda item: item[1], reverse=False)[-self.top_k_elements:]} len_counts = len(counts) functions = [] functions2 =[] for i, _ in enumerate(counts.items()): if i == len_counts - 2: break if self.use_markov: functions.append(lambda *args: [np.array([0 for _ in range(args[0].shape[0])]), np.max([np.array([0 for _ in range(args[0].shape[0])]), np.min([np.array([0.5 for _ in range(args[0].shape[0])]), 1 - np.sum(args, axis = 0) - np.max(args, axis = 0), (1-np.sum(args, axis = 0))/2], axis = 0)], axis = 0)]) else: functions.append(lambda *args: [0, max(0, min(0.5, 1 - sum(args) - max(args), (1-sum(args))/2))]) functions2.append(lambda *args: [0, max(0, min(0.5, 1 - sum(args) - max(args), (1-sum(args))/2))]) # Outermost limit functions.append(lambda *args: [0, 0.5]) functions2.append(lambda *args: [0, 0.5]) denom_functions = [] for i, _ in enumerate(counts.items()): if i == len_counts - 2: break denom_functions.append(lambda *args: [0, 1-np.sum(args, axis = 0)]) # Outermost limit denom_functions.append(lambda *args: [0, 1]) exec( f'''def integrand({",".join(["a" + str(i) for i in range(len(functions))])}): counts = {counts} ks = list(counts.keys()) args = [{",".join(["a" + str(i) for i in range(len(functions))])}] outp = np.prod([args[i] ** counts[k] for i, k in enumerate(list(counts.keys())[:-1])], axis = 0) * (1 - np.sum(args, axis = 0)) ** counts[list(counts.keys())[-1]] return outp ''' ) return_dict = { 'most_common' : most_common, 'prob' : -1, 'stop' : False, } try: # print('Computing Integration') opts = {} opts = {'limit': 3, 'epsrel' : 1e-1,'epsabs': 1e-1} if self.use_markov: N = min(500000, 5000 * 2**len(functions)) N = 50000 * 1 if len(functions) <= 4 else 50000 * (2** ((len(functions) - 3)//2)) prob = self.integrate_mcs(locals()['integrand'], functions, N = N) / self.integrate_mcs(locals()['integrand'], denom_functions, N = N) else: prob = integrate.nquad(locals()['integrand'], functions, opts = opts)[0] / integrate.nquad(locals()['integrand'], denom_functions, opts = opts)[0] return_dict['prob'] = prob return_dict['stop'] = prob >= conf_thresh except Exception as e: # print error message print(f"Error during numerical integration: {e}") return return_dict class AlwaysFalseStoppingCriteria(StoppingCriterias): def __init__(self, *args, **kwargs) -> None: super().__init__() def should_stop(self, answers : List, *args, **kwargs) -> Dict: return { 'most_common' : Counter(answers).most_common(1)[0][0], 'prob' : -1, 'stop' : False, }
AdaptiveConsistency
/AdaptiveConsistency-1.0.0.tar.gz/AdaptiveConsistency-1.0.0/adaptive_consistency/stopping_criterias.py
stopping_criterias.py
from __future__ import division import numpy as np import pandas as pd import seaborn as sns from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.pyplot as plt def build_ddm_axis(a, tr, z, tb=1200): sns.set(style='white') f, ax = plt.subplots(1, figsize=(8.5, 7), sharex=True) w = tb # tr = tr - 50 xmin=tr - 100 plt.setp(ax, xlim=(xmin - 51, w + 1), ylim=(0 - (.01 * a), a + (.01 * a))) ax.hlines(y=a, xmin=xmin, xmax=w, color='#3572C6', linewidth=4) ax.hlines(y=0, xmin=xmin, xmax=w, color='#e5344a', linewidth=4) ax.hlines(y=z, xmin=xmin, xmax=w, color='k', alpha=.4, linestyles='--', linewidth=3) ax.vlines(x=xmin-50, ymin=-.1, ymax=a+.1, color='k', alpha=.15, linewidth=5) ax.hlines(y=z, xmin=xmin, xmax=tr, color='k', linewidth=4) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_yticks([]) sns.despine(top=True, right=True, bottom=True, left=True, ax=ax) divider = make_axes_locatable(ax) axx1 = divider.append_axes("top", size=1.2, pad=0.0, sharex=ax) axx2 = divider.append_axes("bottom", size=1.2, pad=0.0, sharex=ax) plt.setp(axx1, xlim=(xmin - 51, w + 1), ylim=(0 - (.01 * a), a + (.01 * a))) plt.setp(axx2, xlim=(xmin - 51, w + 1), ylim=(0 - (.01 * a), a + (.01 * a))) axx1.hist([0], normed=False, bins=np.linspace(200, tb, num=9), alpha=1., color='White') axx2.hist([0], normed=False, bins=np.linspace(200, tb, num=9), alpha=1., color='White') for axx in [axx1, axx2]: for spine in ['top', 'left', 'bottom', 'right']: axx.spines[spine].set_visible(False) axx.set_xticklabels([]) axx.set_yticklabels([]) return f, [ax, axx1, axx2] def plot_ddm_traces(df, traces, parameters, colors=['#3572C6', '#e5344a'], plot_v=False, deadline=1.2): a, tr, v, z, si, dx, dt = parameters deadline=traces.shape[1] zStart = z * a trSteps = int(tr/dt) rt1 = df[df.choice==1].rt.values / dt rt0 = df[df.choice==0].rt.values / dt f, axes = build_ddm_axis(a, trSteps, zStart, tb=deadline) ax, axx1, axx2 = axes clr1, clr0 = colors sns.kdeplot(rt1, alpha=.5, linewidth=0, color=clr1, ax=axx1, shade=True, clip=(rt1.min(), rt1.max()), bw=35) sns.kdeplot(rt0, alpha=.5, linewidth=0, color=clr0, ax=axx2, shade=True, clip=(rt0.min(), rt0.max()), bw=35) axx1.set_ylim(0, .004) axx2.set_ylim(.02, 0.0002) delay = np.ones(trSteps) * zStart for i in range(int(df.shape[0]/2)): trace = traces[i] c = clr1 nsteps = np.argmax(trace[trace<=a]) + 2 if df.iloc[i]['choice']==0: c = clr0 nsteps = np.argmin(trace[trace>=0]) + 2 y = np.hstack([delay, trace[:nsteps]]) x = np.arange(delay.size, y.size) ax.plot(x, trace[:nsteps], color=c, alpha=.19) if plot_v: accum_x = np.arange(rt1.mean())*.001 driftRate = zStart + (accum_x * v) x = np.linspace(trSteps, rt1.mean(), accum_x.size) ax.plot(x, driftRate, color='k', linewidth=3) return ax def compare_drift_effects(dataframes, param_list, colors=["#3498db", "#f19b2c", '#009e07', '#3572C6', '#e5344a', "#9B59B6"], deadline=1.2): a, tr, v, z, si, dx, dt = param_list[0] zStart = z * a trSteps = int(tr/dt) deadline = pd.concat(dataframes).rt.max() / dt f, axes = build_ddm_axis(a, trSteps, zStart, tb=deadline) ax, axx1, axx2 = axes ax.hlines(y=a, xmin=trSteps-100, xmax=deadline, color='k', linewidth=4) ax.hlines(y=0, xmin=trSteps-100, xmax=deadline, color='k', linewidth=4) for i, df in enumerate(dataframes): c = colors[i] a, tr, v, z, si, dx, dt = param_list[i] zStart = z * a trSteps = int(tr/dt) rt1 = df[df.choice==1].rt.values / dt - 50 rt0 = df[df.choice==0].rt.values / dt - 50 sns.kdeplot(rt1, alpha=.35, linewidth=0, color=c, ax=axx1, shade=True, clip=(rt1.min(), rt1.max()), bw=35) sns.kdeplot(rt0, alpha=.35, linewidth=0, color=c, ax=axx2, shade=True, clip=(rt0.min(), rt0.max()), bw=35) accum_x = np.arange(rt1.mean())*.001 driftRate = zStart + (accum_x * v) x = np.linspace(trSteps, rt1.mean(), accum_x.size) ax.plot(x, driftRate, color=c, linewidth=3.5) axx1.set_ylim(0, .005) axx2.set_ylim(.02, 0.0001) return ax
AdaptiveDecisionMaking-2018
/AdaptiveDecisionMaking_2018-0.0.1-py3-none-any.whl/ADMCode/visualize.py
visualize.py
============ AdaptivePELE ============ |MIT license| |GitHub release| |PyPI release| |Conda release| |DOI| AdaptivePELE is a Python module to perform enhancing sampling of molecular simulation built around the Protein Energy Landscape Exploration method (`PELE <https://pele.bsc.es/pele.wt>`_) developed in the Electronic and Atomic Protein Modelling grop (`EAPM <https://www.bsc.es/discover-bsc/organisation/scientific-structure/electronic-and-atomic-protein-modeling-eapm>`_) at the Barcelona Supercomputing Center (`BSC <https://www.bsc.es>`_). Usage ----- AdaptivePELE is called with a control file as input parameter. The control file is a json document that contains 4 sections: general parameters, simulation parameters, clustering parameters and spawning parameters. The first block refers to general parameters of the adaptive run, while the other three blocks configure the three steps of an adaptive sampling run, first run a propagation algorithm (simulation), then cluster the trajectories obtained (clustering) and finally select the best point to start the next iteration (spawning). An example of usage:: python -m AdaptivePELE.adaptiveSampling controlFile.conf Installation ------------ There are two methods to install AdaptivePELE, from repositories, either PyPI or Conda (recommended), or directly from source. To install from PyPI simply run:: pip install AdaptivePELE To install from Conda simply run:: conda install -c nostrumbiodiscovery -c conda-forge adaptive_pele To install from source, you need to install and compile cython files in the base folder with:: git clone https://github.com/AdaptivePELE/AdaptivePELE.git cd AdaptivePELE python setup.py build_ext --inplace Also, if AdaptivePELE was not installed in a typical library directory, a common option is to add it to your local PYTHONPATH:: export PYTHONPATH="/location/of/AdaptivePELE:$PYTHONPATH" Documentation ------------- The documentation for AdaptivePELE can be found `here <https://adaptivepele.github.io/AdaptivePELE/>`_ Contributors ------------ `Daniel Lecina <https://github.com/lecina>`_, `Joan Francesc Gilabert <https://github.com/cescgina>`_, `Oriol Gracia <https://github.com/OriolGraCar>`_, `Daniel Soler <https://github.com/danielSoler93>`_ Mantainer --------- Joan Francesc Gilabert ([email protected]) Citation -------- AdaptivePELE is research software. If you make use of AdaptivePELE in scientific publications, please cite it. The BibTeX reference is:: @article{Lecina2017, author = {Lecina, Daniel and Gilabert, Joan Francesc and Guallar, Victor}, doi = {10.1038/s41598-017-08445-5}, issn = {2045-2322}, journal = {Scientific Reports}, number = {1}, pages = {8466}, pmid = {28814780}, title = {{Adaptive simulations, towards interactive protein-ligand modeling}}, url = {http://www.nature.com/articles/s41598-017-08445-5}, volume = {7}, year = {2017} } .. |MIT license| image:: https://img.shields.io/badge/License-MIT-blue.svg :target: https://lbesson.mit-license.org/ .. |GitHub release| image:: https://img.shields.io/github/release/AdaptivePELE/AdaptivePELE.svg :target: https://github.com/AdaptivePELE/AdaptivePELE/releases/ .. |PyPI release| image:: https://img.shields.io/pypi/v/AdaptivePELE.svg :target: https://pypi.org/project/AdaptivePELE/ .. |DOI| image:: https://zenodo.org/badge/DOI/10.1038/s41598-017-08445-5.svg :target: https://doi.org/10.1038/s41598-017-08445-5 .. |Conda release| image:: https://anaconda.org/nostrumbiodiscovery/adaptive_pele/badges/version.svg :target: https://anaconda.org/NostrumBioDiscovery/adaptive_pele
AdaptivePELE
/AdaptivePELE-1.7.1.tar.gz/AdaptivePELE-1.7.1/README.rst
README.rst
# `AdaptoLogit` package ## Introduction `AdaptoLogit` is a python package that proposes the implementation of adaptive lasso to solve logistic regression models. ## Dependencies `AdaptoLogit` requires: - Numpy >= 1.2 - SciPy >= 1.7.0 - Scikit-learn >= 1.0 ## User installation If you already have a working installation of numpy, scipy and scikit-learn, the easiest way to install **AdaptoLogit** is using pip: ```sh pip install AdaptoLogit ``` ## Usage Example In the following example, the package is used to apply adaptive lasso logistic regression on simulated binary data. Cross validation is carried out to get the optimal subset of parameters for the data. ```py from sklearn.model_selection import GridSearchCV import numpy as np import AdaptoLogit as al from sklearn.datasets import make_classification # Generate data X, y = make_classification(random_state=8) # 100 samples, 20 features, 2 informative # Estimate weights weight = al.AdaptiveWeights(power_weight=(0.5,1,1.5)) weight.fit(X, y) # Build model model = al.AdaptiveLogistic() # Cross validation for best subset of parameters param_grid = {'C':[1e-3, 1e-2, 1e-1, 1, 10, 100, 1000], 'weight_array': weight.lasso_weights_, 'solver': ['saga','liblinear'], 'max_iter': [1000, 10000]} grid_search = GridSearchCV(model, param_grid, cv=3, scoring='accuracy', n_jobs=8) grid_search.fit(X, y) final_model = grid_search.best_estimator_ # Model coefficients print("Model coefficients ", final_model.coef_) ```
AdaptoLogit
/AdaptoLogit-0.0.1.tar.gz/AdaptoLogit-0.0.1/README.md
README.md
import asyncio import logging import operator import secrets import time import urllib import async_timeout ADAX_DEVICE_TYPE_HEATER_BLE = 5 BLE_COMMAND_STATUS_OK = 0 BLE_COMMAND_STATUS_INVALID_WIFI = 1 MAX_BYTES_IN_COMMAND_CHUNK = 17 UUID_ADAX_BLE_SERVICE = "3885cc10-7c18-4ad4-a48d-bf11abf7cb92" UUID_ADAX_BLE_SERVICE_CHARACTERISTIC_COMMAND = "0000cc11-0000-1000-8000-00805f9b34fb" _LOGGER = logging.getLogger(__name__) try: import bleak except FileNotFoundError: _LOGGER.error("Import bleak failed", exc_info=True) bleak = None class Adax: """Adax data handler.""" def __init__(self, device_ip, access_token, websession, timeout=15): """Init adax data handler.""" self.device_ip = device_ip self._access_token = access_token self.websession = websession self._url = "https://" + device_ip + "/api" self._headers = {"Authorization": "Basic " + self._access_token} self._timeout = timeout async def set_target_temperature(self, target_temperature): """Set target temperature.""" payload = { "command": "set_target", "time": int(time.time()), "value": int(target_temperature * 100), } async with async_timeout.timeout(self._timeout): async with self.websession.get( self._url, params=payload, headers=self._headers ) as response: _LOGGER.debug("Heater response %s", response.status) if response.status != 200: _LOGGER.error( "Failed to set target temperature %s %s", response.status, response.reason, ) return response.status async def get_status(self): """Get heater status.""" payload = {"command": "stat", "time": int(time.time())} try: async with async_timeout.timeout(self._timeout): async with self.websession.get( self._url, params=payload, headers=self._headers ) as response: if response.status != 200: _LOGGER.error( "Failed to get status %s %s", response.status, response.reason, ) return None, None response_json = await response.json() except asyncio.TimeoutError: return None, None _LOGGER.debug("Heater response %s %s", response.status, response_json) data = {} data["target_temperature"] = response_json["targTemp"] / 100 data["current_temperature"] = response_json["currTemp"] / 100 return data class AdaxConfig: """Adax config handler.""" def __init__(self, wifi_ssid, wifi_psk): self.wifi_ssid = wifi_ssid self.wifi_psk = wifi_psk self._access_token = secrets.token_hex(10) self._device_ip = None self._mac_id = None @property def device_ip(self): """Return device ip.""" return self._device_ip @property def mac_id(self): """Return mac id.""" return self._mac_id @property def access_token(self): """Return access token.""" return self._access_token def notification_handler(self, _, data): if not data: _LOGGER.warning("No data") return byte_list = list(data) status = byte_list[0] _LOGGER.debug("notification_handler %s", byte_list) if status == BLE_COMMAND_STATUS_INVALID_WIFI: _LOGGER.debug("Invalid WiFi credentials %s") raise InvalidWifiCred if status == BLE_COMMAND_STATUS_OK and byte_list and len(byte_list) >= 5: self._device_ip = "%d.%d.%d.%d" % ( byte_list[1], byte_list[2], byte_list[3], byte_list[4], ) _LOGGER.debug("Heater Registered, use with IP %s", self._device_ip) _LOGGER.debug("Status %s", byte_list) async def configure_device(self): if bleak is None: _LOGGER.error("Bleak library not loaded") return _LOGGER.debug( "Press and hold OK button on the heater until the blue led starts blinking" ) device, self._mac_id = await scan_for_available_ble_device() _LOGGER.debug("device: %s", device) if not device: return False async with bleak.BleakClient(device) as client: _LOGGER.debug("start_notify") await client.start_notify( UUID_ADAX_BLE_SERVICE_CHARACTERISTIC_COMMAND, self.notification_handler, ) ssid_encoded = urllib.parse.quote(self.wifi_ssid) psk_encoded = urllib.parse.quote(self.wifi_psk) access_token_encoded = urllib.parse.quote(self._access_token) byte_list = list( bytearray( "command=join&ssid=" + ssid_encoded + "&psk=" + psk_encoded + "&token=" + access_token_encoded, "ascii", ) ) _LOGGER.debug("write_command") await write_command(byte_list, client) k = 0 while k < 20 and client.is_connected and self._device_ip is None: await asyncio.sleep(1) k += 1 if self._device_ip: _LOGGER.debug( "Heater ip is %s and the token is %s", self._device_ip, self._access_token, ) return True return False async def scan_for_available_ble_device(retry=1): if bleak is None: _LOGGER.error("Bleak library not loaded") return discovered = await bleak.BleakScanner.discover(timeout=60) _LOGGER.debug(discovered) if not discovered: if retry > 0: return await scan_for_available_ble_device(retry - 1) raise HeaterNotFound for discovered_item in discovered: metadata = discovered_item.metadata uuids = metadata.get("uuids") if uuids is None or UUID_ADAX_BLE_SERVICE not in uuids: continue _LOGGER.info("Found Adax heater %s", discovered_item) manufacturer_data = metadata.get("manufacturer_data") _LOGGER.debug("manufacturer_data %s", manufacturer_data) if not manufacturer_data: continue first_bytes = next(iter(manufacturer_data)) _LOGGER.debug("first bytes %s", first_bytes) if first_bytes is None: continue other_bytes = manufacturer_data[first_bytes] _LOGGER.debug(other_bytes) manufacturer_data_list = [ first_bytes % 256, operator.floordiv(first_bytes, 256), ] + list(other_bytes) _LOGGER.debug(manufacturer_data_list) if not device_available(manufacturer_data_list): _LOGGER.warning("Heater not available.") raise HeaterNotAvailable return discovered_item.address, find_mac_id(manufacturer_data_list) if retry > 0: return await scan_for_available_ble_device(retry - 1) raise HeaterNotFound def device_available(manufacturer_data): _LOGGER.debug("device_available") if not manufacturer_data and len(manufacturer_data) < 10: return False type_id = manufacturer_data[0] status_byte = manufacturer_data[1] mac_id = find_mac_id(manufacturer_data) registered = status_byte & (0x1 << 0) managed = status_byte & (0x1 << 1) _LOGGER.debug("device_available %s %s %s %s", mac_id, type_id, registered, managed) return ( mac_id and type_id == ADAX_DEVICE_TYPE_HEATER_BLE and not registered and not managed ) def find_mac_id(manufacturer_data): mac_id = 0 for byte in manufacturer_data[2:10]: mac_id = mac_id * 256 + byte return mac_id async def write_command(command_byte_list, client): byte_count = len(command_byte_list) chunk_count = operator.floordiv(byte_count, MAX_BYTES_IN_COMMAND_CHUNK) if chunk_count * MAX_BYTES_IN_COMMAND_CHUNK < byte_count: chunk_count += 1 sent_byte_count = 0 chunk_nr = 0 while chunk_nr < chunk_count: is_last = chunk_nr == (chunk_count - 1) chunk_data_length = ( byte_count - sent_byte_count if is_last else MAX_BYTES_IN_COMMAND_CHUNK ) chunk = [chunk_nr, 1 if is_last else 0] + command_byte_list[ sent_byte_count : (sent_byte_count + chunk_data_length) ] await client.write_gatt_char( UUID_ADAX_BLE_SERVICE_CHARACTERISTIC_COMMAND, bytearray(chunk) ) sent_byte_count += chunk_data_length chunk_nr += 1 class InvalidWifiCred(Exception): """Invalid wifi credentials exception.""" class HeaterNotAvailable(Exception): """Heater not available exception.""" class HeaterNotFound(Exception): """Heater not found exception."""
Adax-local
/Adax-local-0.1.5.tar.gz/Adax-local-0.1.5/adax_local/__init__.py
__init__.py
======================================== Separating Concerns Using Object Add-Ons ======================================== (NEW in version 0.6: the``Registry`` base class, and the ``ClassAddOn.for_frame()`` classmethod.) In any sufficiently-sized application or framework, it's common to end up lumping a lot of different concerns into the same class. For example, you may have business logic, persistence code, and UI all jammed into a single class. Attribute and method names for all sorts of different operations get shoved into a single namespace -- even when using mixin classes. Separating concerns into different objects, however, makes it easier to write reusable and separately-testable components. The AddOns package (``peak.util.addons``) lets you manage concerns using ``AddOn`` classes. ``AddOn`` classes are like dynamic mixins, but with their own private attribute and method namespaces. A concern implemented using add-ons can be added at runtime to any object that either has a writable ``__dict__`` attribute, or is weak-referenceable. ``AddOn`` classes are also like adapters, but rather than creating a new instance each time you ask for one, an existing instance is returned if possible. In this way, add-ons can keep track of ongoing state. For example, a ``Persistence`` add-on might keep track of whether its subject has been saved to disk yet:: >>> from peak.util.addons import AddOn >>> class Persistence(AddOn): ... saved = True ... def changed(self): ... self.saved = False ... def save_if_needed(self): ... if not self.saved: ... print "saving" ... self.saved = True >>> class Thing: pass >>> aThing = Thing() >>> Persistence(aThing).saved True >>> Persistence(aThing).changed() >>> Persistence(aThing).saved False >>> Persistence(aThing).save_if_needed() saving >>> Persistence(aThing).save_if_needed() # no action taken This makes it easy for us to, for example, write a loop that saves a bunch of objects, because we don't need to concern ourselves with initializing the state of the persistence add-on. A class doesn't need to inherit from a special base in order to be able to have this state tracked, and it doesn't need to know *how* to initialize it, either. Of course, in the case of persistence, a class does need to know *when* to call the persistence methods, to indicate changedness and to request saving. However, a library providing such an add-on can also provide decorators and other tools to make this easier, while still remaining largely independent of the objects involved. Indeed, the AddOns library was actually created to make it easier to implement functionality using function or method decorators. For example, one can create a ``@synchronized`` decorator that safely locks an object -- see the example below under `Threading Concerns`_. In summary, the AddOns library provides you with a basic form of AOP, that lets you attach (or "introduce", in AspectJ terminology) additional attributes and methods to an object, using a private namespace. (If you also want to do AspectJ-style "advice", the PEAK-Rules package can be used to do "before", "after", and "around" advice in combination with add-ons.) .. contents:: **Table of Contents** Basic API --------- If you need to, you can query for the existence of an add-on:: >>> Persistence.exists_for(aThing) True And by default, it won't exist:: >>> anotherThing = Thing() >>> Persistence.exists_for(anotherThing) False Until you refer to it directly, e.g.:: >>> Persistence(aThing) is Persistence(anotherThing) False At which point it will of course exist:: >>> Persistence.exists_for(anotherThing) True And maintain its state, linked to its subject:: >>> Persistence(anotherThing) is Persistence(anotherThing) True Until/unless you delete it (or its subject is garbage collected):: >>> Persistence.delete_from(anotherThing) >>> Persistence.exists_for(anotherThing) False AddOn Keys and Instances ------------------------ Add-ons are stored either in their subject's ``__dict__``, or if it does not have one (or is a type object with a read-only ``__dict__``), they are stored in a special dictionary linked to the subject via a weak reference. By default, the dictionary key is the add-on class, so there is exactly one add-on instance per subject:: >>> aThing.__dict__ {<class 'Persistence'>: <Persistence object at...>} But in some cases, you may wish to have more than one instance of a given add-on class for a subject. (For example, PEAK-Rules uses add-ons to represent indexes on different expressions contained within rules.) For this purpose, you can redefine your AddOn's ``__init__`` method to accept additional arguments besides its subject. The additional arguments become part of the key that instances are stored under, such that more than one add-on instance can exist for a given object:: >>> class Index(AddOn, dict): ... def __init__(self, subject, expression): ... self.expression = expression >>> something = Thing() >>> Index(something, "x>y")["a"] = "b" >>> dir(something) ['__doc__', '__module__', (<class 'Index'>, 'x>y')] >>> "a" in Index(something, "z<22") False >>> Index(something, "x>y") {'a': 'b'} >>> Index(something, "x>y").expression 'x>y' >>> dir(something) ['__doc__', '__module__', (<class 'Index'>, 'x>y'), (<class 'Index'>, 'z<22')] >>> Index.exists_for(something, 'x>y') True >>> Index.exists_for(anotherThing, 'q==42') False By default, an add-on class' key is either the class by itself, or a tuple containing the class, followed by any arguments that appeared in the constructor call after the add-on's subject. However, you can redefine the ``addon_key()`` classmethod in your subclass, and change it to do something different. For example, you could make different add-on classes generate overlapping keys, or you could use attributes of the arguments to generate the key. You could even generate a string key, to cause the add-on to be attached as an attribute!:: >>> class Leech(AddOn): ... def addon_key(cls): ... return "__leech__" ... addon_key = classmethod(addon_key) >>> something = Thing() >>> Leech(something) is something.__leech__ True The ``addon_key`` method only receives the arguments that appear *after* the subject in the constructor call. So, in the case above, it receives no arguments. Had we called it with additional arguments, we'd have gotten an error:: >>> Leech(something, 42) Traceback (most recent call last): ... TypeError: addon_key() takes exactly 1 argument (2 given) Naturally, your ``addon_key()`` and ``__init__()`` (and/or ``__new__()``) methods should also agree on how many arguments there can be, and what they mean! In general, you should include your add-on class (or some add-on class) as part of your key, so as to make collisions with other people's add-on classes impossible. Keys should also be designed for thread-safety, where applicable. (See the section below on `Threading Concerns`_ for more details.) Role Storage and Garbage Collection ----------------------------------- By the way, the approach above of using an string as an add-on key won't always make the add-on into an attribute of the subject! If an object doesn't have a ``__dict__``, or that ``__dict__`` isn't writable (as in the case of type objects), then the add-on is stored in a weakly-keyed dictionary, maintained elsewhere:: >>> class NoDict(object): ... __slots__ = '__weakref__' >>> dictless = NoDict() >>> Leech(dictless) <Leech object at ...> >>> dictless.__leech__ Traceback (most recent call last): ... AttributeError: 'NoDict' object has no attribute '__leech__' Of course, if an object doesn't have a dictionary *and* isn't weak-referenceable, there's simply no way to store an add-on for it:: >>> ob = object() >>> Leech(ob) Traceback (most recent call last): ... TypeError: cannot create weak reference to 'object' object However, there is an ``addons_for()`` function in the ``peak.util.addons`` module that you can extend using PEAK-Rules advice. Once you add a method to support a type that otherwise can't be used with add-ons, you should be able to use any and all kinds of add-on objects with that type. (Assuming, of course, that you can implement a suitable storage mechanism!) Finally, a few words regarding garbage collection. If you don't want to create a reference cycle, don't store a reference to your subject in your add-on. Even though the ``__init__`` and ``__new__`` messages get the subject passed in, you are not under any obligation to *store* the subject, and often won't need to. Usually, the code that is accessing the add-on knows what subject is in use, and can pass the subject to the add-on's methods if needed. It's rare that the add-on really needs to keep a reference to the subject past the ``__new__()`` and ``__init__()`` calls. Add-on instances will usually be garbage collected at the same time as their subject, unless there is some other reference to them. If they keep a reference to their subject, their garbage collection may be delayed until Python's cycle collector is run. But if they don't keep a reference, they will usually be deleted as soon as the subject is:: >>> def deleting(r): ... print "deleting", r >>> from weakref import ref >>> r = ref(Leech(something), deleting) >>> del something deleting <weakref at ...; dead> (Add-ons that are stored outside the instance dictionary of their subject, however, may take slightly longer, as Python processes weak reference callbacks.) It is also *not* recommended that you have ``__del__`` methods on your add-on objects, especially if you keep a reference to your subject. In such a case, garbage collection may become impossible, and both the add-on and its subject would "leak" (i.e., take up memory forever without being recoverable). Class Add-Ons ------------- Sometimes, it's useful to attach add-ons to classes instead of instances. You could use normal ``AddOn`` classes, of course, as they work just fine with both classic classes and new-style types -- even built-ins:: >>> Persistence.exists_for(int) False >>> Persistence(int) is Persistence(int) True >>> Persistence.exists_for(int) True >>> class X: pass >>> Persistence.exists_for(X) False >>> Persistence(X) is Persistence(X) True >>> Persistence.exists_for(X) True But, sometimes you have add-ons that are specifically intended for adding metadata to classes -- perhaps by way of class or method decorators. In such a case, you need a way to access the add-on *before* its subject even exists! The ``ClassAddOn`` base class provides a mechanism for this. It adds an extra classmethod, ``for_enclosing_class()``, that you can use to access the add-on for the class that is currently being defined in the scope that invoked the caller. For example, suppose we want to have a method decorator that adds the method to some class-level registry:: >>> from peak.util.addons import ClassAddOn >>> class SpecialMethodRegistry(ClassAddOn): ... def __init__(self, subject): ... self.special_methods = {} ... super(SpecialMethodRegistry, self).__init__(subject) >>> def specialmethod(func): ... smr = SpecialMethodRegistry.for_enclosing_class() ... smr.special_methods[func.__name__] = func ... return func >>> class Demo: ... def dummy(self, foo): ... pass ... dummy = specialmethod(dummy) >>> SpecialMethodRegistry(Demo).special_methods {'dummy': <function dummy at ...>} >>> class Demo2(object): ... def dummy(self, foo): ... pass ... dummy = specialmethod(dummy) >>> SpecialMethodRegistry(Demo2).special_methods {'dummy': <function dummy at ...>} You can of course use the usual add-on API for class add-ons:: >>> SpecialMethodRegistry.exists_for(int) False >>> SpecialMethodRegistry(int).special_methods['x'] = 123 >>> SpecialMethodRegistry.exists_for(int) True Except that you cannot explicitly delete them, they must be garbage collected naturally:: >>> SpecialMethodRegistry.delete_from(Demo) Traceback (most recent call last): ... TypeError: ClassAddOns cannot be deleted Delayed Initialization ~~~~~~~~~~~~~~~~~~~~~~ When a class add-on is initialized, the class may not exist yet. In this case, ``None`` is passed as the first argument to the ``__new__`` and ``__init__`` methods. You must be able to handle this case correctly, if your add-on will be accessed inside a class definition with ``for_enclosing_class()``. You can, however, define a ``created_for()`` instance method that will be called as soon as the actual class is available. It is also called by the default ``__init__`` method, if the add-on is initially created for a class that already exists. Either way, the ``created_for()`` method should be called at most once for any given add-on instance. For example:: >>> class SpecialMethodRegistry(ClassAddOn): ... def __init__(self, subject): ... print "init called for", subject ... self.special_methods = {} ... super(SpecialMethodRegistry, self).__init__(subject) ... ... def created_for(self, cls): ... print "created for", cls.__name__ >>> class Demo: ... def dummy(self, foo): ... pass ... dummy = specialmethod(dummy) init called for None created for Demo Above, ``__init__`` was called with ``None`` since the type didn't exist yet. However, accessing the add-on for an existing type (that doesn't have the add- on yet) will call ``__init__`` with the type, and the default implementation of ``ClassAddOn.__init__`` will also call ``created_for()`` for us, when it sees the subject is not ``None``:: >>> SpecialMethodRegistry(float) init called for <type 'float'> created for float <SpecialMethodRegistry object at ...> >>> SpecialMethodRegistry(float) # created_for doesn't get called again <SpecialMethodRegistry object at ...> One of the most useful features of having this ``created_for()`` method is that it allows you to set up class-level metadata that involves inherited settings from base classes. In ``created_for()``, you have access to the class' ``__bases__`` and or ``__mro__``, and you can just ask for an instance of the same add-on for those base classes, then incorporate their data into your own instance as appropriate. You are guaranteed that any such add-ons you access will already be initialized, including having their ``created_for()`` method called. Since this works recursively, and because class add-ons can be attached even to built-in types like ``object``, the work of creating a correct class metadata registry is immensely simplified, compared to having to special case such base classes, check for bases where no metadata was added or defined, etc. Instead, classes that didn't define any metadata will just have an add-on instance containing whatever was setup by your add-on's ``__init__()`` method, plus whatever additional data was added by its ``created_for()`` method. Thus, metadata accumulation using class add-ons can actually be simpler than doing the same things with metaclasses, since metaclasses can't be retroactively added to existing classes. Of course, class add-ons can't entirely replace metaclasses or base class mixins, but for the things they *can* do, they are much easier to implement correctly. Keys, Decoration, and ``for_enclosing_class()`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Class add-ons can have add-on keys, just like regular add-ons, and they're implemented in the same way. And, you can pass the extra arguments as positional arguments to ``for_enclosing_class()``. For example:: >>> class Index(ClassAddOn): ... def __init__(self, subject, expr): ... self.expr = expr ... self.funcs = [] ... super(Index, self).__init__(subject) >>> def indexedmethod(expr): ... def decorate(func): ... Index.for_enclosing_class(expr).funcs.append(func) ... return func ... return decorate >>> class Demo: ... def dummy(self, foo): ... pass ... dummy = indexedmethod("x*y")(dummy) >>> Index(Demo, "x*y").funcs [<function dummy at ...>] >>> Index(Demo, "y+z").funcs [] Note, by the way, that you do not need to use a function decorator to add metadata to a class. You just need to be calling ``for_enclosing_class()`` in a function called directly from the class body:: >>> def special_methods(**kw): ... smr = SpecialMethodRegistry.for_enclosing_class() ... smr.special_methods.update(kw) >>> class Demo: ... special_methods(x=23, y=55) init called for None created for Demo >>> SpecialMethodRegistry(Demo).special_methods {'y': 55, 'x': 23} By default, the ``for_enclosing_class()`` method assumes is it being called by a function that is being called directly from the class suite, such as a method decorator, or a standalone function call as shown above. But if you make a call from somewhere else, such as outside a class statement, you will get an error:: >>> special_methods(z=42) Traceback (most recent call last): ... SyntaxError: Class decorators may only be used inside a class statement Similarly, if you have a function that calls ``for_enclosing_class()``, but then you call that function from another function, it will still fail:: >>> def sm(**kw): ... special_methods(**kw) >>> class Demo: ... sm(x=23, y=55) Traceback (most recent call last): ... SyntaxError: Class decorators may only be used inside a class statement This is because ``for_enclosing_class()`` assumes the class is being defined two stack levels above its frame. You can change this assumption, however, by using the ``level`` keyword argument:: >>> def special_methods(level=2, **kw): ... smr = SpecialMethodRegistry.for_enclosing_class(level=level) ... smr.special_methods.update(kw) >>> def sm(**kw): ... special_methods(level=3, **kw) >>> class Demo: ... sm(x=23) ... special_methods(y=55) init called for None created for Demo >>> SpecialMethodRegistry(Demo).special_methods {'y': 55, 'x': 23} Alternately, you can pass a specific Python frame object via the ``frame`` keyword argument to ``for_enclosing_class()``, or use the ``for_frame()`` classmethod instead. ``for_frame()`` takes a Python stack frame, followed by any extra positional arguments needed to create the key. Class Registries (NEW in version 0.6) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For many of common class add-on use cases, you just want a dict-like object with "inheritance" for the values in base classes. The ``Registry`` base class provides this behavior, by subclassing ``ClassAddOn`` and the Python ``dict`` builtin type, to create a class add-on that's also a dictionary. It then overrides the ``created_for()`` method to automatically populate itself with any inherited values from base classes. Let's define a ``MethodGoodness`` registry that will store a "goodness" rating for methods:: >>> from peak.util.addons import Registry >>> class MethodGoodness(Registry): ... """Dictionary of method goodness""" >>> def goodness(value): ... def decorate(func): ... MethodGoodness.for_enclosing_class()[func.__name__]=value ... return func ... return decorate >>> class Demo(object): ... def aMethod(self, foo): ... pass ... aMethod = goodness(17)(aMethod) ... def another_method(whinge, spam): ... woohoo ... another_method = goodness(-99)(another_method) >>> MethodGoodness(Demo) {'aMethod': 17, 'another_method': -99} So far, so good. Let's see what happens with a subclass:: >>> class Demo2(Demo): ... def another_method(self, fixed): ... pass ... another_method = goodness(42)(another_method) >>> MethodGoodness(Demo2) {'another_method': 42, 'aMethod': 17} Values set in base class registries are automatically added to the current class' registry of the same type and key, if the current class doesn't have an entry defined. Python's new-style method resolution order is used to determine the precedence of inherited attributes. (For classic classes, a temporary new-style class is created that inherits from the classic class, in order to determine the resolution order, then discarded.) Once the class in question has been created, the registry gets an extra attribute, ``defined_in_class``, which is a dictionary listing the entries that were actually defined in the corresponding class, e.g.:: >>> MethodGoodness(Demo).defined_in_class {'aMethod': 17, 'another_method': -99} >>> MethodGoodness(Demo2).defined_in_class {'another_method': 42} As you can see, this second dictionary contains only the values registered in that class, and not any inherited values. Finally, note that ``Registry`` objects have one additional method that can be useful to call from a decorator: ``set(key, value)``. This method will raise an error if a different value already exists for the given key, and is useful for catching errors in class definitions, e.g.: >>> def goodness(value): ... def decorate(func): ... MethodGoodness.for_enclosing_class().set(func.__name__, value) ... return func ... return decorate >>> class Demo3(object): ... def aMethod(self, foo): ... pass ... aMethod = goodness(17)(aMethod) ... def aMethod(self, foo): ... pass ... aMethod = goodness(27)(aMethod) Traceback (most recent call last): ... ValueError: MethodGoodness['aMethod'] already contains 17; can't set to 27 Threading Concerns ------------------ Add-on lookup and creation is thread-safe (i.e. race-condition free), so long as the add-on key contains no objects with ``__hash__`` or ``__equals__`` methods involve any Python code (as opposed to being pure C code that doesn't call any Python code). So, unkeyed add-ons, or add-ons whose keys consist only of instances of built-in types (recursively, in the case of tuples) or types that inherit their ``__hash__`` and ``__equals__`` methods from built-in types, can be initialized in a thread-safe manner. This does *not* mean, however, that two or more add-on instances can't be created for the same subject at the same time! Code in an add-on class' ``__new__`` or ``__init__`` methods **must not** assume that it will in fact be the only add-on instance attached to its subject, if you wish the code to be thread-safe. This is because the ``AddOn`` access machinery allows multiple threads to *create* an add-on instance at the same time, but only one of those objects will *win* the race to become "the" add-on instance, and no thread can know in advance whether it will win. Thus, if you wish your ``AddOn`` instances to do something *to* their constructor arguments at initialization time, you must either give up on your add-on being thread-safe, or use some other locking mechanism. Of course, add-on initialization is only one small part of the overall thread- safety puzzle. Unless your add-on exists only to compute some immutable metadata about its subject, the rest of your add-on's methods need to be thread-safe also. One way to do that, is to use a ``@synchronized`` decorator, combined with a ``Locking`` add-on:: >>> class Locking(AddOn): ... def __init__(self, subject): ... from threading import RLock ... self.lock = RLock() ... def acquire(self): ... print "acquiring" ... self.lock.acquire() ... def release(self): ... self.lock.release() ... print "released" >>> def synchronized(func): ... def wrapper(self, *__args,**__kw): ... Locking(self).acquire() ... try: ... func(self, *__args,**__kw) ... finally: ... Locking(self).release() ... ... from peak.util.decorators import rewrap ... return rewrap(func, wrapper) >>> class AnotherThing: ... def ping(self): ... print "ping" ... ping = synchronized(ping) >>> AnotherThing().ping() acquiring ping released If the ``Locking()`` add-on constructor were not thread-safe, this decorator would not be able to do its job correctly, because two threads accessing an object that didn't *have* the add-on yet, could end up locking two different locks, and proceeding to run the supposedly-"synchronized" method at the same time! (In general, thread-safety is harder than it looks. But at least you don't have to worry about this one tiny part of correctly implementing it.) Of course, synchronized methods will be slower than normal methods, which is why AddOns doesn't do anything besides that one small part of the thread-safety puzzle, to avoid penalizing non-threaded code. As the PEAK motto says, STASCTAP! (Simple Things Are Simple, Complex Things Are Possible.) Mailing List ------------ Questions, discussion, and bug reports for this software should be directed to the PEAK mailing list; see http://www.eby-sarna.com/mailman/listinfo/PEAK/ for details.
AddOns
/AddOns-0.7.zip/AddOns-0.7/README.txt
README.txt
This directory exists so that Subversion-based projects can share a single copy of the ``ez_setup`` bootstrap module for ``setuptools``, and have it automatically updated in their projects when ``setuptools`` is updated. For your convenience, you may use the following svn:externals definition:: ez_setup svn://svn.eby-sarna.com/svnroot/ez_setup You can set this by executing this command in your project directory:: svn propedit svn:externals . And then adding the line shown above to the file that comes up for editing. Then, whenever you update your project, ``ez_setup`` will be updated as well.
AddOns
/AddOns-0.7.zip/AddOns-0.7/ez_setup/README.txt
README.txt
import sys DEFAULT_VERSION = "0.6c9" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', } import sys, os try: from hashlib import md5 except ImportError: from md5 import md5 def _validate_md5(egg_name, data): if egg_name in md5_data: digest = md5(data).hexdigest() if digest != md5_data[egg_name]: print >>sys.stderr, ( "md5 validation of %s failed! (Possible download problem?)" % egg_name ) sys.exit(2) return data def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download() except pkg_resources.DistributionNotFound: return do_download() def download_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 ): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log if delay: log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version %s to run (even to display help). I will attempt to download it for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""", version, download_base, delay, url ); from time import sleep; sleep(delay) log.warn("Downloading %s", url) src = urllib2.urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = _validate_md5(egg_name, src.read()) dst = open(saveto,"wb"); dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" try: import setuptools except ImportError: egg = None try: egg = download_setuptools(version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) else: if setuptools.__version__ == '0.0.1': print >>sys.stderr, ( "You have an obsolete version of setuptools installed. Please\n" "remove it from your system entirely before rerunning this script." ) sys.exit(2) req = "setuptools>="+version import pkg_resources try: pkg_resources.require(req) except pkg_resources.VersionConflict: try: from setuptools.command.easy_install import main except ImportError: from easy_install import main main(list(argv)+[download_setuptools(delay=0)]) sys.exit(0) # try to force an exit else: if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close() if __name__=='__main__': if len(sys.argv)>2 and sys.argv[1]=='--md5update': update_md5(sys.argv[2:]) else: main(sys.argv[1:])
AddOns
/AddOns-0.7.zip/AddOns-0.7/ez_setup/__init__.py
__init__.py
from peak.util.decorators import decorate, decorate_class, enclosing_frame, classy from weakref import ref import sys __all__ = ['AddOn', 'ClassAddOn', 'Registry', 'addons_for'] _addons = {} def addons_for(ob): """Get the dictionary that should contain add-ons for `ob`""" try: d = ob.__dict__ sd = d.setdefault return d except (AttributeError, TypeError): r = ref(ob) try: return _addons[r] except KeyError: return _addons.setdefault(ref(ob, _addons.__delitem__), {}) def additional_tests(): import doctest return doctest.DocFileSuite( 'README.txt', package='__main__', optionflags=doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE, ) class AddOn(classy): """Attach extra state to (almost) any object""" __slots__ = () decorate(classmethod) def __class_call__(cls, ob, *data): a = addons_for(ob) addon_key = cls.addon_key(*data) try: return a[addon_key] except KeyError: # Use setdefault() to prevent race conditions ob = a.setdefault(addon_key, super(AddOn, cls).__class_call__(ob, *data)) return ob decorate(classmethod) def addon_key(cls, *args): if args: return (cls,)+args return cls decorate(classmethod) def exists_for(cls, ob, *key): """Does an aspect of this type for the given key exist?""" return cls.addon_key(*key) in addons_for(ob) decorate(classmethod) def delete_from(cls, ob, *key): """Ensure an aspect of this type for the given key does not exist""" a = addons_for(ob) try: del a[cls.addon_key(*key)] except KeyError: pass def __init__(self, subject): pass class ClassAddOn(AddOn): """Attachment/annotation for classes and types""" __slots__ = () decorate(classmethod) def __class_call__(cls, ob, *data): addon_key = cls.addon_key(*data) d = ob.__dict__ if addon_key in d: return d[addon_key] d2 = addons_for(ob) try: return d2[addon_key] except KeyError: # Use setdefault() to prevent race conditions ob = d2.setdefault( addon_key, super(ClassAddOn, cls).__class_call__(ob, *data) ) return ob decorate(classmethod) def for_enclosing_class(cls, *args, **kw): if 'frame' in kw: frame = kw.pop('frame') else: if 'level' in kw: level = kw.pop('level') else: level = 2 frame = sys._getframe(level) if kw: raise TypeError("Unexpected keyword arguments", kw) return cls.for_frame(frame, *args) decorate(classmethod) def for_frame(cls, frame, *args): a = enclosing_frame(frame).f_locals addon_key = cls.addon_key(*args) try: return a[addon_key] except KeyError: # Use setdefault() to prevent race conditions ob = a.setdefault(addon_key, type.__call__(cls, None, *args)) # we use a lambda here so that if we are a registry, Python 2.5 # won't consider our method equal to some other registry's method decorate_class(lambda c: ob.__decorate(c), frame=frame) return ob decorate(classmethod) def exists_for(cls, ob, *key): """Does an aspect of this type for the given key exist?""" addon_key = cls.addon_key(*key) return addon_key in ob.__dict__ or addon_key in addons_for(ob) decorate(classmethod) def delete_from(cls, ob, *key): """Class AddOns are not deletable!""" raise TypeError("ClassAddOns cannot be deleted") def __decorate(self, cls): self.created_for(cls) return cls def created_for(self, cls): """Override to access the decorated class, as soon as it's known""" def __init__(self, subject): """Ensure ``created_for()`` is called, if class already exists""" if subject is not None: self.created_for(subject) class Registry(ClassAddOn, dict): """ClassAddOn that's a dictionary with mro-based inheritance""" __slots__ = () def __new__(cls, subject): if cls is Registry: raise TypeError("You must subclass Registry to use it") return super(Registry, cls).__new__(cls) def __init__(self, subject): dict.__init__(self) super(Registry, self).__init__(subject) def created_for(self, cls): """Inherit the contents of base classes""" try: mro = cls.__mro__[::-1] except AttributeError: mro = type(cls.__name__, (cls,object), {}).__mro__[1:][::-1] data = {} self.defined_in_class = dict(self) mytype = type(self) for base in mro[:-1]: data.update(mytype(base)) data.update(self) self.update(data) def set(self, key, value): if key in self and self[key]!=value: raise ValueError("%s[%r] already contains %r; can't set to %r" % (self.__class__.__name__, key, self[key], value) ) self[key] = value
AddOns
/AddOns-0.7.zip/AddOns-0.7/peak/util/addons.py
addons.py
from PySide2 import QtCore class Font: Regular = 25 Medium = 75 Bold = 99 COLORS = { # old colors # palette "white": "#ffffff", "light1": "#f7f7f7", "light2": "#ededed", "light3": "#dbdbdb", "light4": "#c7c7c7", "middle1": "#adadad", "middle2": "#919191", "middle3": "#787878", "middle4": "#5e5e5e", "dark1": "#3b3b3b", "dark2": "#303030", "dark3": "#242424", "dark4": "#181818", "black": "#000000", "green1": "#5ae4aa", "green2": "#1dcf8e", "green3": "#00ad74", "lime1": "#adf75e", "lime2": "#97de4b", "lime3": "#80c23a", "yellow1": "#f8df52", "yellow2": "#f5ca1b", "yellow3": "#dab00a", "red1": "#ff725c", "red2": "#ea5949", "red3": "#c9423b", "blue1": "#3ad4f2", "blue2": "#11b2df", "blue3": "#1083ad", # Athena2 colors "contrast": "#ffffff", # We use it only if the shape lies on a colored or dark background. "base": "#dbdbdb", # All main text on a dark background. "secondary": "#adadad", # Secondary text: subtitle, signature. "nonessential": "#787878", # Tertiary text if used in conjunction with base and secondary. "disabled": "#5e5e5e", # Disabled element shapes: inactive button, non-editable setting. "inverted": "#000000", # Figures on a light background. "interactive": "#5ae4aa", # Clickable shapes. "attention": "#ff725c", # For attracting attention, reporting a problem, warning you about unwanted consequences. "warning": "#ebab0a", # To alert you to an event that could have negative consequences. "warningContrast": "#f8df52", # To alert you to an event that could have negative consequences. "info": "#80c23a", # To draw the user's attention to an event or process. "transparent": "#00000000", } BACKGROUNDS = { # Athena2 backgrounds "accent": "#F7F7F7", # Для контрастных беков "highest": "#3B3B3B", # Для карточек и основных элементов "high": "#303030", # Для второстепенных беков "base": "#242424", # Средний уровень "low": "#181818", # Неактивные чипсы, подложка свитча и слайдера, чекбокса "lowest": "#000000", # Для выбранных элементов и тулбаров "overlay": "#B3000000", # + opacity 0.7! Полупрозрачные затемнения под элементами, что находятся выше остальных } # === Athena 3 === FIGURE = { "base": "#dbdbdb", "secondary": "#adadad", "nonessential": "#787878", "disabled": "#5e5e5e", "inverted": "#000000", "contrast": "#ffffff", "interactive": "#5ae4af", "attention": "#ff725c", "positive": "#7fc337", "positiveContrast": "#adf75e", "warning": "#ebab0a", "warningContrast": "#f8df52", "transparent": "#00000000", "hazard": "#d080ff", } BG = { "highest": "#404040", "high": "#333333", "base": "#262626", "low": "#1c1c1c", "lowest": "#000000", "accent": "#ffffff", "overlay": "#b3000000", } SPECIAL = { "knob": "#333333", "hole": "#7a7a7a", "divider": "#000000", "white": "#ffffff", "black": "#000000", "selection": "#000000", } TEXT = { "title": { "XXLBold": {"size": 48, "height": 56, "weight": Font.Regular,}, "XLBold": {"size": 32, "height": 40, "weight": Font.Medium,}, "LBold": {"size": 28, "height": 40, "weight": Font.Medium,}, "MBold": {"size": 24, "height": 32, "weight": Font.Medium,}, "SBold": {"size": 20, "height": 28, "weight": Font.Medium,}, "XSBold": {"size": 17, "height": 24, "weight": Font.Medium,}, "XSRegular": {"size": 17, "height": 24, "weight": Font.Regular,}, }, "body": { "LBold": {"size": 16, "height": 24, "weight": Font.Medium,}, "LRegular": {"size": 16, "height": 24, "weight": Font.Regular,}, "MBold": {"size": 14, "height": 20, "weight": Font.Medium,}, "MRegular": {"size": 14, "height": 20, "weight": Font.Regular,}, "SBold": {"size": 12, "height": 16, "weight": Font.Medium,}, "SRegular": {"size": 12, "height": 16, "weight": Font.Regular,}, "XSRegular": {"size": 11, "height": 16, "weight": Font.Medium,}, }, "button": { "MBold": {"size": 17, "height": 24, "weight": Font.Bold,}, "MRegular": {"size": 17, "height": 24, "weight": Font.Regular,}, "SBold": {"size": 13, "height": 20, "weight": Font.Medium,}, }, "special": { "BadgeRegular": {"size": 13, "height": 20, "weight": Font.Regular,}, "SectionCaps": { "size": 13, "height": 20, "weight": Font.Regular, "uppercase": True, }, }, } STATUS = { "DEFAULT": 0, "POSITIVE": 1, "WARNING": 2, "ATTENTION": 3, "HAZARD": 4, "NOT_IMPORTANT": 5, } # === Athena 3 === CONTROLS = { "plus": { "color": COLORS["interactive"], "imageSource": "qrc:/resources/images/Athena/common_icons/plus.svg", }, "minus": { "color": COLORS["attention"], "imageSource": "qrc:/resources/images/Athena/common_icons/minus.svg", }, "alarm": { "color": COLORS["warning"], "imageSource": "qrc:/resources/images/Athena/common_icons/alarm.svg", }, "cross": { "color": BACKGROUNDS["base"], "imageSource": "qrc:/resources/images/Athena/common_icons/cross.svg", }, "back": { "color": BACKGROUNDS["base"], "imageSource": "qrc:/resources/images/Athena/common_icons/Back-M.svg", }, } class Athena3(QtCore.QObject): # Athena 3 figure = QtCore.Property( QtCore.QJsonValue, lambda _: QtCore.QJsonValue.fromVariant(FIGURE), constant=True, ) bg = QtCore.Property( QtCore.QJsonValue, lambda _: QtCore.QJsonValue.fromVariant(BG), constant=True ) special = QtCore.Property( QtCore.QJsonValue, lambda _: QtCore.QJsonValue.fromVariant(SPECIAL), constant=True, ) text = QtCore.Property( QtCore.QJsonValue, lambda _: QtCore.QJsonValue.fromVariant(TEXT), constant=True ) status = QtCore.Property( QtCore.QJsonValue, lambda _: QtCore.QJsonValue.fromVariant(STATUS), constant=True ) class RegexProperty(QtCore.Property): def __init__(self, regex): super().__init__( type=QtCore.QRegExp, fget=lambda _: QtCore.QRegExp(regex), constant=True ) class Regexes(QtCore.QObject): _email_pattern = r"[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*" websiteUrl = RegexProperty(r"^https?:\/\/\w[\w-/]*(\.\w{1,})+$") ip = RegexProperty( r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][" r"0-9]|25[0-5])$" ) scenario_name = RegexProperty(r"^(?!.* )(?=.*[\w-])[\w -]{1,24}$") time = RegexProperty(r"^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$") email = RegexProperty(f"^{_email_pattern}$") multi_emails = RegexProperty(fr"^({_email_pattern}\s+)*({_email_pattern})$") port = RegexProperty( r"^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$" ) qr_code = RegexProperty( r"^([0-9a-fA-F]{11})$|^([0-9a-fA-F]{9})$|^([0-9a-fA-F]{6})$" ) user_passcode = RegexProperty(r"[0-9]{4,6}") object_number = RegexProperty(r"[0-9A-Fa-f]{0,16}") day_time = RegexProperty(r"^([0-1][0-9]|2[0-3]):([0-5][0-9])$") hours = RegexProperty(r"^([0-1][0-9]|2[0-3])$") hours_ampm = RegexProperty(r"^((1|0)?[0-9]) ([AaPp][Mm])$") minutes = RegexProperty(r"^([0-5][0-9])$") scenario_minutes = RegexProperty(r"^([0-5][0-9]|[0-9])$") scenario_seconds = RegexProperty(r"^([0-5][0-9]|[0-9])$") phone = RegexProperty(r"^[\+]?[0-9]{8,16}$") phoneNoCode = RegexProperty(r"^[0-9]{9,10}$") hub_qr = RegexProperty(r"[0-9A-Fa-f-]+") certification_master_key = RegexProperty(r"[0-9A-Fa-f]{0,8}") class Customization(QtCore.QObject): def __init__(self, parent=None): super().__init__(parent) self._athena3 = Athena3() self._regexes = Regexes() ds3 = QtCore.Property(QtCore.QObject, lambda self: self._athena3, constant=True) def _get_colors(self): return QtCore.QJsonValue.fromVariant(COLORS) colors = QtCore.Property(QtCore.QJsonValue, _get_colors, constant=True) def _get_backgrounds(self): return QtCore.QJsonValue.fromVariant(BACKGROUNDS) backgrounds = QtCore.Property(QtCore.QJsonValue, _get_backgrounds, constant=True) def _get_specials(self): return QtCore.QJsonValue.fromVariant(SPECIAL) specials = QtCore.Property(QtCore.QJsonValue, _get_specials, constant=True) def _get_controls(self): return QtCore.QJsonValue.fromVariant(CONTROLS) controls = QtCore.Property(QtCore.QJsonValue, _get_controls, constant=True) def _get_required(self): return " <font color='#ff725c'>*</font>" required = QtCore.Property(str, _get_required, constant=True) def _get_checkbox_true(self): return "<font color='#60e3ab'>✔</font> " checkbox_true = QtCore.Property(str, _get_checkbox_true, constant=True) def _get_checkbox_false(self): return "<font color='#ff0000'>✖</font> " checkbox_false = QtCore.Property(str, _get_checkbox_false, constant=True) def _get_empty(self): return "-" empty = QtCore.Property(str, _get_empty, constant=True) regexes = QtCore.Property(QtCore.QObject, lambda self: self._regexes, constant=True)
AddingLib
/AddingLib-0.1.2.tar.gz/AddingLib-0.1.2/AddLibriary/customization.py
customization.py
function get_image(type, size=null, color_type=null, custom_alarm=null, subtype=null) { let path = "qrc:/resources/images/desktop/delegates/" let no_color_device = [ "10", "11", "12", "13", "16", "17", "18", "1a", "1f", "22", "23", "24", "25", "2a", "2b", "2c", "2d", "2f", "30", "yavir_hub", "yavir_hub_plus", ].includes(type) if (no_color_device) { color_type = null } let device_name = { "01": "DoorProtect", "02": "MotionProtect", "03": "FireProtect", "04": "GlassProtect", "05": "LeaksProtect", "06": "MotionProtectCurtain", "07": "Hub", "08": "CombiProtect", "09" : "FireProtect", "10": "UniversalDevice", "11": "Transmitter", "12": "WallSwitch", "13": "MotionProtectOutdoor", "0a": "KeyPad", "0b": "SpaceControl", "0c": "Button", "0d": "MotionCam", "0e": "MotionProtect", "0f": "DoorProtect", "14": "StreetSiren", "15": "HomeSiren", "16": "WallSwitch", "17": "WallSwitch", "18": "MotionCamOutdoor", "19": "KeyPadPlus", "1a": "DualCurtainOutdoor", "1b": "StreetSirenDoubleDeck", "1c": "MultiTransmitter", "1d": "Wired", "1e": "Socket", "1f": "WallSwitch", "21": "Hub", "yavir_hub": "YavirHub", "fibra_hub": "MultiTransmitter", "yavir_hub_plus": "YavirHubPlus", "22": "UserPicture", "23": "GroupPicture", "24": "RoomPicture", "25": "Camera", "26": "Wired", "26-wired-tamper": "Wired", "26-wired-intrusion": "Wired", "27": "YavirSiren", "28": "YavirKeyPad", "28-keypad-yavir": "YavirKeyPad", "28-reader-yavir": "YavirReader", "29": "YavirKey", "2a": "ScenarioPicture", "2b": "CompanyPicture", "2f": "InstallerPicture", "2c": "SchedulePicture", "2e": "Pass", "30": "AccessCode", "42": "DoubleButton", "43": "KeyPadCombi", "44": "LightSwitch", "45": "MultiTransmitter", "47": "LeaksProtect", // LifeQuality "4c": "SocketBase", "4d": "FireProtect2Base", "61": "DoorProtectFibra", "62": "MotionProtectFibra", "6e": "MotionProtectFibra", "6f": "DoorProtectFibra", "46": "Hub", "64": "GlassProtectFibra", "68": "CombiProtectFibra", "6a": "KeyPad", "74": "StreetSiren", "75": "HomeSiren", "7b": "StreetSirenDoubleDeck", "7c": "MultiTransmitterFibra", "TAG": "Tag", "CARD": "Pass", }[type] // if Wire Input MT if (type == "1d"){ return path + device_name + "/" + generate_wire_alarm_image_filename(color_type, size, custom_alarm) } // if Wire Input if (["26", "26-wired-tamper", "26-wired-intrusion"].includes(type)){ let wire_name = type == "26-wired-intrusion" ? "Intrusion" : "Tamper" return path + device_name + "/" + wire_name + size + ".png" } if (!device_name) { device_name = "RoomPicture" color_type = null } // Add device class name to path let image_path = path + device_name + "/" // Add subtype dir and name if it's subtype if (subtype && subtype != "NO_SUBTYPE") { image_path += subtype + "/" + subtype } else { // Add type of the device image_path += device_name } // Add color to path if exists if (color_type) image_path += add_suffix_by_device_color(color_type) // Add size to path image_path += size // Add ending image_path += ".png" return image_path } function add_suffix_by_device_color(color_type) { let device_color = { "WHITE": "White", "WHITE_LABEL_WHITE": "White", "NO_COLOR_INFO": "White", "BLACK": "Black", "WHITE_LABEL_BLACK": "Black", "PANEL_COLOR_UNSPECIFIED": "White", "PANEL_COLOR_WHITE": "White", "PANEL_COLOR_BLACK": "Black", "PANEL_COLOR_FOG": "Fog", "PANEL_COLOR_GRAPHITE": "Graphite", "PANEL_COLOR_GREY": "Grey", "PANEL_COLOR_IVORY": "Ivory", "PANEL_COLOR_OLIVE": "Olive", "PANEL_COLOR_OYSTER": "Oyster", }[color_type] return device_color ? device_color : "" } function bridgeOutputs(type, size) { var path = "qrc:/resources/images/desktop/delegates/VHFOutputs/" + size + "/" return path + type + ".png" } function generate_wire_alarm_image_filename(color_type, size, custom_alarm="TAMPER_ALARM") { var image_name = "Tamper" if (color_type == 1) { const custom_alarm_map = { "BURGLARY_ALARM": "Intrusion", "FIRE_ALARM": "Fire", "MEDICAL_ALARM": "MedicalHelp", "PANIC_ALARM": "PanicButton", "GAS_ALARM": "Gas", "TAMPER_ALARM":"Tamper", "MALFUNCTION_ALARM": "Malfunction", "LEAK_ALARM": "Leak", "SERVICE_EVENT": "Service", } var image_name = custom_alarm_map[custom_alarm] } return image_name + size + ".png" }
AddingLib
/AddingLib-0.1.2.tar.gz/AddingLib-0.1.2/AddLibriary/resources/js/images.js
images.js
function count_left_arrow(gridView) { if (gridView.currentIndex == 0 || currentIndex == -1) { gridView.currentIndex = gridView.model.length - 1 } else { gridView.currentIndex -= 1 } gridView.positionViewAtIndex(gridView.currentIndex, GridView.Contain) } function count_right_arrow(gridView) { if (gridView.currentIndex == gridView.model.length - 1) { gridView.currentIndex = 0 } else { gridView.currentIndex += 1 } gridView.positionViewAtIndex(gridView.currentIndex, GridView.Contain) } function createIconObject(parent, icon) { var path = "qrc:/resources/qml/screens/home/pages/objects/object/managements/delegates/parts/".concat("", icon) var component = Qt.createComponent(path); var element = component.createObject(parent); if (element == null) { // Error handling console.log("Error creating object"); } } function get_data_hub_state(state) { var url; var text = tr.disarmed; var color = ui.colors.white switch(state) { case "DISARMED": url = "qrc:/resources/images/pro/icons_groups/disarmed.svg"; text = tr.disarmed break; case "DISARMED_NIGHT_MODE_OFF": url = "qrc:/resources/images/pro/icons_groups/disarmed.svg"; text = tr.disarmed break; case "ARMED": url = "qrc:/resources/images/pro/icons_groups/armed.svg"; text = tr.armed break; case "ARMED_NIGHT_MODE_OFF": url = "qrc:/resources/images/pro/icons_groups/armed.svg"; text = tr.armed break; case "ARMED_NIGHT_MODE_ON": url = "qrc:/resources/images/pro/icons_groups/armed.svg"; text = tr.armed break; case "DISARMED_NIGHT_MODE_ON": url = "qrc:/resources/images/icons/night-mode.svg"; text = tr.part_arm break; case "PARTIALLY_ARMED_NIGHT_MODE_ON": url = "qrc:/resources/images/icons/night-mode.svg"; text = tr.part_arm break; case "NIGHT_MODE": url = "qrc:/resources/images/icons/night-mode.svg"; text = tr.part_arm break; case "PARTIALLY_ARMED_NIGHT_MODE_OFF": url = "qrc:/resources/images/icons/icon-a-hub-status-icon-partially-armed.svg"; text = tr.selective_armed break; case "PERIMETER_ARMED": url = ""; text = tr.perimeter_armed break; case "APP_EXIT_TIMER_IN_PROGRESS": url = "qrc:/resources/images/icons/tsa-red.svg"; text = tr.arming_in_progress; color = ui.colors.red2 break; case "SECOND_STAGE_TIMER_IN_PROGRESS": url = "qrc:resources/images/icons/tsa-green.svg"; text = tr.arming_in_progress; color = ui.colors.lime2 break; case "ARMING_INCOMPLETE": url = "qrc:/resources/images/icons/tsa-yellow.svg"; text = tr.arming_incomplete color = ui.colors.yellow1 break; case "FINAL_DOOR_BOUNCE_TIMER_IN_PROGRESS": url = "qrc:resources/images/icons/tsa-green.svg"; text = tr.arming_in_progress; color = ui.colors.lime2 break; } return [url, text, color] } function check_feature_enabled(source_type, code) { // SOCKET TYPE G PLUS EVENTS if (code.toUpperCase().includes("4C_31")) return __socket_type_g_plus_features__ let features_flag_map = { "44": __light_switch_features__, "47": __life_quality_features__, "4d": __fp2_features__, } return source_type in features_flag_map ? features_flag_map[source_type] : true }
AddingLib
/AddingLib-0.1.2.tar.gz/AddingLib-0.1.2/AddLibriary/resources/js/utils.js
utils.js
var exit_popup_instance = null; var text_popup_instance = null; var update_popup_instance = null; function add_access_card_popup(mode) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AddAccessCardPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"mode": mode}) popup.open() } function add_access_card_flow_popup(hub, type, color, user_id) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AddAccessCardFlowPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"hub": hub, "type": type, "color": color, "user_id": user_id}) popup.open() } function create_popup(name, properties={}) { var path = "qrc:/resources/qml/screens/popups/".concat("", name); var component = Qt.createComponent(path); var err = component.errorString(); if (err) console.log(err); var popup = component.createObject(application, properties); popup.open(); return popup } function text_popup(title, information) { if (text_popup_instance != null) return var component = Qt.createComponent( "qrc:/resources/qml/components/911/DS3/popups/Dialog.qml") var err = component.errorString() if (err) console.log(err) text_popup_instance = component.createObject(application, { title: title, text: information, }) text_popup_instance.onClosed.connect(function() { text_popup_instance = null }) text_popup_instance.open() } function exit_popup(action) { if (exit_popup_instance) return var component = Qt.createComponent("qrc:/resources/qml/screens/popups/ExitPopup.qml") var err = component.errorString() if (err) console.log(err) exit_popup_instance = component.createObject(application, {"action": action}) exit_popup_instance.onClosed.connect(function(){exit_popup_instance = null}) exit_popup_instance.open() } function create_notification(properties={}, incubate=true) { var path = "qrc:/resources/qml/components/911/Notification.qml"; var component = Qt.createComponent(path); var err = component.errorString(); if (err) console.log(err); if (incubate) { return component.incubateObject(application, properties); } else { return component.createObject(application, properties); } } function scheme_image_popup(gridView, incidentPage) { return create_popup("SchemeImagePopup.qml", {"grid": gridView, "incidentPage": incidentPage}); } function wait_popup() { return create_popup("WaitPopup.qml"); } function add_employee_popup() { return create_popup("AddEmployeePopup2.qml"); } function add_fast_response_team_popup() { return create_popup("AddFastResponseTeamPopup.qml"); } function user_popup() { return create_popup("UserPopup.qml"); } function calendar_popup(action, selectedDate, allowFuture, allowPast=true, additionalParams=null) { var data = {"action": action, "selectedDate": selectedDate, "allowFuture": allowFuture, "allowPast": allowPast} if (additionalParams) { data = Object.assign({}, data, additionalParams) } return create_popup("CalendarPopup.qml", data); } function sign_up_popup(step=0, email="", phoneNumber="") { return create_popup("SignUpPopup.qml", {"stepAlt": step, "userEmail": email, "phoneNumber": phoneNumber}); } function add_responsible_person_popup() { return create_popup("AddResponsiblePersonPopup.qml"); } function confirmation_deletion_popup(task, text=null) { return create_popup("ConfirmationDeletionPopup.qml", {"task": task, "popup_text": text}); } function easter_egg_popup() { return create_popup("EasterEggPopup.qml"); } function motion_cam_popup(grid, incidentPage) { return create_popup("MotionCamPopup.qml", {"grid": grid, "incidentPage": incidentPage}); } function facility_motion_cam_popup(event) { return create_popup( event.event.hub_event.source_type == "0D" ? "FacilityMotionCamPopup.qml" : "FacilityMotionCamOutdoorPopup.qml", {"event": event} ); } function upload_facility_media() { return create_popup("UploadFacilityMediaPopup.qml"); } function delete_facility_media(media) { return create_popup("DeleteFacilityMediaPopup.qml", {"media": media}); } function update_facility_media(media) { return create_popup("UpdateFacilityMediaPopup.qml", {"media": media}); } function to_sleep_mode_popup(facility_id) { return create_popup("ToSleepModePopup.qml", {"facilityId": facility_id}); } function add_facility_note() { return create_popup("AddFacilityNotePopup.qml"); } function add_object_popup(connectionsAdd=false, hub_id="", name="", number="", hub_company_binding_state=null) { return create_popup("AddObjectPopup.qml", { "connectionsAdd": connectionsAdd, "hubId": hub_id, "name": name, "number": number, "hubCompanyBindingState": hub_company_binding_state }); } function schedule_menu_popup(parent) { return create_popup("ScheduleMenuPopup.qml", {"parent": parent}); } function schedule_time_popup(parent, updateBody) { return create_popup("ScheduleTimePopup.qml", {"parent": parent, "updateBody": updateBody}); } function password_change_popup(email="") { return create_popup("PasswordChangePopup.qml", {"email": email}); } function user_settings_popup() { return create_popup("UserSettingsPopup.qml"); } function user_changed_password_popup() { return create_popup("user_settings/PasswordChangedPopup.qml"); } function maps_popup(info) { return create_popup("MapsPopup.qml", {"info": info}); } function remove_facility(facility, mode="facility") { return create_popup("RemoveImmediately.qml", {"facility": facility, "mode": mode}); } function confirm_change_password(title, additionalTitle) { return create_popup("ConfirmChangePasswordSettingUser.qml", {'title': title, "additionalTitle": additionalTitle}); } function notification_popup(text) { return create_popup("NotificationPopup.qml", {"text": text}); } function edit_phone_number_popup() { return create_popup("EditPhoneNumberPopup.qml"); } function edit_email_popup(email) { return create_popup("EditEmailPopup.qml", {"email": email}); } function confirmation_common_popup(todo, text, buttonText=null, buttonColor=null) { var additional = {"todo": todo, "text": text} if (buttonText) additional["buttonText"] = buttonText if (buttonColor) additional["buttonColor"] = buttonColor return create_popup("ConfirmCommonPopup.qml", additional); } function facilities_search_popup(objectsStack) { return create_popup("FacilitiesSearchPopup.qml", {"objectsStack": objectsStack}); } function incidents_logs(activities, parent, x, y, iconY) { return create_popup( "IncidentsLogsPopup.qml", {"activities": activities, "parent": parent, "x1": x - 344, "y1": y, "iconY": iconY}); } function report_popup(data) { return create_popup("ReportPopup.qml", data); } function update_popup(update_data) { if (update_popup_instance) update_popup_instance.destroy() var path = "qrc:/resources/qml/UpdatePopup.qml"; var component = Qt.createComponent(path); var err = component.errorString(); if (err) console.log(err); update_popup_instance = component.createObject(application, {"update_data": update_data}); update_popup_instance.open(); update_popup_instance.onClosed.connect(function() { update_popup_instance = null }) return update_popup_instance } function time_sync_popup() { return create_popup("TimeSyncPopup.qml"); } function connections_filter_popup(filters, counters, total_counter) { return create_popup("ConnectionsFilterPopup.qml", { "counters":counters, "filters": filters, "total_counter": total_counter }); } function delete_translator_facility_popup(text, remove) { return create_popup("DeleteTranslatorFacilityPopup.qml", { "text": text, "remove": remove}); } function create_911_channel_popup(settings, mode="facility") { // temporary return create_popup("Create911ChannelPopup.qml", {"settings": settings, "mode": mode}); } function remove_911_channel_popup(settings) { // temporary return create_popup("Remove911ChannelPopup.qml", {"settings": settings}); } function delete_hub_company_binding(settings, mode="facility") { // temporary return create_popup("DeleteHubCompanyBindingPopup.qml", {"settings": settings, "mode": mode}); } function delete_installer(settings, reloadSignal, mode, insertData) { // temporary return create_popup("DeleteInstallerPopup.qml", {"settings": settings, "reloadSignal": reloadSignal, "mode": mode, "insertData": insertData}); } function add_alt_object_popup(mode="facility") { // temporary return create_popup("AddAltObjectPopup.qml", {"mode": mode}); } function plan_full_screen_popup(url) { return create_popup("PlanFullScreenPopup.qml", {"url": url}); } function create_workplace_popup(workplace, incident_id=null) { return create_popup("CreateWorkplacePopup.qml", {"workplace": workplace, "incident_id": incident_id}); } function facility_versioning_popup(text, continue_saving) { return create_popup("FacilityVersioningPopup.qml", {"text": text, "continue_saving": continue_saving}); } function bindings_filter_popup() { return create_popup("BindingsFilterPopup.qml"); } function company_incident_settings_popup() { return create_popup("CompanyIncidentSettingsPopup.qml"); } function hubs_availability_popup(result) { return create_popup("HubsAvailabilityPopup.qml", {"result": result}); } function installer_access_popup(parent, facility_id, employee_id, mode) { return create_popup("InstallerAccessPopup.qml", {"parent": parent, "facilityId": facility_id, "employeeId": employee_id, "mode": mode}); } function add_installer_popup(facility) { return create_popup("AddInstallersPopup.qml", {"facility": facility}); } function facilities_permissions_popup(employee) { return create_popup("FacilitiesPermissionsPopup.qml", {"employee": employee}); } function add_installer_facility_popup(employee) { return create_popup("AddInstallersFacilityPopup.qml", {"employee": employee}); } function add_multitransmitter_device_popup(roomIndex, device) { return create_popup("AddMultitransmitterDevicePopup.qml", {"roomIndex": roomIndex, "mtr_device": device}); } function pro_access_popup(parent, hub) { return create_popup("ProAccessPopup.qml", {"parent": parent, "hub": hub}); } function terminate_session_warning_popup(logoutText, todo, isTwoFa) { return create_popup("AjaxWarningSessionPopup.qml", {"logoutText": logoutText, "todo": todo, "isTwoFa": isTwoFa}); } function second_step_2fa_popup() { return create_popup("SecondStepTwoFaPopup.qml"); } function confirm_action_popup(contentText, todo, settings = {}) { return create_popup( "AjaxConfirmAction.qml", { "contentText": contentText, "todo": todo, "labelText": settings.labelText, "saveColor": settings.saveColor, "confirmText": settings.confirmText, "exitText": settings.exitText } ); } function two_fa_activated() { return create_popup("TwoFaActivatedPopup.qml") } function two_fa_confirm_login(loginData) { return create_popup("AjaxTwoFaConfirmLoginPopup.qml", {"loginData": loginData}) } function sessions_popup() { return create_popup("AjaxSessionsPopup.qml") } function confirm_entering_popup(session) { return create_popup("AjaxConfirmEntering.qml", {"session": session}) } function hub_alarm_countdown_popup(action, ignoreAlarms, incidentItem=null) { return create_popup("AlarmCountdownTimerPopup.qml", {"action": action, "ignoreAlarms": ignoreAlarms, "incidentItem": incidentItem}) } function dco_event_info_popup(eventCode) { return create_popup("DcoEventInfoPopup.qml", {"eventCode": eventCode}) } function antimasking_sensors_failed_popup() { return create_popup("AntimaskingSensorFailedPopup.qml") } function voltage_drop_popup(device_type) { return create_popup("VoltageDropPopup.qml") } function internal_crash_popup() { return create_popup("InternalCrashPopup.qml") } function confirm_email_popup(confirmationInfo, companyStack, ownership) { return create_popup("ConfirmEmailPopup.qml", {"confirmationInfo": confirmationInfo, "companyStack": companyStack, "ownership": ownership}) } function image_popup(url) { return create_popup("ImagePopup.qml", {"url": url}) } function confirm_email_popup_alt(confirmationInfo, companyStack, ownership) { return ownership ? create_popup("ConfirmEmailPopup.qml", {"confirmationInfo": confirmationInfo, "companyStack": companyStack, "ownership": ownership}) : create_popup("ConfirmEmailEditPopup.qml", {"confirmationInfo": confirmationInfo, "preset": companyStack}) } function cancel_wizard_popup(close_wizard_action) { return create_popup("CancelWizardPopup.qml", {'close_wizard_action': close_wizard_action}) }
AddingLib
/AddingLib-0.1.2.tar.gz/AddingLib-0.1.2/AddLibriary/resources/js/popups.js
popups.js
var exit_popup_instance = null; var malf_popup_instance = null; var text_popup_instance = null; var error_popup_instance = null; var agreement_popup_instance = null; var delete_account_verification_popup_instance = null; function popupByPath(path, properties={}) { var component = Qt.createComponent(path); var err = component.errorString(); if (err) console.log(err); var popup = component.createObject(application, properties); popup.open(); return popup } function waitPopup(waitSignal, waitCallback=undefined, options=undefined) { var component = Qt.createComponent("qrc:/resources/qml/components/911/DS3/popups/WaitPopup.qml") var popup = component.createObject(application, Object.assign({ waitSignal: waitSignal, waitCallback: waitCallback }, options)) popup.open() } function add_hub_popup() { var component = Qt.createComponent( "qrc:/resources/qml/screens/hubs/popups/AddHubPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function please_wait_popup(description = tr.request_send, timeout = 30, endSignals = undefined) { var component = Qt.createComponent("qrc:/resources/qml/components/911/DS3/popups/StatusPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {description: description, timeout: timeout, endSignals: endSignals}) popup.open() return popup } function please_wait_invite_users_popup() { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/PleaseWaitInviteUserPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function text_popup(title, information) { if (text_popup_instance != null) return var component = Qt.createComponent( "qrc:/resources/qml/components/911/DS3/popups/Dialog.qml") var err = component.errorString() if (err) console.log(err) text_popup_instance = component.createObject(application, { title: title, text: information, }) text_popup_instance.onClosed.connect(function() { text_popup_instance = null }) text_popup_instance.open() } function error_popup(error) { if (error_popup_instance != null) return var component = Qt.createComponent( "qrc:/resources/qml/components/911/DS3/popups/ModalInfo.qml") var err = component.errorString() if (err) console.log(err) error_popup_instance = component.createObject(application, { sections: [{ "description": error }], }) error_popup_instance.onClosed.connect(function() { error_popup_instance = null }) error_popup_instance.open() } function hub_settings_popup(device) { var component = Qt.createComponent( "qrc:/resources/qml/screens/hub/devices/settings/HubSettings.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"device": device}) popup.open() } function add_room_popup() { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AddRoomPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function room_settings_popup(room) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/RoomSettingsPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"room": room}) popup.open() } function room_delete_popup(room) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/DeleteRoomPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"room": room}) popup.open() } function hub_delete_popup(hub) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/DeleteHubPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function change_hub_name_popup() { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/ChangeHubNamePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function app_restart_required_popup() { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AppRestartRequiredPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function invite_popup(title) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/managements/settings/InvitePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"title": title}) popup.open() } function select_wifi_popup_advanced() { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/managements/settings/wifi/SelectWifiNetworkAdvancedPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function add_group_popup() { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/managements/settings/groups/AddGroupPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function group_settings_popup(group) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/managements/settings/groups/GroupSettingsPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"group": group}) popup.open() } function group_delete_popup(room) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/managements/settings/groups/DeleteGroupPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"group": group}) popup.open() } function select_devices_popup(group) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/managements/settings/groups/SelectDevicesPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"group": group}) popup.open() } function select_group_popup(devices) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/managements/settings/groups/SelectGroupPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"devices": devices}) popup.open() } function request_access_popup() { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/RequestAccessPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function add_device_popup(hub, roomIndex) { var component = Qt.createComponent("qrc:/resources/qml/screens/home/pages/objects/object/popups/AddDevicePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"hub": hub, "roomIndex": roomIndex}) popup.open() } function select_add_device_popup(roomIndex, management=null, from_devices=true) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/SelectAddDevicePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"roomIndex": roomIndex, "management": management, "from_devices": from_devices}) popup.open() } function device_settings_popup(device, openCompanies=false) { var component = Qt.createComponent(device.settings_popup) var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"device": device, "openCompanies": openCompanies}) popup.open() } function vhf_output_settings_popup(device, output_number) { var component = Qt.createComponent(device.output_settings_popup) var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"device": device, "output_number": output_number}) popup.open() } function delete_device_popup(hub_id, device, management) { var component = Qt.createComponent("qrc:resources/qml/screens/home/pages/objects/object/managements/settings/DeleteDevicePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"hub_id": hub_id, "device": device, "management": management}) popup.open() } function interconnect_popup(fire_alarms, management=null, isCriticalCOAlarm=null) { var component = Qt.createComponent("qrc:/resources/qml/screens/pro/pages/hubs/hub/popups/StopInterconnectPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, { "fire_alarms": fire_alarms, "management": management, "isCriticalCOAlarm": isCriticalCOAlarm, }) popup.open() return popup } function malfunctions_popup(data, incident=null) { if (malf_popup_instance != null) return var component = Qt.createComponent("qrc:/resources/qml/screens/home/pages/objects/object/popups/MalfunctionsPopup.qml") var err = component.errorString() if (err) console.log(err) malf_popup_instance = component.createObject( application, {"malfunctions_data": data, "incident": incident} ) malf_popup_instance.onClosed.connect(function() { malf_popup_instance = null }) malf_popup_instance.open() return malf_popup_instance } function map_popup(information, mode) { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/AjaxMapPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"information": information, "mode": mode}) popup.open() return popup } function whats_new(data) { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/AjaxWhatsNewPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"information": data}) popup.open() return popup } function user_popup() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/AjaxUserPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function application_settings_popup() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/AjaxAppPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function report_problem() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/AjaxProblemPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function exit_popup() { if (exit_popup_instance) return var component = Qt.createComponent("qrc:/resources/qml/components/desktop/AjaxExitPopup.qml") var err = component.errorString() if (err) console.log(err) exit_popup_instance = component.createObject(application) exit_popup_instance.onClosed.connect(function(){exit_popup_instance = null}) exit_popup_instance.open() } function user_settings_popup() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/AjaxUserSettingsPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function change_user_name_popup(nameField, currentName) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxChangeUserNamePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"nameField": nameField, "currentName": currentName}) popup.open() } function add_camera_popup(roomIndex, rooms) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AddCameraPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"roomIndex": roomIndex, "rooms": rooms}) popup.open() } function change_user_email_popup() { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxChangeUserEmailPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function enter_codes(data) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxEnterCodesPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"data": data}) popup.open() } function change_user_password_popup() { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxChangeUserPasswordPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function change_user_phone_popup() { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxChangeUserPhonePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function image_popup(target, url, isRounded) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/ChangeImagePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"target": target, "url": url, "isRounded": isRounded}) popup.open() } function motion_cam_popup(data) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxMotionCamPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"data": data}) popup.open() } function add_wire_input_popup(roomIndex, management=null) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AddWireInputPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"roomIndex": roomIndex, "management": management}) popup.open() } function add_wire_siren_popup(roomIndex, management=null) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AddWireSirenPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"roomIndex": roomIndex, "management": management}) popup.open() } function add_yavir_access_control_popup(roomIndex, management=null) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AddYavirAccessControlPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"roomIndex": roomIndex, "management": management}) popup.open() } function key_reg_time_popup(hub_id, text, management=null) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/KeyRegTimePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"hub_id": hub_id, "text": text, "management": management}) popup.open() } function user_key_reg_time_popup(text) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/UserKeyRegTimePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"text": text}) popup.open() } function confirm_invites_popup(text, pro, emails, management=null) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxConfirmInvitesPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"text": text, "pro": pro, "emails": emails, "management": management}) popup.open() } function update_popup(info) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxUpdatePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"info": info}) popup.open() } function please_wait_download_popup() { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxPleaseWaitDownloadPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function open_address_map() { var component = Qt.createComponent( "qrc:/resources/qml/screens/hub/devices/settings/address/MapPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function agreement_popup(url) { if (agreement_popup_instance) return var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxAgreementPopup.qml") var err = component.errorString() if (err) console.log(err) agreement_popup_instance = component.createObject(application, {"url": url}) agreement_popup_instance.onClosed.connect(function(){agreement_popup_instance = null}) agreement_popup_instance.open() } function video_surveillance_settings() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/ezviz/VideoSurveillancePopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function ezviz_login_popup() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/ezviz/CloudLoginPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function ezviz_popup() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/ezviz/UserPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function add_ezviz_camera_popup() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/ezviz/AddCameraPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() return popup } function add_common_camera_popup(roomIndex, rooms) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/popups/AddCommonCameraPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"roomIndex": roomIndex, "rooms": rooms}) popup.open() } function add_hikvision_safire_camera_popup(roomIndex, camType, data) { var component = Qt.createComponent("qrc:/resources/qml/screens/home/pages/objects/object/popups/AddHikvisionSafireCameraPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"roomIndex": roomIndex, "camType": camType, "info": data.data}) popup.open() } function choose_hikvision_safire_camera_popup(data) { var component = Qt.createComponent("qrc:/resources/qml/screens/home/pages/objects/object/popups/ChooseHikvisionCameraPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"info": data}) popup.open() } function arm_disarm_hub_settings_popup(scenario, device) { var component = Qt.createComponent( "qrc:/resources/qml/screens/home/pages/objects/object/managements/settings/hub_scenarios/ArmDisarmScheduleSettingsPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"scenario": scenario, "device": device}) popup.open() return popup } function enable_interconnect_warning_popup(frame_length) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxFireInterconnectWarningPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"frame_length": frame_length}) popup.open() return popup } function timezones_warning_popup(todo) { var component = Qt.createComponent("qrc:/resources/qml/components/911/DS3/popups/Dialog.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject ( application, { title: tr.hub_time_zone_is_not_set_title, text: tr.hub_time_zone_is_not_set_text, firstButtonText: tr.continue_, secondButtonText: tr.cancel, firstButtonCallback: todo } ) popup.open() return popup } function confirm_or_cancel(headerText, confirmText, todo, actionText=null) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxConfirmOrCancelPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"headerText": headerText, "confirmText": confirmText, "todo": todo, "actionText": actionText}) popup.open() return popup } function not_pd_compliant_devices_popup(not_pd_devices) { var component = Qt. createComponent("qrc:/resources/qml/components/desktop/NotPDCompliantDevicesPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, { "not_pd_devices" : not_pd_devices }) popup.open() return popup } function confirm_clear_notofications(confrimText, callback) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxDeleteNotificationsPopup.qml"); var err = component.errorString(); if (err) console.log(err); var popup = component.createObject(application, {"confirmText": confrimText, "callback": callback}); popup.open(); return popup; } function wizard_action_popup(headerLabel, content, saveText, todo) { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/WizardActionPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject( application, { "headerLabel" : headerLabel, "contentText": content, "saveContent": saveText, "todo": todo } ) popup.open() return popup } function interconnect_delay_popup(fire_alarms, trigger, management=null) { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/InterconnectDelayPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject( application, { "fire_alarms": fire_alarms, "trigger": trigger, "management": management } ) popup.open() return popup } function reset_alarm_popup(hub, management=null) { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/ResetAlarmPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"hub": hub, "management": management}) popup.open() return popup } function chimes_activation_popup() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/AjaxChimesPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function reset_power_for_fire_devices(todo, devices, management=null) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxFireAlarmsDetected.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application, {"todo": todo, "mtr_devices": devices, "management": management}) popup.open() return popup } function confirm_action_popup(contentText, todo, settings = {}) { var component = Qt.createComponent( "qrc:/resources/qml/components/desktop/AjaxConfirmAction.qml"); var err = component.errorString(); if (err) console.log(err); var popup = component.createObject( application, { "contentText": contentText, "todo": todo, "labelText": settings.labelText, "saveColor": settings.saveColor, "confirmText": settings.confirmText, "exitText": settings.exitText, "cancelTodo": settings.cancelTodo, "closeTodo": settings.closeTodo, } ); popup.open(); return popup; } function migration_summary_popup() { var component = Qt.createComponent("qrc:/resources/qml/components/desktop/MigrationSummaryPopup.qml") var err = component.errorString() if (err) console.log(err) var popup = component.createObject(application) popup.open() } function delete_account_verification_popup() { if (delete_account_verification_popup_instance != null) return var component = Qt.createComponent("qrc:/resources/qml/screens/home/pages/objects/object/popups/delete_account_wizard/Verification.qml") var err = component.errorString() if (err) console.log(err) delete_account_verification_popup_instance = component.createObject(application, {}) delete_account_verification_popup_instance.onClosed.connect(function() { delete_account_verification_popup_instance = null }) delete_account_verification_popup_instance.open() }
AddingLib
/AddingLib-0.1.2.tar.gz/AddingLib-0.1.2/AddLibriary/resources/js/desktop/popups.js
popups.js
[![License Apache 2.0](https://badgen.net/badge/license/apache2.0/blue)](https://github.com/Microsoft/DeepSpeed/blob/master/LICENSE) [![PyPI version](https://badge.fury.io/py/deepspeed.svg)](https://pypi.org/project/deepspeed/) [![Downloads](https://pepy.tech/badge/deepspeed)](https://pepy.tech/project/deepspeed) [![Build](https://badgen.net/badge/build/check-status/blue)](#build-pipeline-status) [![Twitter](https://img.shields.io/twitter/follow/MSFTDeepSpeed)](https://twitter.com/intent/follow?screen_name=MSFTDeepSpeed) <div align="center"> <img src="docs/assets/images/DeepSpeed_light.svg#gh-light-mode-only" width="400px"> <img src="docs/assets/images/DeepSpeed_dark_transparent.svg#gh-dark-mode-only" width="400px"> </div> ## Latest News <b> <span style="color:orange" > DeepSpeed empowers ChatGPT-like model training with a single click, offering 15x speedup over SOTA RLHF systems with unprecedented cost reduction at all scales; [learn how](https://github.com/microsoft/DeepSpeed/tree/master/blogs/deepspeed-chat)</span>.</b> * ***[2023/04] 🚀 [DeepSpeed Chat: Easy, Fast and Affordable RLHF Training of ChatGPT-like Models at All Scales](https://github.com/microsoft/DeepSpeed/tree/master/blogs/deepspeed-chat)*** [[English](https://github.com/microsoft/DeepSpeed/tree/master/blogs/deepspeed-chat/README.md)] [[中文](https://github.com/microsoft/DeepSpeed/tree/master/blogs/deepspeed-chat/chinese/README.md)] [[日本語](https://github.com/microsoft/DeepSpeed/tree/master/blogs/deepspeed-chat/japanese/README.md)]🚀 * [2023/03] [Scaling Large-Scale Generative Mixture-of-Expert Multimodal Model With VL-MoE](https://www.deepspeed.ai/2023/03/30/multi-modal.html) * [2023/02] [Automatic Tensor Parallelism: Enables tensor parallelism by default without an injection policy](https://www.deepspeed.ai/tutorials/automatic-tensor-parallelism/) * [2022/12] [DeepSpeed Data Efficiency: A composable library that makes better use of data, increases training efficiency, and improves model quality](https://www.deepspeed.ai/2022/12/11/data-efficiency.html) * [2022/11] [Stable Diffusion Image Generation under 1 second w. DeepSpeed MII](https://github.com/microsoft/DeepSpeed-MII/tree/main/examples/benchmark/txt2img) * [2022/10] [DeepSpeed-MII: instant speedup on 24,000+ open-source DL models with up to 40x cheaper inference](https://www.deepspeed.ai/2022/10/10/mii.html) * [2022/09] [ZeRO-Inference: Democratizing massive model inference](https://www.deepspeed.ai/2022/09/09/zero-inference.html) * [2022/07] [Azure and DeepSpeed empower easy-to-use and high-performance model training](https://azure.microsoft.com/en-us/blog/azure-empowers-easytouse-highperformance-and-hyperscale-model-training-using-deepspeed/) --- # Extreme Speed and Scale for DL Training and Inference ***[DeepSpeed](https://www.deepspeed.ai/) enables world's most powerful language models like [MT-530B](https://www.microsoft.com/en-us/research/blog/using-deepspeed-and-megatron-to-train-megatron-turing-nlg-530b-the-worlds-largest-and-most-powerful-generative-language-model/) and [BLOOM](https://huggingface.co/blog/bloom-megatron-deepspeed)***. It is an easy-to-use deep learning optimization software suite that powers unprecedented scale and speed for both training and inference. With DeepSpeed you can: * Train/Inference dense or sparse models with billions or trillions of parameters * Achieve excellent system throughput and efficiently scale to thousands of GPUs * Train/Inference on resource constrained GPU systems * Achieve unprecedented low latency and high throughput for inference * Achieve extreme compression for an unparalleled inference latency and model size reduction with low costs --- # DeepSpeed's three innovation pillars <img src="docs/assets/images/3pillars.png" width="800px"> ## DeepSpeed-Training DeepSpeed offers a confluence of system innovations, that has made large scale DL training effective, and efficient, greatly improved ease of use, and redefined the DL training landscape in terms of scale that is possible. These innovations such as ZeRO, 3D-Parallelism, DeepSpeed-MoE, ZeRO-Infinity, etc. fall under the training pillar. Learn more: [DeepSpeed-Training](https://www.deepspeed.ai/training/) ## DeepSpeed-Inference DeepSpeed brings together innovations in parallelism technology such as tensor, pipeline, expert and ZeRO-parallelism, and combines them with high performance custom inference kernels, communication optimizations and heterogeneous memory technologies to enable inference at an unprecedented scale, while achieving unparalleled latency, throughput and cost reduction. This systematic composition of system technologies for inference falls under the inference pillar. Learn more: [DeepSpeed-Inference](https://www.deepspeed.ai/inference) ## DeepSpeed-Compression To further increase the inference efficiency, DeepSpeed offers easy-to-use and flexible-to-compose compression techniques for researchers and practitioners to compress their models while delivering faster speed, smaller model size, and significantly reduced compression cost. Moreover, SoTA innovations on compression like ZeroQuant and XTC are included under the compression pillar. Learn more: [DeepSpeed-Compression](https://www.deepspeed.ai/compression) --- # DeepSpeed Software Suite ## DeepSpeed Library The [DeepSpeed](https://github.com/microsoft/deepspeed) library (this repository) implements and packages the innovations and technologies in DeepSpeed Training, Inference and Compression Pillars into a single easy-to-use, open-sourced repository. It allows for easy composition of multitude of features within a single training, inference or compression pipeline. The DeepSpeed Library is heavily adopted by the DL community, and has been used to enable some of the most powerful models (see [DeepSpeed Adoption](#deepspeed-adoption)). ## Model Implementations for Inference (MII) [Model Implementations for Inference (MII)](https://github.com/microsoft/deepspeed-mii) is an open-sourced repository for making low-latency and high-throughput inference accessible to all data scientists by alleviating the need to apply complex system optimization techniques themselves. Out-of-box, MII offers support for thousands of widely used DL models, optimized using DeepSpeed-Inference, that can be deployed with a few lines of code, while achieving significant latency reduction compared to their vanilla open-sourced versions. ## DeepSpeed on Azure DeepSpeed users are diverse and have access to different environments. We recommend to try DeepSpeed on Azure as it is the simplest and easiest method. The recommended method to try DeepSpeed on Azure is through AzureML [recipes](https://github.com/Azure/azureml-examples/tree/main/v1/python-sdk/workflows/train/deepspeed). The job submission and data preparation scripts have been made available [here](https://github.com/microsoft/Megatron-DeepSpeed/tree/main/examples/azureml). For more details on how to use DeepSpeed on Azure, please follow the [Azure tutorial](https://www.deepspeed.ai/tutorials/azure/). --- # DeepSpeed Adoption DeepSpeed is an important part of Microsoft’s new [AI at Scale](https://www.microsoft.com/en-us/research/project/ai-at-scale/) initiative to enable next-generation AI capabilities at scale, where you can find more information [here](https://innovation.microsoft.com/en-us/exploring-ai-at-scale). DeepSpeed has been used to train many different large-scale models, below is a list of several examples that we are aware of (if you'd like to include your model please submit a PR): * [Megatron-Turing NLG (530B)](https://www.microsoft.com/en-us/research/blog/using-deepspeed-and-megatron-to-train-megatron-turing-nlg-530b-the-worlds-largest-and-most-powerful-generative-language-model/) * [Jurassic-1 (178B)](https://uploads-ssl.webflow.com/60fd4503684b466578c0d307/61138924626a6981ee09caf6_jurassic_tech_paper.pdf) * [BLOOM (176B)](https://huggingface.co/blog/bloom-megatron-deepspeed) * [GLM (130B)](https://github.com/THUDM/GLM-130B) * [YaLM (100B)](https://github.com/yandex/YaLM-100B) * [GPT-NeoX (20B)](https://github.com/EleutherAI/gpt-neox) * [AlexaTM (20B)](https://www.amazon.science/blog/20b-parameter-alexa-model-sets-new-marks-in-few-shot-learning) * [Turing NLG (17B)](https://www.microsoft.com/en-us/research/blog/turing-nlg-a-17-billion-parameter-language-model-by-microsoft/) * [METRO-LM (5.4B)](https://arxiv.org/pdf/2204.06644.pdf) DeepSpeed has been integrated with several different popular open-source DL frameworks such as: | | Documentation | | ---------------------------------------------------------------------------------------------- | -------------------------------------------- | <img src="docs/assets/images/transformers-light.png#gh-light-mode-only" width="250px"><img src="docs/assets/images/transformers-dark.png#gh-dark-mode-only" width="250px"> | [Transformers with DeepSpeed](https://huggingface.co/docs/transformers/main/main_classes/deepspeed) | | <img src="docs/assets/images/accelerate-light.png#gh-light-mode-only" width="250px"><img src="docs/assets/images/accelerate-dark.png#gh-dark-mode-only" width="250px"> | [Accelerate with DeepSpeed](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) | | <img src="docs/assets/images/lightning-light.svg#gh-light-mode-only" width="200px"><img src="docs/assets/images/lightning-dark.svg#gh-dark-mode-only" width="200px"> | [Lightning with DeepSpeed](https://lightning.ai/docs/pytorch/stable/advanced/model_parallel.html#deepspeed) | | <img src="docs/assets/images/mosaicml.svg" width="200px"> | [MosaicML with DeepSpeed](https://docs.mosaicml.com/projects/composer/en/latest/trainer/using_the_trainer.html?highlight=deepspeed#deepspeed-integration) | | <img src="docs/assets/images/determined.svg" width="225px"> | [Determined with DeepSpeed](https://docs.determined.ai/latest/training/apis-howto/deepspeed/overview.html) | --- # Build Pipeline Status | Description | Status | | ----------- | ------ | | NVIDIA | [![nv-torch19-p40](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch19-p40.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch19-p40.yml) [![nv-torch19-v100](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch19-v100.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch19-v100.yml) [![nv-torch-latest-v100](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch-latest-v100.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch-latest-v100.yml) [![nv-inference](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-inference.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-inference.yml) [![nv-nightly](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-nightly.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-nightly.yml) | | AMD | [![amd-mi100](https://github.com/microsoft/DeepSpeed/actions/workflows/amd-mi100.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/amd-mi100.yml) [![amd-mi200](https://github.com/microsoft/DeepSpeed/actions/workflows/amd-mi200.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/amd-mi200.yml) | | CPU | [![nv-torch-latest-cpu](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch-latest-cpu.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch-latest-cpu.yml) | | PyTorch Nightly | [![nv-torch-nightly-v100](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch-nightly-v100.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-torch-nightly-v100.yml) | | Integrations | [![nv-transformers-v100](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-transformers-v100.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-transformers-v100.yml) [![nv-lightning-v100](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-lightning-v100.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-lightning-v100.yml) [![nv-accelerate-v100](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-accelerate-v100.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-accelerate-v100.yml)[![nv-megatron](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-megatron.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-megatron.yml)[![nv-mii](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-mii.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/nv-mii.yml) | | Misc | [![Formatting](https://github.com/microsoft/DeepSpeed/actions/workflows/formatting.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/formatting.yml) [![pages-build-deployment](https://github.com/microsoft/DeepSpeed/actions/workflows/pages/pages-build-deployment/badge.svg)](https://github.com/microsoft/DeepSpeed/actions/workflows/pages/pages-build-deployment) [![Documentation Status](https://readthedocs.org/projects/deepspeed/badge/?version=latest)](https://deepspeed.readthedocs.io/en/latest/?badge=latest)[![python](https://github.com/microsoft/DeepSpeed/actions/workflows/python.yml/badge.svg?branch=master)](https://github.com/microsoft/DeepSpeed/actions/workflows/python.yml) | # Installation The quickest way to get started with DeepSpeed is via pip, this will install the latest release of DeepSpeed which is not tied to specific PyTorch or CUDA versions. DeepSpeed includes several C++/CUDA extensions that we commonly refer to as our 'ops'. By default, all of these extensions/ops will be built just-in-time (JIT) using [torch's JIT C++ extension loader that relies on ninja](https://pytorch.org/docs/stable/cpp_extension.html) to build and dynamically link them at runtime. ## Requirements * [PyTorch](https://pytorch.org/) must be installed _before_ installing DeepSpeed. * For full feature support we recommend a version of PyTorch that is >= 1.9 and ideally the latest PyTorch stable release. * A CUDA or ROCm compiler such as [nvcc](https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/#introduction) or [hipcc](https://github.com/ROCm-Developer-Tools/HIPCC) used to compile C++/CUDA/HIP extensions. * Specific GPUs we develop and test against are listed below, this doesn't mean your GPU will not work if it doesn't fall into this category it's just DeepSpeed is most well tested on the following: * NVIDIA: Pascal, Volta, Ampere, and Hopper architectures * AMD: MI100 and MI200 ## PyPI We regularly push releases to [PyPI](https://pypi.org/project/deepspeed/) and encourage users to install from there in most cases. ```bash pip install deepspeed ``` After installation, you can validate your install and see which extensions/ops your machine is compatible with via the DeepSpeed environment report. ```bash ds_report ``` If you would like to pre-install any of the DeepSpeed extensions/ops (instead of JIT compiling) or install pre-compiled ops via PyPI please see our [advanced installation instructions](https://www.deepspeed.ai/tutorials/advanced-install/). ## Windows Windows support is partially supported with DeepSpeed. On Windows you can build wheel with following steps, currently only inference mode is supported. 1. Install pytorch, such as pytorch 1.8 + cuda 11.1 2. Install visual cpp build tools, such as VS2019 C++ x64/x86 build tools 3. Launch cmd console with Administrator privilege for creating required symlink folders 4. Run `python setup.py bdist_wheel` to build wheel in `dist` folder # Features Please checkout [DeepSpeed-Training](https://www.deepspeed.ai/training), [DeepSpeed-Inference](https://www.deepspeed.ai/inference) and [DeepSpeed-Compression](https://www.deepspeed.ai/compression) pages for full set of features offered along each of these three pillars. # Further Reading All DeepSpeed documentation, tutorials, and blogs can be found on our website: [deepspeed.ai](https://www.deepspeed.ai/) | | Description | | ---------------------------------------------------------------------------------------------- | -------------------------------------------- | | [Getting Started](https://www.deepspeed.ai/getting-started/) | First steps with DeepSpeed | | [DeepSpeed JSON Configuration](https://www.deepspeed.ai/docs/config-json/) | Configuring DeepSpeed | | [API Documentation](https://deepspeed.readthedocs.io/en/latest/) | Generated DeepSpeed API documentation | | [Tutorials](https://www.deepspeed.ai/tutorials/) | Tutorials | | [Blogs](https://www.deepspeed.ai/posts/) | Blogs | # Contributing DeepSpeed welcomes your contributions! Please see our [contributing](CONTRIBUTING.md) guide for more details on formatting, testing, etc.<br/> Thanks so much to all of our amazing contributors! <a href="https://github.com/microsoft/DeepSpeed/graphs/contributors"> <img src="https://contrib.rocks/image?repo=microsoft/DeepSpeed&r=" width="800px"/> </a> ## Contributor License Agreement This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. ## Code of Conduct This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. # Publications 1. Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He. (2019) ZeRO: memory optimizations toward training trillion parameter models. [arXiv:1910.02054](https://arxiv.org/abs/1910.02054) and [In Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC '20)](https://dl.acm.org/doi/10.5555/3433701.3433727). 2. Jeff Rasley, Samyam Rajbhandari, Olatunji Ruwase, and Yuxiong He. (2020) DeepSpeed: System Optimizations Enable Training Deep Learning Models with Over 100 Billion Parameters. [In Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining (KDD '20, Tutorial)](https://dl.acm.org/doi/10.1145/3394486.3406703). 3. Minjia Zhang, Yuxiong He. (2020) Accelerating Training of Transformer-Based Language Models with Progressive Layer Dropping. [arXiv:2010.13369](https://arxiv.org/abs/2010.13369) and [NeurIPS 2020](https://proceedings.neurips.cc/paper/2020/hash/a1140a3d0df1c81e24ae954d935e8926-Abstract.html). 4. Jie Ren, Samyam Rajbhandari, Reza Yazdani Aminabadi, Olatunji Ruwase, Shuangyan Yang, Minjia Zhang, Dong Li, Yuxiong He. (2021) ZeRO-Offload: Democratizing Billion-Scale Model Training. [arXiv:2101.06840](https://arxiv.org/abs/2101.06840) and [USENIX ATC 2021](https://www.usenix.org/conference/atc21/presentation/ren-jie). 5. Hanlin Tang, Shaoduo Gan, Ammar Ahmad Awan, Samyam Rajbhandari, Conglong Li, Xiangru Lian, Ji Liu, Ce Zhang, Yuxiong He. (2021) 1-bit Adam: Communication Efficient Large-Scale Training with Adam's Convergence Speed. [arXiv:2102.02888](https://arxiv.org/abs/2102.02888) and [ICML 2021](http://proceedings.mlr.press/v139/tang21a.html). 6. Samyam Rajbhandari, Olatunji Ruwase, Jeff Rasley, Shaden Smith, Yuxiong He. (2021) ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning. [arXiv:2104.07857](https://arxiv.org/abs/2104.07857) and [SC 2021](https://dl.acm.org/doi/abs/10.1145/3458817.3476205). 7. Conglong Li, Ammar Ahmad Awan, Hanlin Tang, Samyam Rajbhandari, Yuxiong He. (2021) 1-bit LAMB: Communication Efficient Large-Scale Large-Batch Training with LAMB's Convergence Speed. [arXiv:2104.06069](https://arxiv.org/abs/2104.06069) and [HiPC 2022](https://hipc.org/advance-program/). 8. Conglong Li, Minjia Zhang, Yuxiong He. (2021) The Stability-Efficiency Dilemma: Investigating Sequence Length Warmup for Training GPT Models. [arXiv:2108.06084](https://arxiv.org/abs/2108.06084) and [NeurIPS 2022](https://openreview.net/forum?id=JpZ5du_Kdh). 9. Yucheng Lu, Conglong Li, Minjia Zhang, Christopher De Sa, Yuxiong He. (2022) Maximizing Communication Efficiency for Large-scale Training via 0/1 Adam. [arXiv:2202.06009](https://arxiv.org/abs/2202.06009). 10. Samyam Rajbhandari, Conglong Li, Zhewei Yao, Minjia Zhang, Reza Yazdani Aminabadi, Ammar Ahmad Awan, Jeff Rasley, Yuxiong He. (2022) DeepSpeed-MoE: Advancing Mixture-of-Experts Inference and Training to Power Next-Generation AI Scale [arXiv:2201.05596](https://arxiv.org/abs/2201.05596) and [ICML 2022](https://proceedings.mlr.press/v162/rajbhandari22a.html). 11. Shaden Smith, Mostofa Patwary, Brandon Norick, Patrick LeGresley, Samyam Rajbhandari, Jared Casper, Zhun Liu, Shrimai Prabhumoye, George Zerveas, Vijay Korthikanti, Elton Zhang, Rewon Child, Reza Yazdani Aminabadi, Julie Bernauer, Xia Song, Mohammad Shoeybi, Yuxiong He, Michael Houston, Saurabh Tiwary, Bryan Catanzaro. (2022) Using DeepSpeed and Megatron to Train Megatron-Turing NLG 530B, A Large-Scale Generative Language Model [arXiv:2201.11990](https://arxiv.org/abs/2201.11990). 12. Xiaoxia Wu, Zhewei Yao, Minjia Zhang, Conglong Li, Yuxiong He. (2022) Extreme Compression for Pre-trained Transformers Made Simple and Efficient. [arXiv:2206.01859](https://arxiv.org/abs/2206.01859) and [NeurIPS 2022](https://openreview.net/forum?id=xNeAhc2CNAl). 13. Zhewei Yao, Reza Yazdani Aminabadi, Minjia Zhang, Xiaoxia Wu, Conglong Li, Yuxiong He. (2022) ZeroQuant: Efficient and Affordable Post-Training Quantization for Large-Scale Transformers. [arXiv:2206.01861](https://arxiv.org/abs/2206.01861) and [NeurIPS 2022](https://openreview.net/forum?id=f-fVCElZ-G1). 14. Reza Yazdani Aminabadi, Samyam Rajbhandari, Minjia Zhang, Ammar Ahmad Awan, Cheng Li, Du Li, Elton Zheng, Jeff Rasley, Shaden Smith, Olatunji Ruwase, Yuxiong He. (2022) DeepSpeed Inference: Enabling Efficient Inference of Transformer Models at Unprecedented Scale. [arXiv:2207.00032](https://arxiv.org/abs/2207.00032) and [SC 2022](https://dl.acm.org/doi/abs/10.5555/3571885.3571946). 15. Zhewei Yao, Xiaoxia Wu, Conglong Li, Connor Holmes, Minjia Zhang, Cheng Li, Yuxiong He. (2022) Random-LTD: Random and Layerwise Token Dropping Brings Efficient Training for Large-scale Transformers. [arXiv:2211.11586](https://arxiv.org/abs/2211.11586). 16. Conglong Li, Zhewei Yao, Xiaoxia Wu, Minjia Zhang, Yuxiong He. (2022) DeepSpeed Data Efficiency: Improving Deep Learning Model Quality and Training Efficiency via Efficient Data Sampling and Routing. [arXiv:2212.03597](https://arxiv.org/abs/2212.03597). 17. Xiaoxia Wu, Cheng Li, Reza Yazdani Aminabadi, Zhewei Yao, Yuxiong He. (2023) Understanding INT4 Quantization for Transformer Models: Latency Speedup, Composability, and Failure Cases. [arXiv:2301.12017](https://arxiv.org/abs/2301.12017). 18. Syed Zawad, Cheng Li, Zhewei Yao, Elton Zheng, Yuxiong He, Feng Yan. (2023) DySR: Adaptive Super-Resolution via Algorithm and System Co-design. [ICLR:2023](https://openreview.net/forum?id=Pgtn4l6eKjv). 19. Sheng Shen, Zhewei Yao, Chunyuan Li, Trevor Darrell, Kurt Keutzer, Yuxiong He. (2023) Scaling Vision-Language Models with Sparse Mixture of Experts. [arXiv:2303.07226](https://arxiv.org/abs/2303.07226). 20. Quentin Anthony, Ammar Ahmad Awan, Jeff Rasley, Yuxiong He, Aamir Shafi, Mustafa Abduljabbar, Hari Subramoni, Dhabaleswar Panda. (2023) MCR-DL: Mix-and-Match Communication Runtime for Deep Learning [arXiv:2303.08374](https://arxiv.org/abs/2303.08374) and will appear at IPDPS 2023. # Videos 1. DeepSpeed KDD 2020 Tutorial 1. [Overview](https://www.youtube.com/watch?v=CaseqC45DNc&list=PLa85ZdUjfWS21mgibJ2vCvLziprjpKoW0&index=29) 2. [ZeRO + large model training](https://www.youtube.com/watch?v=y4_bCiAsIAk&list=PLa85ZdUjfWS21mgibJ2vCvLziprjpKoW0&index=28) 3. [17B T-NLG demo](https://www.youtube.com/watch?v=9V-ZbP92drg&list=PLa85ZdUjfWS21mgibJ2vCvLziprjpKoW0&index=27) 4. [Fastest BERT training + RScan tuning](https://www.youtube.com/watch?v=o1K-ZG9F6u0&list=PLa85ZdUjfWS21mgibJ2vCvLziprjpKoW0&index=26) 5. DeepSpeed hands on deep dive: [part 1](https://www.youtube.com/watch?v=_NOk-mBwDYg&list=PLa85ZdUjfWS21mgibJ2vCvLziprjpKoW0&index=92), [part 2](https://www.youtube.com/watch?v=sG6_c4VXLww&list=PLa85ZdUjfWS21mgibJ2vCvLziprjpKoW0&index=94), [part 3](https://www.youtube.com/watch?v=k9yPkBTayos&list=PLa85ZdUjfWS21mgibJ2vCvLziprjpKoW0&index=93) 6. [FAQ](https://www.youtube.com/watch?v=nsHu6vEgPew&list=PLa85ZdUjfWS21mgibJ2vCvLziprjpKoW0&index=24) 2. Microsoft Research Webinar * Registration is free and all videos are available on-demand. * [ZeRO & Fastest BERT: Increasing the scale and speed of deep learning training in DeepSpeed](https://note.microsoft.com/MSR-Webinar-DeepSpeed-Registration-On-Demand.html). 3. [DeepSpeed on AzureML](https://youtu.be/yBVXR8G8Bg8) 4. Community Tutorials * [DeepSpeed: All the tricks to scale to gigantic models (Mark Saroufim)](https://www.youtube.com/watch?v=pDGI668pNg0) * [Turing-NLG, DeepSpeed and the ZeRO optimizer (Yannic Kilcher)](https://www.youtube.com/watch?v=tC01FRB0M7w) * [Ultimate Guide To Scaling ML Models (The AI Epiphany)](https://www.youtube.com/watch?v=hc0u4avAkuM)
Adeepspeed
/Adeepspeed-0.9.2.tar.gz/Adeepspeed-0.9.2/README.md
README.md
# DeepSpeed Team import torch import deepspeed import subprocess import argparse from .ops.op_builder.all_ops import ALL_OPS from .git_version_info import installed_ops, torch_info from deepspeed.accelerator import get_accelerator GREEN = '\033[92m' RED = '\033[91m' YELLOW = '\033[93m' END = '\033[0m' SUCCESS = f"{GREEN} [SUCCESS] {END}" OKAY = f"{GREEN}[OKAY]{END}" WARNING = f"{YELLOW}[WARNING]{END}" FAIL = f'{RED}[FAIL]{END}' INFO = '[INFO]' color_len = len(GREEN) + len(END) okay = f"{GREEN}[OKAY]{END}" warning = f"{YELLOW}[WARNING]{END}" def op_report(verbose=True): max_dots = 23 max_dots2 = 11 h = ["op name", "installed", "compatible"] print("-" * (max_dots + max_dots2 + len(h[0]) + len(h[1]))) print("DeepSpeed C++/CUDA extension op report") print("-" * (max_dots + max_dots2 + len(h[0]) + len(h[1]))) print("NOTE: Ops not installed will be just-in-time (JIT) compiled at\n" " runtime if needed. Op compatibility means that your system\n" " meet the required dependencies to JIT install the op.") print("-" * (max_dots + max_dots2 + len(h[0]) + len(h[1]))) print("JIT compiled ops requires ninja") ninja_status = OKAY if ninja_installed() else FAIL print('ninja', "." * (max_dots - 5), ninja_status) print("-" * (max_dots + max_dots2 + len(h[0]) + len(h[1]))) print(h[0], "." * (max_dots - len(h[0])), h[1], "." * (max_dots2 - len(h[1])), h[2]) print("-" * (max_dots + max_dots2 + len(h[0]) + len(h[1]))) installed = f"{GREEN}[YES]{END}" no = f"{YELLOW}[NO]{END}" for op_name, builder in ALL_OPS.items(): dots = "." * (max_dots - len(op_name)) is_compatible = OKAY if builder.is_compatible(verbose) else no is_installed = installed if installed_ops[op_name] else no dots2 = '.' * ((len(h[1]) + (max_dots2 - len(h[1]))) - (len(is_installed) - color_len)) print(op_name, dots, is_installed, dots2, is_compatible) print("-" * (max_dots + max_dots2 + len(h[0]) + len(h[1]))) def ninja_installed(): try: import ninja # noqa: F401 except ImportError: return False return True def nvcc_version(): import torch.utils.cpp_extension cuda_home = torch.utils.cpp_extension.CUDA_HOME if cuda_home is None: return f"{RED} [FAIL] cannot find CUDA_HOME via torch.utils.cpp_extension.CUDA_HOME={torch.utils.cpp_extension.CUDA_HOME} {END}" try: output = subprocess.check_output([cuda_home + "/bin/nvcc", "-V"], universal_newlines=True) except FileNotFoundError: return f"{RED} [FAIL] nvcc missing {END}" output_split = output.split() release_idx = output_split.index("release") release = output_split[release_idx + 1].replace(',', '').split(".") return ".".join(release) def debug_report(): max_dots = 33 report = [("torch install path", torch.__path__), ("torch version", torch.__version__), ("deepspeed install path", deepspeed.__path__), ("deepspeed info", f"{deepspeed.__version__}, {deepspeed.__git_hash__}, {deepspeed.__git_branch__}")] if get_accelerator().device_name() == 'cuda': hip_version = getattr(torch.version, "hip", None) report.extend([("torch cuda version", torch.version.cuda), ("torch hip version", hip_version), ("nvcc version", (None if hip_version else nvcc_version())), ("deepspeed wheel compiled w.", f"torch {torch_info['version']}, " + (f"hip {torch_info['hip_version']}" if hip_version else f"cuda {torch_info['cuda_version']}")) ]) else: report.extend([("deepspeed wheel compiled w.", f"torch {torch_info['version']} ")]) print("DeepSpeed general environment info:") for name, value in report: print(name, "." * (max_dots - len(name)), value) def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--hide_operator_status', action='store_true', help='Suppress display of installation and compatibility statuses of DeepSpeed operators. ') parser.add_argument('--hide_errors_and_warnings', action='store_true', help='Suppress warning and error messages.') args = parser.parse_args() return args def main(hide_operator_status=False, hide_errors_and_warnings=False): if not hide_operator_status: op_report(verbose=not hide_errors_and_warnings) debug_report() def cli_main(): args = parse_arguments() main(hide_operator_status=args.hide_operator_status, hide_errors_and_warnings=args.hide_errors_and_warnings) if __name__ == "__main__": main()
Adeepspeed
/Adeepspeed-0.9.2.tar.gz/Adeepspeed-0.9.2/deepspeed/env_report.py
env_report.py