def lte_connect(hw): total_chrono.start() lte = None signal_quality = None with TimedStep("LTE init"): pycom.nvs_set("lte_on", True) lte = network.LTE() with TimedStep("LTE attach"): lte.attach() try: while True: wdt.feed() if lte.isattached(): break if tschrono.read_ms() > 150 * 1000: raise TimeoutError("Timeout during LTE attach") time.sleep_ms(50) finally: try: signal_quality = pycom_util.lte_signal_quality(lte) _logger.info("LTE attached: %s. Signal quality %s", lte.isattached(), signal_quality) co2unit_errors.info(hw, "Comm cycle. LTE attached: {}. Signal quality {}".format(lte.isattached(), signal_quality)) except: _logger.exception("While trying to measure and log signal strength") with TimedStep("LTE connect"): lte.connect() while True: wdt.feed() if lte.isconnected(): break if tschrono.read_ms() > 120 * 1000: raise TimeoutError("Timeout during LTE connect (%s)") time.sleep_ms(50) return lte, signal_quality
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 cleanup(): try: uos.unlink(__filename()) pycom.nvs_set('queue_size', 0) except OSError as e: print('error while removing data file: {}'.format(e.errno)) pass
def getResetCause(): try: reset_cause = machine.reset_cause() debug( "Reset cause: " + str(reset_cause) + " - Sleeping secs: " + str(globalVars.deepSleepSec), "v") try: globalVars.deepSleepSec = pycom.nvs_get('deepSleepSecs') except BaseException as ea: checkError("Error getting flash value of", ea) if globalVars.deepSleepSec == 0: debug("Coming from other reasons", "v") BeepBuzzer(1) elif globalVars.deepSleepSec > 0: pycom.nvs_set('deepSleepSecs', 0) globalVars.deepSleepSec = 0 if synchronizeRTC(): globalVars.flag_rtc_syncro = True BeepBuzzer(0.2) else: debug("Another reason for the reset", "v") BeepBuzzer(1) except BaseException as e: checkError("Error getting reset cause", e)
def nvs_transmit(): while True: time.sleep(5) try: os.stat('data.dat') exists = True except: exists = False if exists: gc.collect() gc.mem_free() p0 = int(pycom.nvs_get('p0')) p1 = int(pycom.nvs_get('p1')) pycom.nvs_set('t', p1) if p1 > p0: print (p0) print (p1) f1 = open('data.dat', 'rb') f1.seek(p0) payload = binascii.hexlify(f1.read(p1-p0)) print(payload) f1.close() sendATcommandPOST(payload) print("Transmission completed")
def make_payload(): pycom.rgbled(blue) #distance = distance_median() count = pycom.nvs_get('dist') utime.sleep_us(100) #randomize water distance distance = os.urandom(1)[0] print("distance = {0} inches".format(distance)) utime.sleep_ms(100) #subract 0.1V from battery voltage every 5 counts c = count v = pycom.nvs_get('v') if c % 5 == 0: v += 1 pycom.nvs_set('v', v) print("v={0}".format(v)) voltage = 4.0 - v * 0.1 print("Measured Voltage: {0}V".format(voltage)) #randomize flow rate x = os.urandom(1)[0] flow_rate = x % 4 if (flow_rate < 3): print(flow_rate) else: flow_rate -= 1 print(flow_rate) print("Flow Rate: {0}".format(flow_rate)) #generate encoded packet to send to webapp full_packet = ustruct.pack('f', count) + ustruct.pack( 'f', float(distance)) + ustruct.pack('f', voltage) + ustruct.pack( 'f', float(flow_rate)) return full_packet
def registerDevice(self): # Register Device ! try: print(" Registering device ") myobj = {} myobj["mac"] = ubinascii.hexlify(machine.unique_id(), ':').decode() myobj["firmware_version"] = "1.0.0" headers = { "Content-Type": "application/json", "x-access-token": self.authToken } x = post(config.register, json=myobj, headers=headers) # print(x.text) firmware_version = x.json() try: pycom.nvs_set("fwversion", firmware_version["firmware_version"]) print("Fw version value set !") except: pycom.nvs_set("fwversion", "0") print("Failed to set firmware version") if x.status_code == 200: print("Device Registered") except Exception as e: print("failed to register device: ", e)
def checkRollout(self): try: print("......Checking for rollouts............") # check device next rollout myobj = {} myobj["mac"] = ubinascii.hexlify(machine.unique_id(), ':').decode() myobj["firmware_version"] = "1.0.0" headers = { "Content-Type": "application/json", "x-access-token": self.authToken } x = post(config.checkRollout, json=myobj, headers=headers) if x.status_code == 200: print(x.text) next_rollout = x.json() if "rollout_id" in next_rollout: print(" rollout ID exists ") pycom.nvs_set("rolloutid", next_rollout["rollout_id"]) self.rolloutid = next_rollout["rollout_id"] self.firmware_id = next_rollout["firmware_id"] print("....Rollout ID set....") return True else: print(" --- No new Rollout avaliable ----") return False except Exception as e: print("Check Rollout failed: ", e)
def flash_detect_main(): flash_counter = pycom.nvs_get('flash_counter') if flash_counter is None: flash_counter = 0 flash_counter += 1 pycom.nvs_set('flash_counter', flash_counter) go_back_to_sleep()
def test_pycom_nv_set_get(self): pycom.nvs_set("test_key_asdf", 1234) val = pycom.nvs_get("test_key_asdf") self.assertEqual(val, 1234) pycom.nvs_set("test_key_asdf", 5678) val = pycom.nvs_get("test_key_asdf") self.assertEqual(val, 5678)
def aggregate(): try: pycom.nvs_set('val', int(pycom.nvs_get('val')) + 1) except: pycom.nvs_set('val', 0) print('Deepsleep Remaining: ' + str(machine.remaining_sleep_time())) print('New Aggregate: ' + str(pycom.nvs_get('val'))) print('Current Message ID: ' + str(pycom.nvs_get('msgID')))
def run(self): flash_count = nvs_get_default("co2_flash_count", 0) import co2unit_measure co2unit_measure.wdt = wdt co2unit_measure.measure_sequence(hw, flash_count=flash_count) _logger.info("Resetting flash count after recording it") pycom.nvs_set("co2_flash_count", flash_count)
def send(self, data: bytes): if self._sock is None: self._sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self._sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) self._sock.setblocking(True) self._sock.send(data) self._sock.setblocking(False) self._air_time = self._air_time_base + self._lora.stats().tx_time_on_air pycom.nvs_set('air', self._air_time)
def LoRaSend(val,ch): sl = socket.socket(socket.AF_LORA, socket.SOCK_RAW) sl.setblocking(True) sl.send(encrypt(SITE+mac()+'/'+ch+'&'+val)) # Send on LoRa Network & wait Reply sl.setblocking(False) try: pycom.nvs_set('msgID',pycom.nvs_get('msgID')+1) except: pycom.nvs_set('msgID',0) print("Sent",ch)
def char_cb(chr): global srv events = chr.events() if events & Bluetooth.CHAR_READ_EVENT: print('read', chr) if events & Bluetooth.CHAR_WRITE_EVENT: print('write', chr.value()) pycom.nvs_set('ble', 1) srv.stop() logger.GATT = True
def __init__(self, bq25895): self._bq25895 = bq25895 self.adc = ADC() self.p_SHDN_ = Pin('P21', mode=Pin.OUT) #shutdown/enable ampli op self.pwr_ticks = utime.ticks_us() try: pycom.nvs_get("pwr_uAH") except Exception as e: pycom.nvs_set("pwr_uAH", 0) self.pwr_nAH = 0 self.__alarm = Timer.Alarm(self.mesure, 1, periodic=True)
def deep_sleep(): id = pycom.nvs_get('msg_id') pycom.nvs_set('msg_id', id + 1) print('Start deep sleep...') py.setup_int_pin_wake_up(True) py.setup_int_wake_up(False, True) #py.setup_sleep(3600) # 1 hour py.setup_sleep(600) # 10 min deep_sleep_led() py.go_to_sleep()
def _record_seq_ack(self, buffer_file, seq, ack): if self.use_nvs: pycom.nvs_set("wkb" + str(_SEQ_ID_IDX), seq) pycom.nvs_set("wkb" + str(_ACK_ID_IDX), ack) return packed_seq_id = struct.pack(_POS_VALUE_FORMAT, seq) packed_ack_id = struct.pack(_POS_VALUE_FORMAT, ack) buffer_file.seek(_SEQ_ID_IDX) buffer_file.write(packed_seq_id) buffer_file.seek(_ACK_ID_IDX) buffer_file.write(packed_ack_id)
def mesure(self, alarm): old = self.pwr_ticks self.pwr_ticks = utime.ticks_us() delta = utime.ticks_diff(self.pwr_ticks, old) self.pwr_nAH = self.pwr_nAH + int(self.getPWR() * delta / 3600) uAH = self.pwr_nAH // 1000 #print("nAH : {}, uAH : {}".format(self.pwr_nAH, uAH)) if uAH > 0: self.pwr_nAH = self.pwr_nAH - (uAH * 1000) uAH = pycom.nvs_get("pwr_uAH") + uAH #print("pwr_uAH :{}".format(uAH)) pycom.nvs_set("pwr_uAH", uAH)
def receive(self, rx=None): if len(rx) == 0: #No hay mensaje de recepciĆ³n pass else: if rx[0] == 82: #Orden de Cambio Data Rate (ASCII hex R=0x52 dec 87) print("Cambiando Data Rate %d" % (int.from_bytes(rx[1:], 'big'))) self.dr = int.from_bytes( rx[1:], 'big') #Decodifica el valor del nuevo data Rate pycom.nvs_set('data_rate', self.data_rate) #Lo guarda en NVRAM else: pass
def myEnd(debug=False): heartbeat(False); nvs_set('myReset',ticks_ms()/1000) if debug or (ticks_ms() > 30*60*1000): myLed = LEDblink(alarm=15) else: myLed = LEDblink(count=1,alarm=(60*10)) while True: if not myLed.max: break if myLed.max < 0: sleep_ms(15*1000) else: sleep_ms(60*60*1000) if debug: print("system reset"); sleep(1) reset()
def nvs_get(key, default_value=0): """ Get value for key from NVRAM. Create the key if it does not exist. :param str key: :param int default_value: value to use when creating the key :return value int: (NVRAM can only store integers) """ value = pycom.nvs_get(key) if value is None: pycom.nvs_set(key, int(default_value)) value = int(default_value) return value
def sendATcommandPOST(payload): uart.readall() if (sendATcommandNoEcho('ATE0') != 'MODEM_OK'): error_handler() print("Disabled echo") if (sendATcommandReset('AT+CFUN=1,1') != 'MODEM_OK'): error_handler() time.sleep(15) uart.readall() print("Modem Reset") if (sendATcommandNoEcho('ATE0') != 'MODEM_OK'): error_handler() print("Disabled echo") if (sendATcommand('AT+SAPBR=3,1,"Contype","GPRS"', 'OK') != 'MODEM_OK'): error_handler() print("Set GPRS contex") if (sendATcommand('AT+SAPBR=3,1,"APN","'+CONFIG_APN+'"', 'OK') != 'MODEM_OK'): error_handler() print("Set APN") while True: if(checkGPRS() == 'MODEM_OK'): print("Attached to GPRS network") if (sendATcommand('AT+SAPBR=3,1,"Contype","GPRS"', 'OK') != 'MODEM_OK'): error_handler() print("Set GPRS contex") if (sendATcommand('AT+SAPBR=3,1,"APN","'+CONFIG_APN+'"', 'OK') != 'MODEM_OK'): error_handler() print("Set APN") if (sendATcommand('AT+HTTPINIT', 'OK') != 'MODEM_OK'): error_handler() print("Configured HTTP parameters AT+HTTPINIT") if (sendATcommand('AT+HTTPPARA="CID",1', 'OK') != 'MODEM_OK'): error_handler() print("Configured HTTP parameters CID") if (sendATcommand('AT+HTTPPARA="CONTENT","application/json"', 'OK') != 'MODEM_OK'): error_handler() print("Configured HTTP parameters CONTENT") if (sendATcommand('AT+HTTPPARA="URL","http://'+CONFIG_URL+'"', 'OK') != 'MODEM_OK'): error_handler() print("Configured HTTP parameters URL") if (sendATcommand('AT+HTTPDATA='+str(len(str(payload,"utf-8"))+18)+',5000', 'DOWNLOAD') != 'MODEM_OK'): error_handler() print("Configured HTTP parameters AT+HTTPDATA and ready to push payload") if (sendATcommand('d='+str(payload,"utf-8")+'&m=867622011165381', 'OK') != 'MODEM_OK'): error_handler() print("Payload pushed") if (sendData() == 'MODEM_OK'): pycom.nvs_set('p0', int(pycom.nvs_get('t'))) print("Data succesfully sent!") return("MODEM_OK") else: print ("ERROR: Server offline need to try again later") return("ERROR")
def writeLongList(self, name, longVars, maxLen): i = 0 while i < len(longVars) and i < maxLen: pycom.nvs_set(name + str(i) + 'l', struct.unpack(">I", longVars[i][-4:])[0]) pycom.nvs_set(name + str(i) + 'm', struct.unpack(">H", longVars[i][0:2])[0]) i = i + 1 try: pycom.nvs_erase(name + str(i) + 'l') pycom.nvs_erase(name + str(i) + 'm') except: return else: return
def debug_level(level): global DEBUG if level is None: try: ret = pycom.nvs_get('pymesh_debug') except: ret = None return ret try: ret = int(level) except: return DEBUG = ret pycom.nvs_set('pymesh_debug', DEBUG)
def on_boot_fn(value=None, default=default, erase=False): if erase: return nvs_erase(key) elif value == None: return nvs_get(key, default=default) else: return pycom.nvs_set(key, value)
def PowerFailCb(logger): power_fail = Pin(POWER_FAIL_PIN) if debouncedPFSignal(power_fail) == 1: #stopTasksButLora() # save power by leaving all non essential tasks ASAP pycom.nvs_set(POWER_FAIL_STATE, MODE_POWER_FAIL) unixLocalTime= time.time() + time.timezone() pycom.nvs_set(POWER_FAIL_TS, unixLocalTime) currentAlarmLoraMessageToSend = buildPFAlarmMessage(unixLocalTime) lora_queue_immediate_semaphore.acquire(0) rand=int(getRandom() * 2000) # 0-2000 value time.sleep_ms(rand) # just randow m wait of 3s LoraQueueImmediate.put(currentAlarmLoraMessageToSend) lora_queue_immediate_semaphore.acquire(1,2) # wait 2s max for msg to be sent by the Lora task time.sleep_ms(WAIT_TIME_BEFORE_SLEEP) # time for the LoRA MAC layer to send that message rand=int(getRandom() * 20) # 0-20 value machine.deepsleep((WAKEUP_DELAY+rand)*1000) # GO TO SLEEP NOW AND PRESERVE POWER
def lte_deinit(lte): if not lte: return try: if lte.isconnected(): with TimedStep("LTE disconnect"): lte.disconnect() if lte.isattached(): with TimedStep("LTE detach"): lte.detach() finally: with TimedStep("LTE deinit"): lte.deinit() pycom.nvs_set("lte_on", False)
def _connect_and_send(network): # TODO: pridat casovace if network == 0: # wifi pycom.rgbled(0x003300) if wifi_connect(): if wifi_send() == 1: pycom.rgbled(0x000000) logger.W = True return True else: debug_led(0x330000, 0.3) logger.W = False return False else: debug_led(0x330000, 0.3) logger.W = False return False if network == 1: # ble pycom.rgbled(0x030033) # blue pycom.nvs_set('ble', 0) gatt_connect() gatt_service() for _ in range(10): idle() sleep(3) ble = pycom.nvs_get('ble') if ble == 1: debug_led(0x003300, 0.3) logger.B = True return True else: debug_led(0x330000, 0.3) logger.B = False return False if network == 2: # Sigfox pycom.rgbled(0x090114) ret = sigfox_send() pycom.rgbled(0x000000) if ret == 5: logger.S = True return True logger.S = False return False
def _int_handler(self, pin_o): l.info("BQ>BQ25895 interrupt") REG0C1 = self.read_byte( 0x0C) #1st read reports the pre-existing fault register REG0C2 = self.read_byte( 0x0C) #2nd read reports the current fault register status REG0B = self.read_byte( 0x0B) #2nd read reports the current fault register status l.debug("0x0C1st:{:08b} 0x0C2nd:{:08b} 0x0B:{:08b}".format( REG0C1, REG0C2, REG0B)) if self.pg_stat_last != REG0B & 0b00000100: self.pg_stat_last = REG0B & 0b00000100 if REG0B & 0b00000100 > 1: print("RAZ pwr_uAH ") pycom.nvs_set("pwr_uAH", 0) if self._user_handler is not None: self._user_handler(REG0C1, REG0C2, REG0B)