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 settime(): t = time() import machine import utime tm = utime.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm) print(utime.localtime())
def get_localtime(raw=False): import utime localtime = utime.localtime() if raw: return utime.mktime(localtime) else: return DateTimeCmd.datetime_str(localtime)
def getCloudChannelBaseDefinitionJSON(self, owner, latestmesagedefinition): """ Prepares the bare bones JSON structure for our CC definition HTTP->SEaaS """ now = utime.localtime() name = '{}_for_{}'.format(self.getStreamId(), self.getDeviceId()) ccdef = { "owner": owner, "enabled_interval": { "start": '{0:04d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}.000+0000'.format(*now) }, "cc_name": name, "log_headers": True, "log_body": True, "versioned_message_definition_pk": { "owner": owner, "name": self.getStreamId(), "version": latestmesagedefinition }, "cc_in_sources": [ { "end_point_type": "HTTP", "user_defined_urls": [ name ] } ], # "cc_in_sources": [ # { # "end_point_type": "MQTT", # "user_defined_urls": [ # name # ], # "username": ownerMQTT, # "password": passwordMQTT # } # ], "cc_out_sinks": [ { "name": name, "output_type": "SEAAS", "active": True, "identity_transform": True, "conditions": [], "subscription": { "seaas_destination": { "device_id": self.getDeviceId() } } } ] } return ccdef
def settime(ms_accuracy=False): import machine import utime if ms_accuracy: t, ms = time(ms_accuracy=True) else: t, ms = time(ms_accuracy=False), 0 tm = utime.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (ms,) r = machine.RTC() r.datetime(tm) print(r.datetime())
def settime(timezone_offset): # noqa t = ntp() tm = utime.localtime(t + timezone_offset * 60 * 60) try: # wipy return machine.RTC(datetime=tm) except: # esp8266 tm = tm[0:3] + (0,) + tm[3:6] + (0,) rtc = machine.RTC() rtc.datetime(tm) return rtc
def date(ref=None): from utime import localtime, time if ref: assert type(ref) is tuple d = ref else: d = localtime(time()) days = 'Sun Mon Tue Wen Thu Fri Sat'.split(' ') mos = 'Yo Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ') now = '%-3s %-3s %02d %02d:%02d:%02d %4d%s' % \ ( days[d[6]], mos[d[1]], d[2], d[3], d[4], d[5], d[0], ' ' + \ str(cfg.timezone) if cfg.timezone else '') del time, localtime return now
def get_ntp_time(): print('get_ntp_time().... ') year = utime.localtime()[0] #get current year now=ntptime.time() print('getntptime() :', utime.localtime()) HHMarch = utime.mktime((year,3 ,(31-(int(5*year/4+4))%7),1,0,0,0,0,0)) #Time of March change to CEST HHOctober = utime.mktime((year,10,(31-(int(5*year/4+1))%7),1,0,0,0,0,0)) #Time of October change to CET print('HHMarch :', HHMarch) print('HHOctober :', HHOctober) print('ntptime.NTP_DELTA :', ntptime.NTP_DELTA) if now < HHMarch : # we are before last sunday of march ntptime.NTP_DELTA = 3155673600-3600 # CET: UTC+1H print('ntptime.NTP_DELTA before last sunday of march:', ntptime.NTP_DELTA) elif now < HHOctober : # we are before last sunday of october ntptime.NTP_DELTA = 3155673600-7200 # CEST: UTC+2H print('ntptime.NTP_DELTA before last sunday of october:', ntptime.NTP_DELTA) else: # we are after last sunday of october ntptime.NTP_DELTA = 3155673600-3600 # CET: UTC+1H print('ntptime.NTP_DELTA : after last sunday of october', ntptime.NTP_DELTA) ntptime.settime() # set the rtc datetime from the remote server
def process(self): if self.verbose: print("getting ntptime") is_time_set = False while not is_time_set: try: ntptime.settime() if self.verbose: print("ntptime was set") is_time_set = True except: time.sleep(1) if self.verbose: print(".", end="") tm = time.localtime() # add delay tm_sec = time.mktime((tm[0], tm[1], tm[2], tm[3] + self.utcDelay, tm[4], tm[5], tm[6], tm[7])) tm = time.localtime(tm_sec) # convert to format for rtc tm = tm[0:3] + (0, ) + tm[3:6] + (0, ) # set real time clock on controller machine.RTC().datetime(tm)
def make_description(self, path, fname, full): global _month_name if full: stat = uos.stat(self.get_absolute_path(path, fname)) file_permissions = ("drwxr-xr-x" if (stat[0] & 0o170000 == 0o040000) else "-rw-r--r--") file_size = stat[6] try: tm = localtime(stat[7]) if tm[0] != localtime()[0]: description = "{} 1 owner group {:>10} {} {:2} {:>5} {}\r\n".\ format(file_permissions, file_size, _month_name[tm[1]], tm[2], tm[0], fname) else: description = "{} 1 owner group {:>10} {} {:2} {:02}:{:02} {}\r\n".\ format(file_permissions, file_size, _month_name[tm[1]], tm[2], tm[3], tm[4], fname) except OverflowError: description = "{} 1 owner group {:>10} {}\r\n".\ format(file_permissions, file_size, fname) else: description = fname + "\r\n" return description
def get_sunrise_time(self, date=None): """ Calculate the sunrise time for given date. :param date: Reference date. Today if not provided. :return: UTC sunrise datetime :raises: SunTimeException when there is no sunrise and sunset on given location and date """ date = localtime() if date is None else date sr = self._calc_sun_time(date, True) if sr is None: raise SunTimeException( 'The sun never rises on this location (on the specified date)') else: return sr
def initialize_rtc_from_ntp(): """Initialize RTC date/time from NTP.""" ntptime.settime() utime.sleep(5) current_time = list(utime.localtime()) time_to_set = [] time_to_set.append(current_time[0]) # Year time_to_set.append(current_time[1]) # Month time_to_set.append(current_time[2]) # Day time_to_set.append(current_time[6]) # Weekday time_to_set.append(current_time[3]) # Hour time_to_set.append(current_time[4]) # Minute time_to_set.append(current_time[5]) # Second _get_rtc().datetime(time_to_set)
def test_time_basics(): rtc = machine.RTC() print('rtc.datetime():', rtc.datetime()) # ...........(2000, 1, 1, 5, 0, 0, 0, 0) rtc.datetime((2019, 5, 1, 4, 13, 12, 11, 0)) # same as in tests.mocks.machine.RTC.datetime print('rtc.datetime():', rtc.datetime()) # ...........(2019, 5, 1, 2, 13, 12, 11, 0) print('utime.localtime():', utime.localtime()) # .....(2019, 5, 1, 13, 12, 11, 2, 121) result = utime.localtime(0) print('utime.localtime(0):', result) assert result == (2000, 1, 1, 0, 0, 0, 5, 1), result result = utime.mktime((2000, 1, 1, 0, 0, 0, 5, 1)) print('utime.mktime((2000, 1, 1, 0, 0, 0, 5, 1)):', result) assert result == 0, result result = utime.mktime((2019, 1, 1, 0, 0, 0, 5, 1)) print('utime.mktime((2019, 1, 1, 0, 0, 0, 5, 1)):', result) assert result == 599616000, result
def get_time(sock=None): try: t = utime.localtime(ntptime.time()) h = zfill(str(t[3]), 2) m = zfill(str(t[4]), 2) s = zfill(str(t[5]), 2) time = "%s:%s:%s GMT\r\n%s/%s/%s" % (h, m, s, t[1], t[2], t[0]) print(time) send_output(sock, time) except: out = "could not get time" print(out) send_output(sock, out)
def sync_rtc(interval=11, max_count=100): print("Try to synchronize network time") rtc = RTC() rtc.ntp_sync('ntp.nict.jp', tz='JST-9') count = 0 while count < max_count: if rtc.synced(): message = 'RTC synced. {}'.format(utime.localtime()) print(message) lcd.println(message, color=lcd.GREEN) break utime.sleep_ms(interval) #print('.') count += 1
def ntp_time_sync(syncing=lambda: _noop()): import ntptime from utime import sleep, localtime time_set = False while not time_set: try: syncing() print('ntp_sync::fetching') ntptime.settime() time_set = True except Exception as e: print('ntp_sync::except:', str(e)) sleep(2) print('ntp_sync::utc:', str(localtime()))
def get_lt_str(self): # TODO Daylight Saving Time dt = utime.localtime(utime.time() - TIME_ZONE_OFFSET) dt_str = (str(dt[0]) + "-" + str(dt[1]) + "-" + str(dt[2]) + " " + str(int(dt[3])) + ":" + str(dt[4]) + ":" + str(dt[5]) ) return dt_str
async def check_connection(event): global net_fail_count global net_succ_count while True: sta_if = network.WLAN(network.STA_IF) is_connected = sta_if.isconnected() if not is_connected: net_succ_count = 0 net_fail_count += 1 if net_fail_count >= 10: from machine import reset reset() else: event.set() net_succ_count += 1 if net_succ_count >= 5: net_fail_count = 0 if debug: print("Time is:", utime.localtime()[4], ":", utime.localtime()[5], "WIFI is connected: ", event.is_set(), "Nr times failed: ", net_fail_count, net_succ_count, "Free memory: ", gc.mem_free()) await asyncio.sleep(10)
def Hall_handler1(pin): SerRead() global count0 global count1 global count2 global count3 global count4 global flow1 global flow2 global flow3 global flow4 global ReStr global H1Status uart = machine.UART(1, baudrate=115800, tx=Pin(8), rx=Pin(9), bits=8, parity=None, stop=1) if pin.value(): if pin is Hall_Pump_Bed1: now = utime.localtime() Sensor = 'Pump1' count1 = count1 + 2.53 flow1 = round(count1 / 10, 4) ReStr2 = str(", Bed1+: ") + str(flow1) + str(" L") #ReStr2 = str(str(flow1) + str(" L")) print(str(ReStr2)) print( str(+now[2]) + '-' + str(now[1]) + '-' + str(now[0]) + " " + str(now[3]) + ":" + str(now[4]) + ":" + str(now[5]) + str(ReStr)) ReStr = (str(+now[2]) + '-' + str(now[1]) + '-' + str(now[0]) + " " + str(now[3]) + ":" + str(now[4]) + ":" + str(now[5]) + str(ReStr)) ReStr2 = (str(+now[2]) + '-' + str(now[1]) + '-' + str(now[0]) + " " + str(now[3]) + ":" + str(now[4]) + ":" + str(now[5]) + str(" ") + str(ReStr2)) ReStr = str("b'") + str(ReStr) + str("\n") ReStr2 = str("b'") + str(ReStr2) + str("\n") #uart.write(str(ReStr)) H2Status = ReStr2 ReStr = "" led.toggle() #utime.sleep(0.7) H1Status = str(ReStr2) return (H1Status)
def printLocalTime(): global TZ global timeUpdated t1 = str(int(utime.localtime()[0]) - 2000) + "," + str( utime.localtime()[1]) + "," + str(utime.localtime()[2]) + "," + str( utime.localtime()[3]) + "," + str( utime.localtime()[4]) + "," + str(utime.localtime()[5]) timeMsg = t1 + "," + TZ xbee_debug("#T", timeMsg + "\r\n") timeUpdated = True
def history_timestamps(rate, max_sample_index): (year, _, _, now_h, now_m, now_s, _, _) = utime.localtime() now_s += now_m * 60 reltime = year < 2020 # If NTP is not synced, fall back to relative time offsets. if reltime: now_h, now_s = 0, 0 offset = now_s // rate labels = {} for i in range(ceil(max_sample_index / (3600 / rate))): h = now_h - i if reltime else (now_h - i + 24) % 24 half_h = h + 1 if reltime else h labels[offset + 3600 // rate * i - 1800 // rate] = '%d:30' % half_h labels[offset + 3600 // rate * i] = '%d:00' % h return labels
def do_networking(): wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print("connecting to network...") wlan.connect("GIOT", "GIOTGIOTGIOT") while not wlan.isconnected(): pass print("network config:", wlan.ifconfig()) from ntptime import settime settime() import utime print(utime.localtime())
def too_old(file): """Rename unsent files older than buffer days. Params: file(str) Returns: True or False """ filename = file.split("/")[-1] pathname = file.replace("/" + file.split("/")[-1], "") if utime.mktime(utime.localtime()) - utime.mktime([int(filename[0:4]),int(filename[4:6]),int(filename[6:8]),0,0,0,0,0]) > constants.BUF_DAYS * 86400: uos.rename(file, pathname + "/" + constants.SENT_FILE_PFX + filename) if pathname + "/" + constants.TMP_FILE_PFX + filename in uos.listdir(pathname): uos.remove(pathname + "/" + constants.TMP_FILE_PFX + filename) return True return False
def display_time(disp, pos_y): '''Draws digital time in hh:mm:ss AM/PM format Args: disp (display): The display to be drawn on pos_y (int): The y position to start drawing at ''' time = utime.localtime() hours = time[3] if time[3] < 13 else time[3] - 12 am_pm = 'AM' if time[3] < 13 else 'PM' time_string = "{:02d}:{:02d}:{:02d} {}".format(hours, time[4], time[5], am_pm) pos_x = 80 - round(len(time_string) / 2 * 14) disp = display.open() disp.print(time_string, posx=pos_x, posy=pos_y, font=display.FONT20)
def get(self): print("Getting time") time_data = self.ntw.request("GET", self.url) print("Time response =", time_data) if time_data is not None: unix_timestamp = ( int(time_data["unixtime"]) - 946684800 + 3600 * const.CLOCK_UTC_OFFSET ) is_set = True else: unix_timestamp = 0 is_set = False self.tm = utime.localtime(unix_timestamp) machine.RTC().datetime(self.tm[0:3] + (0,) + self.tm[3:6] + (0,)) print("machine time set") return is_set
def time_event(self): while True: time = None if utime.localtime()[4] < 10: time = str(utime.localtime()[3]) + ':0' + str( utime.localtime()[4]) else: time = str(utime.localtime()[3]) + ':' + str( utime.localtime()[4]) if utime.localtime()[4] % 15 == 0 and utime.localtime()[5] == 0: level = self.light_sensor.get_level() self.controller.notify_light_level(level) self.controller.check_time(time) sleep(1)
def save_time(self): (YY, MM, mday, hh, mm, ss, wday, yday) = utime.localtime() self.ds3231.writeto_mem(DS3231_I2C_ADDR, 0, tobytes(dec2bcd(ss))) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 1, tobytes(dec2bcd(mm))) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 2, tobytes(dec2bcd(hh))) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 3, tobytes(dec2bcd(wday + 1))) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 4, tobytes(dec2bcd(mday))) if YY >= 2000: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, tobytes(dec2bcd(MM) | 0b10000000)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, tobytes(dec2bcd(YY - 2000))) else: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, tobytes(dec2bcd(MM))) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, tobytes(dec2bcd(YY - 1900)))
def watch(): while True: # start position for Date if not rtc.synced(): # set color to sync status lcd.setColor(lcd.RED) else: lcd.setColor(lcd.GREEN) # lcd.setCursor(92, 227) # uncomment if you need date on display # lcd.print("Date {}".format(utime.strftime("%Y-%m-%d", utime.localtime()))) # uncomment if needed # start position for time only lcd.setCursor(213, 227) # uncomment if date active (see upper lines) lcd.print(" Time {}".format( utime.strftime('%H:%M:%S', utime.localtime()))) utime.sleep(1)
def get_ccc_day(): ''' Return day of current CCC event ''' (year, month, day, hour, minute, seconds, weekday, _yday) = \ utime.localtime() for start, end, buildup, teardown in events: start_year, end_year = start[0], end[0] start_month, end_month = start[1], end[1] start_day, end_day = start[2], end[2] if year in range(start_year, end_year + 1) \ and month in range(start_month, end_month + 1) \ and day in range(start_day - buildup, end_day + 1 + teardown): color = (255, 0, 0) \ if day < start_day or day > end_day else (0, 255, 0) return day - (start_day - 1), color
def refresh(self, display_lines): if not self.display: self.try_init() if not self.display: return t = utime.localtime() self.display.fill(0) self.display.text('{:02d}:{:02d}:{:02d}'.format(t[3], t[4], t[5]), 0, 0) offset_y = 8 for line in display_lines: self.display.text(line, 0, offset_y) offset_y += 8 try: self.display.show() except Exception as e: print('Error showing display', e)
def DynamicConnectInfo(self): numTime = utime.mktime(utime.localtime()) nonce = self.rundom() msg = "deviceName={}&nonce={}&productId={}×tamp={}".format( self.devicename, nonce, self.productID, numTime) hmacInfo = hmacSha1.hmac_sha1(self.ProductSecret, msg) base64_msg = base64.b64encode(bytes(hmacInfo, "utf8")) data = { "deviceName": self.devicename, "nonce": nonce, "productId": self.productID, "timestamp": numTime, "signature": base64_msg.decode() } data_json = ujson.dumps(data) response = request.post(self.url, data=data_json) res_raw = response.json() code = res_raw.get("code") if code == 1021: print("Device has been activated!") if "tx_secret.json" in uos.listdir(): msg = check_secret(self.devicename) if msg: self.devicePsk = msg self.formatConnectInfo() return 0 else: print( "The device is active, but the key file tx_secret.json is missing." ) return -1 payload = res_raw.get("payload") mode = ucryptolib.MODE_CBC raw = base64.b64decode(payload) key = self.ProductSecret[0:16].encode() iv = b"0000000000000000" cryptos = ucryptolib.aes(key, mode, iv) plain_text = cryptos.decrypt(raw) data = plain_text.decode().split("\x00")[0] self.devicePsk = ujson.loads(data).get("psk") data = {self.devicename: self.devicePsk} save_Secret(data) self.formatConnectInfo()
def test_gps(disp): now = pyb.millis() disp.task() if disp.has_gps_fix(): t = disp.get_date() if t == 0: timestr = "no time data" else: timestr = comutils.fmt_time(utime.localtime(t)) print("GPS[%u]: long= %f , lat= %f , time= %s" % (now, disp.get_longitude(), disp.get_latitude(), timestr)) elif disp.gps_ok: if disp.gps.has_nmea: print("GPS[%u] no fix" % (now)) else: print("GPS[%u] no data" % (now)) else: print("GPS[%u] error" % (now))
def tagify(ob, aux): # TODO: make this extensible? # cbor.register_tag_handler(tagnumber, tag_handler) # where tag_handler takes (tagnumber, tagged_object) if aux == _CBOR_TAG_DATE_STRING: # TODO: parse RFC3339 date string pass if aux == _CBOR_TAG_DATE_ARRAY: return utime.localtime(ob) if aux == _CBOR_TAG_BIGNUM: return _bytes_to_biguint(ob) if aux == _CBOR_TAG_NEGBIGNUM: return -1 - _bytes_to_biguint(ob) if aux == _CBOR_TAG_REGEX: # Is this actually a good idea? Should we just return the tag and the raw value to the user somehow? return ure.compile(ob) return Tag(aux, ob)
def render_text(d, text, blankidx=None): bs = bytearray(text) if blankidx is not None: bs[blankidx:blankidx + 1] = b'_' if MODE == DISPLAY: ltime = utime.localtime() wday = ltime[6] d.print(DAY_STRING[wday] + bs.decode(), fg=(128, 128, 128), bg=None, posx=0, posy=7 * 8) else: fg_color = (0, 255, 128) if MODE in (CHANGE_YEAR, CHANGE_MONTH, CHANGE_DAY) else (0, 128, 128) d.print(MODES[MODE], fg=fg_color, bg=None, posx=0, posy=7 * 8)
def checkBatt(self): volt = self.py.read_battery_voltage() percentage = volt/3.7 if(percentage < .10 and self.batteryTrack == 3): Time = utime.localtime(None) currentTime = str(Time[1]) + "/" + str(Time[2]) + "/" + str(Time[0]) + " at " + str(Time[3]) + ":" + str(Time[4]) + ":" + str(Time[5]) self.Logger.log("Battery life critically low at " + str(percentage*100) + "% at " + currentTime) self.batteryTrack+=1 elif(percentage < .25 and self.batteryTrack == 2): self.Logger.log("Battery life at " + str(percentage*100) +"%") self.batteryTrack+=1 elif(percentage < .5 and self.batteryTrack == 1): self.Logger.log("Battery life at " + str(percentage*100) +"%") self.batteryTrack+=1 elif(percentage <.75 and self.batteryTrack == 0): self.Logger.log("Battery life at " + str(percentage*100) +"%") self.batteryTrack+=1
def getTime(): # convert RTC time to more readable time and date (year, month, day, hour, minute, second, weekday, yearday) = localtime() #t = localtime() hour = (hour % 12) + 7 hour = str(hour) minute = str(minute) if (len(hour) == 1): hour = "0" + hour if (len(minute) == 1): minute = "0" + minute hhmm = hour + ":" + minute return hhmm
def _updateTimestamp(self): now = utime.localtime() self.timestamp = '{0:04d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}.000+0000'.format(*now)
def set_datetime(secs): import utime import machine tm = utime.localtime(secs) tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm)
def get_localtime(self) : secs = utime.time() secs += self.tzd.get_offset_hours() * 60 * 60 return utime.localtime(secs)
def formatTime(self, record, datefmt=None): assert datefmt is None # datefmt is not supported ct = utime.localtime(record.created) return "{0}-{1}-{2} {3}:{4}:{5}".format(*ct)
def secs_to_string(secs=None): import core import utime localtime = utime.localtime(secs) return localtime_to_string(localtime)
wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() for net in nets: if net.ssid == 'FabLab': print('Network found!') wlan.connect(net.ssid, auth=(net.sec, 'MakerFaire'), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!') break rtc = machine.RTC() rtc.init((2015, 1, 1, 1, 0, 0, 0, 0)) print("Before network time adjust", rtc.now()) print('Setting RTC using Sodaq time server') s=socket.socket() addr = socket.getaddrinfo('time.sodaq.net', 80)[0][-1] s.connect(addr) s.send(b'GET / HTTP/1.1\r\nHost: time.sodaq.net\r\n\r\n') ris=s.recv(1024).decode() s.close() rows = ris.split('\r\n') # transform string in list of strings seconds = rows[7] print (seconds) print("After network time adjust") rtc.init(utime.localtime(int(seconds))) print(rtc.now())
def get_datetime_from_secs(secs): import utime tm = utime.localtime(secs) return DateTimeCmd.datetime_str(tm)
def date(secs=False): localtime = utime.localtime() if secs: print(utime.mktime(localtime)) else: print(core.util.localtime_to_string(localtime))
import network, usocket, ustruct, utime SSID='' # Network SSID KEY='' # Network key TIMESTAMP = 2208988800+946684800 # Init wlan module and connect to network print("Trying to connect... (may take a while)...") wlan = network.WINC() wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) # We should have a valid IP now via DHCP print(wlan.ifconfig()) # Create new socket client = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) # Get addr info via DNS addr = usocket.getaddrinfo("pool.ntp.org", 123)[0][4] # Send query client.sendto('\x1b' + 47 * '\0', addr) data, address = client.recvfrom(1024) # Print time t = ustruct.unpack(">IIIIIIIIIIII", data)[10] - TIMESTAMP print ("Year:%d Month:%d Day:%d Time: %d:%d:%d" % (utime.localtime(t)[0:6]))
from machine import SD from machine import Timer from L76GNSS import L76GNSS from pytrack import Pytrack # setup as a station import gc time.sleep(2) gc.enable() # setup rtc rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org") utime.sleep_ms(750) print('\nRTC Set from NTP to UTC:', rtc.now()) utime.timezone(7200) print('Adjusted from UTC to EST timezone', utime.localtime(), '\n') py = Pytrack() l76 = L76GNSS(py, timeout=30) chrono = Timer.Chrono() chrono.start() #sd = SD() #os.mount(sd, '/sd') #f = open('/sd/gps-record.txt', 'w') while (True): coord = l76.coordinates() #f.write("{} - {}\n".format(coord, rtc.now())) print("{} - {} - {}".format(coord, rtc.now(), gc.mem_free()))