示例#1
0
async def main():
    # Create a lock and acquire it so the tasks below must wait
    lock = asyncio.Lock()
    await lock.acquire()
    lock_flag = [True]

    # Create 4 tasks and let them all run
    t0 = asyncio.create_task(task(0, lock, lock_flag))
    t1 = asyncio.create_task(task(1, lock, lock_flag))
    t2 = asyncio.create_task(task(2, lock, lock_flag))
    t3 = asyncio.create_task(task(3, lock, lock_flag))
    await asyncio.sleep(0)

    # Cancel 2 of the tasks (which are waiting on the lock) and release the lock
    t1.cancel()
    t2.cancel()
    lock.release()
    lock_flag[0] = False

    # Let the tasks run to completion
    for _ in range(4):
        await asyncio.sleep(0)

    # The locke should be unlocked
    print(lock.locked())
 def __init__(self,
              spi,
              cs,
              dc,
              rst,
              height=240,
              width=240,
              disp_mode=LANDSCAPE,
              init_spi=False,
              display=GENERIC):
     if not 0 <= disp_mode <= 7:
         raise ValueError('Invalid display mode:', disp_mode)
     if not display in (GENERIC, TDISPLAY):
         raise ValueError('Invalid display type.')
     self._spi = spi  # Clock cycle time for write 16ns 62.5MHz max (read is 150ns)
     self._rst = rst  # Pins
     self._dc = dc
     self._cs = cs
     self.height = height  # Required by Writer class
     self.width = width
     self._offset = display[:2]  # display arg is (x, y, orientation)
     orientation = display[2]  # where x, y is the RAM offset
     self._spi_init = init_spi  # Possible user callback
     self._lock = asyncio.Lock()
     mode = framebuf.GS4_HMSB  # Use 4bit greyscale.
     self.palette = BoolPalette(mode)
     gc.collect()
     buf = bytearray(height *
                     -(-width // 2))  # Ceiling division for odd widths
     self._mvb = memoryview(buf)
     super().__init__(buf, width, height, mode)
     self._linebuf = bytearray(self.width * 2)  # 16 bit color out
     self._init(disp_mode, orientation)
     self.show()
示例#3
0
 def __init__(self,
              uart,
              lock=None,
              set_pin=None,
              reset_pin=None,
              interval_passive_mode=None,
              event=None,
              active_mode=True,
              eco_mode=True,
              assume_sleeping=True):
     self._uart = uart  # accepts a uart object
     self._set_pin = set_pin
     if set_pin is not None:
         set_pin.value(1)
     self._reset_pin = reset_pin
     if reset_pin is not None:
         reset_pin.value(1)
     self._active = True
     self._active_mode = active_mode  # passive mode will be set on first wakeUp() in _read()
     self._eco_mode = eco_mode  # only works with passive mode as sleep is not possible in active_mode
     self._sreader = asyncio.StreamReader(uart)
     self._interval_passive_mode = interval_passive_mode or 60  # in case someone forgets to set it
     if self._eco_mode and self._active_mode is False and self._interval_passive_mode < WAIT_AFTER_WAKEUP + 5:
         self._error(
             "interval_passive_mode can't be less than DEVICE_WAKEUP_TIME of {!s}s"
             .format(WAIT_AFTER_WAKEUP + 5))
         self._interval_passive_mode = 60
     self._event = event
     self._lock = asyncio.Lock()
     self._timestamp = None
     self._sleeping_state = assume_sleeping  # assume sleeping on start by default
     self._invalidateMeasurements()
     self._callback = None  # can be a short coroutine too; no args given
     asyncio.create_task(self._read())
示例#4
0
    def __init__(self,
                 client_id,
                 server,
                 port=1883,
                 user=None,
                 password=None,
                 keepalive=0):
        self.client_id = client_id

        self.reader = None
        self.writer = None

        self.server = server
        self.port = port
        self.user = user
        self.pswd = password
        self.keepalive = keepalive
        self.socket_timeout = 3
        self.lw_topic = None
        self.lw_msg = None
        self.lw_qos = 0
        self.lw_retain = False

        self.connected = False
        self.lock = asyncio.Lock()
示例#5
0
    def __init__(self,
                 client_id=None,
                 broker=None,
                 port=DEFAULT_TCP_PORT,
                 user=None,
                 password=None,
                 keep_alive=DEFAULT_KEEP_ALIVE,
                 debug=False):
        # Client
        self.is_connected = False
        self.first_connection = False
        if client_id == None:
            import random
            self.client_id = "umqtt_async/" + str(random.randint(1, 1000))
        else:
            self.client_id = client_id
        if broker == None:
            raise ValueError("Missing Broker information.")
        self.broker = broker
        self.port = port
        self.user = user
        self.password = password
        self.keep_alive = keep_alive
        self.debug = debug

        # SSL
        self.ssl = False
        self.certs = {}

        # LWT
        self.lw_topic = None
        self.lw_msg = None
        self.lw_qos = DEFAULT_QOS
        self.lw_retain = False

        # Messages and Topics
        self.pid = 0
        self.unack_pid = []
        self.last_message_sent = 0
        self.last_message_received = 0
        self.topics = []
        self.resend_attempts = 2

        # Callbacks
        self.on_message_cb = None
        self.on_connection_cb = None
        self.on_disconnect_cb = None
        self.on_publish_cb = None
        self.on_subscribe_cb = None
        self.on_unsubscribe_cb = None

        # Async
        self.reader = None
        self.writer = None
        self.lock = asyncio.Lock()
        self.loop = asyncio.get_event_loop()

        # Allows Network status to be passed to client.
        self.network_status = False
示例#6
0
 def __init__(self, tcp_server):
     self.tcp_server = tcp_server
     self.i2c = I2C(0, scl=Pin(18), sda=Pin(19),
                    freq=100000)  #For hardware I2C
     #i2c = SoftI2C(scl=Pin(18), sda=Pin(19), freq=5000, timeout=255) #For software I2C
     self.i2c_lock = uasyncio.Lock()
     self.lidar = I2C_lidar(self)
     self.drivetrain = I2C_drivetrain(self)
     uasyncio.create_task(self.i2c_master_routine())
     uasyncio.create_task(self.i2c_drivetrain_routine())
    def __init__(self, store_path="u_config"):

        _sch_name = "_schema"
        _sch_conf = OrderedDict([
            ("name", ("str", "")),
            ("sch", ("dict", ())),
        ])

        self.store = uorm.Store(store_schema=_sch_name, store_path=store_path, store_config=_sch_conf)
        self.lock = asyncio.Lock()
示例#8
0
async def lock_file(file_name):
    global file_locks
    try:
        print('lock', file_name)
        if file_name not in file_locks.keys():
            file_locks[file_name] = uasyncio.Lock()
        print('wait for', file_name)
        await file_locks[file_name].acquire()
        print('locked', file_name)
    except Exception as err:
        print(err)
示例#9
0
 def __init__(self, subs_cb, puback_cb, suback_cb, pingresp_cb, sock_cb=None):
     # Store init params
     self._subs_cb = subs_cb
     self._puback_cb = puback_cb
     self._suback_cb = suback_cb
     self._pingresp_cb = pingresp_cb
     self._sock_cb = sock_cb
     # Init key instance vars
     self._sock = None
     self._lock = asyncio.Lock()
     self.last_ack = 0  # last ACK received from broker
     self._read_buf = b""
示例#10
0
async def run_message_test():
    print('Test Lock class')
    lock = asyncio.Lock()
    asyncio.create_task(run_lock(1, lock))
    asyncio.create_task(run_lock(2, lock))
    asyncio.create_task(run_lock(3, lock))
    print('Test Message class')
    message = Message()
    asyncio.create_task(messageset(message))
    await messagewait(message)  # run_message_test runs fast until this point
    print('Message status {}'.format('Incorrect' if message.is_set() else 'OK'))
    print('Tasks complete')
示例#11
0
async def main():
    lock = asyncio.Lock()

    # Basic acquire/release
    print(lock.locked())
    await lock.acquire()
    print(lock.locked())
    await asyncio.sleep(0)
    lock.release()
    print(lock.locked())
    await asyncio.sleep(0)

    # Use with "async with"
    async with lock:
        print("have lock")

    # 3 tasks wanting the lock
    print("----")
    asyncio.create_task(task_loop(1, lock))
    asyncio.create_task(task_loop(2, lock))
    t3 = asyncio.create_task(task_loop(3, lock))
    await lock.acquire()
    await asyncio.sleep(0)
    lock.release()
    await t3

    # 2 sleeping tasks both wanting the lock
    print("----")
    asyncio.create_task(task_sleep(lock))
    await asyncio.sleep(0.1)
    await task_sleep(lock)

    # 3 tasks, the first cancelling the second, the third should still run
    print("----")
    ts = [None]
    asyncio.create_task(task_cancel(0, lock, ts))
    ts[0] = asyncio.create_task(task_cancel(1, lock))
    asyncio.create_task(task_cancel(2, lock))
    await asyncio.sleep(0.3)
    print(lock.locked())

    # 3 tasks, the second and third being cancelled while waiting on the lock
    print("----")
    t0 = asyncio.create_task(task_cancel(0, lock))
    t1 = asyncio.create_task(task_cancel(1, lock))
    t2 = asyncio.create_task(task_cancel(2, lock))
    await asyncio.sleep(0.05)
    t1.cancel()
    await asyncio.sleep(0.1)
    t2.cancel()
    await asyncio.sleep(0.1)
    print(lock.locked())
示例#12
0
    async def Get(self, aIDs: list = []) -> list:
        R = []
        if (not aIDs): 
            #Roms = W1.scan() # hangs if no devices
            aIDs = self.Obj.scan()

        async with asyncio.Lock():
            self.Obj.convert_temp()
            await asyncio.sleep_ms(750)
            for ID in aIDs:
                Value = self.Obj.read_temp(ID) 
                R.append({'id':ID, 'value':Value})

        return R
示例#13
0
 def __init__(self, conn_id, config, hardware, verbose):
     self.verbose = verbose
     self.initial = True
     self._status = False  # Server status
     self.wlock = asyncio.Lock()
     self.rxmsg = Message()  # rx data ready
     self.tim_boot = Delay_ms(func=self.reboot)
     config.insert(0, conn_id)
     config.append('cfg')  # Marker defines a config list
     self.cfg = ''.join((ujson.dumps(config), '\n'))
     i2c, syn, ack, rst = hardware
     self.chan = asi2c_i.Initiator(i2c, syn, ack, rst, verbose, self._go, (), self.reboot)
     self.sreader = asyncio.StreamReader(self.chan)
     self.swriter = asyncio.StreamWriter(self.chan, {})
     self.lqueue = []  # Outstanding lines
示例#14
0
 def __init__(self, command_topic, state_topic, timeout=_TIMEOUT, **kwargs):
     global _unit_index
     _unit_index += 1
     super().__init__(COMPONENT_NAME,
                      __version__,
                      _unit_index,
                      discover=False,
                      **kwargs)
     self._state = False
     self._topic = command_topic
     self._state_topic = state_topic
     self.lock = asyncio.Lock()
     # in case switch activates a device that will need a while to finish
     self._state_time = 0
     self._timeout = timeout
     _mqtt.subscribeSync(self._state_topic, self.on_message, self)
示例#15
0
    def __init__(self, client_id, server, port, user, password, keepalive,
                 ping_interval, ssl, ssl_params, response_time, clean_init,
                 clean, max_repubs, will, subs_cb, wifi_coro, connect_coro,
                 ssid, wifi_pw):
        # MQTT config
        self.ping_interval = ping_interval
        self._client_id = client_id
        self._user = user
        self._pswd = password
        self._keepalive = keepalive
        if self._keepalive >= 65536:
            raise ValueError('invalid keepalive time')
        self._response_time = response_time * 1000  # Repub if no PUBACK received (ms).
        self._max_repubs = max_repubs
        self._clean_init = clean_init  # clean_session state on first connection
        self._clean = clean  # clean_session state on reconnect
        if will is None:
            self._lw_topic = False
        else:
            self._set_last_will(*will)
        # WiFi config
        self._ssid = ssid  # Required ESP32 / Pyboard D
        self._wifi_pw = wifi_pw
        self._ssl = ssl
        self._ssl_params = ssl_params
        # Callbacks and coros
        self._cb = subs_cb
        self._wifi_handler = wifi_coro
        self._connect_handler = connect_coro
        # Network
        self.port = port
        if self.port == 0:
            self.port = 8883 if self._ssl else 1883
        self.server = server
        if self.server is None:
            raise ValueError('no server specified.')
        self._sock = None
        if LINUX is True:
            self._sta_isconnected = True
        else:
            self._sta_if = network.WLAN(network.STA_IF)
            self._sta_if.active(True)

        self.newpid = pid_gen()
        self.rcv_pids = set()  # PUBACK and SUBACK pids awaiting ACK response
        self.last_rx = ticks_ms()  # Time of last communication from broker
        self.lock = asyncio.Lock()
示例#16
0
 def __init__(self, spi, cs, dc, rst, height=240, width=240, disp_mode=0, init_spi=False):
     self._spi = spi  # Clock cycle time for write 16ns 62.5MHz max (read is 150ns)
     self._rst = rst  # Pins
     self._dc = dc
     self._cs = cs
     self.height = height  # Required by Writer class
     self.width = width
     self._spi_init = init_spi  # Possible user callback
     self._lock = asyncio.Lock()
     mode = framebuf.GS4_HMSB  # Use 4bit greyscale.
     gc.collect()
     buf = bytearray(height * width // 2)
     self._mvb = memoryview(buf)
     super().__init__(buf, width, height, mode)
     self._linebuf = bytearray(self.width * 2)  # 16 bit color out
     self._init(disp_mode)
     self.show()
示例#17
0
    def __init__(self, config):
        # MQTT config
        self._client_id = config['client_id']
        self._user = config['user']
        self._pswd = config['password']
        self._keepalive = config['keepalive']
        if self._keepalive >= 65536:
            raise ValueError('invalid keepalive time')
        self._response_time = config[
            'response_time'] * 1000  # Repub if no PUBACK received (ms).
        self._max_repubs = config['max_repubs']
        self._clean_init = config[
            'clean_init']  # clean_session state on first connection
        self._clean = config['clean']  # clean_session state on reconnect
        will = config['will']
        if will is None:
            self._lw_topic = False
        else:
            self._set_last_will(*will)
        # WiFi config
        self._ssid = config[
            'ssid']  # Required for ESP32 / Pyboard D. Optional ESP8266
        self._wifi_pw = config['wifi_pw']
        self._ssl = config['ssl']
        self._ssl_params = config['ssl_params']
        # Callbacks and coros
        self._cb = config['subs_cb']
        self._wifi_handler = config['wifi_coro']
        self._connect_handler = config['connect_coro']
        # Network
        self.port = config['port']
        if self.port == 0:
            self.port = 8883 if self._ssl else 1883
        self.server = config['server']
        if self.server is None:
            raise ValueError('no server specified.')
        self._sock = None
        self._sta_if = network.WLAN(network.STA_IF)
        self._sta_if.active(True)
        self._sta_if.config(dhcp_hostname=config['hostname'])

        self.newpid = pid_gen()
        self.rcv_pids = set()  # PUBACK and SUBACK pids awaiting ACK response
        self.last_rx = ticks_ms()  # Time of last communication from broker
        self.lock = asyncio.Lock()
示例#18
0
 def __init__(self, *args, **kwargs):
     d = defaults  # d is the config dict: initially populate with default values
     for arg in args:
         d.update(arg)  # Hardware and network configs
     d.update(kwargs)
     # d is now populated.
     self.user_start = d['user_start']
     shan = d['status_handler']
     self.s_han = (default_status_handler, ()) if shan is None else shan  # coro
     self.crash_han = d['crash_handler']
     self.wifi_han = d['wifi_handler']
     self.init_str = buildinit(d)
     self.keepalive = d['keepalive']
     self._evtrun = asyncio.Event()
     self.verbose = d['verbose']
     # Watchdog timeout for ESP8266 (ms).
     wdog = d['timeout'] * 1000
     # SynCom string mode
     self.channel = SynCom(False, d['sckin'], d['sckout'], d['srx'], d['stx'],
                           d['reset'], wdog, True, self.verbose)
     if 'led' in d:
         asyncio.create_task(heartbeat(d['led']))
     # Start the SynCom instance. This will run self.start(). If an error
     # occurs self.quit() is called which returns to Syncom's start() method.
     # This waits on ._die before forcing a failure on the ESP8266 and re-running
     # self.start() to perform a clean restart.
     asyncio.create_task(self.channel.start(self.start, self._die))
     self.subs = {}  # (callback, qos, args) indexed by topic
     self.publock = asyncio.Lock()
     self.puback = asyncio.Event()
     self.evttim = asyncio.Event()
     self.evtwifi = asyncio.Event()
     # Only specify network on first run
     self.first_run = True
     self._time = 0  # NTP time. Invalid.
     # ESP8266 returns seconds from 2000 because I believed the docs.
     # Maintainers change the epoch on a whim.
     # Calculate ofsets in CPython using datetime.date:
     # (date(2000, 1, 1) - date(1970, 1, 1)).days * 24*60*60
     epoch = {2000 : 0, 1970 : 946684800}  # Offset to add.
     self._epoch_fix = epoch[gmtime(0)[0]]  # Find offset on current platform
示例#19
0
 def __init__(self,
              component_name,
              version,
              unit_index: int,
              mqtt_topic: str = None,
              instance_name=None,
              wait_for_lock=True,
              restore_state=True,
              friendly_name=None,
              initial_state=None,
              **kwargs):
     """
     :param mqtt_topic: topic of subclass which controls the switch state. optional. If not ending with "/set", it will be added as the command_topic is being stored.
     :param instance_name: name of the instance. If not provided will get composed of component_name<count>
     :param wait_for_lock: if True then every request waits for the lock to become available,
     :param restore_state: restore the retained state topic state
     meaning the previous device request has to finish before the new one is started.
     Otherwise the new one will get ignored.
     :param friendly_name: friendly name for homeassistant gui
     :param initial_state: intitial state of the switch. By default unknown so first state change request will set initial state.
     """
     super().__init__(component_name, version, unit_index, **kwargs)
     self._state = initial_state  # initial state is unknown if None
     if mqtt_topic and not mqtt_topic.endswith("/set"):
         mqtt_topic = "{}{}".format(mqtt_topic, "/set")
     self._topic = mqtt_topic or _mqtt.getDeviceTopic("{!s}{!s}/set".format(
         component_name, self._count))
     _mqtt.subscribeSync(self._topic,
                         self.on_message,
                         self,
                         check_retained_state=restore_state)
     self._lock = asyncio.Lock()
     # in case switch activates a device that will need a while to finish
     self._wfl = wait_for_lock
     self._name = instance_name
     self._event = None
     self._frn = friendly_name
     self._pub_task = None
     gc.collect()
示例#20
0
 def __init__(self, aPin: int):
     self.Obj = Pin(aPin, Pin.OUT)
     self.Lock = asyncio.Lock()
示例#21
0
 def __init__(self,
              spi,
              cs,
              dc,
              rst,
              height=240,
              width=320,
              usd=False,
              init_spi=False):
     self._spi = spi
     self._cs = cs
     self._dc = dc
     self._rst = rst
     self.height = height
     self.width = width
     self._spi_init = init_spi
     mode = framebuf.GS4_HMSB
     self.palette = BoolPalette(mode)
     gc.collect()
     buf = bytearray(self.height * self.width // 2)
     self._mvb = memoryview(buf)
     super().__init__(buf, self.width, self.height, mode)
     self._linebuf = bytearray(self.width * 2)
     # Hardware reset
     self._rst(0)
     sleep_ms(50)
     self._rst(1)
     sleep_ms(50)
     if self._spi_init:  # A callback was passed
         self._spi_init(spi)  # Bus may be shared
     self._lock = asyncio.Lock()
     # Send initialization commands
     self._wcmd(b'\x01')  # SWRESET Software reset
     sleep_ms(100)
     self._wcd(b'\xcf', b'\x00\xC1\x30')  # PWCTRB Pwr ctrl B
     self._wcd(b'\xed', b'\x64\x03\x12\x81')  # POSC Pwr on seq. ctrl
     self._wcd(b'\xe8', b'\x85\x00\x78')  # DTCA Driver timing ctrl A
     self._wcd(b'\xcb', b'\x39\x2C\x00\x34\x02')  # PWCTRA Pwr ctrl A
     self._wcd(b'\xf7', b'\x20')  # PUMPRC Pump ratio control
     self._wcd(b'\xea', b'\x00\x00')  # DTCB Driver timing ctrl B
     self._wcd(b'\xc0', b'\x23')  # PWCTR1 Pwr ctrl 1
     self._wcd(b'\xc1', b'\x10')  # PWCTR2 Pwr ctrl 2
     self._wcd(b'\xc5', b'\x3E\x28')  # VMCTR1 VCOM ctrl 1
     self._wcd(b'\xc7', b'\x86')  # VMCTR2 VCOM ctrl 2
     # (b'\x88', b'\xe8', b'\x48', b'\x28')[rotation // 90]
     if self.height > self.width:
         self._wcd(b'\x36',
                   b'\x48' if usd else b'\x88')  # MADCTL: RGB portrait mode
     else:
         self._wcd(
             b'\x36',
             b'\x28' if usd else b'\xe8')  # MADCTL: RGB landscape mode
     self._wcd(b'\x37',
               b'\x00')  # VSCRSADD Vertical scrolling start address
     self._wcd(
         b'\x3a',
         b'\x55')  # PIXFMT COLMOD: Pixel format 16 bits (MCU & interface)
     self._wcd(b'\xb1', b'\x00\x18')  # FRMCTR1 Frame rate ctrl
     self._wcd(b'\xb6', b'\x08\x82\x27')  # DFUNCTR
     self._wcd(b'\xf2', b'\x00')  # ENABLE3G Enable 3 gamma ctrl
     self._wcd(b'\x26', b'\x01')  # GAMMASET Gamma curve selected
     self._wcd(
         b'\xe0',
         b'\x0F\x31\x2B\x0C\x0E\x08\x4E\xF1\x37\x07\x10\x03\x0E\x09\x00'
     )  # GMCTRP1
     self._wcd(
         b'\xe1',
         b'\x00\x0E\x14\x03\x11\x07\x31\xC1\x48\x08\x0F\x0C\x31\x36\x0F'
     )  # GMCTRN1
     self._wcmd(b'\x11')  # SLPOUT Exit sleep
     sleep_ms(100)
     self._wcmd(b'\x29')  # DISPLAY_ON
     sleep_ms(100)
示例#22
0
    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_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
            # Improve connection integrity at cost of power consumption.
            esp.sleep_type(esp.SLEEP_NONE)

        self._evfail = asyncio.Event()  # Set by any comms failure
        self._evok = asyncio.Event()  # Set by 1st successful read
        self._s_lock = asyncio.Lock()  # For internal send conflict.
        self._w_lock = asyncio.Lock()  # For .write rate limit
        self._last_wr = utime.ticks_ms()
        self._lineq = Queue(20)  # 20 entries
        self.connects = 0  # Connect count for test purposes/app access
        self._sock = None
        self._acks_pend = ASetByte()  # ACKs which are expected to be received
        gc.collect()
        asyncio.create_task(self._run())
示例#23
0
# MIT license; Copyright (c) 2020 Andrea Corbo

import uasyncio as asyncio
from primitives.message import Message
from primitives.semaphore import Semaphore
from primitives.queue import Queue
import time
import os
import json
import _thread
import pyb
from configs import dfl, cfg

logger = True  # Prints out messages.

f_lock = asyncio.Lock()  # Data file lock.
alert = Message()  # Sms message.
trigger = Message()
timesync = asyncio.Event()  # Gps fix event.
scheduling = asyncio.Event()  # Scheduler event.
disconnect = asyncio.Event()  # Modem event.
u2_lock = asyncio.Lock() # Uart 2 lock.
u4_lock = asyncio.Lock() # Uart 4 lock.

def welcome_msg():
    print(
    '{:#^80}\n\r#{: ^78}#\n\r#{: ^78}#\n\r# {: <20}{: <57}#\n\r# {: <20}{: <57}#\n\r# {: <20}{: <57}#\n\r# {: <20}{: <57}#\n\r{:#^80}'.format(
        '',
        'WELCOME TO ' + cfg.HOSTNAME + ' ' + dfl.SW_NAME + ' ' + dfl.SW_VERSION,
        '',
        ' current time:',
import uasyncio #uasyncio ermöglicht eine gleichzeitige bearbeitung der Messungen und die Daten zu stören
import uarray   #uarray ist das Feld in Micropython
import pyb      #pyb ist das Modul des Pyboards die das Zugreifen der verschiedenen Pins des Pyboards ermöglich

locker = uasyncio.Lock() #schließt und öffnet Teilprogrammen
total_measurements = 20  #Anzahl der gesamten Messungen
schon_gemessen = 0       #Anzahl der schon gemessene Messungen

 async def empfanger(port):   #Verbindung mit dem Komputer
    global total_measurements
    global schon_gemessen
    swriter = uasyncio.StreamWriter(port) 
    sreader = uasyncio.StreamReader(port)

    #Unendliche Schleife, damit dem Komputer ständig mit dem Pyboard im Verbindung steht und dass mit einem Break abgebrochen wird 
    while True:
        await locker.acquire() #das Einzige Teilprogramm das läuft die anderen Teilprogrammen sind gesperrt 
        befehl = await sreader.readline() #empfangt ein Befehl von dem Komputer 
        befehl_ = str(befehl).replace("\\r\\n'", "") #Bearbeitung des Befehls
        
        if befehl_ == "b'zeigeMeasurments":
            await swriter.awrite("ShowMeasurements\r\n") #send dem Komputer ein Befehl, um ihn die förden, die gemessenen Daten zu zeigen
        
        await swriter.awrite("end\r\n")

        if schon_gemessen == total_measurements :
            await swriter.awrite("endeMessungen\r\n") #send dem Komputer ein Befehl, um ihn die förden, das Programm zu beenden
            break
        locker.release() #ermöglicht den anderen Teilprogrammen weiter zu laufen
        await uasyncio.sleep(1)        
示例#25
0
__hour = 7
__minute = 15

sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)

button_1 = utils.Button(12)
neopixel_rgb = utils.RGB(13, 4)

audio = dfplayer.SimpleDFPlayerMini(1, 0, 1)

loop = uasyncio.get_event_loop()
network_updated = uasyncio.Event()
alarm_updated = uasyncio.Event()
time_updated = uasyncio.Event()
volume_lock = uasyncio.Lock()

def main():
    audio.suspend()
    loop = uasyncio.get_event_loop()
    loop.create_task(network_coro())
    loop.create_task(alarm_time_coro())
    loop.run_forever()

def status():
    with open('wifi.json', 'rb') as f:
        wifi = ujson.loads(f.read())
    with open('alarm.json', 'rb') as f:
        alarm = ujson.loads(f.read())
    return {'network' : {'ssid': wifi['ssid'], 'ip': network.WLAN(network.STA_IF).ifconfig()[0], 'connected': network.WLAN(network.STA_IF).isconnected()}, 'time': utils.cettime(), 'alarm' : {'hour': alarm['hour'], 'minute': alarm['minute']}}
示例#26
0
class DS18(ComponentSensor):
    _pins = {}  # pin number/name:onewire()
    _last_conv = {}  # onewire:time
    _lock = asyncio.Lock()

    def __init__(self,
                 pin,
                 rom: str = None,
                 auto_detect=False,
                 precision_temp: int = 2,
                 offset_temp: float = 0,
                 friendly_name=None,
                 **kwargs):
        """
        Class for a single ds18 unit to provide an interface to a single unit.
        Alternatively it can be used to automatically detect all connected units
        and create objects for those units.
        :param pin: pin number/name/object
        :param rom: optional, ROM of the specific DS18 unit, can be string or bytearray
        (in json bytearray not possible). If not given then the first found ds18 unit will be used,
        no matter the ROM. Makes it possible to have a generic ds18 unit.
        :param auto_detect: optional, if true and ROM is None then all connected ds18 units will automatically generate a sensor object with the given options.
        :param precision_temp: the precision to for returning/publishing values
        :param offset_temp: temperature offset to adjust bad sensor readings
        :param friendly_name: friendly name in homeassistant. Has no effect if rom is None and auto_detect True
        """
        if rom is None and auto_detect:
            # only a dummy sensor for detecting connected sensors
            interval_reading = kwargs[
                "interval_reading"] if "interval_reading" in kwargs else None
            interval_publish = kwargs[
                "interval_publish"] if "interval_publish" in kwargs else None
            self._instances = {}  # rom:object
            self._auto_detect = True
            self._kwargs = kwargs  # store kwargs for initialization of detected sensors
            kwargs[
                "interval_reading"] = 60  # scan every 60 seconds for new units
            kwargs["interval_publish"] = -1
        global _unit_index
        _unit_index += 1
        super().__init__(COMPONENT_NAME,
                         __version__,
                         _unit_index,
                         logger=_log,
                         **kwargs)
        self.rom: str = rom
        self._generic = True if rom is None and not auto_detect else False
        if type(pin) == ds18x20.DS18X20:
            self.sensor: ds18x20.DS18X20 = pin
        else:
            self._pins[pin] = ds18x20.DS18X20(onewire.OneWire(Pin(pin)))
            self.sensor: ds18x20.DS18X20 = self._pins[pin]
            self._last_conv[self.sensor] = None
        if rom or not auto_detect:  # sensor with rom or generic sensor
            self._addSensorType(SENSOR_TEMPERATURE, precision_temp,
                                offset_temp, VALUE_TEMPLATE_FLOAT, "°C",
                                friendly_name)
            self._auto_detect = False
        elif self._auto_detect:
            self._kwargs["interval_reading"] = interval_reading
            self._kwargs["interval_publish"] = interval_publish
            self._kwargs["precision_temp"] = precision_temp
            self._kwargs["offset_temp"] = offset_temp
        gc.collect()

    def _default_name(self):
        """Change default name to include sensor ROM. Will change name and default topic."""
        if self.rom is None or self._generic:
            return "{!s}".format(COMPONENT_NAME)
        else:
            return "{!s}_{!s}".format(COMPONENT_NAME, self.rom)

    async def _read(self):
        if self._auto_detect or self._generic:  # auto_detect unit or generic sensor
            roms = []
            for _ in range(4):
                roms_n = self.sensor.scan()
                for rom in roms_n:
                    if rom not in roms:
                        roms.append(rom)
                await asyncio.sleep_ms(100)
            if len(roms) == 0:
                await _log.asyncLog("error", "Found no ds18 unit", timeout=10)
                return
            if self._auto_detect:  # auto_detect instance
                for rom in roms:
                    rom = self.rom2str(rom)
                    if rom not in self._instances:
                        self._instances[rom] = DS18(self.sensor, rom, False,
                                                    **self._kwargs)
                for rom in self._instances:
                    if rom not in roms:  # sensor not connected anymore
                        await self.removeComponent(roms[rom])
                        # will stop its loop and remove component and unsubcribe every topic
                        del self._instances[rom]
                        await _log.asyncLog("info",
                                            "DS18 removed:",
                                            rom,
                                            timeout=5)
            else:  # generic ds18 sensor
                rom = self.rom2str(roms[0])
                if rom != self.rom:  # sensor replaced
                    self.rom: str = rom
                    await _log.asyncLog("info",
                                        "Found new ds18:",
                                        rom,
                                        timeout=5)
        if self.rom is not None:  # DS18 sensor unit
            async with self._lock:
                if self._last_conv[self.sensor] is None or \
                        time.ticks_diff(time.ticks_ms(), self._last_conv[self.sensor]) > 5000:
                    # if sensors did convert time more than 5 seconds ago, convert temp again
                    try:
                        self.sensor.convert_temp()
                    except onewire.OneWireError:
                        await self._setValue(SENSOR_TEMPERATURE, None)
                        await _log.asyncLog("error",
                                            "Sensor rom",
                                            self.rom,
                                            ", onewire not connected?,",
                                            timeout=10)
                        return
                    await asyncio.sleep_ms(750)
                value = None
                err = None
                for _ in range(3):
                    try:
                        value = self.sensor.read_temp(self.str2rom(self.rom))
                    except Exception as e:
                        await asyncio.sleep_ms(100)
                        err = e
                        continue
                if value is None:
                    await self._setValue(SENSOR_TEMPERATURE, None)
                    await _log.asyncLog("error",
                                        "Sensor rom",
                                        self.rom,
                                        "got no value,",
                                        err,
                                        timeout=10)
                    return
                if value == 85.0:
                    await self._setValue(SENSOR_TEMPERATURE, None)
                    await _log.asyncLog(
                        "error",
                        "Sensor rom",
                        self.rom,
                        "got value 85.00 [not working correctly]",
                        timeout=10)
                    return
                await self._setValue(SENSOR_TEMPERATURE, value)

    @staticmethod
    def rom2str(rom: bytearray) -> str:
        return ''.join('%02X' % i for i in iter(rom))

    @staticmethod
    def str2rom(rom: str) -> bytearray:
        a = bytearray(8)
        for i in range(8):
            a[i] = int(rom[i * 2:i * 2 + 2], 16)
        return a
示例#27
0
    connection_details = wlan_network.ifconfig()
    ip_address = connection_details[0]
    netmask = connection_details[1]
    ip_address_segments = (int(item) for item in ip_address.split("."))
    netmask_segments = (int(item) for item in netmask.split("."))
    broadcast_segments = []
    for (ip_address_segment, netmask_segment) in zip(ip_address_segments, netmask_segments):
        if int(netmask_segment) == 255:
            broadcast_segments.append(ip_address_segment)
        else:
            network_segment = ip_address_segment & netmask_segment
            broadcast_segments.append(network_segment + (255 - netmask_segment))
    return ".".join(str(item) for item in broadcast_segments)


discovery_lock = uasyncio.Lock()


async def discover(timeout: int = 5, clazz=None):
    onkyo_magic = eISCPPacket("!xECNQSTN").get_raw()
    pioneer_magic = eISCPPacket("!pECNQSTN").get_raw()
    found_receivers = {}
    broadcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    broadcast_socket.setblocking(0)
    broadcast_address = get_current_broadcast_address()
    own_address = get_current_ip_address()

    async with discovery_lock:
        try:
            broadcast_socket.bind(
                (own_address, eISCP.ONKYO_PORT)
示例#28
0
 def __init__(self, lock=None):
     self.lock = asyncio.Lock() if lock is None else lock
     self.events = []
示例#29
0
'''
Author:      Vladimir Vons <*****@*****.**>
Created:     2018.06.17
License:     GNU, see LICENSE for more details
Description:
'''

import time
import uasyncio as asyncio
#
from Inc.Log import Log
from IncP.Api import TApiBase

Lock = asyncio.Lock()


class TApi(TApiBase):
    Param = {'delay': 1, 'async': True, 'echo': True}

    async def Exec(self, aDelay: float, aAsync: bool, aEcho: bool) -> dict:
        async with Lock:
            if (aAsync):
                await asyncio.sleep(aDelay)
            else:
                time.sleep(aDelay)

            R = {'delay': aDelay, 'async': aAsync, 'echo': aEcho}
            if (aEcho):
                Log.Print(1, 'i', 'sys_sleep', R)
            return R
示例#30
0
async def main():
    lock = asyncio.Lock()  # The Lock instance
    for n in range(1, 4):
        asyncio.create_task(task(n, lock))
    await asyncio.sleep(10)