Example #1
0
 def release(self):
     assert self.locked
     self.locked = False
     if self.wlist:
         #print(self.wlist)
         coro = self.wlist.pop(0)
         core.get_event_loop().call_soon(coro)
Example #2
0
 def release(self):
     assert self.locked
     self.locked = False
     if self.wlist:
         #print(self.wlist)
         coro = self.wlist.pop(0)
         core.get_event_loop().call_soon(coro)
Example #3
0
	def start(self, autobauding=False):
		# Try without flow control first
		self.uart_wrapper = uartparser.UART_with_fileno(rtb.GSM_UART_N, 115200, read_buf_len=256)
		#self.uart_wrapper = uartparser.UART_with_fileno(rtb.GSM_UART_N, 115200, read_buf_len=256, flow=pyb.UART.RTS | pyb.UART.CTS)
		# TODO: schedule something that will reset the board to autobauding mode if it had not initialized within X seconds
		self.uart = uartparser.UARTParser(self.uart_wrapper)
		get_event_loop().create_task(self.uart.start())

		# Power on
		rtb.pwr.GSM_VBAT.request()
		yield from self.push_powerbutton()
		# Assert DTR to enable module UART (we can also sample the DTR pin to see if the module is powered on)
		rtb.GSM_DTR_PIN.low()
		# Just to keep consistent API, make this a coroutine too
		yield
Example #4
0
    def __init__(self, *a, **kw):

        fileno = int(sys.argv[2])
        if fileno == -1: return

        loop = get_event_loop()
        loop.create_task(self.worker())

        self.pipe = open(fileno, 'rb')
Example #5
0
 def acquire(self):
     # As release() is not coro, assume we just released and going to acquire again
     # so, yield first to let someone else to acquire it first
     yield
     #print("acquire:", self.locked)
     while 1:
         if not self.locked:
             self.locked = True
             return True
         #print("putting", core.get_event_loop().cur_task, "on waiting list")
         self.wlist.append(core.get_event_loop().cur_task)
         yield False
Example #6
0
 def acquire(self):
     # As release() is not coro, assume we just released and going to acquire again
     # so, yield first to let someone else to acquire it first
     yield
     #print("acquire:", self.locked)
     while 1:
         if not self.locked:
             self.locked = True
             return True
         #print("putting", core.get_event_loop().cur_task, "on waiting list")
         self.wlist.append(core.get_event_loop().cur_task)
         yield False

def run_to():
    coro = looper1(10)
    task = loop.create_task(coro)
    yield from asyncio.sleep(3)
    if is_uasyncio:
        asyncio.cancel(coro)
    else:
        task.cancel()
    # Need another eventloop iteration for cancellation to be actually
    # processed and to see side effects of the cancellation.
    yield from asyncio.sleep(0)
    assert cancelled

    coro = looper2(10)
    task = loop.create_task(coro)
    yield from asyncio.sleep(2)
    if is_uasyncio:
        asyncio.cancel(coro)
    else:
        task.cancel()
    yield from asyncio.sleep(0)

    # Once saw 3 ping3's output on CPython 3.5.2
    assert output == ['ping1', 'ping1', 'ping1', 'cancelled', 'ping2', 'ping2']


loop = asyncio.get_event_loop()
loop.run_until_complete(run_to())
Example #8
0
def stream(stream_ms):
	while True:
		yield from sleep(stream_ms)
		print("Authorizing...")
		auth = get_auth(gsm.CNUM, "", b'26485001')
		get_event_loop().call_soon(gsm.at_connect(PROXY_IP, USERNAME, PASSWORD))
		print("Preauth: %s" %auth)
		print("Initializing HTTP session...")
		get_event_loop().call_soon(gsm.start_http_session(PROXY_IP))
		print("Retrieving server nonce...")
		get_event_loop().call_soon(gsm.start_http_session(PROXY_IP))
		server_nonce = yield from gsm.http_action("GET", url(server_url, port, "stream"), time=timestamp(), auth=auth)
		print("Possible server nonce: %s" %server_nonce[:])
		if server_nonce and not "CME" in server_nonce:
			print("Succesfully obtained server nonce %s" %server_nonce)
			auth = get_auth(gsm.CNUM, server_nonce, b'42849900')
		else:
			print("Unable to obtain server nonce")

		print("Stopping.")
		get_event_loop().call_soon(gsm.terminate_http_session())

		print("Running production authorization.")
		coords = "test"
		state = "test"
		data = '{"auth":%s, %s, ' %(auth, coords)
		if track_state:
			data += '"state":%s, ' %state
		data += '"time":%s}' %(timestamp())
		print(data)
		print("Posting location data...")

		get_event_loop().call_soon(gsm.start_http_session(PROXY_IP))
		post = yield from gsm.http_action("POST", url(server_url, port, "stream"), data=data)
		get_event_loop().call_soon(gsm.terminate_http_session())
		get_event_loop().call_soon(gsm.at_disconnect())
Example #9
0
def configure():
	get_event_loop().run_until_complete(gsm.at_connect(PROXY_IP, USERNAME, PASSWORD))
	auth = get_auth(gsm.CNUM, "", b'26485001')
	get_event_loop().run_until_complete(gsm.start_http_session(PROXY_IP))
	server_nonce = yield from gsm.http_action("GET", url(server_url, port, "conf"), time=timestamp(), auth=auth)
	get_event_loop().run_until_complete(gsm.terminate_http_session())
	auth = get_auth(gsm.CNUM, server_nonce, b'42849900')

	get_event_loop().run_until_complete(gsm.start_http_session(PROXY_IP))
	conf = yield from gsm.http_action("GET", url(server_url, port, "conf"), time=timestamp(), auth=auth)

	get_event_loop().run_until_complete(gsm.terminate_http_session())
	get_event_loop().run_until_complete(gsm.at_disconnect())

	# Parse configuration settings
	if conf:
		track_location = parse_conf("track_location", conf)
		track_state = parse_conf("track_state", conf)
		measure_ms = parse_conf("measure_interval", conf)
		stream_ms = parse_conf("stream_interval", conf)
		fixed_state_track = parse_conf("fixed_state_track", conf)
		verbose = parse_conf("verbose", conf)
Example #10
0
import rtb
import rtb.pindebug
import logging
#logging.basicConfig(logging.DEBUG)
from uasyncio.core import get_event_loop,sleep
from rtb.gsm import instance as gsm
rtb.pwr.GSM_VBAT.status()

get_event_loop().create_task(gsm.start())
#get_event_loop().create_task(rtb.heartbeat(1))
#get_event_loop().call_later(10000, gsm.at_test())

get_event_loop().run_until_complete(gsm.at_mode_init())
get_event_loop().run_until_complete(gsm.at_test())
get_event_loop().run_until_complete(gsm.set_flow_control())
get_event_loop().run_until_complete(gsm.at_test())

loop = get_event_loop()
loop.run_forever()

get_event_loop().run_until_complete(gsm.at_test())

get_event_loop().run_until_complete(gsm.stop())
rtb.pwr.GSM_VBAT.status()


#get_event_loop().run_until_complete(gsm.start())
#get_event_loop().run_until_complete(gsm.at_test())

Example #11
0
if is_devmode:
    # For devs only: allow code in this directory to overide compiled-in stuff. Dangerous!
    # - using relative paths here so works better on simulator
    # - you must boot w/ non-production-signed firmware to get here
    sys.path.insert(0, 'flash/lib')

    # Give external devs a way to start stuff early
    try:
        import boot2
    except: pass

import ckcc
import uasyncio.core as asyncio

loop = asyncio.get_event_loop()

print("---\nColdcard Wallet from Coinkite Inc. (c) 2018.\n")

# Setup OLED and get something onto it.
from display import Display
dis = Display()
dis.splash()

# Setup membrane numpad (mark 2+)
from mempad import MembraneNumpad
numpad = MembraneNumpad(loop)

# Serial Flash memory
from sflash import SPIFlash
sf = SPIFlash()
Example #12
0
        self.count = 0

    def __call__(self, t, msg):
        self.count += 1
        print("OSC message from: udp://%s:%s" % get_hostport(msg[3]))
        print("OSC address:", msg[0])
        print("Type tags:", msg[1])
        print("Arguments:", msg[2])
        print()


if __name__ == "__main__":
    import time

    logging.basicConfig(
        level=logging.DEBUG if "-v" in sys.argv[1:] else logging.INFO)
    loop = get_event_loop()
    counter = Counter()
    loop.call_soon(run_server("0.0.0.0", 9001, serve, dispatch=counter))
    if __debug__:
        log.debug("Starting asyncio event loop")
    start = time.time()
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        loop.close()
        reqs = counter.count / (time.time() - start)
        print("Requests/second: %.2f" % reqs)
    def __init__(self):
        self.count = 0

    def __call__(self, t, msg):
        self.count += 1
        print("OSC message from: udp://%s:%s" % get_hostport(msg[3]))
        print("OSC address:", msg[0])
        print("Type tags:", msg[1])
        print("Arguments:", msg[2])
        print()


if __name__ == "__main__":
    import time

    logging.basicConfig(level=logging.DEBUG if "-v" in sys.argv[1:] else logging.INFO)
    loop = get_event_loop()
    counter = Counter()
    loop.call_soon(run_server("0.0.0.0", 9001, serve, dispatch=counter))
    if __debug__:
        log.debug("Starting asyncio event loop")
    start = time.time()
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        loop.close()
        reqs = counter.count / (time.time() - start)
        print("Requests/second: %.2f" % reqs)
from uasyncio.core import get_event_loop,sleep
from rtb.accelerometer import onboard as a

a.start()
get_event_loop().call_later(5000, a.stream(500))
loop = get_event_loop()
loop.run_forever()
Example #15
0
import time
import rtb
import logging
logging.basicConfig(logging.DEBUG)
from uasyncio.core import get_event_loop,sleep


get_event_loop().call_later(5000, lambda: print("5k: Time is %s" % time.time()))
get_event_loop().call_later(15000, lambda: print("15k: Time is %s" % time.time()))

loop = get_event_loop()
loop.run_forever()
Example #16
0
import pyb
import rtb

import logging
#logging.basicConfig(logging.DEBUG)
# rtb module patched the eventloop already
#import rtb.eventloop
from uasyncio.core import get_event_loop, sleep

def busylooper():
    while True:
        # TODO: Find out why even though we do yield we manage to block the sleeping tasks...
        yield

get_event_loop().create_task(rtb.heartbeat(1))
#get_event_loop().create_task(busylooper())
get_event_loop().create_task(rtb.heartbeat(2))

get_event_loop().run_forever()
Example #17
0
"""
This product is released under the MIT License (MIT)

Copyright (c) 2019, LEGO System A/S, Aastvej 1, 7190 Billund, Denmark

See LICENSE.txt for the full MIT license notice.
"""
import uasyncio.core as asyncio

loop = asyncio.get_event_loop(len=100)
sleep = asyncio.sleep
sleep_ms = asyncio.sleep_ms


def call_soon(coro):
    loop.call_soon(coro)
    return coro


def cancel(coro):
    try:
        coro.close()
    except ValueError:
        pass

    try:
        asyncio.cancel(coro)
    except:
        pass
Example #18
0
#get_event_loop().create_task(gsm.start())
#get_event_loop().run_until_complete(gsm.at_mode_init())
#get_event_loop().run_until_complete(gsm.add_callbacks())
#get_event_loop().run_until_complete(configure())
#get_event_loop().call_later(10000, lambda: get_event_loop().call_soon(gsm.at_me_init()))
#get_event_loop().call_later(10000, lambda: get_event_loop().call_soon(stream(stream_ms)))

# TODO: only power on when the rest is asleep or if examination triggered
#accel.start()
# TODO: investigate memory leak...
#accel.set_sensitivity(0x01) # Set sensitivity
#accel.conf_mt()
#accel.set_fast_read(True) # 8-bit results

get_event_loop().create_task(gps.start())
get_event_loop().call_later(5000, lambda: get_event_loop().call_soon(gps.set_interval(5000)))
get_event_loop().call_later(10000, lambda: get_event_loop().call_soon(gps.set_interval(1000)))
get_event_loop().call_later(10000, lambda: get_event_loop().call_soon(gps.fill_buffer(measure_ms, maximum_fix_age)))
get_event_loop().call_later(15000, lambda: get_event_loop().call_soon(auto_sleep()))

loop = get_event_loop()
loop.run_forever()

def examine_state(speed_threshold, timeout):
	""" We have triggered this examination and start investigating """
	averaged_mt = 0
	averaged_speed = 0
	original_timeout = timeout

	if gps.last_fix.speed < speed_threshold and timeout:
Example #19
0
def go(operation='', field='chain', value='BTC'):
    import common
    from sram4 import viewfinder_buf
    print('2: Available RAM = {}'.format(gc.mem_free()))

    # Avalanche noise source
    from foundation import Noise
    common.noise = Noise()

    # Get the async event loop to pass in where needed
    common.loop = asyncio.get_event_loop()

    # System
    from foundation import System
    common.system = System()

    print('2.75: Available RAM = {}'.format(gc.mem_free()))
    # Initialize the keypad
    from keypad import Keypad
    common.keypad = Keypad()
    print('3: Available RAM = {}'.format(gc.mem_free()))

    # Initialize SD card
    from files import CardSlot
    CardSlot.setup()
    print('3.5: Available RAM = {}'.format(gc.mem_free()))

    # External SPI Flash
    from sflash import SPIFlash
    common.sf = SPIFlash()

    # Initialize NV settings
    from settings import Settings
    common.settings = Settings(common.loop)
    print('4: Available RAM = {}'.format(gc.mem_free()))

    # Initialize the display and show the splash screen
    from display import Display
    print("disp 1")
    common.dis = Display()
    print("disp 2")
    common.dis.set_brightness(common.settings.get('screen_brightness', 100))
    print("disp 3")
    common.dis.splash()
    print('5: Available RAM = {}'.format(gc.mem_free()))

    # Allocate buffers for camera
    from constants import VIEWFINDER_WIDTH, VIEWFINDER_HEIGHT, CAMERA_WIDTH, CAMERA_HEIGHT

    # QR buf is 1 byte per pixel grayscale
    import uctypes
    common.qr_buf = uctypes.bytearray_at(0x20000000,
                                         CAMERA_WIDTH * CAMERA_HEIGHT)
    # common.qr_buf = bytearray(CAMERA_WIDTH * CAMERA_HEIGHT)
    print('6: Available RAM = {}'.format(gc.mem_free()))

    # Viewfinder buf 1s 1 bit per pixel and we round the screen width up to 240
    # so it's a multiple of 8 bits.  The screen height of 303 minus 31 for the
    # header and 31 for the footer gives 241 pixels, which we round down to 240
    # to give one blank (white) line before the footer.
    common.viewfinder_buf = bytearray(
        (VIEWFINDER_WIDTH * VIEWFINDER_HEIGHT) // 8)
    print('7: Available RAM = {}'.format(gc.mem_free()))

    # Show REPL welcome message
    print("Passport by Foundation Devices Inc. (C) 2020.\n")

    print('8: Available RAM = {}'.format(gc.mem_free()))

    from foundation import SettingsFlash
    f = SettingsFlash()

    if operation == 'dump':
        print('Settings = {}'.format(common.settings.curr_dict))
        print('addr = {}'.format(common.settings.addr))
    elif operation == 'erase':
        f.erase()
    elif operation == 'set':
        common.settings.set(field, value)
    elif operation == 'stress':
        for f in range(35):
            print("Round {}:".format(f))
            print('  Settings = {}'.format(common.settings.curr_dict))
            common.settings.set('field_{}'.format(f), f)
            common.settings.save()

        print('\nFinal Settings = {}'.format(common.settings.curr_dict))

    # This "pa" object holds some state shared w/ bootloader about the PIN
    try:
        from pincodes import PinAttempt

        common.pa = PinAttempt()
        common.pa.setup(b'')
    except RuntimeError as e:
        print("Secure Element Problem: %r" % e)
    print('9: Available RAM = {}'.format(gc.mem_free()))

    # Setup the startup task
    common.loop.create_task(startup())

    run_loop()
Example #20
0
import rtb
import logging
#logging.basicConfig(logging.DEBUG)
from uasyncio.core import get_event_loop,sleep
from rtb.gps import instance as gps
rtb.pwr.GPS_VCC.status()

get_event_loop().create_task(gps.start())

get_event_loop().create_task(rtb.heartbeat(1))
# this call_later thing doesn't quite seem to work event this way (the problem is that uart get data first and poll return "early"
get_event_loop().call_later(5000, lambda: get_event_loop().call_soon(gps.set_interval(5000)))
get_event_loop().call_later(10000, lambda: get_event_loop().call_soon(gps.set_interval(1000)))
# Apparently this does the UART song&dance immediately
#get_event_loop().call_later(5000, gps.set_interval(5000))

loop = get_event_loop()
loop.run_forever()

get_event_loop().run_until_complete(gps.stop())
rtb.pwr.GPS_VCC.status()


import nmea
rmc = b'$GNRMC,193202.000,A,6007.2666,N,02423.8747,E,0.16,354.15,140315,,,A*76'
f = nmea.parse_gprmc(rmc.format()) # use .format to cast to string
f.received_messages & nmea.MSG_GPRMC

# Valid fix
gsa = b'$GNGSA,A,3,20,06,10,31,02,,,,,,,,1.79,1.54,0.92*1D'
# no fix