def __init__(self, self_addr, addr, serial, baud, launch_serial, receive, send, slave): print("Starting ISP_Server!") self.connected = False self.client_connected = False self.server = None self.client = None port = [2700, 2701] if slave: from ucollections import deque port = port[::-1] else: from collections import deque self.d_to_send = deque((), 128) self.d_to_write = deque((), 128) if receive: _thread.start_new_thread(self.connect, (self_addr, addr, port[0])) if send: _thread.start_new_thread(self.start_server, (self_addr, addr, port[1])) self.ser = isp_writer.open_serial(serial, baud) while not self.connected and not self.client_connected: sleep(0.2) _thread.start_new_thread(self.send, ()) _thread.start_new_thread(self.read_serial, ()) _thread.start_new_thread(self.receive, ()) _thread.start_new_thread(self.write_serial, ()) print("ISP_Server started!")
def __init__(self, runq_len=16, waitq_len=16, ioq_len=0): self.runq = ucollections.deque((), runq_len, True) self.ioq_len = ioq_len if ioq_len: self.ioq = ucollections.deque((), ioq_len, True) self._call_io = self._call_now else: self._call_io = self.call_soon self.waitq = utimeq.utimeq(waitq_len) # Current task being run. Task is a top-level coroutine scheduled # in the event loop (sub-coroutines executed transparently by # yield from/await, event loop "doesn't see" them). self.cur_task = None
def __init__(self, runq_len=16, waitq_len=16): self.runq = ucollections.deque((), runq_len, True) self.waitq = utimeq.utimeq(waitq_len) # Current task being run. Task is a top-level coroutine scheduled # in the event loop (sub-coroutines executed transparently by # yield from/await, event loop "doesn't see" them). self.cur_task = None
def __init__(self, columns, rows, uart_id, background=BLUE, foreground=YELLOW, enable_cursor=True): self.uart = UART(uart_id, 115200) self.key_buffer = deque((), 10) self.screen = Screen(columns, rows) self.screen.dirty.clear() self.screen_buffer = [[None] * columns for _ in range(rows)] self.input_stream = Stream(self.screen) self.lcd_device = LCD(rate=42000000) self.lcd = self.lcd_device.initCh(color=foreground, font='Amstrad_8', scale=1) self.foreground = foreground self.background = background self.lcd.fillMonocolor(background) self.rows = rows self.columns = columns self.show_cursor = True self.cursor_delay = 20 self.last_draw_cursor_time = time.ticks_ms() self.last_cursor_x = 0 self.last_cursor_y = 0 self.draw_cursor_in_progress = False self.enable_cursor = enable_cursor
def __init__(self): self._parser_state = self.PARSERSTATE_IDLE self._current_message_packet = None self._current_byte_counter = 0 self._current_integer = 0 # Micropython needs a defined size of deque self._packet_queue = deque((), 10)
def __init__(self, text=[""], scl_pin=22, sda_pin=21, width=128, height=64, max_queue=10): self.q = deque((), 10) self.scl_pin = scl_pin self.sda_pin = sda_pin self.width = width self.height = height self.enabled = True self.text = text self.p = sys.platform self.x_text = 0 self.y_text = 0 self.x_image = 10 self.y_image = 10 if self.p == "esp32": i2c = I2C(-1, scl=Pin(self.scl_pin), sda=Pin(self.sda_pin)) self.oled = ssd1306.SSD1306_I2C(self.width, self.height, i2c) self.clear() _loop = asyncio.get_event_loop() _loop.create_task(self.loop_process())
def __init__(self, states): self._state_table = states self._current_state = None self._queue = deque((), 100) self._queue_lock = _thread.allocate_lock() self._timer = None self._thread = None self._timer_callback = None
def __init__(self, input_stream, output_stream): """Constructor. input_stream and output_stream need to be (bytes) IO with non-blocking Read() and Write() binary functions.""" self._input_stream = input_stream self._output_stream = output_stream # Micropython needs a defined size of deque self._incoming_bytes_buffer = deque((), 300) # List/Deque of integers self._received_packet_parser = MessagePacketParser()
def __init__(self, i2c, address=0x40): pca9685.PCA9685.__init__(self, i2c, address) self.freq(1000) self.data_cache = () self.DataCache = deque(self.data_cache, 10) self.left_value = 0 self.right_value = 0 self.front_after = 0 self.left_right = 0
def __init__(self): self.tasks = deque((), 20) self.poller = select.poll() self.wait = {} self.tasks.append(self.micro_server()) self.led = Pin(0, Pin.OUT)
def __init__(self, pin=14, pull=None, active_state=1, bounce_ms=1000, event_loop=None): self.active_queue = deque((), 10) self.pin = pin self.pull = pull self.active_state = active_state self.bounce_ms = bounce_ms if event_loop: event_loop.create_task(self.check_changes())
def print_tail_from_jotter(self, n_lines): """Read and print the last n lines to stdout.""" try: tail_lines = deque((), n_lines) with open(self._filename, 'r') as f: line = f.readline() while line: l = line.rstrip("\n") tail_lines.append(l) line = f.readline() for l in tail_lines: print(l) except OSError: pass
def __init__(self, response_cb, events_cb, timer, device): self.response_cb = response_cb self.events_cb = events_cb self.us_timer = timer # Allocate a bound method reference for use in a callback # (see https://docs.micropython.org/en/latest/reference/isr_rules.html#creation-of-python-objects # and https://forum.micropython.org/viewtopic.php?f=2&t=4027&p=23118#p23118) self.on_timer_ref = self.on_timer self.device = device self.updates_queue = deque((), CC_UPDATES_QUEUE_SIZE) self.sync_counter = 0 self.handshake_attempts = 0 self.handshake_timeout = 0 self.dev_desc_timeout = 0 self.comm_state = WAITING_SYNCING self.sync_message = None self.protocol = CCProtocol()
def __init__(self, id = 2, baudrate=115200, timeout=5000, motoctl = 'X6'): self.uart = None self.motoctl = Pin(motoctl) self.motoctl_timer = Timer(2, freq = 20000) self.motoPWM_channel = self.motoctl_timer.channel(1, Timer.PWM, pin=self.motoctl) self.motoPWM_channel.pulse_width_percent(50) self.connect(id, baudrate, timeout) self._rxbuffer = bytearray(32) self._headings = array('H', [0 for i in range(READINGS_LENGTH)])#heading = heading[i]/64.0 self._distances = array('H', [0 for i in range(READINGS_LENGTH)])#distance = distance[i]/4.0 #in mm self._readings_index = 0 self._descriptor_queue = collections.deque((), 32) #File fifo self._next_data_type = None self._status = None self._error = None self._scanerrors = 0
def __init__(self, loop): super(MembraneNumpad, self).__init__(loop) # No idea how to pick a safe timer number. self.timer = pyb.Timer(7) self.cols = [ Pin(i, Pin.IN, pull=Pin.PULL_UP) for i in ('M2_COL0', 'M2_COL1', 'M2_COL2') ] self.rows = [ Pin(i, Pin.OUT_OD, value=0) for i in ('M2_ROW0', 'M2_ROW1', 'M2_ROW2', 'M2_ROW3') ] # We scan in random order, because Tempest. # - scanning only starts when something pressed # - complete scan is done before acting on what was measured self.scan_order = array.array('b', list(range(NUM_ROWS))) # each full scan is pushed onto this, only last one kept if overflow self.scans = deque((), 50, 0) # internal to timer irq handler self._history = None # see _start_scan self._scan_count = 0 self._cycle = 0 self.waiting_for_any = True # time of last press self.lp_time = 0 for c in self.cols: c.irq(self.anypress_irq, Pin.IRQ_FALLING | Pin.IRQ_RISING) # ready to start self.loop = loop
def __init__(self,temper_threshold=20): self.tasks=deque( () , 20) self.poller=select.poll() self.wait={} self.mail_sent=0 self.threshold=temper_threshold self.sensor=dht.DHT11(Pin(2)) try: self.sensor.measure() self.temp=self.sensor.temperature() self.hum=self.sensor.humidity() except: self.temp=0 self.hum=0 print("Can not measure") self.tasks.append(self.micro_server())
def __init__(self, my_id, server, port=8123, ssid='', pw='', timeout=2000, conn_cb=None, conn_cb_args=None, verbose=False, led=None, wdog=False): self._my_id = '{}{}'.format(my_id, '\n') # Ensure >= 1 newline self._server = server self._ssid = ssid self._pw = pw self._port = port self._to = timeout # Client and server timeout self._tim_short = timeout // 10 self._tim_ka = timeout // 4 # Keepalive interval self._concb = conn_cb self._concbargs = () if conn_cb_args is None else conn_cb_args self._verbose = verbose self._led = led if wdog: if platform == 'pyboard': self._wdt = machine.WDT(0, 20000) def wdt(): def inner(feed=0): # Ignore control values if not feed: self._wdt.feed() return inner self._feed = wdt() else: def wdt(secs=0): timer = machine.Timer(-1) timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=lambda t: self._feed()) cnt = secs run = False # Disable until 1st feed def inner(feed=WDT_CB): nonlocal cnt, run, timer if feed == 0: # Fixed timeout cnt = secs run = True elif feed < 0: # WDT control/callback if feed == WDT_CANCEL: timer.deinit() # Permanent cancellation elif feed == WDT_CB and run: # Timer callback and is running. cnt -= 1 if cnt <= 0: machine.reset() return inner self._feed = wdt(20) else: self._feed = lambda x: None self._sta_if = network.WLAN(network.STA_IF) ap = network.WLAN(network.AP_IF) # create access-point interface ap.active(False) # deactivate the interface self._sta_if.active(True) gc.collect() if platform == 'esp8266': import esp esp.sleep_type( esp.SLEEP_NONE ) # Improve connection integrity at cost of power consumption. self._evfail = asyncio.Event() self._s_lock = asyncio.Lock() # For internal send conflict. self._last_wr = utime.ticks_ms() self._lineq = deque((), 20, True) # 20 entries, throw on overflow self.connects = 0 # Connect count for test purposes/app access self._sock = None self._ok = False # Set after 1st successful read self._acks_pend = SetByte() # ACKs which are expected to be received gc.collect() asyncio.create_task(self._run())
# Tests for deques with "check overflow" flag and other extensions # wrt to CPython. try: try: from ucollections import deque except ImportError: from collections import deque except ImportError: print("SKIP") raise SystemExit # Initial sequence is not supported try: deque([1, 2, 3], 10) except ValueError: print("ValueError") # Not even empty list, only empty tuple try: deque([], 10) except ValueError: print("ValueError") # Only fixed-size deques are supported, so length arg is mandatory try: deque(()) except TypeError: print("TypeError") d = deque((), 2, True)
time.sleep(5) print("esperando publicar..") print(telemetry) def onRead(sensorObj, **kwargs): q = kwargs["queue"] telemetry = { "voltage": sensorObj.voltage, "current": sensorObj.current, "power": sensorObj.power } d.append(telemetry) print("Bus Voltage: %.3f V" % sensorObj.voltage) print("Current: %.3f mA" % sensorObj.current) print("Power: %.3f mW" % sensorObj.power) d = deque((), 11) kwargs = { "queue": d } #Crea hilo para lectura del sensor am2315 ina219 = INA219_(buffLen = 3, period = 5, sem = None, on_read = onRead, **kwargs) #Comienza lectura del sensor _thread.start_new_thread(ina219.run, ()) _thread.start_new_thread(lambda: publish_loop(**kwargs), ()) time.sleep(17) ina219.stop() # Detiene el sensor ina219.join() # Espera a que el sensor se detenga #ina219.start()
class Morse: encoding = { 'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '.': '.-.-.-', ',': '--..--', '?': '..--..', '!': '-.-.--', '/': '--.-.', '(': '-.--.', ')': '-.--.-', '&': '.-...', ':': '---...', ';': '-.-.-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '_': '..--.-', "'": '.----.', '"': '.-..-.', '$': '...-..-', '@': '.--.-.', ' ': '^' } colors = { 'R': 0x1f0000, 'O': 0x1f1000, 'Y': 0x1f1900, 'G': 0x000f00, 'B': 0x00001f, 'I': 0x090010, 'V': 0x1d101d, 'W': 0x1f1f1f } color = colors['W'] unit_len = 75 char_queue = deque((), 2048, 1) char_queue_lock = _thread.allocate_lock() beep = False def __init__(self, pin=0): print("Morse()") pycom.heartbeat(False) if pin != 0: self.pwm = machine.PWM(0, 1500) self.pwm_channel = self.pwm.channel(0, pin='P' + str(pin), duty_cycle=0.0) self.beep = True _thread.start_new_thread(lambda: self.output_loop(), ()) def add_to_queue(self, char): while True: try: with self.char_queue_lock: self.char_queue.append(char) return except IndexError: machine.idle() def beep_on(self): if self.beep: self.pwm_channel.duty_cycle(0.5) def beep_off(self): if self.beep: self.pwm_channel.duty_cycle(0.0) def enqueue_message(self, msg, color='W'): if msg[0:2] == '!!': color_char = msg[2:3] msg = msg[3:] if color_char in self.colors: color = color_char else: print("Illegal color code (" + color_char + ")") code = ','.join( map(lambda x: self.encoding.get(x, ''), list(msg.lower()))) code = color + code + '^,' for c in list(code): self.add_to_queue(c) def light(self, length): pycom.rgbled(self.color) time.sleep_ms(length) pycom.rgbled(0) def output(self, c): if c == '.': self.beep_on() self.light(self.unit_len) self.beep_off() time.sleep_ms(self.unit_len) elif c == '-': self.beep_on() self.light(3 * self.unit_len) self.beep_off() time.sleep_ms(self.unit_len) elif c == ',': time.sleep_ms(2 * self.unit_len) elif c == '^': time.sleep_ms(5 * self.unit_len) elif c in self.colors: self.color = self.colors[c] else: print('Unknown character (' + c + ')') def output_loop(self): while True: with self.char_queue_lock: if self.char_queue: c = self.char_queue.popleft() else: c = '' if c != '': self.output(c) machine.idle()
import gc from mqtt_as import MQTTClient from config import config import uasyncio as asyncio from ucollections import deque # xxx need to change to uasyncio.queues import json from wificonfig import MQTT_SERVER from artpart import ArtPart import logging logging.basicConfig(level=logging.DEBUG) log = logging.getLogger("ArtDirector") gc.collect() q = deque((), 20) # Subscription callback def sub_cb(topic, msg): print((topic, msg)) q.append((topic,msg)) print("len(q) == {}".format(len(q))) async def wifi_han(state): print('Wifi is {}'.format('up' if state else 'down')) await asyncio.sleep(1) # If you connect with clean_session True, must re-subscribe (MQTT spec 3.1.2.4) async def conn_han(client): await client.subscribe('mac/#', 1)
def __init__(self, maxsize=0): super().__init__() self.maxsize = maxsize self._queue = deque((), maxsize)
wifi_ssid = 'DoESLiverpool' wifi_password = '******' mqtt_broker_hostname = '10.0.100.1' mqtt_client_name = "{}{}".format('dinky-esp32-', machine.unique_id()) mqtt_topic_base = "dinky/" channels = [ "motion", ] state = { "motion": 0, } motiontimes = deque((), 60) # Set up neopixel string. np = neopixel.NeoPixel(machine.Pin(4), number_of_leds, bpp=3) # The callback that handles MQTT messages. def mqtt_message_callback(topic, msg): topic = topic.decode('utf-8') msg = msg.decode('utf-8').strip() print("MQTT message:", topic, msg) if topic.startswith(mqtt_topic_base): # Remove the mqtt_topic_base from the start of the topic, # leaving only the subtopic channel = topic[len(mqtt_topic_base):]
def __init__(self, uart: machine.UART): """Constructor. """ self._uart = uart self._incoming_bytes_buffer = deque((), 300) # List/Deque of integers self._received_packet_parser = MessagePacketParser()
def __init__(self, maxsize=0): self.maxsize = maxsize self._queue = deque((), 20)
def __init__(self, button_config, max_queue=10): self.config = button_config self.q = deque((), 10) self.enabled = True _loop = asyncio.get_event_loop() _loop.create_task(self.loop_process())
try: sys.getsizeof except AttributeError: print('SKIP') raise SystemExit print(sys.getsizeof(1) >= 2) print(sys.getsizeof("") >= 2) print(sys.getsizeof((1, 2)) >= 2) print(sys.getsizeof([1, 2]) >= 2) print(sys.getsizeof({1: 2}) >= 2) class A: pass print(sys.getsizeof(A()) > 0) try: assert sys.getsizeof(set()) >= 2 except NameError: pass # Only test deque if we have it try: from ucollections import deque assert sys.getsizeof(deque((), 1)) > 0 except ImportError: pass
try: try: from ucollections import deque except ImportError: from collections import deque except ImportError: print("SKIP") raise SystemExit d = deque((), 2) print(len(d)) print(bool(d)) try: d.popleft() except IndexError: print("IndexError") print(d.append(1)) print(len(d)) print(bool(d)) print(d.popleft()) print(len(d)) d.append(2) print(d.popleft()) d.append(3) d.append(4) print(len(d)) print(d.popleft(), d.popleft())
def __init__(self, loop, my_id, server, port=9999, ssid='', pw='', timeout=4000, conn_cb=None, conn_cb_args=None, verbose=False, led=None, wdog=False): """ Create a client connection object :param loop: uasyncio loop :param my_id: client id :param server: server address/ip :param port: port the server app is running on :param timeout: connection timeout :param conn_cb: cb called when (dis-)connected to server :param conn_cb_args: optional args to pass to connected_cb :param verbose: debug output :param led: led output for showing connection state, heartbeat :param wdog: use a watchdog to prevent the device from getting stuck/frozen/... writes to ensure that all messages are sent in order even if an outage occurs. """ self._loop = loop self._my_id = my_id self._server = server self._ssid = ssid self._pw = pw self._port = port self._to = timeout # Client and server timeout self._tim_short = timeout // 10 self._tim_ka = timeout // 4 # Keepalive interval self._concb = conn_cb self._concbargs = () if conn_cb_args is None else conn_cb_args self._verbose = verbose self._led = led if wdog: if platform == 'pyboard': self._wdt = machine.WDT(0, 20000) def wdt(): def inner(feed=0): # Ignore control values if not feed: self._wdt.feed() return inner self._feed = wdt() else: def wdt(secs=0): timer = machine.Timer(-1) timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=lambda t: self._feed()) cnt = secs run = False # Disable until 1st feed def inner(feed=WDT_CB): nonlocal cnt, run, timer if feed == 0: # Fixed timeout cnt = secs run = True elif feed < 0: # WDT control/callback if feed == WDT_CANCEL: timer.deinit() # Permanent cancellation elif feed == WDT_CB and run: # Timer callback and is running. cnt -= 1 if cnt <= 0: machine.reset() return inner self._feed = wdt(20) else: self._feed = lambda x: None self._sta_if = network.WLAN(network.STA_IF) ap = network.WLAN(network.AP_IF) # create access-point interface ap.active(False) # deactivate the interface self._sta_if.active(True) gc.collect() self._evfail = Event(100) # 100ms pause self._s_lock = Lock() # For internal send conflict. self._last_wr = utime.ticks_ms() self._lineq = deque((), 5, True) # 5 entries, throw on overflow self.connects = 0 # Connect count for test purposes/app access self._sock = None self._ok = False # Set after 1st successful read self._tx_mid = 0 # sent mid +1, used for keeping messages in order self._ack_pend = -1 # ACK which is expected to be received gc.collect() loop.create_task(self._run(loop))
import socket import ustruct as struct import time import select import network as net from ucollections import deque from machine import RTC stopFlag = False taskQueue = deque((), 10) rtc = RTC() def system_to_ntp_time(timestamp): # #"""Convert a system time to a NTP time. # # Parameters: # timestamp -- timestamp in system time # # Returns: # corresponding NTP time # #""" espOffset = 946702800 - ( 5 * 60 * 60 ) # subtract 5hrs (confirmed this makes RTC match UTC+0 on ESP8266) # Your hardware may vary return timestamp + NTP.NTP_DELTA + espOffset # def _to_int(timestamp): # #"""Return the integral part of a timestamp.
# test sys.getsizeof() function import sys try: sys.getsizeof except AttributeError: print('SKIP') raise SystemExit print(sys.getsizeof([1, 2]) >= 2) print(sys.getsizeof({1: 2}) >= 2) class A: pass print(sys.getsizeof(A()) > 0) # Only test deque if we have it try: from ucollections import deque assert sys.getsizeof(deque((), 1)) > 0 except ImportError: pass
def __init__(self): self._parser_state = self.PARSERSTATE_IDLE self._current_message_packet = None self._current_byte_counter = 0 self._current_integer = 0 self._packet_queue = deque((), 10)
try: try: from ucollections import deque except ImportError: from collections import deque except ImportError: print("SKIP") raise SystemExit d = deque((), 2) print(len(d)) print(bool(d)) try: d.popleft() except IndexError: print("IndexError") print(d.append(1)) print(len(d)) print(bool(d)) print(d.popleft()) print(len(d)) d.append(2) print(d.popleft()) d.append(3) d.append(4) print(len(d))