def now(): # Return the current time from the RTC in millisecs from year 2000 rtc = pyb.RTC() secs = utime.time() ms = 1000*(255 -rtc.datetime()[7]) >> 8 if ms < 50: # Might have just rolled over secs = utime.time() return ms + 1000 * secs
def _getToken(self, debug = False): if self.apiKey == None or self.apiSecret == None or self.userName == None : raise OSError('Missing authentication info!') if self.validUntil == None or time() >= self.validUntil: basic_auth = ubinascii.b2a_base64("{}:{}".format(self.apiKey, self.apiSecret)).decode('ascii') auth_header = {'Authorization':'Basic {}'.format(basic_auth), 'Accept':'application/json'} body = 'grant_type=client_credentials&scope=openid' if debug: print(self.connectToURLforToken) resp = http_client.post(self.connectToURLforToken, headers=auth_header, textMsg=body, contentType='application/x-www-form-urlencoded', debug = debug) resp.raise_for_status() resp.content if debug: print ('Response : ') print (resp.content) authInfo = resp.json() self.tokenBearer = authInfo['access_token'] try: self.validUntil = time() + authInfo['expires_in'] localtime(self.validUntil) except OverflowError: if debug: print("Permanent token, setting to 1 week validity") self.validUntil = time() + 7 * 24 * 60 * 60 resp.close() if debug: print ("Token retrieved ! valid until {}".format(localtime(self.validUntil))) else: if debug: print ("Token still valid ! Re-using it ! {}".format(self.tokenBearer))
def perform(self) : import ntptime import core.util import utime old_secs = utime.time() ntptime.settime() new_secs = utime.time() skew = new_secs - old_secs self.min_skew = min(skew, self.min_skew) self.max_skew = max(skew, self.max_skew) if self.verbose : logging.info("ntpd: time set to {} UTC (skew: {} secs)".format(core.util.secs_to_string(new_secs), skew)) return True
def loop(self, timeout=1): """Process network events. """ print("loop") events = self.ep.poll(timeout) print("events = ", events) for fileno, ev in events: if ev & select.EPOLLIN: rc = self.loop_read() if rc or (self._sock is None): return rc if self._sock is None: return MQTT_ERR_NO_CONN now = time.time() self._check_keepalive() if self._last_retry_check+1 < now: # Only check once a second at most # can this go? ############################ self._last_retry_check = now if self._ping_t > 0 and now - self._ping_t >= self._keepalive: # client->ping_t != 0 means we are waiting for a pingresp. # This hasn't happened in the keepalive time so we should disconnect. if self._sock: self._sock.close() self._sock = None return MQTT_ERR_CONN_LOST return MQTT_ERR_SUCCESS
def __init__(self,config,callback): print('System',config) # mode = config.get('MODE', 'OUTPUT') self._interval = config.get('INTERVAL', 30) self._canId = config.get('CAN-ID') self._systemId = config.get('SYSTEM-ID') # self._name = name self._callback = callback print(utime.time())
def call(self): msg = {} value = {} msg['OBJECT']='HEARDBEAT' msg['METHOD'] = 'NULL' value['TIME']=utime.time() msg['CAN-ID'] = self._canId value['SYSTEM-ID'] = self._systemId msg['VALUE']=ujson.dumps(value) self._callback(msg)
def _check_keepalive(self): print("_check_keepalive") now = time.time() print("_check_keepalive: self._last_msg = ", self._last_msg) last_msg = self._last_msg if (self._sock is not None) and (now - last_msg >= self._keepalive): print("_check_keepalive: self._state =", self._state) if self._ping_t == 0: #self._send_pingreq() packet = struct.pack('!BB', PINGREQ, 0) self._packet_queue(PINGREQ, packet, 0, 0) self._last_msg = now
def __init__( self, name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None ): ct = utime.time() self.created = ct self.msecs = (ct - int(ct)) * 1000 self.name = name self.levelno = level self.levelname = _level_dict.get(level, None) self.pathname = pathname self.lineno = lineno self.msg = msg self.args = args self.exc_info = exc_info self.func = func self.sinfo = sinfo
def _handle_publish(self): rc = 0 print("_handle_publish") #needed after packet_handle header = self._in_packet['command'] #!H = ! means Network Byte Order, Size, and Alignment with H means unsigned short 2 bytes # For the 's' format character, the count is interpreted as the length of the bytes, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string # return mtPacket(0b00110001, mtStr(topic), data) pack_format = "!H" + str(len(self._in_packet['packet'])-2) + 's' (slen, packet) = struct.unpack(pack_format, self._in_packet['packet']) pack_format = '!' + str(slen) + 's' + str(len(packet)-slen) + 's' topic, packet = struct.unpack(pack_format, packet) # message.topic = b'test' msg = {} msg['topic'] = topic.decode('utf-8') msg['payload'] = packet msg['timestamp'] = time.time() self.on_message(self, self._userdata, msg) return 0
def __init__(self, client_id="", userdata=None, protocol=3): print("Client Class") self._protocol = protocol self._userdata = userdata self._sock = None self._keepalive = 60 self._message_retry = 20 self._last_retry_check = 0 if client_id == "" or client_id is None: self._client_id = "umqtt" else: self._client_id = client_id self._username = "" self._password = "" self._in_packet = { "command": 0, "have_remaining": 0, "remaining_count": [], "remaining_mult": 1, "remaining_length": 0, "packet": b"", "to_process": 0, "pos": 0} self._current_out_packet = None self._last_msg = time.time() self._ping_t = 0 self._last_mid = 0 self._state = mqtt_cs_new self._max_inflight_messages = 20 self._inflight_messages = 0 self.on_connect = None self.on_message = None self.on_subscribe = None self._host = "" self._port = 1883 self._bind_address = ""
def reconnect(self): """Reconnect the client after a disconnect.""" print("reconnect") self._in_packet = { "command": 0, "have_remaining": 0, "remaining_count": [], "remaining_mult": 1, "remaining_length": 0, "packet": b"", "to_process": 0, "pos": 0} self._current_out_packet = None self._last_msg = time.time() self._ping_t = 0 print("reconnect: self._state =", self._state) self._state = mqtt_cs_new if self._sock: self._sock.close() self._sock = None print("self._sock == None") sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0)) self._sock = sock self._sock.setblocking(0) self.ep = select.epoll() self.fileno = self._sock.fileno() self.ep.register(self.fileno) print("self._sock =", self._sock) return self._send_connect(self._keepalive)
def _packet_write(self): print("_packet_write") while self._current_out_packet: print("_packet_write: self._current_out_packet = ",self._current_out_packet) packet = self._current_out_packet try: write_length = self._sock.send(packet['packet'][packet['pos']:]) except: return 1 if write_length > 0: packet['to_process'] = packet['to_process'] - write_length packet['pos'] = packet['pos'] + write_length if packet['to_process'] == 0: self._current_out_packet = None else: break self._last_msg = time.time() print("_packet_write: end: self._current_out_packet =", self._current_out_packet) return MQTT_ERR_SUCCESS
import os stats = os.statvfs('/') frsize = stats[1] blocks = stats[2] bavail = stats[4] capacity = blocks * frsize free = bavail * frsize print(" mount capacity\tfree\tusage") print(" / {}\t{}\t{}%".format(capacity, free, int( ((capacity - free) / capacity) * 100.0))) def gcollect(): import gc gc.collect() start_time = utime.time() def uptime(): current_secs = utime.time() secs = current_secs - start_time return core.util.duration(secs) def ifconfig(): import network sta_if = network.WLAN(network.STA_IF) if sta_if.active() : (ip, subnet, gateway, dns) = sta_if.ifconfig() print("Station:\n\tip: {}\n\tsubnet: {}\n\tgateway: {}\n\tdns: {}".format(ip, subnet, gateway, dns)) ap_if = network.WLAN(network.AP_IF) if ap_if.active() : (ip, subnet, gateway, dns) = ap_if.ifconfig() print("Access Point:\n\tip: {}\n\tsubnet: {}\n\tgateway: {}\n\tdns: {}".format(ip, subnet, gateway, dns))
def get_currtime(): y, m, d, H, M, *_ = utime.localtime(utime.time() - localtime_offset) return "%d/%d %d:%d" % (m, d, H, M)
def send_frag(self): if self.state == self.ACK_SUCCESS: print("-----------------------------------------------------------------------") return print("----------------------- Preparing to send a message -----------------------") print("{} send_frag!!!!!!!!!!!!!!!!!".format(time.time())) # utime.time() print("all1_send-> {}, resend -> {}, state -> {}".format(self.all1_send, self.resend, self.state)) print("all tiles unsend -> {}".format(self.all_tiles)) for tile in self.all_tiles.get_all_tiles(): print("w: {}, t: {}, sent: {}".format(tile['w-num'], tile['t-num'], tile['sent'])) print("") # if self.state == self.ACK_FAILURE and self.num_of_windows != 1 and self.number_of_ack_waits <= self.num_of_windows: # #waiting for the acks of the others windows # self.number_of_ack_waits += 1 #wait depends on the number of windows # #set ack_time_out_timer # print("waiting for more acks: {}".format(self.number_of_ack_waits)) # return # get contiguous tiles as many as possible fit in MTU. mtu_size = self.protocol.layer2.get_mtu_size() window_tiles, nb_remaining_tiles, remaining_size = self.all_tiles.get_tiles(mtu_size) print("----window tiles to send: {}, nb_remaining_tiles: {}, remaining_size: {}".format(window_tiles, nb_remaining_tiles, remaining_size)) if window_tiles is None and self.resend: print("no more tiles to resend") # how to identify that all tiles are resend and that the ack timeout should be set # to wait for tha last ok. It should be set after retransmission of the last fragment if self.state == self.ACK_FAILURE and self.event_id_ack_wait_timer is None: win = self.last_window_tiles[0]["w-num"] if self.last_window_tiles[0]["w-num"] is not None else 0 if self.last_window_tiles[0]["t-num"] == 0: win += 1 schc_frag = schcmsg.frag_sender_tx( self.rule, dtag=self.dtag, win=win, fcn=schcmsg.get_fcn_all_1(self.rule), mic=self.mic_sent) # set ack waiting timer args = (schc_frag, win,) self.event_id_ack_wait_timer = self.protocol.scheduler.add_event( self.ack_wait_timer, self.ack_timeout, args) print("*******event id {}".format(self.event_id_ack_wait_timer)) # if self.all1_send and self.state == self.ACK_FAILURE: # #case when with the bitmap is not possible to identify the missing tile, # #resend ALL-1 messages # # send a SCHC fragment # args = (self.schc_all_1.packet.get_content(), self.context["devL2Addr"], # self.event_sent_frag) # print("frag sent:", self.schc_all_1.__dict__) # if enable_statsct: # Statsct.set_msg_type("SCHC_ALL_1") # Statsct.set_header_size(schcmsg.get_sender_header_size(self.rule) + # schcmsg.get_mic_size(self.rule)) # self.protocol.scheduler.add_event(0, self.protocol.layer2.send_packet, # args) # print("Sending all-1 beacuse there is an ACK FaILURE but cannot find the missing tiles") # input("") # win = self.last_window_tiles[0]["w-num"] if self.last_window_tiles[0]["w-num"] is not None else 0 # if self.last_window_tiles[0]["t-num"] == 0: # win += 1 # schc_frag = schcmsg.frag_sender_tx( # self.rule, dtag=self.dtag, win=win, # fcn=schcmsg.get_fcn_all_1(self.rule), # mic=self.mic_sent) # set ack waiting timer # args = (schc_frag, win,) # self.event_id_ack_wait_timer = self.protocol.scheduler.add_event( # self.ack_wait_timer, self.ack_timeout, args) # print("*******event id {}".format(self.event_id_ack_wait_timer)) # if window_tiles is not None and not self.all1_send and not self.resend: if window_tiles is not None: print("window_tiles is not None -> {}, resend -> {}".format(self.all1_send, self.resend)) print("") # even when mic is sent, it comes here in the retransmission. if self.all1_send and self.state != self.ACK_FAILURE: # when there is a retransmission, the all-1 is send again and is send before # the ACK-OK is received. One option is not set the timer after the last # retransmission, but i don´t know how to idenfy that all missing fragments # have been send. Also the ALL-1 is not retransmisted (dont know if this should # be like this. For example, if the ALL-1s is lost, the receiver timer expires # and a receiver abort is send. If it arrives, there is not need to retransmit # the message after the retransmission of the missing fragments) # FIX, all-1 is resend print('All-1 ones already send') # cancel timer when there is success # if self.event_id_ack_wait_timer and self.state == self.ACK_SUCCESS: # self.cancel_ack_wait_timer() # else: # print("how to add a timer without sending a message") # fcn = schcmsg.get_fcn_all_1(self.rule) # args = (schc_frag, window_tiles[0]["w-num"],) # elf.event_id_ack_wait_timer = self.protocol.scheduler.add_event( # self.ack_wait_timer, self.ack_timeout, args) # fcn = schcmsg.get_fcn_all_1(self.rule) return elif (nb_remaining_tiles == 0 and len(window_tiles) == 1 and remaining_size >= schcmsg.get_mic_size(self.rule)): print("MESSSAGE TYPE ----> ALL-1 prepared") # make the All-1 frag with this tile. # the All-1 fragment can carry only one tile of which the size # is less than L2 word size. fcn = schcmsg.get_fcn_all_1(self.rule) last_frag_base_size = ( schcmsg.get_sender_header_size(self.rule) + schcmsg.get_mic_size(self.rule) + TileList.get_tile_size(window_tiles)) # check if mic exists, no need no created again if self.mic_sent is None: mic = self.get_mic(self.mic_base, last_frag_base_size) # store the mic in order to know all-1 has been sent. self.mic_sent = mic else: mic = self.mic_sent print("mic_sent -> {}".format(self.mic_sent)) if enable_statsct: Statsct.set_msg_type("SCHC_ALL_1") Statsct.set_header_size(schcmsg.get_sender_header_size(self.rule) + schcmsg.get_mic_size(self.rule)) self.all1_send = True self.state = self.SEND_ALL_1 else: print("MESSSAGE TYPE ----> regular SCHC frag") print("") # regular fragment. fcn = window_tiles[0]["t-num"] mic = None if enable_statsct: Statsct.set_msg_type("SCHC_FRAG") Statsct.set_header_size(schcmsg.get_sender_header_size(self.rule)) schc_frag = schcmsg.frag_sender_tx( self.rule, dtag=self.dtag, win=window_tiles[0]["w-num"], fcn=fcn, mic=mic, payload=TileList.concat(window_tiles)) if mic is not None: print("mic is not None") # set ack waiting timer if enable_statsct: Statsct.set_msg_type("SCHC_FRAG") Statsct.set_header_size(schcmsg.get_sender_header_size(self.rule)) args = (schc_frag, window_tiles[0]["w-num"],) print("all ones") self.schc_all_1 = schc_frag self.event_id_ack_wait_timer = self.protocol.scheduler.add_event( self.ack_wait_timer, self.ack_timeout, args) print("*******event id {}".format(self.event_id_ack_wait_timer)) # save the last window tiles. self.last_window_tiles = window_tiles print("self.last_window_tiles -> {}".format(self.last_window_tiles)) elif self.mic_sent is not None or self.all1_send: print("self.mic_sent is not None state -> {}".format(self.state)) # it looks that all fragments have been sent. print("----------------------- all tiles have been sent -----------------------", window_tiles, nb_remaining_tiles, remaining_size) schc_frag = None self.all1_send = True if self.event_id_ack_wait_timer and self.state == self.ACK_SUCCESS: self.cancel_ack_wait_timer() return else: print("only mic all tiles send") # Here, only MIC will be sent since all tiles has been sent. assert self.last_window_tiles is not None # As the MTU would be changed anytime AND the size of the # significant padding bits would be changed, therefore the MIC # calculation may be needed again. # XXX maybe it's better to check whether the size of MTU is change # or not when the previous MIC was calculated.. last_frag_base_size = (schcmsg.get_sender_header_size(self.rule) + TileList.get_tile_size(self.last_window_tiles)) self.mic_sent = self.get_mic(self.mic_base, last_frag_base_size) # check the win number. # XXX if the last tile number is zero, here window number has to be # incremented. win = self.last_window_tiles[0]["w-num"] if self.last_window_tiles[0]["t-num"] == 0: win += 1 schc_frag = schcmsg.frag_sender_tx( self.rule, dtag=self.dtag, win=win, fcn=schcmsg.get_fcn_all_1(self.rule), mic=self.mic_sent) # set ack waiting timer args = (schc_frag, win,) if enable_statsct: Statsct.set_msg_type("SCHC_ALL_1") Statsct.set_header_size(schcmsg.get_sender_header_size(self.rule) + schcmsg.get_mic_size(self.rule)) self.schc_all_1 = schc_frag self.state = self.SEND_ALL_1 self.event_id_ack_wait_timer = self.protocol.scheduler.add_event( self.ack_wait_timer, self.ack_timeout, args) print("*******event id {}".format(self.event_id_ack_wait_timer)) # send a SCHC fragment """ Changement à corriger args = (schc_frag.packet.get_content(), self.context["devL2Addr"], self.event_sent_frag) """ args = (schc_frag.packet.get_content(), '*', self.event_sent_frag) print("frag sent:", schc_frag.__dict__) self.protocol.scheduler.add_event(0, self.protocol.layer2.send_packet, args)
def boot(): # Check battery voltage and if below a set value power off all peripherals and permanently enter deepsleep. # Letting the battery run down and repeat brownout/POR damages the PYBD. # Cycle the NM3 power supply on the powermodule try: import pyb import machine from pybd_expansion.main.powermodule import PowerModule powermodule = PowerModule() # 2 second delay at the start to allow battery voltage at the ADC to stabilise. timeout_start = utime.time() while utime.time() < timeout_start + 2: utime.sleep_ms(100) vbatt_volts = powermodule.get_vbatt_reading() if vbatt_volts < 3.7: # Turn off the USB pyb.usb_mode(None) low_power_pins(disable_3v3=True, disable_leds=True) powermodule.disable_nm3( ) # Needs to be driven low in order to pull-down the external resistor. while 1: machine.lightsleep() # Enter lightsleep utime.sleep_ms(100) except Exception as the_exception: import sys sys.print_exception(the_exception) pass # Check reason for reset - only update if power on reset. For now we only want to do OTA if requested. # try: # if machine.reset_cause() == machine.PWRON_RESET: # download_and_install_updates_if_available() # commented out during development # except Exception as the_exception: # jotter.get_jotter().jot_exception(the_exception) # import sys # sys.print_exception(the_exception) # pass # # Log to file # Manual OTA request try: # Check for the flag file .USOTA if '.USOTA' in os.listdir(): # Then update is required # Remove the file first os.remove('.USOTA') download_and_install_updates_if_available() except Exception as the_exception: jotter.get_jotter().jot_exception(the_exception) import sys sys.print_exception(the_exception) pass # Log to file # Start the main application # try: start()
def _handle(self, reader, writer): if self.debug > 1: micropython.mem_info() close = True req = None try: request_line = yield from reader.readline() if request_line == b"": if self.debug >= 0: self.log.error("%s: EOF on request start" % reader) yield from writer.aclose() return req = HTTPRequest() # TODO: bytes vs str request_line = request_line.decode() method, path, proto = request_line.split() if self.debug >= 0: self.log.info('%.3f %s %s "%s %s"' % (utime.time(), req, writer, method, path)) path = path.split("?", 1) qs = "" if len(path) > 1: qs = path[1] path = path[0] #print("================") #print(req, writer) #print(req, (method, path, qs, proto), req.headers) # Find which mounted subapp (if any) should handle this request app = self while True: found = False for subapp in app.mounts: root = subapp.url #print(path, "vs", root) if path[:len(root)] == root: app = subapp found = True path = path[len(root):] if not path.startswith("/"): path = "/" + path break if not found: break # We initialize apps on demand, when they really get requests if not app.inited: app.init() # Find handler to serve this request in app's url_map found = False for e in app.url_map: pattern = e[0] handler = e[1] extra = {} if len(e) > 2: extra = e[2] if path == pattern: found = True break elif not isinstance(pattern, str): # Anything which is non-string assumed to be a ducktype # pattern matcher, whose .match() method is called. (Note: # Django uses .search() instead, but .match() is more # efficient and we're not exactly compatible with Django # URL matching anyway.) m = pattern.match(path) if m: req.url_match = m found = True break if not found: headers_mode = "skip" else: headers_mode = extra.get("headers", self.headers_mode) if headers_mode == "skip": while True: l = yield from reader.readline() if l == b"\r\n": break elif headers_mode == "parse": req.headers = yield from self.parse_headers(reader) else: assert headers_mode == "leave" if found: req.method = method req.path = path req.qs = qs req.reader = reader close = yield from handler(req, writer) else: yield from start_response(writer, status="404") yield from writer.awrite("404\r\n") #print(req, "After response write") except Exception as e: if self.debug >= 0: self.log.exc(e, "%.3f %s %s %r" % (utime.time(), req, writer, e)) if close is not False: yield from writer.aclose() if __debug__ and self.debug > 1: self.log.debug("%.3f %s Finished processing request", utime.time(), req)
def on_message(topic, data): if topic == self._topic_info: self._alert = str(data.decode('utf-8')).strip() self._alert_time = utime.time()
def getTime(): return utime.time() * 1000 # Python yo
def is_jwt_valid(self): try: token = json.loads(a2b_base64(self.jwt.decode().split('.')[1])) except Exception: return False return utime.time() - token.get('iat') < 60 * 60 * 24
pin14 = machine.Pin('P14', machine.Pin.IN, machine.Pin.PULL_UP) pin14.callback(trigger=machine.Pin.IRQ_FALLING, handler=pin14_handler) # main lopp while (True): coord = gps.coordinates() print("{} - {}".format(coord, rtc.now())) time.sleep(5) # maybe no need to print coord frequently # button press trigger detect # keep this interruptCounter because hope to know there was one pin button interrupt just generated if interruptCounter > 0: # The disabling and re-enabling of interrupts is done with # the disable_irq and enable_irq functions of the machine module. state = machine.disable_irq() interruptCounter = interruptCounter - 1 machine.enable_irq(state) print("button interrupt complete and data sent") totalInterruptsCounter = totalInterruptsCounter + 1 print("Total button interrupt times is: " + str(totalInterruptsCounter)) print(utime.localtime()) #utime print(utime.time()) #utime #sleep #print("sleep") #py.setup_sleep(600 - time.time())#Initialize sleep duration for 10mins #py.go_to_sleep(gps=True)#use Deep sleep (resets board upon wake up and runs boot.py and main.py),keep gps powered during deepsleep of the pytrack module
def robotlistener(request): # test to ensure command passes to robot driver global motor_a_p global motor_a_m global servo_direction global servo_head_x global servo_hand_y global servo_catch global networkpin global HOLD_LOOSE_TIMEOUT time_loose = 0 # initial time out since last game loose - hall sensor trigger request = str(request) # # get head position # r_headx = re.compile("headx=0\.(\d+)") m_headx = r_headx.search(request) # # # get hand position # r_handy = re.compile("handy=0\.(\d+)") # m_handy = r_handy.search(request) # get body direction turnx # r_turnx = re.compile("turnx=0\.(\d+)") # m_turnx = r_turnx.search(request) # get body speed runy # r_runy = re.compile("runy=0\.(\d+)") # m_runy = r_runy.search(request) # get catch-release trigger # r_catch = re.compile("catch=catch") # # m_catch = r_catch.search(request) # for future catch manipulation # m_catch = r_catch.search(request) # just catch is boolean "catch-release" # try: # print('robot gets this: {}\n{}\n{}\n{}\n{}\n{}'.format(request, # m_headx, # m_handy, # m_turnx, # m_runy, # m_catch)) # except: # print('robot gets request: {}'.format(request)) # this is seems to be running OK (v01) # try: # if r_headx.search(request) is not None: # s_headx = str(m_headx.group(0)) # # print('source string: {}'.format(s_headx)) # headx = r_number.search(s_headx) # # print(' value found: {}'.format(headx.group(0))) # f_headx = float(headx.group(0)) # # print(' float value: {} , value+2 = {} '.format(f_headx, f_headx + 2)) # testing float conv # posx = int(f_headx * 75 + 40) # servo_head_x.duty(posx) # print('DBG processing request for servo_head_x posx {}'.format(posx)) # # if r_headx.search(request) is not None: # s_headx = str(m_headx.group(0)) # # print('source string: {}'.format(s_headx)) # headx = r_number.search(s_headx) # # print(' value found: {}'.format(headx.group(0))) # f_headx = float(headx.group(0)) # # print(' float value: {} , value+2 = {} '.format(f_headx, f_headx + 2)) # testing float conv # posx = int(f_headx * 75 + 40) # servo_head_x.duty(posx) # # # print('got position from joystick hand x,y : {} , {}\n' # # 'got position from joystick run turn : {} \n' # # 'direction , speed : {} , {}'.format(posx, # # '-', # # '-', # # '-', # # '-')) # # # if r_handy.search(request) is not None: # s_handy = str(m_handy.group(0)) # # print('source string: {}'.format(s_handy)) # handy = r_number.search(s_handy) # # print(' value found: {}'.format(handy.group(0))) # f_handy = 1 - float(handy.group(0)) # inverse Y axis # posy = int(f_handy * 75 + 40) # servo_hand_y.duty(posy) # # # print('got position from joystick hand x,y : {} , {}' # # 'got position from joystick run turn : {} \n' # # 'direction , speed : {} , {}'.format('-', # # posy, # # '-', # # '-', # # '-')) # # if r_turnx.search(request) is not None: # s_turnx = str(m_turnx.group(0)) # # print('source string: {}'.format(s_turnx)) # turnx = r_number.search(s_turnx) # # print(' value found: {}'.format(turnx.group(0))) # f_turnx = float(turnx.group(0)) # directionx = int(f_turnx * 75 + 40) # servo_direction.duty(directionx) # # # print('got position from joystick hand x,y : {} , {}' # # 'got position from joystick run turn : {} \n' # # 'direction , speed : {} , {}'.format('-', # # '-', # # directionx, # # '-', # # '-')) # # if r_runy.search(request) is not None: # s_runy = str(m_runy.group(0)) # # print('source string: {}'.format(s_runy)) # runy = r_number.search(s_runy) # # print(' value found: {}'.format(runy.group(0))) # f_runy = float(runy.group(0)) # # if f_runy < 0.5: # m_duty = -1 # else: # m_duty = 1 # # p_duty = int(abs(f_runy * 3000) - 1500) # # # print('got position from joystick hand x,y : {} , {}' # # 'got position from joystick run turn : {} \n' # # 'direction , speed : {} , {}'.format('-', # # '-', # # '-', # # m_duty, # # p_duty)) # motor_a_p.duty(p_duty) # motor_a_m.duty(m_duty) # # networkpin.off() # # if r_catch.search(request) is not None: # just catch is boolean "catch-release" # # print('DBG servo_catch.duty() : {}'.format( # # servo_catch.duty())) # # if servo_catch.duty() < 75: # servo_catch.duty(110) # else: # servo_catch.duty(40) # # time.sleep(0.05) # except: # print('ERR processing request for servo_head_x') # end (v01) # (v01.9) add Hall sensor try: if hall_sensor.value() == 1: # just caught ! time_loose = time.time() give_up() # print('DBG: # just caught !') else: if (time.time() - time_loose) < HOLD_LOOSE_TIMEOUT: pass # still give_up # print('DBG: # still give_up') else: # print('DBG: # robot in action!') networkpin.off() # robot in action! m_headx = r_headx.search(request) m_handy = r_handy.search(request) m_turnx = r_turnx.search(request) m_runy = r_runy.search(request) m_catch = r_catch.search(request) if r_headx.search(request) is not None: s_headx = str(m_headx.group(0)) headx = r_number.search(s_headx) f_headx = float(headx.group(0)) posx = int(f_headx * 75 + 40) servo_head_x.duty(posx) if r_handy.search(request) is not None: s_handy = str(m_handy.group(0)) handy = r_number.search(s_handy) f_handy = 1 - float(handy.group(0)) # inverse Y axis posy = int(f_handy * 75 + 40) servo_hand_y.duty(posy) if r_turnx.search(request) is not None: s_turnx = str(m_turnx.group(0)) turnx = r_number.search(s_turnx) f_turnx = 1 - float(turnx.group(0)) # inverse Y axis directionx = int(f_turnx * 75 + 40) servo_direction.duty(directionx) # if r_runy.search(request) is not None: # s_runy = str(m_runy.group(0)) # runy = r_number.search(s_runy) # f_runy = float(runy.group(0)) # # if f_runy < 0.5: # m_duty = -1 # else: # m_duty = 1 # # p_duty = int(abs(f_runy * 3000) - 1500) # # # print('got position from joystick hand x,y : {} , {}' # # 'got position from joystick run turn : {} \n' # # 'direction , speed : {} , {}'.format('-', # # '-', # # '-', # # m_duty, # # p_duty)) # motor_a_p.duty(p_duty) # motor_a_m.duty(m_duty) # for firmware dated after 2018-04-xx if r_runy.search(request) is not None: s_runy = str(m_runy.group(0)) runy = r_number.search(s_runy) f_runy = float(runy.group(0)) if f_runy < 0.5: # m_duty = -1 m_duty = -300 p_duty = int(1000 - 2000 * f_runy) elif f_runy == 0.5: m_duty = 0 p_duty = 0 else: m_duty = int(f_runy * 1000) p_duty = int(f_runy * 1000) # print('DBG f_runy {}, m_duty {}, p_duty {}'.format(f_runy, m_duty, p_duty)) motor_a_p.duty(p_duty) motor_a_m.duty(m_duty) if r_catch.search(request) is not None: # print('DBG servo_catch.duty() : {}'.format( # servo_catch.duty())) if servo_catch.duty() < 75: servo_catch.duty(110) else: servo_catch.duty(40) except Exception as e: # print('Error searching exact values in received command , {}'.format(type(e), e)) # # hard reset machine.reset()
sleep(1) led_obj.value(0) sleep(1) led_obj.value(1) sleep(1) break # Connect to Wifi connect() # Set machine time to now set_time() # Create JWT Token print("Creating JWT token.") start_time = utime.time() jwt = rd_jwt.create_jwt(PRIVATE_KEY, PROJECT_ID) end_time = utime.time() print(" Created token in", end_time - start_time, "seconds.") # Connect to MQTT Server print("Connecting to MQTT broker...") start_time = utime.time() client = get_client(jwt) end_time = utime.time() print(" Connected in", end_time - start_time, "seconds.") # Read from DHT22 #print("Reading from DHT22") #result1 = suhu() #print("Suhu", result1)
def now(): return int(utime.time())
while True: print("Cycle ", count) count = count + 1 # Platform data = os.uname() send_payload({ 'sysname': data[0], 'nodename': data[1], 'release': data[2], 'version': data[3], 'machine': data[4] }) # RTC send_payload({'rtc': utime.time()}) # Sysclk send_payload({'sysclk': machine.freq()}) # Device ID send_payload({'device_id': binascii.hexlify(machine.unique_id())}) # LoRa bandwidth send_payload({'bandwidth': n.lora.bandwidth()}) # LoRa frequency send_payload({'frequency': n.lora.frequency()}) # LoRa power mode send_payload({'power_mode': n.lora.power_mode()})
def _packet_read(self): print("_packet_read") if self._in_packet['command'] == 0: try: command = self._sock.recv(1) except socket.error as err: if err.errno == EAGAIN: return MQTT_ERR_AGAIN print(err) return 1 else: if len(command) == 0: return 1 command = struct.unpack("!B", command) self._in_packet['command'] = command[0] if self._in_packet['have_remaining'] == 0: # Read remaining # Algorithm for decoding taken from pseudo code at # http://publib.boulder.ibm.com/infocenter/wmbhelp/v6r0m0/topic/com.ibm.etools.mft.doc/ac10870_.htm while True: try: byte = self._sock.recv(1) except socket.error as err: if err.errno == EAGAIN: return MQTT_ERR_AGAIN print(err) return 1 else: byte = struct.unpack("!B", byte) byte = byte[0] self._in_packet['remaining_count'].append(byte) # Max 4 bytes length for remaining length as defined by protocol. # Anything more likely means a broken/malicious client. if len(self._in_packet['remaining_count']) > 4: return MQTT_ERR_PROTOCOL self._in_packet['remaining_length'] = self._in_packet['remaining_length'] + (byte & 127)*self._in_packet['remaining_mult'] self._in_packet['remaining_mult'] = self._in_packet['remaining_mult'] * 128 if (byte & 128) == 0: break self._in_packet['have_remaining'] = 1 self._in_packet['to_process'] = self._in_packet['remaining_length'] while self._in_packet['to_process'] > 0: try: data = self._sock.recv(self._in_packet['to_process']) except socket.error as err: if err.errno == EAGAIN: return MQTT_ERR_AGAIN print(err) return 1 else: self._in_packet['to_process'] = self._in_packet['to_process'] - len(data) self._in_packet['packet'] = self._in_packet['packet'] + data # All data for this packet is read. self._in_packet['pos'] = 0 rc = self._packet_handle() # Free data and reset values self._in_packet = dict( command=0, have_remaining=0, remaining_count=[], remaining_mult=1, remaining_length=0, packet=b"", to_process=0, pos=0) self._last_msg = time.time() return rc
def testPingTimeout(self): # Make connection self.cl.run() task = self.loop.pop() res = next(task) self.assertEqual(uasyncio.IOWrite, type(res)) with self.assertRaises(StopIteration): next(task) self.assertTrue(self.cl.connected) # Mock writer. self.cl.writer = MockWriter() # Run all tasks once res = next(self.cl.reader_task) self.assertEqual(uasyncio.IORead, type(res)) res = next(self.cl.writer_task) self.assertEqual(False, res) res = next(self.cl.ping_task) self.assertEqual(self.cl.keepalive // 2 * 1000, res) # Resume ping task - expect PING message sent res = next(self.cl.ping_task) self.assertEqual(self.cl.keepalive // 2 * 1000, res) # _ping message in queue present self.assertEqual(len(self.cl.pend_writes), 1) # Emulate that we've got PONG response self.cl.last_pong = utime.time() res = next(self.cl.ping_task) # Connection should remain active, no mo messages self.assertTrue(self.cl.connected) self.assertEqual(len(self.cl.pend_writes), 1) self.loop.clear() # Next ping task cycle - emulate ping timeout res = next(self.cl.ping_task) # Drain writer (2 message to be "sent") self.assertEqual(len(self.cl.pend_writes), 2) drain_writer(self.cl.writer_task) # Emulate pong timeout self.cl.last_pong = 0 res = next(self.cl.ping_task) # Reconnection should be scheduled self.assertFalse(self.cl.connected) # All canceled tasks should be scheduled to final run self.assertEqual(self.loop.queue_len(), 3) # Run all canceled tasks (except last one - connect_task) for idx in range(len(self.loop.queue) - 1): t = self.loop.pop() with self.assertRaises(StopIteration): next(t) # One task should remain - connect_task self.assertEqual(self.loop.queue_len(), 1) # Reconnect self.cl.writer = MockWriter() task = self.loop.pop() res = next(task) self.assertEqual(uasyncio.IOWrite, type(res)) with self.assertRaises(StopIteration): next(task) # Check if new "connection" established self.assertIsNone(self.cl.connect_task) self.assertEqual(self.loop.queue, [ (0, self.cl.reader_task), (0, self.cl.ping_task), (0, self.cl.writer_task), ]) # 1 pending message: CONNECT self.assertEqual(len(self.cl.pend_writes), 1)
def pin_interrupt(): global motionDetected, lastMotionTime lastMotionTime = utime.time() motionDetected = True
while not station.isconnected(): pass print("Connected to wifi") # Setup static IP address if a static IP has been configured if "ip" in config["wifi"]: ifconfig = list(station.ifconfig()) ifconfig[0] = config["wifi"]["ip"] station.ifconfig(tuple(ifconfig)) print(station.ifconfig()) # Setup realtime clock rtc = RTC() ntptime.settime() print("Set time to", rtc.datetime()) boot_time = time.time() + UNIX_EPOCH_OFFSET resync_rtc_timer = Timer(-1) resync_rtc_timer.init(period=MS_IN_HOUR, mode=Timer.PERIODIC, callback=resync_rtc) # Setup MQTT mqtt = MQTTClient( "powermeter", config["mqtt"]["server"], user=config["mqtt"]["username"], password=config["mqtt"]["password"], ) mqtt_pub_timer = Timer(-1) mqtt_pub_timer.init(period=MS_IN_MINUTE, mode=Timer.PERIODIC, callback=mqtt_pub) mqtt.connect() # Run garbage collector
print("{} - {}".format(coord, rtc.now())) #Read the button, if pressed then send the Coordinates to LoRA button = Pin('P14', mode=Pin.IN, pull=Pin.PULL_UP) print("{}".format(machine.Pin('P14').value())) if button == 1 and is_pressed: print('Button Pressed!') is_pressed = False # if coord == (None, None): # print("Retry getting coordinates...") # #pycom.rgbled(0x7f7f00) #YELLOW # # else: print("sending to Lora") pycom.rgbled(0x007f00) #GREEN #payload = convert_payload(lat, lon, alt, hdop) #s.send(bytes(payload)) s.send( struct.pack("<i", int(coord[0] * 100000)) + struct.pack("<i", int(coord[1] * 100000)) + struct.pack("<H", int(utime.time()))) time.sleep(1) # delay to ensure message sent before going to sleep lora.nvram_save() #nvram print("sent") print(utime.localtime()) #utime print(utime.time()) #utime #sleep #print("sleep") #py.setup_sleep(600 - time.time())#Initialize sleep duration for 10mins #py.go_to_sleep(gps=True)#use Deep sleep (resets board upon wake up and runs boot.py and main.py),keep gps powered during deepsleep of the pytrack module
# 画面初期化 axp.setLDO2Vol(2.7) #バックライト輝度調整(中くらい) draw_lcd() print('>> Disp init OK') # 時刻表示スレッド起動 _thread.start_new_thread(time_count, ()) print('>> Time Count thread ON') # ボタン検出スレッド起動 btnA.wasPressed(buttonA_wasPressed) btnB.wasPressed(buttonB_wasPressed) print('>> Button Check thread ON') # タイムカウンタ初期値設定 np_c = utime.time() tp_c = utime.time() am_c = utime.time() tp_f = False # 積算電力量応答の有無フラグ # メインループ while True: line = None # UDPデータの受信処理 if bp35a1.any() != 0: line = bp35a1.readline() u.read(line) # print(line) #全ログ取得デバッグ用 if u.type == 'E7': # [E7]なら受信データは瞬時電力計測値 data_mute = False draw_w() if ESP_NOW_F: # ESP NOW一斉同報発信を使う場合
url = "http://www.muslimthaipost.com/prayertimes/solaat.php?TYcHwyNDtkQVVUTzttQVVUTzt5QVVUTzsxMzA7MTY2OyMwMDAwRkY7IzAwMDBGRjsjRkZGRkZGOyNGRkZGRkY7I0ZGRkZGRjsjRkZGRkZGOyNGRkZGRkY7IzAwMDAwMDsjMDAwMDAwOyMwMDAwMDA7Ozs7Ozs7Ozs7Ozs7Ozs7OzI7MDswO3BkfFBTOzE7OzE7MS4yO2M2Mw==" r = http_client.get(url) html = r.text line = html.split('<font color=#000000>') return [line[3].split(' ')[0],line[5].split(' ')[0],line[7].split(' ')[0],line[9].split(' ')[0],line[11].split(' ')[0]] # --- Main --- prv_tick = utime.ticks_ms() interval = 1*1000 #clear screen display.fill(0) display.show() (year,month,day,hour,minute,second,week,days) = utime.localtime(utime.time()+3600*7) print (year,month,day,hour,minute,second) showclock(hour,minute) #----- MP3 ----------# print("start prayer") player = scanplayer.ScanPlayer() ptime = getPlayerTime() #ptime = ['09:22','09:23','09:24','13:40','13:41'] print (ptime) ps = [True,True,True,True,True,True] ctime = '' while True: cur_tick = utime.ticks_ms() if cur_tick - prv_tick > interval :
def get_localtime(self) : secs = utime.time() secs += self.tzd.get_offset_hours() * 60 * 60 return utime.localtime(secs)
frsize = stats[1] blocks = stats[2] bavail = stats[4] capacity = blocks * frsize free = bavail * frsize print(" mount capacity\tfree\tusage") print(" / {}\t{}\t{}%".format( capacity, free, int(((capacity - free) / capacity) * 100.0))) def gcollect(): import gc gc.collect() start_time = utime.time() def uptime(): current_secs = utime.time() secs = current_secs - start_time return core.util.duration(secs) def ifconfig(): import network sta_if = network.WLAN(network.STA_IF) if sta_if.active(): (ip, subnet, gateway, dns) = sta_if.ifconfig() print("Station:\n\tip: {}\n\tsubnet: {}\n\tgateway: {}\n\tdns: {}". format(ip, subnet, gateway, dns))
def time(self): """Get current time.""" return utime.time()
def mktemp(): return "/tmp/tmp%d" % utime.time()
import umqtt3 as mqtt import utime as time # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): #print(msg.topic+" "+str(msg.payload)) print('new'+msg['topic']+str(msg['payload'])) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("54.173.234.69", 1883, 60) while 1: client.loop() print(time.time()) time.sleep(4)
from binascii import hexlify, unhexlify import utime data = b'zlutoucky kun upel dabelske ody' h = hexlify(data) if h != b'7a6c75746f75636b79206b756e207570656c20646162656c736b65206f6479': raise Exception("Error") data2 = unhexlify(h) if data2 != data: raise Exception("Error") start = utime.time() for x in range(100000): d = unhexlify(h) print("100000 iterations in: " + str(utime.time() - start)) print("OK")
def uptime(): current_secs = utime.time() secs = current_secs - start_time return core.util.duration(secs)
def time(self): return time.time()
pressed_i = 0 pressed_loops = 0 last_press = 0.0 feed_times = [] sleeping = True while True: if sleeping == False: if button.value() == 1: # Button is not pressed if pressed_i > 0: pressed_loops = pressed_i pressed_i = 0 elif button.value() == 0: # Button is pressed last_press = utime.time() pressed_loops = 0 pressed_i += 1 if pressed_loops > 0 and pressed_loops < 8: print("short press") pressed_loops = 0 feed_times.append(get_currtime()) display(feed_times) elif pressed_loops >= 8: print("long press", pressed_loops) pressed_loops = 0 feed_times.pop(-1) display(feed_times) if sleeping == True and button.value() == 0:
if __name__ == "__main__": lcd_init() display('Hello , Today is Thursday!') connect_wifi() #global switchStatus switchIO = Pin(14, Pin.OUT) # 设定IO为LOW为初始电平 switchStatus = 0 gpio_init(switchIO) recvData = b"" recvFlag = True t = utime.time() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # the time of recv frequecy s.settimeout(4) connect_bigiot(s) while True: try: recvData = s.recv(100) recvFlag = True print("0recvFlag is :\t", recvFlag) except: recvFlag = False utime.sleep(1) t = keepOnline(s, t) print("1recvFlag is :\t", recvFlag) if recvFlag:
cpm25 += data.cpm25 cpm10 += data.cpm10 pm25 += data.pm25 pm10 += data.pm10 mean_data = PMSData(cpm25/len(frames), cpm10/len(frames), \ pm25/len(frames), pm10/len(frames)) if lock.locked(): print('waiting for humidity/temp/voltage reading') while lock.locked(): machine.idle() time_alive = alive_timer.read_ms() timestamp = utime.time() print('cPM25: {}, cPM10: {}, PM25: {}, PM10: {}, temp: {}, rh: {}, Vbat: {}, time: {}' \ .format(mean_data.cpm25, mean_data.cpm10, mean_data.pm25, mean_data.pm10, \ measurements.temperature, measurements.rel_humidity, measurements.voltage, time_alive)) datapoint = DataPoint(timestamp=timestamp, pm10=mean_data.pm10, pm25=mean_data.pm25, temperature=measurements.temperature, humidity=measurements.rel_humidity, voltage=measurements.voltage, duration=time_alive, version=VERSION) # store datapoints, and if sent, the RTC was synced so update the external RTC
def _handle(self, reader, writer): if self.debug: micropython.mem_info() request_line = yield from reader.readline() if request_line == b"": print(reader, "EOF on request start") yield from writer.aclose() return req = HTTPRequest() # TODO: bytes vs str request_line = request_line.decode() method, path, proto = request_line.split() print('%.3f %s %s "%s %s"' % (utime.time(), req, writer, method, path)) path = path.split("?", 1) qs = "" if len(path) > 1: qs = path[1] path = path[0] headers = {} while True: l = yield from reader.readline() if l == b"\r\n": break # TODO: bytes vs str l = l.decode() k, v = l.split(":", 1) headers[k] = v.strip() # print("================") # print(req, writer) # print(req, (method, path, qs, proto), headers) # Find which mounted subapp (if any) should handle this request app = self while True: found = False for subapp in app.mounts: root = subapp.url print(path, "vs", root) if path[:len(root)] == root: app = subapp found = True path = path[len(root):] if not path or path[0] != "/": path = "/" + path break if not found: break # We initialize apps on demand, when they really get requests if not app.inited: app.init() # Find handler to serve this request in app's url_map found = False for e in app.url_map: pattern = e[0] handler = e[1] if path == pattern: found = True break elif not isinstance(pattern, str): # Anything which is non-string assumed to be a ducktype # pattern matcher, whose .match() method is called. (Note: # Django uses .search() instead, but .match() is more # efficient and we're not exactly compatible with Django # URL matching anyway.) m = pattern.match(path) if m: req.url_match = m found = True break if found: req.method = method req.path = path req.qs = qs req.headers = headers req.reader = reader yield from handler(req, writer) else: yield from start_response(writer, status="404") yield from writer.awrite("404\r\n") #print(req, "After response write") yield from writer.aclose() if __debug__ and self.debug > 1: print(req, "Finished processing request")
async def foo(): start = time.time() while time.time() - start < 1: await asyncio.sleep(0) loop.stop()
async def foo(): start = time.time() while time.time() - start < 0.3: await asyncio.sleep(0) loop.stop()
def nownr(): # Return the current time from the RTC: caller ensures transition has occurred return 1000 * utime.time() + (1000 * (255 -rtc.datetime()[7]) >> 8)
def log(text): print(str(utime.time()) + ": " + text)
umeasurements.reset() connect() set_time() gc.collect() # Keep track of when the device started and IP adderess freeMem = float(umemory.free().replace("%", "")) umeasurements.writeMeasurement( { "id": config.google_cloud_config['device_id'], "name": net_if.ifconfig()[0] }, 'startup', freeMem) loopCnt = 0 ip = net_if.ifconfig()[0] jwtExpiry = utime.time() + config.jwt_config['token_ttl'] jwt = create_jwt(config.google_cloud_config['project_id'], config.jwt_config['private_key'], config.jwt_config['algorithm'], config.jwt_config['token_ttl']) # Do initial MQTT connection to get thew probeConfig probeConfig = mqttProcessConfigAndMeasurements() while jwtExpiry > utime.time(): loopCnt += 1 # main loop print('****** ', loopCnt, " memory:", umemory.free()) loopStartTime = utime.time()
def get(self): now = time.time() if now > self.last_read + self.UPDATE_CYCLE: self._update() self.last_read = now return self.state