def make_description(path, fname, full): if full: if (path == '/') and ((fname == 'flash') or (fname == 'sd')): file_permissions = "drwxrwxrwx" file_size = 0 file_time = utime.strftime("%b %d %H:%M") else: stat = uos.stat(get_absolute_path(path, fname)) file_size = stat[6] ftime = utime.localtime(stat[7]) if (stat[0] & 0o170000 == 0o040000): # directory file_permissions = "drwxrwxrwx" else: # file file_permissions = "-rw-rw-rw-" if utime.localtime()[0] == ftime[0]: file_time = utime.strftime("%b %d %H:%M", ftime) else: file_time = utime.strftime("%b %d %Y", ftime) description = "{} 1 owner group {:>10} {} {}\r\n".format( file_permissions, file_size, file_time, fname) else: description = fname + "\r\n" return description
def evaluate(self): if self.isRunning: self.currentTime = utime.time() self.currentHour = "{}".format( utime.strftime('%H', utime.localtime())) self.currentHourMinute = "{}".format( utime.strftime('%H:%M', utime.localtime())) self.currentLightSensorValue = self.lightSensor.luminance() self.isLight = self.__isItLight() self.isDark = not self.isLight self.light.evaluate() self.doorOpener.evaluate() self.fence.evaluate()
def wifi(ssid="HackheimWifi", pwd="TeletextFTW"): sta_if = network.WLAN(network.STA_IF); sta_if.active(True) sta_if.connect(ssid, pwd) tmo = 50 while not sta_if.isconnected(): utime.sleep_ms(100) tmo -= 1 if tmo == 0: break if tmo > 0: ifcfg = sta_if.ifconfig() print("WiFi started, IP:", ifcfg[0]) utime.sleep_ms(500) rtc = machine.RTC() print("Synchronize time from NTP server ...") rtc.ntp_sync(server="hr.pool.ntp.org") tmo = 100 while not rtc.synced(): utime.sleep_ms(100) tmo -= 1 if tmo == 0: break if tmo > 0: utime.sleep_ms(200) print("Time set:", utime.strftime("%c")) print("")
def loop2(): cleared=False while True: gc.collect() utime.sleep_ms(100) # reduce power consumption machine.idle() if not cleared: oled.clear() cleared=True if not queue.empty(): print("debug: {}".format(queue.qsize())) _time, pin = queue.get() print('{0} pin change {1}'.format(utime.strftime("%H:%M:%S", _time), pin)) oled.text('{0} pin change'.format(utime.strftime("%H:%M:%S", _time)), 0, 35) cleared=False
def init(): tft.font(tft.FONT_Default) fw,fh = tft.fontSize() tft.clear() tft.text(0,0*fh, "connecting...") station = network.WLAN(network.STA_IF) station.active(True) station.connect("box", "pass") time.sleep(2) if station.isconnected(): tft.text(0, 1*fh, "connected:") tft.text(0, 2*fh, station.ifconfig()[0]) rtc = machine.RTC() rtc.ntp_sync(server="hr.pool.ntp.org") tmo = 100 while not rtc.synced(): utime.sleep_ms(100) tmo -= 1 if tmo == 0: break if tmo > 0: tft.text(0, 3*fh, "Time set") utime.sleep_ms(500) t = rtc.now() a = utime.strftime("%c") tft.text(0, 4*fh, a)
def log(self, level, msg, *args): if self.isEnabledFor(level): levelname = self._level_str(level) if args: msg = msg % args logMsg = '' if self.name == 'root': logMsg = "{} - {} - {}".format(utime.strftime('%Y-%m-%d %H:%M:%S', utime.localtime()), levelname, msg) else: logMsg = "{} - {}:{} - {}".format(utime.strftime('%Y-%m-%d %H:%M:%S', utime.localtime()), levelname, self.name, msg) print(logMsg) if 'logs.log' in os.listdir() and os.stat("logs.log")[6] > 64000: os.remove("logs.log") with open("logs.log", "a") as file_object: file_object.write(logMsg + "\n")
def datetimestr(self): import sys if sys.platform == 'esp8266': year, month, day, hour, minute, second, millis, _tzinfo = utime.localtime( ) return "%d-%02d-%02dT%02d:%02d:%02d.%03d" % ( year, month, day, hour, minute, second, millis) else: return utime.strftime("%Y-%m-%dT%H:%M:%S.0000")
def __write_to_socket(self, s): contentLength = self.__calculate_content_length() s.write(b'Content-Length: %d\r\n' % contentLength) s.write(b'\r\n') s.write('{"public":true,"files":{"' + utime.strftime('%Y%m%d-%H%M%S', utime.localtime()) + '.log":{"content":"') with open(self._file_path, 'rb') as file_object: for line in file_object: s.write(line.replace(b'"', b'\"').replace(b'\n', b'<br/>')) s.write('"}}}')
def _updateTimeUsingNTP(): ulogging.info('Updating time...') import machine, utime from ..hardware.components.ds3231 import DS3231 rtc = machine.RTC() rtc.ntp_sync(server="0.be.pool.ntp.org", tz="CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00") ds3231 = DS3231(machine.I2C(freq=400000, sda=21, scl=22)) ds3231.save_time() ulogging.info("Updated time to {}".format( utime.strftime('%H:%M:%S', utime.localtime())))
def datacb(msg): print("[{}] Data arrived - topic: {}, message:{}".format(msg[0], msg[1], msg[2])) try: zz = json.loads(msg[2]) except: zz = {} #msg = zz.get('message', '') t = "{}".format(utime.strftime("%c", utime.localtime())) bullets = zz.get('bullets', True) tft.clear() #n = line_height #20 n = 0 for item in zz.get('text',['No text']): if not item.strip(): #n+=line_height continue #font.set_bold(False) n+=4 if bullets else 2 # makes multi-line bullets more separated from prev and next bullet if n+line_height > height: break if item[0] == '#': item=item[1:] #font.set_bold(True) if item[0] == '*': item=item[1:] #foo.blit(star, (2,n+7)) elif bullets: #foo.blit(bullet_surface, (7,n+13)) #(4,n+13) pass # neither a star in front of item or a bullet else: #max_chars_line+= 1 pass print("item=",item) lines = wrap(item, max_chars_line) # if line is just whitespace it returns [] print("lines=",lines) for line in lines: # a line could be blank and right now display_text doesn't like that if line.strip(): display_text(line, n) n+=line_height if zz.get('header')=='Weather': tft.circle(120, 150, 30, tft.YELLOW, tft.YELLOW) gc.collect()
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 update_clock(self): if self._isShown: if self._isSleeping: return elif self._lastInteraction + 120 < utime.time(): self._sleep() else: lcd.textClear(90, 85, ' ', lcd.WHITE) lcd.setCursor(105, 85) lcd.print("{}".format( utime.strftime('%H:%M:%S', utime.localtime()))) lcd.textClear(90, 115, ' ', lcd.WHITE) lcd.setCursor(112, 115) lcd.print("{} C".format(kippenstal.getTemperature()))
def datacb(msg): print("[{}] Data arrived - topic: {}, message:{}".format( msg[0], msg[1], msg[2])) try: zz = json.loads(msg[2]) except: zz = {} msg = zz.get('message', '') t = zz.get('time', "{}".format(utime.strftime("%c", utime.localtime()))) if msg == 'on': pin15.value(1) elif msg == 'off': pin15.value(0) else: pass d.fill(0) d.show() d.text(topic, 0, 0) d.text(t, 0, 12) d.text(msg, 0, 24) d.show()
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)
sta_if.active(True) sta_if.connect("mySSID", "wifi_password") tmo = 50 while not sta_if.isconnected(): utime.sleep_ms(100) tmo -= 1 if tmo == 0: sta_if.disconnect() break if tmo > 0: print("WiFi started") utime.sleep_ms(500) rtc = machine.RTC() print("Synchronize time from NTP server ...") rtc.ntp_sync(server="hr.pool.ntp.org") tmo = 100 while not rtc.synced(): utime.sleep_ms(100) tmo -= 1 if tmo == 0: break if tmo > 0: print("Time set") utime.sleep_ms(500) t = rtc.now() utime.strftime("%c") print("")
def loop(): while True: machine.idle() # reduce power consumption _time, pin = queue.get() # block till entry print("queue.qsize(): {}".format(queue.qsize())) print('{0} pin change {1}'.format(utime.strftime("%H:%M:%S", _time), pin))
def datetimestr(self): import sys if sys.platform == 'esp8266': return core.util.secs_to_string() else: return utime.strftime("%Y-%m-%dT%H:%M:%S.0000")
sta_if = network.WLAN(network.STA_IF) _ = sta_if.active(True) sta_if.connect("mySSID", "wifi_password") tmo = 50 while not sta_if.isconnected(): utime.sleep_ms(100) tmo -= 1 if tmo == 0: break if tmo > 0: ifcfg = sta_if.ifconfig() print("WiFi started, IP:", ifcfg[0]) utime.sleep_ms(500) rtc = machine.RTC() print("Synchronize time from NTP server ...") rtc.ntp_sync(server="hr.pool.ntp.org") tmo = 100 while not rtc.synced(): utime.sleep_ms(100) tmo -= 1 if tmo == 0: break if tmo > 0: utime.sleep_ms(200) print("Time set:", utime.strftime("%c")) print("") _ = network.ftp.start()
def main(): print( ' __ __ ___ _______ ______ _______ _______ __ __ _______ _______ ' ) print( '| |_| || | | || _ | | || || | | || || |' ) print( '| || | | || | || | _ || _ || |_| || _ || _____|' ) print( '| || | | || |_||_ | | | || |_| || || | | || |_____ ' ) print( '| || | | _|| __ || |_| || ___||_ _|| |_| ||_____ |' ) print( '| ||_|| || | | |_ | | | || || | | | | | _____| |' ) print( '|_| |_||___| |_______||___| |_||_______||___| |___| |_______||_______|' ) print('small OS for micropython ver ' + version + ' by theCodeman') print('https://github.com/TheCodeman/myos') print('MicroPython Version : {} Platform : {}'.format( sys.version, sys.platform)) timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=intCallback) while True: str = input(uos.getcwd() + '>') cmd = str.split() # print(cmd) if len(str) != 0: if cmd[0] == 'cd': try: uos.chdir(cmd[1]) except: print('bad dir') elif cmd[0] == 'ls': print('Current Directory ', uos.getcwd()) total = 0 #F 1366 lora.py print('Type Size Filename') print('----------------------------------') if len(cmd) == 2: path = cmd[1] else: path = uos.getcwd() try: for l in uos.ilistdir(path): if l[1] & 0x4000: print('D{0:>31}'.format(l[0])) else: # F 3360 myos.py total += int(uos.stat(l[0])[6]) print('F {0:<8}{1:>16}'.format( uos.stat(l[0])[6], l[0])) print('----------------------------------') print('File Size Total: {0}'.format(total)) except Exception as e: print(e) elif cmd[0] == 'cp': if len(cmd) == 3: try: with open(cmd[1], 'rb') as source: print('Source {0}'.format(cmd[1])) data = source.read() source.close() except Exception as e: print(e) try: with open(cmd[2], 'wb') as dest: print('Dest {0}'.format(cmd[2])) dest.write(data) dest.close() except Exception as e: print(e) else: print( 'cp requires source filename and destination filename ' ) elif cmd[0] == 'run': if len(cmd) == 2: __import__(cmd[1]) del sys.modules[cmd[1]] else: print('Need File Name') elif cmd[0] == 'lr': if networkUp: if len(cmd) == 1: res = ssh.list(settings.remoteIP + settings.remotePath, settings.uname, settings.upass) else: res = ssh.list( settings.remoteIP + settings.remotePath + cmd[1], settings.uname, settings.upass) print(res[0]) if res[0] == 0: print(res[1]) print(res[2]) else: print('No Network Connection') elif cmd[0] == 'put': if networkUp: res = ssh.put(settings.remoteIP + settings.remotePath + cmd[1], settings.uname, settings.upass, file=cmd[1]) if res[0] == 0: print('File %s copied to %s' % (cmd[1], settings.remotePath)) else: print('No Network Connection') elif cmd[0] == 'get': if networkUp: res = ssh.get(settings.remoteIP + settings.remotePath + cmd[1], settings.uname, settings.upass, file='$$$.tmp') if res[0] == 0: try: uos.remove(cmd[1]) except: pass uos.rename('$$$.tmp', cmd[1]) print('File %s copied from %s' % (cmd[1], settings.remotePath)) else: uos.remove('$$$.tmp') print('File Not Found') else: print('No Network Connection') elif cmd[0] == 'edit': pye(cmd[1]) elif cmd[0] == 'rm': try: uos.remove(cmd[1]) except: print('no file') elif cmd[0] == 'md': try: uos.mkdir(cmd[1]) except: print("Need Directory Name") elif cmd[0] == 'rmdir': try: uos.rmdir(cmd[1]) except: print("Need Directory Name") elif cmd[0] == 'reset': machine.reset() elif cmd[0] == 'cat': line = 0 try: f = open(cmd[1], 'r') while True: str = f.readline() if str == "": break print(str, end="") line += 1 if line > 25: print( '----- press space to continue or q to quit -----', end="") ret = getch() print( '\r \r', end="") if ret == 'q': break else: line = 0 f.close() except: print('no file') elif cmd[0] == 'time': print('Time set to: {}'.format( utime.strftime('%c', utime.localtime()))) elif cmd[0] == 'df': if len(cmd) == 1: fs_stat = uos.statvfs(uos.getcwd()) else: fs_stat = uos.statvfs(cmd[1]) fs_size = fs_stat[0] * fs_stat[2] fs_free = fs_stat[0] * fs_stat[3] print('File System Size {:,} - Free Space {:,}'.format( fs_size, fs_free)) elif cmd[0] == 'wget': if networkUp: try: response = urequests.get(cmd[1]) if response.status_code == 200: print(type(response)) print(response.text) print(type(response.text)) fileName = cmd[1].split('/') print(fileName) print(fileName[-1]) f = open(fileName[-1], 'w') f.write(response.text) f.close() else: print('Error: {0} {1}'.format( response.status_code, response.reason.decode('utf-8'))) except Exception as e: print(e) else: print('No Network Connection') elif cmd[0] == 'wifi': try: if cmd[1] == 'active': nic.active(True) if cmd[1] == 'deactive': nic.active(False) if cmd[1] == 'config': status = nic.ifconfig() print( 'IP: {0}\n\rSubnet: {1}\r\nGateway: {2}\r\nDNS: {3}' .format(status[0], status[1], status[2], status[3])) if cmd[1] == 'isconnected': print(nic.isconnected()) if cmd[1] == 'connect': try: nic.connect(cmd[2], cmd[3]) except Exception as e: print(e) if cmd[1] == 'scan': stations = nic.scan() for s in stations: if s[4] == 0: authmode = 'Open' if s[4] == 1: authmode = 'Wep' if s[4] == 2: authmode = 'WPA-PSK' if s[4] == 3: authmode = 'WPA2-PSK' if s[4] == 4: authmode = 'WPA/WPA2-PSK' print( 'SSID: {0:<32} Channel: {1} RSSSI: {2} Auth Type: {3}' .format(s[0].decode('utf-8'), s[2], s[3], authmode)) except Exception as e: print(e) print(' no action') elif cmd[0] == 'umountsd': try: uos.umountsd() except Exception as e: print(e) elif cmd[0] == 'mountsd': try: uos.mountsd() except Exception as e: print(e) elif cmd[0] == 'help': print('Command List') print('----------------------------------') print('ls - list files current directory') print( 'lr - list files on remote server optional directory') print('cat - display file') print('rm - remove file') print('df - display drive space') print('time - display time and date') print('get - scp from server') print('put - scp to server') print('md - make directory') print('rmdir - remove directory') print('run - run python script') print('edit - edit file using pye') print('modules - list installed modules') print('reset - reset board') print('wget - get file over http and save to file') print('----------------------------------') elif cmd[0] == 'exit': timer.deinit() return 1 elif cmd[0] == 'update': if networkUp: res = ssh.get(settings.remoteIP + settings.remotePath + 'micropyos.py', settings.uname, settings.upass, file='$$$.tmp') if res[0] == 0: try: uos.remove('micropyos.py') except: pass uos.rename('$$$.tmp', 'micropyos.py') print('File %s copied from %s' % ('micropyos.py', settings.remotePath)) else: uos.remove('$$$.tmp') print('File Not Found') timer.deinit() return 2 else: print('No Network Connection') elif cmd[0] == 'modules': for m in sys.modules: print(m) elif cmd[0] == 'settings': pye('settings.py') else: print('unknown command')
while not wlan.isconnected(): pass print('network config:', wlan.ifconfig()) utime.sleep(5) rtc = RTC() print("synchronize time with NTP server ...") # limit the time waiting since sometimes never connects rtc.ntp_sync(server="pool.ntp.org") for n in range(10): if rtc.synced(): break utime.sleep_ms(100) else: print("Could not synchronize with ntp") print("Time set to: {}".format(utime.strftime("%c", utime.localtime()))) mqttc = network.mqtt(mqtt_id, mqtt_aws_host, connected_cb=conncb, clientid=mqtt_id) utime.sleep(1) mqttc.config(subscribed_cb=subscb, data_cb=datacb) mqttc.subscribe(topic) cur_time = utime.time() while 1: t = utime.time() if t > cur_time + 600: print(utime.strftime("%c", utime.localtime()))
#end mqtt callbacks ################################################################ mqttc = network.mqtt(mqtt_id, "mqtt://" + mqtt_aws_host, connected_cb=conncb, clientid=mqtt_id) mqttc.start() utime.sleep(1) #mqttc.config(subscribed_cb=subscb, data_cb=datacb) #mqttc.subscribe(topic) cur_time = utime.time() while 1: t = utime.strftime("%x %X", utime.localtime()) z = bme.read_compensated_data() temp = 32 + 9 * z[0] / 500 humidity = z[2] / 1024 print(temp) print(humidity) mqttc.publish( pub_topic, json.dumps({ "header": "340 CCR: {}".format(location), "text": [ "{}".format(t), "temperature: {:.1f}".format(temp), "humidity: {:.0f}%".format(humidity) ],
# There's currently no timezone support in MicroPython, so # utime.localtime() will return UTC time (as if it was .gmtime()) # https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/blob/master/MicroPython_BUILD/components/micropython/docs/zones.csv rtc_timeout=10 rtc = machine.RTC() rtc.ntp_sync(server=settings.ntpserver, tz=settings.tz) while not rtc.synced(): utime.sleep_ms(1000) rtc_timeout -= 1 if rtc_timeout == 5: rtc.ntp_sync(server=settings.ntpserver2, tz="UTC-1") if rtc_timeout == 0: ntp_settime(rtc) break print("Time set:", utime.strftime("%c", utime.localtime())) # mDNS ... https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/wiki/mdns mdns = network.mDNS() _ = mdns.start("mPy", "MicroPython with mDNS") _ = mdns.addService('_ftp', '_tcp', 21, "MicroPython", {"board": "ESP32", "service": "mPy FTP File transfer", "passive": "True"}) _ = mdns.addService('_telnet', '_tcp', 23, "MicroPython", {"board": "ESP32", "service": "mPy Telnet REPL"}) _ = mdns.addService('_http', '_tcp', 80, "MicroPython", {"board": "ESP32", "service": "mPy Web server"}) utime.sleep_ms(1000) # FTP & Telnet Server network.ftp.start(user=settings.FTP_LOGIN, password=settings.FTP_PASSWD, buffsize=1024, timeout=300) network.telnet.start(user=settings.FTP_LOGIN, password=settings.FTP_PASSWD, timeout=300)
def datetimestr(self) : import sys if sys.platform == 'esp8266': return core.util.secs_to_string() else: return utime.strftime("%Y-%m-%dT%H:%M:%S.0000")