def unlock_sim_pin(self, code): """ Unlocks SIM. Do NOT use this function unless you are absolutely out of equipment (cell phones) """ if code: yield from self.retrieve_urc('AT+CPIN=%s' %code) yield from sleep(2000) yield from self.retrieve_urc('AT+CLCK="SC",0,"%s"' %code) yield from sleep(2000)
def looper2(iters): for i in range(iters): print1("ping2") if BUSY_SLEEP: t = time.time() while time.time() - t < delay(1): yield from asyncio.sleep(0) else: yield from asyncio.sleep(delay(1)) return 10
def auto_sleep(): while True: if gps.nofix >= 1020000: # if gps.nofix == 0 or # 17 min and no fix / flown over sleep("No fix in 17 minutes") if track_state and gps.last_fix: if gps.last_fix.speed < THRESHOLD: next_state = yield from examine_state(20, THRESHOLD+0.5) # check from Blinky print("State: %s" %next_state) if not fixed_state_track: if next_state is not state: pass # Post state as a Notice else: state = next_state yield
def looper1(iters): global cancelled try: for i in range(iters): print1("ping1") if BUSY_SLEEP: t = time.time() while time.time() - t < delay(1): yield from asyncio.sleep(0) else: yield from asyncio.sleep(delay(1)) return 10 except asyncio.CancelledError: print1("cancelled") cancelled = True
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: #averaged_mt += int(accel.stream()[3:5]) #accel.mt.x # TODO: buffer averaged_speed += gps.last_fix.speed yield from sleep(1000) timeout-=1 check = original_timeout-timeout #try: #averaged_mt /= check if check > 0: a = (float) averaged_speed / check # Floating point math eats up all RAM... if check >= 10: # Low speed state lasted longer than 10*measure_ms if a < 1.0: # averaged_mt > 0xfd and return "STATIONARY" else: return "OPERATING" else: return "IN_TRANSIT" # Just traffic lights or something #except ZeroDivisionError: return "IN_TRANSIT" # TODO: re-check with smaller timeout?
def at_mode_init(self, save=False, fixedBaud=True): """ Configure and save configuration. Run this if you use Tracker for the first time """ yield from sleep(9000) self.uart.verbose = True # Make sure autobauding autobauds resp = yield from self.uart.cmd("AT") resp = yield from self.uart.cmd("ATE1") resp = yield from self.uart.cmd("AT+CFUN=0") if fixedBaud: # Set fixed baudrate resp = yield from self.uart.cmd("AT+IPR=115200") # Set hardware flow control yield from self.set_flow_control() else: # Use autobaud resp = yield from self.uart.cmd("AT+IPR=0") # Network registration messages enable resp = yield from self.uart.cmd("AT+CREG=2") # CME error report mode resp = yield from self.uart.cmd("AT+CMEE=1") # Network time fetch enable resp = yield from self.uart.cmd("AT+CLTS=1") # Show current profile resp = yield from self.uart.cmd("AT&V") # Save changes if save: resp = yield from self.uart.cmd("ATE0&W") resp = yield from self.uart.cmd("AT") resp = yield from self.uart.cmd("AT") # Set full functionality resp = yield from self.uart.cmd("AT+CFUN=0") resp = yield from self.uart.cmd("AT+CFUN?") resp = yield from self.uart.cmd("AT+CFUN=1") resp = yield from self.uart.cmd("AT+CNUM")
def http_action(self, method, url, data=None, *args, **kwargs): """ Called after HTTP session is started """ self.uart.urc.OVERRIDE = True # return raw data if kwargs: # Add parameters url += '?' for x in kwargs: url += "%s=%s&" % (x, kwargs[x]) url = url[:-1] # Take off final '&' print("Destination url: %s" %url) # Debug output # Set HTTP params yield from self.uart.cmd('AT+HTTPPARA="CID",1') yield from self.uart.cmd('AT+HTTPPARA="URL","%s"' %url) m = self.get_method(method) if m == 1:#self.get_method("POST"): # Set additional HTTP params for data size = len(data.encode('utf-8')) yield from self.uart.cmd('AT+HTTPDATA=%s,5000' %(size)) # Data size in bytes and timeout yield from self.uart.cmd(data) yield from self.uart.cmd('AT+HTTPACTION=%d' %m) # 0, 1, 2 | GET, POST, HEAD yield from sleep(5000) resp = yield from self.retrieve_urc('AT+HTTPREAD', timeout=1000) self.uart.urc.OVERRIDE = False return resp
def examine_state(self, timeout): """ We have triggered this examination and start investigating """ # TODO: SET STANDBY MODE to enable config to the function exhibit # TODO: Only wake up if triggered accel.set_sensitivity(0x00) # Veeery sensitive if gps.speed < 0.05 and not not timeout: averaged_mt += accel.mt.x yield from sleep(1000) timeout-=1 accel.set_sensitivity(0x08) # TODO: What do we even need this mode for...? try: averaged_mt /= (20-timeout) if check >= 10: # Low speed state lasted longer than 10 seconds if averaged_mt > 0xfd: return "STATIONARY" else: return "OPERATING" # Or... in a traffic jam...? else: return "IN_TRANSIT" # Just traffic lights or something. except ZeroDivisionError: return "IN_TRANSIT" # TODO: re-check with smaller timeout?
def stream(self): yield from sleep(self.stream_ms) coords = gps._buffer(len(gps._buffer)) # JSON'd. TODO: 3 last items maybe? data = '{%s}' %coords post = yield from self.http_action("POST", self.url("stream"), time=self.timestamp(), data=data, auth=authorize("stream")) self.at_terminate_http_session() self.at_disconnect()
def run(): coro = looper1() task = loop.create_task(coro) if is_uasyncio: asyncio.cancel(coro) else: task.cancel() yield from asyncio.sleep(0)
def task(i, lock): print(lock) while 1: yield from lock.acquire() print("Acquired lock in task", i) yield from asyncio.sleep(0.5) # yield lock.release() lock.release()
def serve(data, caddr, **params): if __debug__: log.debug("Client request handler coroutine called.") handle_osc(data, caddr, **params) # simulate long running request handler yield from sleep(1) if __debug__: log.debug("Finished processing request,")
def looper2(iters): for i in range(iters): print1("ping2") # sleep() isn't properly cancellable #yield from asyncio.sleep(1.0) t = time.time() while time.time() - t < 1: yield from asyncio.sleep(0) return 10
def put(self, val): """Returns generator which can be used for putting item in a queue. Usage:: yield from queue.put(item) """ while self.qsize() > self.maxsize and self.maxsize: print('here for some unknown reason') yield from sleep(self._attempt_delay) self._put(val)
def at_me_init(self): """ Set module functional""" yield from sleep(5000) self.uart.verbose = True #yield from self.add_callbacks() # +verbose # Pimpelipom resp = yield from self.uart.cmd("AT") resp = yield from self.uart.cmd("ATE1") ready = yield from self.at_ready() if ready: self.READY = True yield from sleep(2000) # Obtain subscriber number for 'client ID' self.CNUM = yield from self.retrieve_urc('AT+CNUM', urc="NUM", index=1, timeout=4000) attached = yield from self.retrieve_urc('AT+CGATT?', urc="GATT", timeout=4000) self.CGATT = '1' in attached if self.CGATT: yield from self.uart.cmd('AT+CGATT=0') # Detach GPRS
def put(self, val): """Returns generator which can be used for putting item in a queue. Usage:: yield from queue.put(item) """ while self.qsize() >= self.maxsize and self.maxsize: yield from sleep(self._attempt_delay) self._put(val)
def get(self): """Returns generator, which can be used for getting (and removing) an item from a queue. Usage:: item = yield from queue.get() """ while not self.qsize(): #print('nothing on the q') yield from sleep(self._attempt_delay) return self._get()
def get(self): """Returns generator, which can be used for getting (and removing) an item from a queue. Usage:: item = yield from queue.get() """ while not self._queue: yield from sleep(self._attempt_delay) return self._get()
def at_connect(self, PROXY_IP, USERNAME, PASSWORD): """ Connects to GPRS proxy server. Connection may only be carried out if CPIN is ready """ #if self.READY: yield from self.uart.cmd('AT') yield from self.uart.cmd('AT+CIPSHUT') yield from self.uart.cmd('AT+CIPSTATUS') yield from sleep(500) # 'Flow control.' yield from self.uart.cmd('AT+CGDCONT=1,"IP","%s"' %(PROXY_IP)) yield from sleep(500) yield from self.uart.cmd('AT+CIPMUX=0') # Set up single connection mode yield from sleep(500) # Attach GPRS yield from self.uart.cmd("AT+CGATT=1") yield from sleep(500) yield from self.uart.cmd('AT+CSTT="%s", "%s", "%s"' %(PROXY_IP, USERNAME, PASSWORD)) yield from sleep(500) yield from self.uart.cmd('AT+CIICR') # Bringing up the wireless takes a while yield from sleep(8000) # If you can't connect, no signal, or your card does not support GPRS... # TODO: Enable URC and see if you can get local IP. return true yield from self.uart.cmd('AT+CIFSR') # Local IP get, might be mandatory
def looper1(iters): global cancelled try: for i in range(iters): print1("ping1") # sleep() isn't properly cancellable #yield from asyncio.sleep(1.0) t = time.time() while time.time() - t < 1: yield from asyncio.sleep(0) return 10 except asyncio.CancelledError: print1("cancelled") cancelled = True
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']
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())
def looper1(): assert False yield from asyncio.sleep(0)
def _usleep(self, us): """Delay by (sleep) us microseconds.""" yield from sleep(us / 1000)
def looper(iters): for i in range(iters): print("ping") yield from asyncio.sleep(1.0) return 10
def run_to(): try: ret = yield from asyncio.wait_for(looper(2), 1) print("result:", ret) assert False except asyncio.TimeoutError: print("Coro timed out") print("=================") try: ret = yield from asyncio.wait_for(looper(2), 2) print("result:", ret) assert False except asyncio.TimeoutError: print("Coro timed out") print("=================") try: ret = yield from asyncio.wait_for(looper(2), 3) print("result:", ret) except asyncio.TimeoutError: print("Coro timed out") assert False loop = asyncio.get_event_loop() loop.run_until_complete(run_to()) loop.run_until_complete(asyncio.sleep(1))
def push_powerbutton(self, push_time=2000): rtb.GSM_PWR_PIN.low() yield from sleep(push_time) rtb.GSM_PWR_PIN.high()
def wakeup(): """Wake up from sleep. This assumes slow-clock is set to 1""" rtb.GSM_DTR_PIN.low() # The serial port is ready after 50ms yield from sleep(50)