def nvs_write(): while True: time.sleep(1) print('Write.....') p = int(pycom.nvs_get('p')) pycom.nvs_set('t'+str(p), utime.mktime(utime.gmtime())) pycom.nvs_set('d'+str(p), utime.mktime(utime.gmtime())) p = p + 1 pycom.nvs_set('p', p) print(pycom.nvs_get('p'))
def ping_st(smartthings_handler, check_interval=300): while True: initialize_rtc() body = {'check_in_at': tools.datetime_to_iso(utime.gmtime(), "Z")} smartthings_handler.notify(body) gc.collect() utime.sleep(check_interval)
def rtc(self, time_to_set): """ Set the DS3231 RTC Args: time_to_set (number): Seconds since epoch """ self.rtc_tm = utime.gmtime(time_to_set)
def forceRTC(dt, type_dt): global rtc try: # dt = pycom.nvs_get('rtc') if type_dt == "tuple": print("Step RTC - Forcing Tuple RTC to " + str(dt)) rtc.init(dt) elif type_dt == "epoch": print("Step RTC - Forcing Epoch RTC to " + str(int(dt))) rtc.init(utime.gmtime(int(dt))) utime.sleep(3) tools.debug("Setting time: " + str(int(utime.time())), "v") try: pycom.nvs_set('clock', str(int(utime.time()))) except OSError as err: tools.debug("Error setting RTC: " + str(err), "v") utime.sleep(5) try: dt_current = pycom.nvs_get('clock') except OSError as err: dt_current = -1 tools.debug("Error getting RTC: " + str(err), "v") tools.debug( "Current time: " + str(int(dt_current)) + " - RTC: " + str(getDatetime()), "v") except Exception as e1: checkError("Step RTC - Error initializing parametetr", e1)
def settime(): t = time() import machine tm = utime.gmtime(t) machine.RTC().datetime( (tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
def makePayload(self, event): payload = None command = event['Command'] idbytes = event['ID'].to_bytes(2, 'little') event_ts = event['Time'] try: if command == eventlog.CMD_TAG_DETECTED: # Tag with 4-Byte UID detected # <0x01> <Event ID 0..1> <Timestamp 0..3> <UID 0..3/6/9> timeBytes = event_ts.to_bytes(4, 'little') uid = event['Data'][0:10] # remove trailing 0x00 uid_size = 10 for i in range(uid_size - 1, 3, -1): if uid[i] != 0x00: break uid_size = uid_size - 1 uid = uid[:uid_size] payload = bytes([0x01]) + idbytes + timeBytes + uid uidText = ubinascii.hexlify(uid).decode() self.log("CMD 0x01 [NFC_DETECTED] SEQ#", event['ID'], ". uid =", uidText, ", ts =", event_ts) if command == eventlog.CMD_TIME_REQUEST2: # ask backend for current time (new) # <0x04> <ID 0..1> <Our Time 0..3> mytime = time.time().to_bytes(4, 'little') payload = bytes([command]) + idbytes + mytime self.log("CMD 0x04 [TIME_REQUEST] ID#", event['ID'], ". our_time =", time.time(), utime.gmtime(time.time())) if command == eventlog.CMD_TIME_CHANGED: # <0x05> <Event ID 0..1> <Our Time 0..3> <Old Time 0..3> mytime = event_ts.to_bytes(4, 'little') oldTime = event['Data'][0:4] payload = bytes([eventlog.CMD_TIME_CHANGED ]) + idbytes + mytime + oldTime self.log("CMD 0x05 [TIME_CHANGED] SEQ#", event['ID'], ". our_time =", event_ts, utime.gmtime(event_ts), ", old_time =", oldTime) except Exception as e: self.log("ERROR: Unable to prepare LORA payload:", e.args[0], e) return payload
def settime(): t, micro_sec = time() import machine import utime print("server: " + str(host) + " Time: " + str(t)) tm = utime.gmtime(t) machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], micro_sec))
def setTime(): logger.log('Setting time...') if connection.test(): tm = utime.gmtime(ntptime.time()) machine.RTC().datetime( (tm[0], tm[1], tm[2], tm[6] + 1, tm[3] + 2, tm[4], tm[5], 0)) logger.log('Time is set!') else: logger.log('Time could not be set!')
def next_time_of_day(hour, minute): tt = time.gmtime() yy, mo, dd, hh, mm = tt[0:5] if hh <= hour and mm < minute: next_tt = (yy, mo, dd, hour, minute, 0, 0, 0) else: next_tt = (yy, mo, dd + 1, hour, minute, 0, 0, 0) return next_tt
def initRTC(): global rtc try: dt = pycom.nvs_get('clock') print("Step RTC - Initializing RTC to " + str(int(dt))) rtc.init(utime.gmtime(int(dt))) utime.sleep(2) except Exception as e1: checkError("Step RTC - Error initializing parametetr", e1)
def sync_clock(self, epoc): try: rtc = RTC() rtc.init(utime.gmtime(epoc)) except Exception as ex: print("Exception setting system data/time: {}".format(ex)) return False return True
def next_even_minutes(minutes_divisor, plus=0): tt = time.gmtime() yy, mo, dd, hh, mm = tt[0:5] next_minutes = (mm // minutes_divisor) * minutes_divisor + plus if next_minutes <= mm: next_minutes += minutes_divisor # time.mktime() will handle minutes overflow as you would expect: # e.g. 14:70 -> 15:10 next_tt = (yy, mo, dd, hh, next_minutes, 0, 0, 0) return next_tt
def calculate_new_time(duration_sec, hour_begin, minute_begin, sec_begin): '''get duration and current time hour, minute and seconds and returns a new time tuple''' systemdate = utime.gmtime() #print(systemdate) temp_begin_sec = utime.mktime((systemdate[0], systemdate[1], systemdate[2], hour_begin, minute_begin, sec_begin, 0, 0)) #print(temp_begin_sec) temp_begin_sec = temp_begin_sec + duration_sec new_time_tuple = utime.localtime(temp_begin_sec) #print(new_time) return new_time_tuple
def initTime(): print('initTime()....') rtc = RTC() rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time print('Time : ', rtc.datetime()) # get date and time # synchronize with ntp # need to be connected to wifi ntptime.settime() # set the rtc datetime from the remote server print('Time(UTC): ', rtc.datetime()) # get the date and time in UTC #print('rtc.now():', rtc.now()) print('Time:', utime.gmtime())
def setntp(ntpserver, timezone): res = False try: import ntptime ntptime.host = ntpserver t = ntptime.time() tm = utime.gmtime(t + (timezone * 60)) machine.RTC().datetime( (tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0)) res = True except: res = False return res
def start(self): try: tools.debug("Scheduler - Daily Reset: " + globalVars.dailyreset, "v") tools.debug( "Scheduler - Start Downlink: " + globalVars.startDownlink, "v") tools.debug("Scheduler - End Downlink: " + globalVars.endDownlink, "v") tools.debug( "Scheduler - Starting scheduler, Time: " + str(utime.gmtime()), "v") except BaseException as e: checkError("Error on scheduler", e)
def checkDutyCycle(self): try: dt = utime.gmtime() if globalVars.flag_rtc_syncro == False: tools.debug( "Scheduler - RTC is not syncronized, so not possible to check the DutyCycle properly", "v") return dt_dm = str(dt[6]) + " " + str(dt[2]) + "-" + str( dt[1]) + "-" + str(dt[0]) + " " + str(dt[3]) + ":" + str( dt[4]) + ":" + str(dt[5]) tools.debug( "Scheduler - Current date: " + str(dt_dm) + " - Daily ends at: " + globalVars.dailyStandBy + "- Downlinks begin at: " + globalVars.startDownlink, "v") # --------- S1 (Sleep Cycle 1) - From End of the day to first Downlink message --------------- if dt[3] == int( globalVars.dailyStandBy.split(":") [0]) and dt[4] == int( globalVars.dailyStandBy.split(":")[1]) and dt[5] > int( globalVars.dailyStandBy.split(":")[2]) and dt[5] < ( int(globalVars.dailyStandBy.split(":")[2]) + 60): rnd_tmp_1 = tools.calculateSleepTime(globalVars.dailyStandBy, globalVars.startDownlink) tools.debug( "Scheduler - DutyCycle - Going to sleep because the day ends and until the downlinks begin: " + str(rnd_tmp_1), "v") tools.deepSleepWiloc(rnd_tmp_1) # --------- S2 - Backup sleeping process in case the device is still on when passing the maximum downlink time --------------- if dt[3] == int( globalVars.endDownlink.split(":")[0]) and dt[4] == int( globalVars.endDownlink.split(":")[1]) and dt[5] > int( globalVars.endDownlink.split(":")[2]) and dt[5] < ( int(globalVars.endDownlink.split(":")[2]) + 60): rnm_tmp = tools.calculateSleepTime(globalVars.endDownlink, globalVars.dailyStart) tools.debug( "Scheduler - DutyCycle - Going to sleep until the day begins: " + str(rnm_tmp), "v") tools.deepSleepWiloc(rnm_tmp) # ---------- Check if today is the day OFF -------------- if dt[6] in globalVars.dayOff: tools.debug( "Scheduler - Going to sleep because is the day OFF", "v") tools.deepSleepWiloc(86460) except BaseException as e: checkError("Error on scheduler", e)
def checkNextReset(self): dt = utime.gmtime() tools.debug( "Scheduler: " + str(dt[6]) + " " + str(dt[2]) + "-" + str(dt[1]) + "-" + str(dt[0]) + " " + str(dt[3]) + ":" + str(dt[4]) + ":" + str(dt[5]), 'v') if dt[3] == int(globalVars.dailyreset.split(":")[0]) and dt[4] == int( globalVars.dailyreset.split(":")[1]) and dt[5] > int( globalVars.dailyreset.split(":")[2]) and dt[5] < ( int(globalVars.dailyreset.split(":")[2]) + 15): tools.debug( "Scheduler - Reseting module because of daily schedule", "v") utime.sleep(2) machine.reset()
def acquireNetworkTime(self, wdt): self.log("Starting time sync") self.isAlreadyRunning = True isClockSynced = False clockSyncID = 0 sleepDuration = self.options['clock_sync_retry_interval'] sleepFactor = 1.3 sleepMaxSeconds = 300 if wdt != None: sleepMaxSeconds = (config.WDT_MAIN_TIMEOUT / 1000) - 2 while not isClockSynced: # watchdog feed if (config.WDT_MAIN_TIMEOUT > 0): wdt.feed() self.led.error() try: clockSyncID += 1 if clockSyncID > 30: clockSyncID = 0 clockSyncEvent = { 'ID': clockSyncID, 'Command': eventlog.CMD_TIME_REQUEST2, 'Time': time.time(), 'Data': None } # get time oldTime = time.time() tuple_time = self.onNetworkTimeRequest(clockSyncEvent) #tuple # handle response if tuple_time != None: self.setTime(tuple_time, False) timeDifference = time.time() - oldTime # is clock synced? if abs(timeDifference) < self.options['clock_accuracy']: isClockSynced = True self.isAlreadyRunning = False self.log("Clock is now synced to ", utime.gmtime(time.time()), "with accuracy of", abs(timeDifference), "seconds") except Exception as e: self.log("ERROR", "Unable to synchronize clock:", e.args[0], e) if not isClockSynced: time.sleep(sleepDuration)
def save_time(self): (YY, MM, DD, hh, mm, ss, wday, yday) = utime.gmtime() wday += 1 # needs to be 1 == Monday, 7 == Sunday self.ds3231.writeto_mem(DS3231_I2C_ADDR, 0, dec2bcd(ss)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 1, dec2bcd(mm)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 2, dec2bcd(hh)) # Sets to 24hr mode self.ds3231.writeto_mem(DS3231_I2C_ADDR, 3, dec2bcd(wday)) # 1 == Monday, 7 == Sunday self.ds3231.writeto_mem(DS3231_I2C_ADDR, 4, dec2bcd(DD)) if YY >= 2000: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, dec2bcd(MM) | 0b10000000) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, dec2bcd(YY-2000)) else: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, dec2bcd(MM)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, dec2bcd(YY-1900))
def set_time(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1B addr = socket.getaddrinfo('192.168.68.111', 123)[0][-1] res = s.sendto(NTP_QUERY, addr) msg = s.recv(48) s.close() seconds = struct.unpack("!I", msg[40:44])[0] fract = struct.unpack("!I", msg[44:48])[0] ms = ((fract * 1000) >> 32) * 1000 tm = utime.gmtime(seconds - NTP_DELTA) machine.RTC().datetime( (tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], ms))
def getGPS(): global py try: l76 = L76GNSS(py) coord = dict(latitude='', longitude='', HDOP=0.0) loop_counter = 5 if globalVars.gps_enabled == True: while coord['latitude'] == '' and coord[ 'longitude'] == '' and loop_counter > 0: debug("GPS Acquisition, loop: " + str(loop_counter), "v") loop_counter = loop_counter - 1 coord = l76.get_location(debug=False, tout=globalVars.gps_timeout) debug( "HDOP: " + str(coord['HDOP']) + "Latitude: " + str(coord['latitude']) + " - Longitude: " + str(coord['longitude']), 'v') if coord['latitude'] != '' and coord['longitude'] != '': haversine(coord['latitude'], coord['longitude'], globalVars.last_lat_tmp, globalVars.last_lon_tmp) big_endian_latitude = bytearray( struct.pack(">I", int(coord['latitude'] * 1000000))) big_endian_longitude = bytearray( struct.pack(">I", int(coord['longitude'] * 1000000))) dt = l76.getUTCDateTimeTuple(debug=False) if dt is not None: forceRTC(dt, "tuple") debug( "Updating timestamp from GPS - " + str(utime.time()) + " - GMT: " + str(utime.gmtime()), "v") globalVars.flag_rtc_syncro = True if (coord['latitude'] == '') or (coord['longitude'] == '') or (float( str(coord['HDOP'])) > float(globalVars.min_hdop)): return None, None else: globalVars.last_lat_tmp = coord['latitude'] globalVars.last_lon_tmp = coord['longitude'] return big_endian_latitude, big_endian_longitude except BaseException as e: checkError("Error getting GPS", e) return None, None
def __init__(self, *args, **kwargs): d = defaults # d is the config dict: initially populate with default values for arg in args: d.update(arg) # Hardware and network configs d.update(kwargs) # d is now populated. self.user_start = d['user_start'] shan = d['status_handler'] self.s_han = (default_status_handler, ()) if shan is None else shan # coro self.crash_han = d['crash_handler'] self.wifi_han = d['wifi_handler'] self.init_str = buildinit(d) self.keepalive = d['keepalive'] self._evtrun = asyncio.Event() self.verbose = d['verbose'] # Watchdog timeout for ESP8266 (ms). wdog = d['timeout'] * 1000 # SynCom string mode self.channel = SynCom(False, d['sckin'], d['sckout'], d['srx'], d['stx'], d['reset'], wdog, True, self.verbose) if 'led' in d: asyncio.create_task(heartbeat(d['led'])) # Start the SynCom instance. This will run self.start(). If an error # occurs self.quit() is called which returns to Syncom's start() method. # This waits on ._die before forcing a failure on the ESP8266 and re-running # self.start() to perform a clean restart. asyncio.create_task(self.channel.start(self.start, self._die)) self.subs = {} # (callback, qos, args) indexed by topic self.publock = asyncio.Lock() self.puback = asyncio.Event() self.evttim = asyncio.Event() self.evtwifi = asyncio.Event() # Only specify network on first run self.first_run = True self._time = 0 # NTP time. Invalid. # ESP8266 returns seconds from 2000 because I believed the docs. # Maintainers change the epoch on a whim. # Calculate ofsets in CPython using datetime.date: # (date(2000, 1, 1) - date(1970, 1, 1)).days * 24*60*60 epoch = {2000 : 0, 1970 : 946684800} # Offset to add. self._epoch_fix = epoch[gmtime(0)[0]] # Find offset on current platform
def checkOvernightCycle(self, frameid, framescounter): try: dt = utime.gmtime() if globalVars.flag_rtc_syncro == False: tools.debug( "Scheduler - RTC is not syncronized, so not possible to check the DutyCycle properly", "v") return current_wiloc_dt = str(dt[3]) + ":" + str(dt[4]) + ":" + str(dt[5]) slp_tm_day = tools.calculateSleepTime(current_wiloc_dt, globalVars.dailyStandBy) tools.debug( "Scheduler - Overnight start: " + globalVars.startDownlink + "- Overnight end: " + globalVars.endDownlink, "v") if slp_tm_day < 0: if frameid == framescounter: #------ Sleep cycle 3 (S3) --------- slp_tm = tools.calculateSleepTime(current_wiloc_dt, globalVars.dailyStart) tools.debug( "Overnight Scheduler - Going to sleep until day begins: " + str(slp_tm), "v") tools.deepSleepWiloc(slp_tm) else: #------ Sleep cycle 2 (S2) --------- rnd_secs = tools.random() tools.debug( "Overnight Scheduler - Going to sleep until next downlink: " + str(rnd_secs), "v") tools.deepSleepWiloc(rnd_secs) else: tools.debug( "Overnight Scheduler - Message received during the day, not going to sleep, current date: " + str(current_wiloc_dt) + " - Remaining day: " + str(slp_tm_day), "v") except BaseException as e: checkError("Error on scheduler OvernightCycle", e)
def save_time(self): (YY, MM, DD, hh, mm, ss, wday, yday) = utime.gmtime() wday += 1 # needs to be 1 == Monday, 7 == Sunday ###################### # Change RTC Hours # To do that change the value of hh with your current hours ####################### #Example: #hh = 8 self.ds3231.writeto_mem(DS3231_I2C_ADDR, 0, dec2bcd(ss)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 1, dec2bcd(mm)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 2, dec2bcd(hh)) # Sets to 24hr mode self.ds3231.writeto_mem(DS3231_I2C_ADDR, 3, dec2bcd(wday)) # 1 == Monday, 7 == Sunday self.ds3231.writeto_mem(DS3231_I2C_ADDR, 4, dec2bcd(DD)) if YY >= 2000: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, dec2bcd(MM) | 0b10000000) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, dec2bcd(YY - 2000)) else: self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5, dec2bcd(MM)) self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6, dec2bcd(YY - 1900))
def prettydate(JulianDay, format="{:%d %H:%M:%S}"): ''' generates string representation of julianday ''' if not JulianDay: JulianDay=julianday() if sys.implementation.name == "micropython": tobj = machine.RTC().datetime() else: tobj = datetime.datetime.now() # time.gmtime() else: if sys.implementation.name == "micropython": tobj = time.gmtime(unixsecond(JulianDay)) else: tobj = datetime.datetime.fromtimestamp(unixsecond(JulianDay)) #print("tobj={}".format(tobj.hour)) if format=="#j4": fd = int(4*(JulianDay % 1)) return ('after noon','evening','night','morning')[fd] #print("tobj:{}".format(tobj)) if sys.implementation.name == "micropython": return("{} {}:{}:{}").format(tobj[2],tobj[4],tobj[5],tobj[6]) return format.format(tobj) return ("{} {}:{}:{}").format(tobj.tm_mday,tobj.tm_hour,tobj.tm_min,tobj.tm_sec) return time.strftime(format, tobj)
def time(): NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1B addr = socket.getaddrinfo(host, 123)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.settimeout(1) res = s.sendto(NTP_QUERY, addr) msg = s.recv(48) finally: s.close() val = struct.unpack("!I", msg[40:44])[0] EPOCH_YEAR = utime.gmtime(0)[0] if EPOCH_YEAR == 2000: # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60 NTP_DELTA = 3155673600 elif EPOCH_YEAR == 1970: # (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60 NTP_DELTA = 2208988800 else: raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR)) return val - NTP_DELTA
while not sta_if.isconnected(): pass print("Connected! IP = ", sta_if.ifconfig()[0]) #oled.text("IP: " + sta_if.ifconfig()[0], 0, 30) #oled.show() #time.sleep(0.25) rtc = machine.RTC() # Sync RTC over NTP if not rtc.synced(): rtc.ntp_sync(server="hr.pool.ntp.org", tz="CET-1CEST") while not rtc.synced(): pass print(utime.gmtime()) print(utime.localtime()) # Send MQtt message def conncb(task): print("[{}] Connected".format(task)) def disconncb(task): print("[{}] Disconnected".format(task)) def subscb(task): print("[{}] Subscribed".format(task))
def gmtime_time(): return utime.gmtime(utime.time())
import machine import utime rtc = machine.RTC() rtc.ntp_sync(server="hr.pool.ntp.org", tz="CET-1CEST") rtc.synced() True utime.gmtime() (2018, 1, 29, 16, 3, 18, 2, 29) utime.localtime() (2018, 1, 29, 17, 3, 30, 2, 29)