def publishBackup(topic=""): global msg_payload global payload_Topic global msg_ReadyRcv global tempUpdate global temp_Inbound global precipUpdate global precip_Inbound global alertUpdate global alert_Inbound global dailyUpdate global temp_Topic global daily_Topic global precip_Topic global topic_ToSend global msg_ToSend global missed_Obs global topic_File global msg_File if (topic == daily_Topic or topic == precip_Topic): topic_ToSend[missed_Obs] = payload_Topic log = uio.open(topic_File, mode="a") log.write(topic + "\n") time.sleep(0.5) log.close() msg_ToSend[missed_Obs] = msg_payload log1 = uio.open(msg_File, mode="a") log1.write(msg_payload + "\n") time.sleep(0.5) log1.close() missed_Obs = missed_Obs + 1 msg_payload = "" payload_Topic = ""
def publish_Backup(): global msg_payload global payload_Topic global daily_Topic global precip_Topic global topic_ToSend global msg_ToSend global obs_publishReady global topic_File global msg_File topic_ToSend.append(payload_Topic) msg_ToSend.append(msg_payload) obs_publishReady = obs_publishReady + 1 if (payload_Topic == daily_Topic or payload_Topic == precip_Topic): log = uio.open(topic_File, mode="a") log.write(payload_Topic + "\n") time.sleep(0.5) log.close() log1 = uio.open(msg_File, mode="a") log1.write(msg_payload + "\n") time.sleep(0.5) log1.close() msg_payload = "" payload_Topic = ""
def remove_data(user_in, dictk): no_ssid() f4 = uio.open(mydb, "r") data_rd = ujson.load(f4) f4.close() if SSID_COUNT and user_in in dictk: del data_rd["ssid"][user_in] del data_rd["password"][user_in] f4 = uio.open(mydb, 'w') counter1 = 0 counter2 = 0 update_ssid = {} update_password = {} for v in data_rd["ssid"].values(): counter1 += 1 update_ssid.update({str(counter1): v}) for v in data_rd["password"].values(): counter2 += 1 update_password.update({str(counter2): v}) data_rd["ssid"] = update_ssid data_rd["password"] = update_password ujson.dump(data_rd, f4) f4.close() print("Done.") time.sleep(3) station() if SSID_COUNT and not user_in in dictk: print("Incorrect input. Deleting nothing.") time.sleep(2) station()
def readFiles(): global missed_Obs global topic_ToSend global msg_ToSend global topic_File global msg_File obs_ToAdd = 0 currentNum = missed_Obs with uio.open(topic_File, mode="r") as log: topics_pending = log.readlines() num = len(topics_pending) obs_ToAdd = num lineCnt = 0 while lineCnt < num: t = topics_pending[lineCnt] topic_ToSend[currentNum] = t[:len(t) - 1] lineCnt = lineCnt + 1 currentNum = currentNum + 1 log.close() currentNum = missed_Obs with uio.open(msg_File, mode="r") as log: msg_pending = log.readlines() num = len(msg_pending) lineCnt = 0 while lineCnt < num: m = msg_pending[lineCnt] msg_ToSend[currentNum] = m[:len(m) - 1] lineCnt = lineCnt + 1 currentNum = currentNum + 1 log.close() missed_Obs = missed_Obs + obs_ToAdd
def readFiles(): global obs_publishReady global topic_ToSend global msg_ToSend global topic_File global msg_File global file_lineRef global tfile_readComplete global mfile_readComplete obs_ToAdd = 0 temp_Line = file_lineRef start_Read = temp_Line currentNum = obs_publishReady with uio.open(topic_File, mode="r") as log: topics_pending = log.readlines() num = len(topics_pending) if num > 0: i = 0 incr_Read = start_Read while i < 50 - currentNum: t = topics_pending[incr_Read] topic_ToSend.append(t[:len(t)-1]) incr_Read = incr_Read + 1 if incr_Read == num: i = 50 - currentNum tfile_readComplete = True file_lineRef = 0 else: i = i + 1 obs_ToAdd = obs_ToAdd + 1 log.close() with uio.open(msg_File, mode="r") as log1: msg_pending = log1.readlines() num = len(msg_pending) i = 0 incr_Read = start_Read while i < 50 - currentNum: m = msg_pending[incr_Read] msg_ToSend.append(m[:len(m)-1]) incr_Read = incr_Read + 1 if incr_Read == num: i = 50 - currentNum mfile_readComplete = True file_lineRef = 0 else: i = i + 1 log1.close() obs_publishReady = obs_publishReady + obs_ToAdd if tfile_readComplete == False: file_lineRef = file_lineRef + obs_ToAdd else: pass else: log.close() tfile_readComplete = True mfile_readComplete = True file_lineRef = 0
def createFiles(): global topic_File global msg_File log = uio.open(topic_File, mode="x") log.close() log1 = uio.open(msg_File, mode="x") log1.close()
def createFiles(): global topic_File global msg_File global file_lineRef global tfile_readComplete global mfile_readComplete log = uio.open(topic_File, mode="x") log.close() log1 = uio.open(msg_File, mode="x") log1.close() tfile_readComplete = True mfile_readComplete = True file_lineRef = 0
def ssids(user_dict): no_ssid() f3 = uio.open(mydb, "r") f3r = ujson.load(f3) f3.close() user_eyes = [] if SSID_COUNT: global SSID_SUCCESS SSID_SUCCESS = True for k, v in f3r['ssid'].items(): ssid = v password = f3r['password'][k] data_ssids = {k: (ssid, password)} user_dict.update(data_ssids) user_eyes.append((int(k), ssid)) user_eyes.sort() for itm in user_eyes: print("[" + str(itm[0]) + "] " + itm[1]) if not SSID_COUNT: SSID_SUCCESS = False print(""" There is no database with saved networks. Returning to the station. """) time.sleep(4) station()
def create_new_document(path): content = "time," for sesname in SensorList: content = content + "mm." + sesname + "," content = content + "\n" with uio.open(path, 'w') as file_Object: file_Object.write(content)
def dump_data(self, filename): allocs_now = micropython.alloc_count() allocs_per_last_line = allocs_now - self.last_alloc_count self.count_last_line(allocs_per_last_line) with open(filename, "w") as f: for key, val in self.data.items(): f.write("{} {total_allocs} {calls}\n".format(key, **val))
def write(self): print('write - run') f = io.open(SETTINGS_TXT, "w") f.write(json.dumps(self._set_data)) f.close() print('write - over') return
def deleteFiles(): global topic_File global msg_File try: log = uio.open(topic_File) log.close() uos.remove(topic_File) except OSError: pass try: log1 = uio.open(msg_File) log1.close() uos.remove(msg_File) except OSError: pass
def init(): # print("Initialize Buzzer") # buzzer.low() print("Initialize LEDs") pyb_red_led.off() pyb_green_led.off() pyb_blue_led.off() print("Initialize Horn") # high is off horn.high() print("Initialize Headlight") # high is off headlight.high() print("Initialize DAC") throttle_out.write(0) regen_out.write(0) print("Initialize Key") # High is off # key.high() if key_switch.value(): bike_on = True setup_rtc() # Check Bike / Switch State if key_switch.value(): bike_on = True hmi.set('sleep',0) filename = '/sd/logs/' + get_datetime_filename() + '.csv' log = uio.open(filename,'w') log.write('date,time,volts,amps,speed,temp,throttle,regen,ax,ay,az,angx,angy,angz\n') print('Log: ' + filename + ' open') if headlight_switch.value(): light_on = True hmi.light = 1 headlight.low() # We just got power to the PyBoard but the bike # key is off. Make sure HMI is sleeping # Turn off light & horn else: bike_on = False hmi.set('sleep',1) light_on = False hmi.light = 0 headlight.high() # This currently always sets the page to main # but we need to be synced with the display or updates won't work # Alternately we could get_page() and this should be done if we use passwords # Not sure what happens here if HMI is sleeping. # HMI Should be on? This might not work during sleep mode hmi.set_page(hmi.page)
def main(): global AIOKey, userName try: with uio.open('aio.key', mode='r') as f: key = ujson.loads(f.readline()) AIOKey = key['AIOkey'] userName = key['userName'] except: print("Couldent get credentials!!") return #get temp from the MCP9808 sensor TC = getTemperature() sendValToFeed(userName, 'foo', TC) #get temp/humidty ffrom the SHT31 sensor TF, RH = getSHT() sendValToFeed(userName, 'bassementtempf', TF) sendValToFeed(userName, 'basementrh', RH) # should we goto sleep? ctrl = getLastVal(userName, 'ctrl') print(ctrl.json()) if (ctrl.json()['value'] == 'ON'): import machine rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) #if so for how long? t = int(getLastVal(userName, 'updatetime').json()['value']) rtc.alarm(rtc.ALARM0, t * 60 * 1000) # machine.deepsleep()
def exists(self): """Check if baseline exists.""" try: with uio.open(self._BASELINE_FILE, mode='r'): return True except OSError: return False
def do_append(ssid=""): f1 = uio.open(mydb, "r") flr = ujson.load(f1) f1.close() new_ssid = "" if ssid != "": new_ssid = ssid if ssid == "": print('Type SSID:') new_ssid = input("<:> ") while True: if new_ssid != "": print('Type PASSWORD for ' + new_ssid) new_password = input("<:> ") if new_password == "": print("A password cannot be empty!") time.sleep(2) continue # Here it checks if the network already exists in the database. if new_ssid in flr["ssid"].values() and new_password in flr["password"].values(): print(""" This network exists in the database. Returning back to station. """) time.sleep(3) station() break if new_password != "": file_w = uio.open(mydb, "w") flr["ssid"][str(len(flr["ssid"]) + 1)] = new_ssid flr["password"][str(len(flr["password"]) + 1)] = new_password ujson.dump(flr, file_w) file_w.close() print("Network " + new_ssid + " is added successfully!") time.sleep(3) station() break if new_ssid == "": print("Adding nothing. Returning back to station") time.sleep(2) station() break
def reset(self): print('reset - run') f = io.open(SETTINGS_TXT, "w") f.write(json.dumps(INIT_SET_DATA)) f.close() self._set_data = INIT_SET_DATA.copy() print('reset - over') return
def atexit(): print("\n------------------ script exited ------------------") print("Total traces executed: ", __prof__.trace_count) with open(".coverage", "w") as f: # wtf so private much beautiful wow f.write("!coverage.py: This is a private format, don't read it directly!") # poormans json f.write(str(__prof__.coverage_data()).replace("'", '"'))
def make_file_transport(path): output = uio.open(path, 'wb') def send(message): output.write(message) output.write('\n') return send
def no_ssid(): global SSID_COUNT SSID_COUNT = False file_r = uio.open(mydb, "r") data_no_ssid = ujson.load(file_r) file_r.close() if len(data_no_ssid["ssid"]) > 0: SSID_COUNT = True
def get_property(self, key): filename = key + ".config" if (self._file_exists(filename)): file = uio.open(filename, "rt") value = file.read() file.close() else: print("Could not find property with name " + key) return None return value
def DeleteOldFile(log): if log == True: # delete existing log file if it exists try: log = uio.open(LOG_FILE) log.close() uos.remove(LOG_FILE) except OSError: # Do nothing, the file does not exist. pass
def LogData(self): if self.log_info == True: n = len(self.arr) with uio.open(LOG_FILE, mode="a") as log: for i in range(n): dummy = log.write("%s\n" % (self.arr[i])) else: n = len(self.arr) for i in range(n): print("%s\n" % self.arr[i])
def create_get_addresses_handler(file_path): file = uio.open(file_path) payload = file.read() file.close() def handler(w, req): w.headers['content-type'] = 'application/json' w.write(payload) return handler
def ftps_downloadFile(fileport=0, sz=0, df_chunk=1000): global temp_File global topic_ToSend global msg_ToSend global msg_Topic global obs_publishReady global wdt global temp_Path global file_szRcvd file_Size = sz data_Received = 0 uos.chdir(temp_Path) log = uio.open(temp_File, mode="w") try: ftp_conn2 = FTP(port=fileport, user=None, passwd=None, timeout=20) ftp_conn2.download(port=fileport) time.sleep(5) except: log.close() topic_ToSend.append(msg_Topic) msg_ToSend.append("Could not Access FTPS for download") obs_publishReady = obs_publishReady + 1 else: excess_Data = file_Size % df_chunk while (data_Received < file_Size): if ((file_Size - data_Received) > df_chunk): try: data = ftp_conn2.rcv(df_chunk) except OSError: pass else: data_Received = data_Received + len(data) wdt.feed() if len(data) > 0: log.write(data) time.sleep(0.5) else: pass else: try: data = ftp_conn2.rcv(excess_Data) except OSError: pass else: data_Received = data_Received + len(data) wdt.feed() if len(data) > 0: log.write(data) time.sleep(0.5) else: pass log.close() file_szRcvd = data_Received
def load(): config_path = "config/platform-%s.json" % sys.platform config_stream = None try: config_stream = uio.open(config_path) return ujson.load(config_stream) except OSError as err: raise Exception("Failed to open config file: %s - %s" % (config_path, err)) finally: if config_stream != None: config_stream.close()
def dump(self, filename): if not self._filter: self._filter = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)]) import uio f = uio.open(filename) total_read = 0 while True: n = f.readinto(self._buf) if n: self.dump_buf(total_read, self._buf, n) total_read += n else: break
def does_file_exist(filename): """ does_file_exist Returns true if the given filename exists, false otherwise. """ exists = False try: with uio.open(filename, mode='r') as infofile: exists = True infofile.close() except OSError: pass return exists
def read_Version(): global current_FS_Version global version_File global temp_Path global empty_Text uos.chdir(temp_Path) info = empty_Text with uio.open(version_File, mode="r") as log: info = log.readlines() log.close() ver = info[0] current_FS_Version = ver.rstrip()
def firmware_upgrade(firmware_file): """Upgrade ccs811 firmware. For example: firmware_upgrade('CCS811_SW000246_1-00.bin') """ reset = Pin(config.rst2) wake = config.wake # Pulse Reset pin print("Enter boot mode...") reset.value(0) utime.sleep_ms(100) reset.value(1) utime.sleep_ms(100) # Set Wake low wake.value(0) utime.sleep_ms(100) # Erase application print("Erase application...") i2c.writeto_mem(ADDRESS, 0xf1, bytearray([0xe7, 0xa7, 0xe6, 0x09])) utime.sleep_ms(500) # Send firmware to ccs811 print("Load firmware...") with uio.open(firmware_file, mode='rb') as firmware: while True: bytes = firmware.read(8) if len(bytes) == 0: break payload = bytearray([0xf2]) for b in bytes: payload.append(b) i2c.writeto(ADDRESS, payload) print(binascii.hexlify(payload)) # i2c.writeto_mem(ADDRESS, 0xf2, bytearray(bytes)) utime.sleep_ms(50) # Verify application - this does not work, always prints 0 # Power off to complete print("Verify...") i2c.writeto_mem(ADDRESS, 0xf3, bytearray([0x01])) utime.sleep_ms(500) status = i2c.readfrom_mem(ADDRESS, 0x00, 1) print(status[0]) print(status[0] & 0x30) # Set Wake low wake.value(1) print("Done - Power device off and on again")