Exemplo n.º 1
0
 async def consume(self, data: dict):
     if ENCRYPTED_OUTPUT:
         st = Sec()
         self.send(st.enc_paylaod(data))
     else:
         self.send(data)
     sleep(0)
Exemplo n.º 2
0
 async def consume(self, data):
     if ENCRYPTED_OUTPUT:
         st = Sec()
         self.publish(st.enc_paylaod(data))
     else:
         self.publish(data)
     sleep(0)
Exemplo n.º 3
0
 async def __op(self, p):
     asyncio.sleep(0)
     try:
         mop = p[OP].lower()
         if mop == 'on':
             self.__relay.on()
         elif mop == 'off':
             self.__relay.off()
         elif mop == 'flip':
             self.flip()
         elif mop == 'blink':
             onms = p[ON_MS]
             offms = p[OFF_MS]
             if type(onms) == int and type(offms) == int:
                 asyncio.create_task(self.async_blink(int(onms), int(offms)))
             else:
                 return INVALID_ARGS
         elif mop == 'stop-blink':
             self.stop_async_blink()
         else:
             return INVALID_ARGS
     except BaseException as e:
         log.debug("Op error: %r", e)
         return INVALID_ARGS
     return result(200, None, self.get_state())
Exemplo n.º 4
0
async def default_status_handler(mqtt_link, status):
    await asyncio.sleep_ms(0)
    if status == SPECNET:
        if mqtt_link.first_run:
            mqtt_link.first_run = False
            return 1  # By default try specified network on 1st run only
        asyncio.sleep(30)  # Pause before reboot.
        return 0  # Return values are for user handlers: see pb_status.py
Exemplo n.º 5
0
 async def _display_image(self, img, x_offset=0, y_offset=10):
     for y, row in enumerate(img.strip().split("\n")):
         for x, c in enumerate(row):
             self.oled.pixel(
                 x_offset + x + self.x_image,
                 y_offset + y + self.y_image,
                 (1, 0)[int(c)],
             )
             asyncio.sleep(0)
     self.oled.show()
Exemplo n.º 6
0
 async def monitor(self):
     '''
     清理非法连接
     '''
     log.debug("BLE connection monitor")
     while True:
         try:
             sleep(1)
             self.check_auth()
         except: # NOSONAR # pylint: disable=W0702
             pass
Exemplo n.º 7
0
async def test_async():
    relay = Relay(2)
    relay.on()
    print("on")
    asyncio.sleep(1)
    relay.off()
    print("off")
    asyncio.sleep(1)
    asyncio.create_task(relay.async_blink())
    for i in range(0,10):
        print(i)
        if i == 5:
            relay.stop_async_blink()
        await asyncio.sleep(1)
Exemplo n.º 8
0
 def worker(self):
     """
     """
     while True:
         coro = yield from self.comm.coro_queue.get()
         if coro[0] < self.eventloop.time():
             self.in_map = True
             curried_func = coro[1]
             if self.comm.ID in curried_func['sense_nodes']:
                 print('starting sampler')
                 yield from self.sense_worker(curried_func)
                 print('finished sampler')
             if self.comm.ID in curried_func['map_nodes']:
                 maps = curried_func['map_nodes']
                 positions = [
                     i for i, e in enumerate(maps) if e == self.comm.ID
                 ]
                 print('positions: ', positions)
                 for idx in positions:
                     print('starting mapper', idx)
                     data = yield from self.comm.sense_queue.get(
                         str(idx) + '_' + curried_func['u'])
                     print('got data')
                     u = yield from self.map_worker(curried_func, data, idx)
                     print('finished mapper')
             if self.comm.ID in curried_func['reduce_nodes']:
                 print('reducing')
                 u = yield from self.reduce_worker(curried_func)
                 print('reduced')
             self.in_map = False
         else:
             yield from self.comm.coro_queue.put(coro)
             yield from asyncio.sleep(0)
Exemplo n.º 9
0
async def test(opc):
    import ujson
    x = await opc.int_op('sys/config', 'get', None)
    print(x)
    x = await opc.int_op('wifi/config', 'get', None)
    print(x)
    x = await opc.int_op('cron/config', 'get', None)
    print(x)
    x = await opc.int_op('sys/info', 'get', None)
    print(x)
    r = request('sys/echo', 'set', 'Hi')
    x = await opc.op_request(r, False)
    print(x)
    r = request('cron/at', 'set', one_time_job())
    x = await opc.op_request(r, False)
    print(x)
    asyncio.sleep(1)
Exemplo n.º 10
0
async def turn_on_pump(pump, on_time):
    if pump == Pump.PH_PUMP:
        print('turning on pump {}'.format(pump))
        Pump.pump_1_pin.on()
        asyncio.create_task(client.publish(resp_pub, 'ph:on', qos=1))
        w = await (asyncio.sleep(on_time))
        print('turning off pump {}'.format(pump))
        Pump.pump_1_pin.off()
        asyncio.create_task(client.publish(resp_pub, 'ph:off', qos=1))
    elif pump == Pump.ORP_PUMP:
        print('turning on pump {}'.format(pump))
        Pump.pump_2_pin.on()
        asyncio.create_task(client.publish(resp_pub, 'orp:on', qos=1))
        w = await (asyncio.sleep(on_time))
        print('turning off pump {}'.format(pump))
        Pump.pump_2_pin.off()
        asyncio.create_task(client.publish(resp_pub, 'orp:off', qos=1))

    return True
Exemplo n.º 11
0
 def sleep_until_scheduled(self):
     until_next_epoch = self.comm.coro_queue._queue[0][
         0] - self.eventloop.time()
     #check to make sure it's not negative:
     if until_next_epoch > 0:
         #pyb.delay( min(until_next_epoch,self.sleep_for) )
         #yield from asyncio.sleep(self.wait_atleast[self.sleep_mode])
         #print('going to sleep for: ', min(until_next_epoch,self.sleep_for))
         time_asleep = self.sleep(min(until_next_epoch, self.sleep_for))
         self.eventloop.increment_time(time_asleep)
     yield from asyncio.sleep(0)
Exemplo n.º 12
0
    def __init__(self):
        self._tasks = []

        # We alias some of asyncio's functions.
        self.run = uasyncio.run
        self.sleep = uasyncio.sleep
        self.wait_for = uasyncio.wait_for

        # Standard asyncio doesn't have sleep_ms, so we shim it.
        self.sleep_ms = getattr(uasyncio, 'sleep_ms',
                                lambda ms: uasyncio.sleep(ms / 1000))
Exemplo n.º 13
0
 def run(self):
     """ run this part only. for dev purposes. normally, the artdirector starts the loop
     use self.start() to start/restart the part"""
     loop = asyncio.get_event_loop()
     self.running = True
     log.debug("starting update task")
     log.debug("run: before start self.update_coro: %s", self.update_coro)
     self.start()
     log.debug("run: after start self.update_coro: %s", self.update_coro)
     # loop.run_until_complete(asyncio.sleep_ms(self.duration*self.num_cycles+1000))
     loop.run_until_complete(asyncio.sleep(15))
Exemplo n.º 14
0
	def retrieve_response(self, cmd, urc="", index=0, timeout=600, interval=200):
		resp_str = ""
		timeout_iterate = int(timeout / interval)
		returned = False

		if not urc: # use default URC
			urc = cmd[3:] # By default, urc is [AT+]URC[?][=<sth>]
			if cmd.endswith('?'): # Command was a query or test command
				urc = urc[:-1] # Remove questionmark
			if "=" in urc: # Command was an execution command or test command
				urc = (str(urc.split("=")))[0] # Exclude parameters
			#print("DEBUG: Searching for this urc: %s" %urc)

		while timeout_iterate:
			timeout_iterate = max(0, timeout_iterate)
			timeout_iterate -= 1
			resp_str = self._current_buffer

			# Cut out commands from possible responses in case ECHO is not off...
			culled_cmd = cmd[len("AT"):]
			if resp_str.startswith(culled_cmd):
				resp_str = resp_str[len(culled_cmd):]

			if not urc in resp_str:
				if 'CME' in resp_str: # We encountered an error, return it
					returned = True
				else:
					yield from sleep(interval) # Wait for response...
			else:	
				returned = True

			if returned:
				if not 'CME' in resp_str: # Don't try to find echo from errors
					resp_str = resp_str[resp_str.index(urc)+len(urc)+2:] # Remember to take off ": "
					# If not override				
					try:
						end = resp_str.index('+')
						resp_str = resp_str[:end]
					except ValueError:
						end = None
					print("%s --- %s" %(cmd, resp_str))
					self.flush()
				
					# Return 'raw data' by default (eg. http data)

					if not self.OVERRIDE: # Return data in index, not raw data
						response = resp_str.split(",") # URC indices split
						index = min(index, len(response)-1)
						#response[index] = response[index][1:-1] # Take off double quotes
						resp_str = response[index]
				return resp_str
		else:
			return ""
Exemplo n.º 15
0
    def __await__(self):
        self._update()
        if self._at_limit():  # All other threads are also at limit
            if self._func is not None:
                launch(self._func, self._args)
            self._reset(not self._down)
            return

        direction = self._down
        while True:  # Wait until last waiting thread changes the direction
            if direction != self._down:
                return
            yield from asyncio.sleep(0)
Exemplo n.º 16
0
    def __await__(self):
        self._update()
        if self._at_limit():  # All other threads are also at limit
            if self._func is not None:
                launch(self._func, self._args)
            self._reset(not self._down)
            return

        direction = self._down
        while True:  # Wait until last waiting thread changes the direction
            if direction != self._down:
                return
            yield from asyncio.sleep(0)
Exemplo n.º 17
0
def events(req, resp):
    logging.info("Event source %r connected", resp)
    yield from resp.awrite("HTTP/1.0 200 OK\r\n")
    yield from resp.awrite("Content-Type: text/event-stream\r\n")
    yield from resp.awrite("\r\n")
    try:
        while True:
            if APP.push_event:
                yield from resp.awrite("data: %s\n\n" % APP.push_event)
            yield from asyncio.sleep(0.1)
    except OSError:
        logging.info("Event source connection closed")
        yield from resp.aclose()
Exemplo n.º 18
0
 def check_acknowledged(self, msg_id):
     """check if the message associated with msg_id was 
     acknowledged. If no ack within 3 seconds, return failed"""
     counter = 0
     while (msg_id not in self.completed_msgs):  # and (counter<20):
         yield from asyncio.sleep(0.05)
         counter += 1
     try:
         status, retries = self.completed_msgs[msg_id]
         del self.completed_msgs[msg_id]
     except KeyError:
         status = 'timed out'
         retries = None
     return status, retries
Exemplo n.º 19
0
def events(req, resp):
    print("Event source connected")
    yield from resp.awrite("HTTP/1.0 200 OK\r\n")
    yield from resp.awrite("Content-Type: text/event-stream\r\n")
    yield from resp.awrite("\r\n")
    i = 0
    try:
        while True:
            yield from resp.awrite("data: %d\n\n" % i)
            yield from uasyncio.sleep(1)
            i += 1
    except OSError:
        print("Event source connection closed")
        yield from resp.aclose()
Exemplo n.º 20
0
def events(req, resp):
    print("Event source connected")
    yield from resp.awrite("HTTP/1.0 200 OK\r\n")
    yield from resp.awrite("Content-Type: text/event-stream\r\n")
    yield from resp.awrite("\r\n")
    i = 0
    try:
        while True:
            yield from resp.awrite("data: %d\n\n" % i)
            yield from uasyncio.sleep(1)
            i += 1
    except OSError:
        print("Event source connection closed")
        yield from resp.aclose()
Exemplo n.º 21
0
 def events(self, req, resp):
     # print("Event source connected")
     yield from resp.awrite("HTTP/1.0 200 OK\r\n")
     yield from resp.awrite("Content-Type: text/event-stream\r\n")
     yield from resp.awrite("\r\n")
     try:
         last_v = -1
         while True:
             if self.display_web.state['v'] != last_v:
                 yield from resp.awrite("data: %s\n\n" %
                                        ujson.dumps(self.display_web.state))
                 last_v = self.display_web.state['v']
             yield from uasyncio.sleep(0.25)
     except OSError:
         # print("Event source connection closed")
         yield from resp.aclose()
Exemplo n.º 22
0
 def run(self, num_cycles=None):
     """ run this part only. for dev purposes. normally, the artdirector starts the loop
     use self.start() to start/restart the part"""
     if num_cycles is not None:
         self.num_cycles = num_cycles
     loop = asyncio.get_event_loop()
     self.running = True
     log.debug("starting update task")
     log.debug("run: before start self.update_coro: %s", self.update_coro)
     self.start()
     log.debug("run: after start self.update_coro: %s", self.update_coro)
     runtime = self.duration * self.num_cycles + 1000
     log.info("start run with duration %d for %d cycles at %d",
              self.duration, self.num_cycles, ticks_ms())
     loop.run_until_complete(asyncio.sleep(runtime / 1000 + 1))
     log.info("ended run for %d cycles at %d", self.num_cycles, ticks_ms())
Exemplo n.º 23
0
 def reduce_worker(self, curried_func):
     user = curried_func['u']
     reduce_controller = curried_func['reduce_func']
     reduce_logic = curried_func['reduce_arg']
     num_mappers = curried_func['num_mappers']
     num_reducers = len(curried_func['reduce_nodes'])
     i = 0
     #check if all num_mappers have given a map_done message
     results = {}
     already_seen = set()
     while i < num_mappers:
         yield from asyncio.sleep(0.05)
         kv = yield from self.comm.kv_queue.get(user)
         if kv[0].x == "MAP_DONE":
             ##print('got map done from ',i)
             if kv[1] not in already_seen:
                 i += 1
                 already_seen.add(kv[1])
         else:
             yield from self.comm.kv_queue.put(kv, user)
     #getting here means all map functions are finished- q size wont change in this function
     while self.comm.kv_queue.qsize(user):
         grouped_pairs, key = self.get_groupedby(
             self.comm.kv_queue._qs[user])  #, first_pair)
         #key = first_pair[0].x
         values = grouped_pairs
         reduce_gen = reduce_controller(reduce_logic, key, values)
         #now advance the generator
         for j in timed_gen(reduce_gen, user, key=key):
             if isinstance(j, asyncio.Sleep):
                 yield j
             else:
                 if j is not None:
                     ##print('got a result from reducer! ', j)
                     results[key] = j[1]
     #reduce is now finished on all pairs of key, values
     result_tx = {
         'res': (num_reducers, nested_json_dump(results)),
         'u': self.add_id(curried_func['u'])
     }
     print('reduce finished: ', result_tx)
     #return to sink node
     yield from self.node_to_node(result_tx, self.comm.address_book[99])
     print('map-reduce finished')
     self.comm.kv_queue.remove(user)
     return curried_func['u']
Exemplo n.º 24
0
 def testaccel(self, sample_length):
     fname = '/etc/init.d/beeview_liss/192.168.123.{}.json'.format(self.ID)
     print('opening: ', fname)
     gc.collect()
     print(gc.mem_free())
     i = 0
     while True:
         try:
             with open(fname) as json_data:
                 d = ujson.loads(json_data.read())
                 yield from asyncio.sleep(0)
                 trimmed = {k: v[0:sample_length] for k, v in d.items()}
                 return trimmed
         except MemoryError:
             gc.collect()
             i += 1
             trimmed = []
     return trimmed
Exemplo n.º 25
0
def treat(req, resp):
    global servo

    if req.method != "POST":
        logger.debug("method = %s, skipping", req.method)
        return

    yield from req.read_form_data()

    portion_size = float(req.form.get("portion", "2"))

    logger.debug("set speed to %s", config.TURN_SPEED)
    servo.speed(config.TURN_SPEED)
    sleeptime = portion_size * config.SMALL_PORTION_TIME
    logger.debug("wait %s seconds", sleeptime)
    yield from uasyncio.sleep(sleeptime)
    logger.debug("set speed to 0")
    servo.speed(0)
    logger.debug("done")

    headers = {"Location": ".."}
    yield from picoweb.start_response(resp, status="303", headers=headers)
Exemplo n.º 26
0
 def send_and_wait(self, byte_chunk, addr, frame_id=None, level=0):
     """given a chunk of a message to send to addr
     send the chunk, and then wait for confirmation that
     the message has sent before returning"""
     if not frame_id:
         frame_id = self.comm.id_counter()
     print('sending frame id: ', frame_id, self.completed_msgs)
     yield from self.comm.writer.network_awrite(byte_chunk, addr, frame_id)
     status, retries = yield from self.check_acknowledged(frame_id)
     success = b'\x00'
     if status == success:
         print('success sending: ', frame_id, byte_chunk, level)
         return retries, level
     else:
         #wait a second first
         yield from asyncio.sleep(0.2 + 0.2 * level)
         print('trying again: ', frame_id)
         retries, level = yield from self.send_and_wait(byte_chunk,
                                                        addr,
                                                        frame_id=frame_id,
                                                        level=level + 1)
         return retries, level
Exemplo n.º 27
0
 def sleep_ms(ms):
     asyncio.sleep(ms / 1000)
Exemplo n.º 28
0
def click_clock():
    # or async def click_clock(): in python 3.5
    while True:
        data['counter'] += 1
        yield from uasyncio.sleep(1) 
Exemplo n.º 29
0
async def run_gc():
    gc.collect()
    gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())
    asyncio.sleep(30)
Exemplo n.º 30
0
 def __await__(self):
     while not self._flag:
         yield from asyncio.sleep(0)
Exemplo n.º 31
0
def run1():
    for i in range(1):
        print('Hello World')
        yield from asyncio.sleep(2)
    print("run1 finished")
Exemplo n.º 32
0
def run2():
    for i in range(3):
        print('bar')
        yield run1()
        yield from asyncio.sleep(1)
Exemplo n.º 33
0
 def run_func(mapp, data):
     self.in_map = True
     for j in mapp(self, data):
         yield j
         yield from asyncio.sleep(0.1)  #allow to check for input
     self.in_map = False
Exemplo n.º 34
0
 def __await__(self):
     while not self._flag:
         yield from asyncio.sleep(0)
Exemplo n.º 35
0
 def reduce_func(reducc, key, values):
     self.in_map = True
     for j in reducc(self, key, values):
         yield j
         yield from asyncio.sleep(0.1)  #allow to check for input
     self.in_map = False
Exemplo n.º 36
0
 def find_neighbours(self):
     while True:
         self.get_fn()
         yield from asyncio.sleep(600)