def __init__(self, splash, cursor_bmp): logging.getLogger("Paint").debug("Creating a CursorPoller") self._mouse_cursor = Cursor( board.DISPLAY, display_group=splash, bmp=cursor_bmp, cursor_speed=2 ) self._x_offset = cursor_bmp.width // 2 self._y_offset = cursor_bmp.height // 2 self._cursor = DebouncedCursorManager(self._mouse_cursor) self._logger = logging.getLogger("Paint")
def __init__( self, socket, iface, id_scope: str, device_id: str, key: str, logger: Logger = None, ): """Creates an instance of the device registration service :param socket: The network socket :param str id_scope: The ID scope of the device to register :param str device_id: The device ID of the device to register :param str key: The primary or secondary key of the device to register :param adafruit_logging.Logger logger: The logger to use to log messages """ self._id_scope = id_scope self._device_id = device_id self._key = key self._logger = logger if logger is not None else logging.getLogger( "log") self._mqtt = None self._auth_response_received = False self._operation_id = None self._hostname = None self._socket = socket self._iface = iface
def __init__(self, network_manager, secrets, log=False): # Validate NetworkManager network_manager_type = str(type(network_manager)) if "ESPSPI_WiFiManager" in network_manager_type: self._wifi = network_manager else: raise TypeError("This library requires a NetworkManager object.") # Validate Secrets if hasattr(secrets, "keys"): self._secrets = secrets else: raise AttributeError( "Project settings are kept in secrets.py, please add them there!" ) self._logger = None if log is True: self._logger = logging.getLogger("log") self._logger.setLevel(logging.DEBUG) # Configuration, from secrets file self._proj_id = secrets["project_id"] self._region = secrets["cloud_region"] self._reg_id = secrets["registry_id"] self._device_id = secrets["device_id"] self._private_key = secrets["private_key"] self.broker = "mqtt.googleapis.com" self.username = b"unused" self.cid = self.client_id
def attach_logger(self, logger_name="log"): """Initializes and attaches a logger to the MQTTClient. :param str logger_name: Name of the logger instance """ self.logger = logging.getLogger(logger_name) self.logger.setLevel(logging.INFO)
def __init__(self, motor_pin, port, baudrate=115200, timeout=1): '''Initilize RPLidar object for communicating with the sensor. Parameters port : busio.UART or str Serial port instance or name of the port to which the sensor is connected baudrate : int, optional Baudrate for serial connection (the default is 115200) timeout : float, optional Serial port connection timeout in seconds (the default is 1) ''' self.motor_pin = motor_pin self.port = port self.baudrate = baudrate self.timeout = timeout self.motor_running = False self.logger = logging.getLogger('rplidar') self.is_CP = not isinstance(port, str) if self.is_CP: _serial_port = port else: global serial import serial self.connect() self.start_motor()
def __connect(cs_pin, ready_pin, reset_pin, secrets) -> ESPSPI_WiFiManager: logger = logging.getLogger("log") spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, cs_pin, ready_pin, reset_pin) wifi = ESPSPI_WiFiManager(esp, secrets, attempts=5) MQTT.set_socket(socket, esp) logger.debug("MAC addr: " + ", ".join([hex(i) for i in esp.MAC_address])) logger.debug("Connecting to AP...") wifi.connect() logger.info("Connected to " + str(esp.ssid, "utf-8") + "\tRSSI: " + str(esp.rssi)) logger.debug("My IP address is " + esp.pretty_ip(esp.ip_address)) logger.debug("Setting time") ntp = NTP(esp) while not ntp.valid_time: ntp.set_time() logger.debug("Failed to obtain time, retrying in 1 second...") time.sleep(1) logger.info("Time: " + str(time.time())) return wifi
def _run_request_with_retry(url, body, headers): retry = 0 r = None logger = logging.getLogger("log") while retry < 10: gc.collect() try: logger.debug("Trying to send...") r = requests.post(url, data=body, headers=headers) if r.status_code != 200: raise CustomVisionError(r.text) break except RuntimeError as runtime_error: logger.info("Could not send data, retrying after 5 seconds: " + str(runtime_error)) retry = retry + 1 if retry >= 10: raise time.sleep(0.5) continue gc.collect() return r
def __init__(self, callback: IoTMQTTCallback, wifi_manager: ESPSPI_WiFiManager, hostname: str, device_id: str, key: str, token_expires: int = 21600, logger: logging = None): """Create the Azure IoT MQTT client :param wifi_manager: The WiFi manager :param IoTMQTTCallback callback: A callback class :param str hostname: The hostname of the MQTT broker to connect to, get this by registering the device :param str device_id: The device ID of the device to register :param str key: The primary or secondary key of the device to register :param int token_expires: The number of seconds till the token expires, defaults to 6 hours :param adafruit_logging logger: The logger """ self._wifi_manager = wifi_manager self._callback = callback self._mqtt_connected = False self._auth_response_received = False self._mqtts = None self._device_id = device_id self._hostname = hostname self._key = key self._token_expires = token_expires self._username = "******".format(self._hostname, device_id, self._iotc_api_version) self._passwd = self._gen_sas_token() self._logger = logger if logger is not None else logging.getLogger( "log")
def __init__( self, callback: IoTMQTTCallback, socket, iface, hostname: str, device_id: str, key: str, token_expires: int = 21600, logger: logging = None, ): """Create the Azure IoT MQTT client :param IoTMQTTCallback callback: A callback class :param socket: The socket to communicate over :param iface: The network interface to communicate over :param str hostname: The hostname of the MQTT broker to connect to, get this by registering the device :param str device_id: The device ID of the device to register :param str key: The primary or secondary key of the device to register :param int token_expires: The number of seconds till the token expires, defaults to 6 hours :param adafruit_logging logger: The logger """ self._callback = callback self._socket = socket self._iface = iface self._mqtt_connected = False self._auth_response_received = False self._mqtts = None self._device_id = device_id self._hostname = hostname self._key = key self._token_expires = token_expires self._username = "******".format(self._hostname, device_id, constants.IOTC_API_VERSION) self._passwd = self._gen_sas_token() self._logger = logger if logger is not None else logging.getLogger("log") self._is_subscribed_to_twins = False
def __init__(self, display=board.DISPLAY): self._logger = logging.getLogger("Paint") self._logger.setLevel(logging.DEBUG) self._display = display self._w = self._display.width self._h = self._display.height self._x = self._w // 2 self._y = self._h // 2 self._splash = displayio.Group(max_size=5) self._bg_bitmap = displayio.Bitmap(self._w, self._h, 1) self._bg_palette = displayio.Palette(1) self._bg_palette[0] = Color.BLACK self._bg_sprite = displayio.TileGrid(self._bg_bitmap, pixel_shader=self._bg_palette, x=0, y=0) self._splash.append(self._bg_sprite) self._palette_bitmap = displayio.Bitmap(self._w, self._h, 5) self._palette_palette = displayio.Palette(len(Color.colors)) for i, c in enumerate(Color.colors): self._palette_palette[i] = c self._palette_sprite = displayio.TileGrid( self._palette_bitmap, pixel_shader=self._palette_palette, x=0, y=0) self._splash.append(self._palette_sprite) self._fg_bitmap = displayio.Bitmap(self._w, self._h, 5) self._fg_palette = displayio.Palette(len(Color.colors)) for i, c in enumerate(Color.colors): self._fg_palette[i] = c self._fg_sprite = displayio.TileGrid(self._fg_bitmap, pixel_shader=self._fg_palette, x=0, y=0) self._splash.append(self._fg_sprite) self._color_palette = self._make_color_palette() self._splash.append(self._color_palette) self._display.show(self._splash) self._display.refresh_soon() gc.collect() self._display.wait_for_frame() if hasattr(board, 'TOUCH_XL'): self._poller = TouchscreenPoller(self._splash, self._cursor_bitmap()) elif hasattr(board, 'BUTTON_CLOCK'): self._poller = CursorPoller(self._splash, self._cursor_bitmap()) else: raise AttributeError('PYOA requires a touchscreen or cursor.') self._pressed = False self._last_pressed = False self._location = None self._last_location = None self._pencolor = 7
def __init__(self, display=board.DISPLAY): self._logger = logging.getLogger("Turtle") self._logger.setLevel(logging.DEBUG) self._display = display self._w = self._display.width self._h = self._display.height self._x = self._w // 2 self._y = self._h // 2 self._speed = 6 self._heading = 90 self._logomode = False self._splash = displayio.Group(max_size=3) self._bg_bitmap = displayio.Bitmap(self._w, self._h, 1) self._bg_palette = displayio.Palette(1) self._bg_palette[0] = Color.BLACK self._bg_sprite = displayio.TileGrid(self._bg_bitmap, pixel_shader=self._bg_palette, x=0, y=0) self._splash.append(self._bg_sprite) self._fg_bitmap = displayio.Bitmap(self._w, self._h, 5) self._fg_palette = displayio.Palette(len(Color.colors) + 1) self._fg_palette.make_transparent(0) for i, c in enumerate(Color.colors): self._fg_palette[i + 1] = c self._fg_sprite = displayio.TileGrid(self._fg_bitmap, pixel_shader=self._fg_palette, x=0, y=0) self._splash.append(self._fg_sprite) self._turtle_bitmap = displayio.Bitmap(9, 9, 2) self._turtle_palette = displayio.Palette(2) self._turtle_palette.make_transparent(0) self._turtle_palette[1] = Color.WHITE for i in range(4): self._turtle_bitmap[4 - i, i] = 1 self._turtle_bitmap[i, 4 + i] = 1 self._turtle_bitmap[4 + i, 7 - i] = 1 self._turtle_bitmap[4 + i, i] = 1 self._turtle_sprite = displayio.TileGrid( self._turtle_bitmap, pixel_shader=self._turtle_palette, x=-100, y=-100) self._drawturtle() self._splash.append(self._turtle_sprite) self._penstate = False self._pencolor = None self.pencolor(Color.WHITE) self._display.show(self._splash) self._display.refresh_soon() gc.collect() self._display.wait_for_frame()
def __init__(self, splash, cursor_bmp): logging.getLogger('Paint').debug('Creating a TouchscreenPoller') self._display_grp = splash self._touchscreen = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR, board.TOUCH_YD, board.TOUCH_YU, calibration=((9000, 59000), (8000, 57000)), size=(320, 240)) self._cursor_grp = displayio.Group(max_size=1) self._cur_palette = displayio.Palette(3) self._cur_palette.make_transparent(0) self._cur_palette[1] = 0xFFFFFF self._cur_palette[2] = 0x0000 self._cur_sprite = displayio.TileGrid(cursor_bmp, pixel_shader=self._cur_palette) self._cursor_grp.append(self._cur_sprite) self._display_grp.append(self._cursor_grp) self._x_offset = cursor_bmp.width // 2 self._y_offset = cursor_bmp.height // 2
def __init__( self, socket, iface, device_connection_string: str, token_expires: int = 21600, logger: logging = None, ): """Create the Azure IoT Central device client :param socket: The network socket :param iface: The network interface :param str device_connection_string: The Iot Hub device connection string :param int token_expires: The number of seconds till the token expires, defaults to 6 hours :param adafruit_logging logger: The logger """ self._socket = socket self._iface = iface self._token_expires = token_expires self._logger = logger if logger is not None else logging.getLogger( "log") connection_string_values = {} try: cs_args = device_connection_string.split(DELIMITER) connection_string_values = dict( arg.split(VALUE_SEPARATOR, 1) for arg in cs_args) except (ValueError, AttributeError) as e: raise ValueError( "Connection string is required and should not be empty or blank and must be supplied as a string" ) from e if len(cs_args) != len(connection_string_values): raise ValueError("Invalid Connection String - Unable to parse") _validate_keys(connection_string_values) self._hostname = connection_string_values[HOST_NAME] self._device_id = connection_string_values[DEVICE_ID] self._shared_access_key = connection_string_values[SHARED_ACCESS_KEY] self._logger.debug("Hostname: " + self._hostname) self._logger.debug("Device Id: " + self._device_id) self._logger.debug("Shared Access Key: " + self._shared_access_key) self._on_connection_status_changed = None self._on_direct_method_invoked = None self._on_cloud_to_device_message_received = None self._on_device_twin_desired_updated = None self._on_device_twin_reported_updated = None self._mqtt = None
def __init__(self, mode=BMP085_STANDARD, address=BMP085_I2CADDR, i2c=None, **kwargs): self._logger = logging.getLogger('Adafruit_BMP.BMP085') self._logger.setLevel(logging.ERROR) # Check that mode is valid. if mode not in [BMP085_ULTRALOWPOWER, BMP085_STANDARD, BMP085_HIGHRES, BMP085_ULTRAHIGHRES]: raise ValueError('Unexpected mode value {0}. Set mode to one of BMP085_ULTRALOWPOWER, BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES'.format(mode)) self._mode = mode self._address = address if (i2c == None): # Create I2C device. i2c = busio.I2C(board.SCL, board.SDA) self._device = I2CDevice(i2c, address) # Load calibration values. self._load_calibration()
def __init__(self, socket, id_scope: str, device_id: str, key: str, logger: Logger = None): """Creates an instance of the device registration service :param socket: The network socket :param str id_scope: The ID scope of the device to register :param str device_id: The device ID of the device to register :param str key: The primary or secondary key of the device to register :param adafruit_logging.Logger logger: The logger to use to log messages """ self._id_scope = id_scope self._device_id = device_id self._key = key self._logger = logger if logger is not None else logging.getLogger("log") requests.set_socket(socket)
def __init__( self, socket, iface, id_scope: str, device_id: str, key: str, token_expires: int = 21600, logger: logging = None, ): """Create the Azure IoT Central device client :param socket: The network socket :param iface: The network interface :param str id_scope: The ID Scope of the device in IoT Central :param str device_id: The device ID of the device in IoT Central :param str key: The primary or secondary key of the device in IoT Central :param int token_expires: The number of seconds till the token expires, defaults to 6 hours :param adafruit_logging logger: The logger """ self._socket = socket self._iface = iface self._id_scope = id_scope self._device_id = device_id self._key = key self._token_expires = token_expires self._logger = logger if logger is not None else logging.getLogger( "log") self._device_registration = None self._mqtt = None self.on_connection_status_changed = None """A callback method that is called when the connection status is changed. This method should have the following signature: def connection_status_changed(connected: bool) -> None """ self.on_command_executed = None """A callback method that is called when a command is executed on the device. This method should have the following signature: def connection_status_changed(method_name: str, payload: str) -> IoTResponse: This method returns an IoTResponse containing a status code and message from the command call. Set this appropriately depending on if the command was successfully handled or not. For example, if the command was handled successfully, set the code to 200 and message to "OK": return IoTResponse(200, "OK") """ self.on_property_changed = None """A callback method that is called when property values are updated. This method should have the following signature:
def __init__( self, device_name="EnviroPlus", debug=False ): self.current_time = time.monotonic() self.logger = logging.getLogger('enviro+') self.device_name = device_name self.debug = debug self.connected = False if self.debug: self.logger.set_logger_level("DEBUG") else: self.logger.set_logger_level("INFO") self._setup_wifi()
def __init__(self, wifi_manager: ESPSPI_WiFiManager, id_scope: str, device_id: str, key: str, logger: Logger = None): """Creates an instance of the device registration :param wifi_manager: WiFiManager object from ESPSPI_WiFiManager. :param str id_scope: The ID scope of the device to register :param str device_id: The device ID of the device to register :param str key: The primary or secondary key of the device to register :param adafruit_logging.Logger key: The primary or secondary key of the device to register """ wifi_type = str(type(wifi_manager)) if "ESPSPI_WiFiManager" not in wifi_type: raise TypeError("This library requires a WiFiManager object.") self._wifi_manager = wifi_manager self._id_scope = id_scope self._device_id = device_id self._key = key self._logger = logger if logger is not None else logging.getLogger("log")
def __init__( self, update_timeout=2.0, debug=False ): self.current_time = time.monotonic() self.logger = logging.getLogger('enviro+') self.state = WAITING self.prev_state = self.state self.readings = SensorData() self.update_timeout = update_timeout self.calibration_timeout = 30.0 * 60 self.last_update_time = 0 self.last_calibration_time = 0 self.debug = debug # callbacks self._on_update_callbacks = [] self._init_sensors()
def __init__(self, wifi_manager: ESPSPI_WiFiManager, device_connection_string: str, token_expires: int = 21600, logger: logging = None): self._token_expires = token_expires self._logger = logger if logger is not None else logging.getLogger( "log") self._wifi_manager = wifi_manager connection_string_values = {} try: cs_args = device_connection_string.split(DELIMITER) connection_string_values = dict( arg.split(VALUE_SEPARATOR, 1) for arg in cs_args) except (ValueError, AttributeError): raise ValueError( "Connection string is required and should not be empty or blank and must be supplied as a string" ) if len(cs_args) != len(connection_string_values): raise ValueError("Invalid Connection String - Unable to parse") _validate_keys(connection_string_values) self._hostname = connection_string_values[HOST_NAME] self._device_id = connection_string_values[DEVICE_ID] self._shared_access_key = connection_string_values[SHARED_ACCESS_KEY] self._logger.debug("Hostname: " + self._hostname) self._logger.debug("Device Id: " + self._device_id) self._logger.debug("Shared Access Key: " + self._shared_access_key) self.on_connection_status_changed = None self.on_direct_method_called = None self.on_cloud_to_device_message_received = None self.on_device_twin_desired_updated = None self.on_device_twin_reported_updated = None self._mqtt = None
def __init__(self, esp, secrets, log=False): self._esp = esp # Validate Secrets if hasattr(secrets, "keys"): self._secrets = secrets else: raise AttributeError( "Project settings are kept in secrets.py, please add them there!" ) self.logger = None if log is True: self.logger = logging.getLogger("log") self.logger.setLevel(logging.DEBUG) # Configuration, from secrets file self._proj_id = secrets["project_id"] self._region = secrets["cloud_region"] self._reg_id = secrets["registry_id"] self._device_id = secrets["device_id"] self._private_key = secrets["private_key"] self.broker = "mqtt.googleapis.com" self.username = b"unused" self.cid = self.client_id
""" import adafruit_logging as logging import adafruit_rsa.prime import adafruit_rsa.pem import adafruit_rsa.common import adafruit_rsa.randnum import adafruit_rsa.core __version__ = "1.2.3" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RSA.git" # pylint: disable=invalid-name, useless-object-inheritance, redefined-builtin, no-name-in-module, too-few-public-methods log = logging.getLogger(__name__) log.setLevel(logging.INFO) DEFAULT_EXPONENT = 65537 class AbstractKey(object): """Abstract superclass for private and public keys.""" __slots__ = ("n", "e") def __init__(self, n, e): self.n = n self.e = e @classmethod
#################### # Load the fonts time_font = bitmap_font.load_font('/fonts/Anton-Regular-104.bdf') time_font.load_glyphs(b'0123456789:') # pre-load glyphs for fast printing alarm_font = bitmap_font.load_font('/fonts/Helvetica-Bold-36.bdf') alarm_font.load_glyphs(b'0123456789:') temperature_font = bitmap_font.load_font('/fonts/Arial-16.bdf') temperature_font.load_glyphs(b'0123456789CF') #################### # Set up logging logger = logging.getLogger('alarm_clock') logger.setLevel(logging.ERROR) # change as desired #################### # Functions def create_text_areas(configs): """Given a list of area specifications, create and return test areas.""" text_areas = [] for cfg in configs: textarea = Label(cfg['font'], text=' '*cfg['size']) textarea.x = cfg['x'] textarea.y = cfg['y'] textarea.color = cfg['color'] text_areas.append(textarea) return text_areas
# SPDX-FileCopyrightText: 2021 Alec Delaney # SPDX-License-Identifier: MIT import board import busio from digitalio import DigitalInOut import storage import adafruit_sdcard import adafruit_logging as logging from adafruit_logging.extensions import FileHandler # Get chip select pin depending on the board, this one is for the Feather M4 Express sd_cs = board.D10 # Set up an SD card to write to spi = busio.SPI(board.SCK, board.MOSI, board.MISO) cs = DigitalInOut(sd_cs) sdcard = adafruit_sdcard.SDCard(spi, cs) vfs = storage.VfsFat(sdcard) storage.mount(vfs, "/sd") # Initialize log functionality log_filepath = "/sd/testlog.log" logger = logging.getLogger("testlog") file_handler = FileHandler(log_filepath) logger.addHandler(file_handler) logger.setLevel(logging.INFO) logger.info("Logger initialized!") logger.debug("You can even add debug statements to the log!")
import colours # imports import time from system import System from behaviours import Behaviours from forward_behaviour import ForwardBehaviour from whisker_behaviour import WhiskerBehaviour # from chase_behaviour import ChaseBehaviour # from run_away_behaviour import RunAwayBehaviour from wander_behaviour import WanderBehaviour import drive import adafruit_logging as logging logger = logging.getLogger('mouse') logger.setLevel(config.LOGGING_LEVEL) # Figure out if we're autonomous autonomous = False try: with open(config.LOG_FILE, 'w') as fp: # first, get rid of any previous log fp.write('Log\r\n') autonomous = True except OSError as e: pass # fake drive system if config.DEBUG is set and we're teathered. system = System(drive.make_drive(config.DEBUG and not autonomous))
# # Notes: # This is to be run using CircuitPython 5.x # Date: 15/05/2019 # Last Updated: 11/05/2020 (wallarug) import time import board import busio from digitalio import DigitalInOut, Direction from pulseio import PWMOut, PulseIn, PulseOut import adafruit_logging as logging logger = logging.getLogger('code') logger.setLevel(logging.INFO) # Customisation these variables DEBUG = False USB_SERIAL = False SMOOTHING_INTERVAL_IN_S = 0.025 ACCEL_RATE = 10 ## cannot have DEBUG and USB_SERIAL if USB_SERIAL: DEBUG = False ## functions def servo_duty_cycle(pulse_ms, frequency = 60): """
def __init__( self, broker, port=None, username=None, password=None, client_id=None, is_ssl=True, log=False, keep_alive=60, ): self._sock = None # broker try: # set broker IP self.broker = _the_interface.unpretty_ip(broker) except ValueError: # set broker URL self.broker = broker # port/ssl self.port = MQTT_TCP_PORT if is_ssl: self.port = MQTT_TLS_PORT if port is not None: self.port = port # session identifiers self.user = username # [MQTT-3.1.3.5] self.password = password if (self.password is not None and len(password.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT): raise MMQTTException("Password length is too large.") if client_id is not None: # user-defined client_id MAY allow client_id's > 23 bytes or # non-alpha-numeric characters self.client_id = client_id else: # assign a unique client_id self.client_id = "cpy{0}{1}".format( randint(0, int(time.monotonic() * 100) % 1000), randint(0, 99)) # generated client_id's enforce spec.'s length rules if len(self.client_id) > 23 or not self.client_id: raise ValueError( "MQTT Client ID must be between 1 and 23 bytes") self.keep_alive = keep_alive self.user_data = None self.logger = None if log is True: self.logger = logging.getLogger("log") self.logger.setLevel(logging.INFO) self._sock = None self._is_connected = False self._msg_size_lim = MQTT_MSG_SZ_LIM self._pid = 0 self._timestamp = 0 # List of subscribed topics, used for tracking self._subscribed_topics = [] # Server callbacks self.on_message = None self.on_connect = None self.on_disconnect = None self.on_publish = None self.on_subscribe = None self.on_unsubscribe = None self.last_will()
def __init__(self, display=None): if display: self._display = display else: try: self._display = board.DISPLAY except AttributeError: raise RuntimeError( "No display available. One must be provided.") self._logger = logging.getLogger("Turtle") self._logger.setLevel(logging.INFO) self._w = self._display.width self._h = self._display.height self._x = self._w // 2 self._y = self._h // 2 self._speed = 6 self._heading = 90 self._logomode = False self._fullcircle = 360.0 self._degreesPerAU = 1.0 self._mode = "standard" self._angleOffset = 0 self._splash = displayio.Group(max_size=3) self._bg_bitmap = displayio.Bitmap(self._w, self._h, 1) self._bg_palette = displayio.Palette(1) self._bg_palette[0] = Color.BLACK self._bg_sprite = displayio.TileGrid(self._bg_bitmap, pixel_shader=self._bg_palette, x=0, y=0) self._splash.append(self._bg_sprite) self._fg_bitmap = displayio.Bitmap(self._w, self._h, 5) self._fg_palette = displayio.Palette(len(Color.colors) + 1) self._fg_palette.make_transparent(0) for i, c in enumerate(Color.colors): self._fg_palette[i + 1] = c self._fg_sprite = displayio.TileGrid(self._fg_bitmap, pixel_shader=self._fg_palette, x=0, y=0) self._splash.append(self._fg_sprite) self._turtle_bitmap = displayio.Bitmap(9, 9, 2) self._turtle_palette = displayio.Palette(2) self._turtle_palette.make_transparent(0) self._turtle_palette[1] = Color.WHITE for i in range(4): self._turtle_bitmap[4 - i, i] = 1 self._turtle_bitmap[i, 4 + i] = 1 self._turtle_bitmap[4 + i, 7 - i] = 1 self._turtle_bitmap[4 + i, i] = 1 self._turtle_sprite = displayio.TileGrid( self._turtle_bitmap, pixel_shader=self._turtle_palette, x=-100, y=-100) self._drawturtle() self._splash.append(self._turtle_sprite) self._penstate = False self._pencolor = None self._pensize = 1 self.pencolor(Color.WHITE) self._display.show(self._splash) gc.collect()
# CircuitPython demo - Keyboard emulator import time import board import digitalio import usb_hid from adafruit_hid.keyboard import Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import Keycode import adafruit_logging as logging logger = logging.getLogger('macrolog') # A simple neat keyboard demo in CircuitPython # The pins we'll use, each will have an internal pullup, also defines the key order and count keypress_pins = [board.A3, board.A1, board.A2] # Our array of key objects key_pin_array = [] # https://circuitpython.readthedocs.io/projects/hid/en/latest/api.html#adafruit-hid-keycode-keycode # Any key may be entered as a single keycode, a string, or a list # Use a string to type out simple text - \t for tab \n for return \b for backspace # If using a list, the keys will be sent in order, to press two keys together (ie - shift+tab), make a list within the list keys_pressed = [ Keycode.TAB, [[Keycode.SHIFT, Keycode.TAB], Keycode.UP_ARROW], [Keycode.TAB, Keycode.UP_ARROW] ] if len(keys_pressed) < len(keypress_pins):
Adafruit invests time and resources providing this open source code. Please support Adafruit and open source hardware by purchasing products from Adafruit! Written by Dave Astels for Adafruit Industries Copyright (c) 2019 Adafruit Industries Licensed under the MIT license. All text above must be included in any redistribution. """ import time import adafruit_gps import adafruit_logging as logging logger = logging.getLogger('main') class Gps(object): def __init__(self, uart): self._gps = adafruit_gps.GPS(uart, debug=False) self._latitude = 0 self._longitude = 0 def begin(self): self._gps.send_command( b'PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') self._gps.send_command(b'PMTK220,1000') def get_fix(self): try: