Example #1
0
    def __init__(self, loop):
        # once pressed, and released; keys show up in this queue
        self._changes = Queue(24)
        self.key_pressed = ''

        self.debug = 0  # 0..2

        self.last_event_time = utime.ticks_ms()
Example #2
0
    def __init__(self):

        self.queue = Queue()
        self.msub = {}
        self.mpub = []
        self.run = False
        self.m_addr = "MQTT->"
        self.msg_sz = len(self.m_addr)
Example #3
0
    def __init__(self, loop):
        # once pressed, and released; keys show up in this queue
        self._changes = Queue(24)
        self.key_pressed = ''
        self._disabled = False

        self.debug = 0  # 0..2
        self.repeat_delay = 450  # (ms) time to wait before first key-repeat

        self.last_event_time = utime.ticks_ms()
Example #4
0
    def __init__(self, loop):
        # once pressed, and released; keys show up in this queue
        self._changes = Queue(24)
        self.key_pressed = ''
        self._disabled = False

        # hook needed for IRQ
        global _singleton
        assert not _singleton
        _singleton = self

        self.cols = [Pin(i) for i in ('COL0', 'COL1', 'COL2')]
        self.rows = [Pin(i) for i in ('ROW0', 'ROW1', 'ROW2', 'ROW3')]
        self.pins = self.cols + self.rows

        # Lots of tuning here:
        # - higher CTPH (high pulse length) helps w/ sensitivity and reliability
        # - decrease prescale to speed up acq, but to a point.
        # - CTPH+CTPL has big impact on overal sample time
        # - larger pulse prescale => more noise margin, MAYBE; but too slow to do own averaging
        #
        self.tsc = touch.Touch(channels=self.pins,
                               caps=['CS0', 'CS1', 'CS2'],
                               handler=self.irq,
                               float_unused=0,
                               CTPH=12,
                               CTPL=12,
                               pulse_prescale=4,
                               max_count=16383)

        self.debug = 0  # 0..2
        self.sensitivity = 1  # 0..2: 0=sensitive, 2=less-so
        self.baseline = None
        self.count = 0
        self.levels = array.array('I', (0 for i in range(NUM_PINS)))
        self.prev_levels = array.array('I', (0 for i in range(NUM_PINS)))
        self.scan_pin = 0

        self.last_event_time = utime.ticks_ms()

        self.trigger_baseline = False

        # Scan in random order, because tempest.
        # But Tempest? Scan order, when we scan completely, everytime,
        # doesn't reveal anything, and the difference between touch
        # vs no touch is a few millivolts anyway... but harmless?
        self.scan_order = list(range(7))
        shuffle(self.scan_order)

        # begin scanning sequence
        self.loop = loop
        self.start()
    def __init__(self) -> None:
        """
        MQTT Service for the tlvlp.iot project
        Handles the connection and communication with the server via an MQTT broker

        Currently it is using a blocking MQTT client with asynchronous co-routines. This results in blocking all the
        other coros for the duration of the connection (usually around 2-3s and the timeout is 15s)

        Tested on ESP32 MCUs
        """

        print("MQTT service - Initializing service")
        self.mqtt_client = None
        self.connection_in_progress = False
        self.message_queue_incoming = Queue(config.mqtt_queue_size)
        self.message_queue_outgoing = Queue(config.mqtt_queue_size)
        # Add scheduled tasks
        loop = asyncio.get_event_loop()
        loop.create_task(self.connection_checker_loop())
        loop.create_task(self.incoming_message_checker_loop())
        loop.create_task(self.outgoing_message_sender_loop())
        print("MQTT service - Service initialization complete")
Example #6
0
    def __init__(self, config, status_led=None, layout=TEL_12_KEY):
        """Initialise/Reinitialise the instance."""

        self.queue = Queue(maxsize=7)

        self.running = False

        self.led = status_led

        self.code_buffer = []

        self.config = config

        self.keys = layout

        self.key_state = [self.KEY_UP] * 16

        # Pins
        self.rows = [ 2, 3, 4, 5 ]
        self.cols = [ 34, 35, 36, 39 ]

        self.row_pins = [ Pin(pin_num, Pin.OUT) for pin_num in self.rows ]
        self.col_pins = [ Pin(pin_num, Pin.IN, Pin.PULL_DOWN) for pin_num in self.cols ]
Example #7
0
 def __init__(self):
     self.queue = Queue()
     self.msub = {}
     self.mpub = []
     self.sid = 0
Example #8
0
# aqtest.py Demo/test program for MicroPython library micropython-uasyncio.queues
# Author: Peter Hinch
# Copyright Peter Hinch 2017 Released under the MIT license

try:
    import asyncio_priority as asyncio
except ImportError:
    import uasyncio as asyncio

from uasyncio.queues import Queue

q = Queue()


async def slow_process():
    await asyncio.sleep(2)
    return 42


async def bar():
    print('Waiting for slow process.')
    result = await slow_process()
    print('Putting result onto queue')
    await q.put(result)  # Put result on q


async def foo():
    print("Running foo()")
    result = await (q.get())
    print('Result was {}'.format(result))
Example #9
0
async def main_task(loop):

    # initialize features
    connect()  # TOOD: write seperate function for wlan
    ntptime.settime()  # set time
    #config_num = init_dip_button()
    config_num = 5
    i2c = init_i2c()
    lan = init_lan()
    init_fan()

    print(config_num)

    # configs
    display_config = {
        'pin_r': 16,
        'pin_l': 17,
        'num_leds': 14,
        'update_rate': 1.5
    }
    sps30_config = {'i2c': i2c, 'lock': None, 'update_rate': 1.5}
    sht31_config = {'i2c': i2c, 'lock': None, 'update_rate': 1.5}
    logic_config = {'logic_pin': 33}
    mqtt_config = {'broker': '192.168.50.100'}

    f = open('config.json', 'r')
    configs = ujson.load(f)["config"]
    f.close()

    mode = configs[config_num]["mode"]
    thres = configs[config_num]["thres"]

    # initialize queues
    main_queue = Queue()
    display_queue = Queue()
    mqtt_queue = Queue()
    logic_queue = Queue()

    # initialize tasks
    display_instance = display_task(display_queue, display_config)
    mqtt_instance = mqtt_task(mqtt_queue, mqtt_config)
    sps30_instance = sps30_task(main_queue, sps30_config)
    sht31_instance = sht31_task(main_queue, sht31_config)
    logic_instance = logic_task(logic_queue, logic_config)

    # starting tasks
    loop.create_task(display_instance)
    loop.create_task(mqtt_instance)
    loop.create_task(sps30_instance)
    loop.create_task(sht31_instance)
    loop.create_task(logic_instance)

    print("Config: " + str(config_num))
    await display_queue.put(
        ('percent', config_num / 8))  # TODO: change config_num
    time.sleep(2)

    pm10_percent = 0
    co2_percent = 0
    voc_percent = 0

    while True:
        msg = await main_queue.get()
        data = msg[1]
        if msg[0] == 'sps30_info':
            #print(data)
            pass
        elif msg[0] == 'sps30_data':
            pm10_percent = data["pm10_mass"] / thres["pm10"]
            print("PM10: " + str(data["pm10_mass"]))
            await mqtt_queue.put(('pm', data))
        elif msg[0] == 'sht31_info':
            print(data)
        elif msg[0] == 'sht31_data':
            print(data)
        else:
            print('unkown message: ' + msg[0])

        display_percent = max(pm10_percent, co2_percent, voc_percent)
        if display_percent >= 1.0:
            await logic_queue.put(('on', ''))
        else:
            await logic_queue.put(('off', ''))
        await display_queue.put(('percent_smooth', display_percent))
Example #10
0
    def init(self,
             queue_size=QUEUE_SIZE_DEFAULT,
             start=START_DEFAULT,
             long_keypress_count=LONG_KEYPRESS_COUNT_DEFAULT):
        """Initialise/Reinitialise the instance."""

        ## Create the queue to push key events to.
        self.queue = Queue(maxsize=queue_size)

        self.running = start
        self.long_keypress_count = long_keypress_count

        ## The chars on the keypad
        keys = [
            '1',
            '2',
            '3',
            'A',
            '4',
            '5',
            '6',
            'B',
            '7',
            '8',
            '9',
            'C',
            '*',
            '0',
            '#',
            'D',
        ]

        ## The chars to display/return when the key is pressed down for a long time.
        self.chars_long = [
            'm',
            'i',
            'e',
            'a',
            'n',
            'j',
            'f',
            'b',
            'o',
            'k',
            'g',
            'c',
            'p',
            'l',
            'h',
            'd',
        ]

        ## Initialise all keys to the UP state.
        self.keys = [{
            'char': key,
            'state': self.KEY_UP,
            'down_count': 0
        } for key in keys]

        ## Pin names for rows and columns.
        self.rows = ['PD1', 'PD3', 'PD5', 'PD7']
        self.cols = ['PD9', 'PD11', 'PD13', 'PD15']

        ## Initialise row pins as outputs.
        self.row_pins = [Pin(pin_name, mode=Pin.OUT) for pin_name in self.rows]

        ## Initialise column pins as inputs.
        self.col_pins = [
            Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN)
            for pin_name in self.cols
        ]

        self.row_scan_delay_ms = 40 // len(self.rows)
Example #11
0
import pyb
import network

import led36
from lsm9ds1 import LSM9DS1

import uasyncio
from uasyncio.websocket.server import WSReader, WSWriter
from uasyncio.queues import Queue

import picoweb

import os

measurement_queue = Queue()


if pyb.SDCard().present():
    os.mount(pyb.SDCard(), '/sd')
    print("Mounted SD Card")
    print("/sd:", os.listdir("/sd/"))
    print("/sd/web:", os.listdir("/sd/web"))
else:
    print("No SD Card present!")


def init_led_tile():
    led36.brightness(100)
    led36.illu(0, 0, 0)