def do_terminal(s): print("[Type +++ to exit terminal]") while True: print("Input command:") cmd = input_line(s) if cmd == '+++': break elif cmd == 'erase': eraseSettings() print("erase done") mcu.reset() elif cmd == 'name': settings = readSettings() print("Old name:", settings["name"]) print("New name:") name = input_line(s) if name: print("Saving name:", name) settings["name"] = name saveSettings(settings) mcu.reset() elif cmd == 'modem': do_modem_passthru(s) break elif cmd == 'gnss': global gnss gnss.debug = not gnss.debug print("gnss debug =", gnss.debug) break elif cmd == 'mqtt': global client if client is not None: client.debug = not client.debug print("mqtt debug =", client.debug) break
def pub_event_handler(): global ready while True: try: # Sync ready = True core_sample_lock.acquire() ready = False print("======== reading") # Read from 4-20mA channel1, resistive channel1 analog_val = fzbox.read_420(1) temperature = fzbox.read_resistive(1) print(" - temp:", temperature) print(" - analog:", analog_val) # Organize data in json dict to_send = {} to_send['temp'] = temperature to_send['analog'] = analog_val print("======== done") # Publish data to ZDM cloud service device.publish(to_send, "data") sleep(100) rssi = fzbox.get_rssi() # yellow blink if low signal, green blink otherwise if rssi < -70: fzbox.reverse_pulse('Y', 100) else: fzbox.reverse_pulse('G', 100) except Exception as e: print('Publish exception: ', e) fzbox.error_cloud() mcu.reset()
def run(): sms_timer = 0 while True: mcu_reset = False sleep(1000) sms_timer += 1 # parse SMS commands try: if check_sms and modem and (sms_timer >= 15 or modem.pending_sms() > 0): sms_timer = 0 mcu_reset = read_and_parse_sms() except Exception as e: print("utils SMS failure", e) # control battery charger and input level if is_powersupply_toolow(): print("Power supply too low!") mcu_reset = True else: update_charger() # handle reset if mcu_reset: if modem: modem.shutdown() print("utils MCU reset") mcu.reset()
def reset(): """ .. function:: reset() Reset the device """ mcu.reset()
def init_rtc(): while True: try: wifi.link(SSID, wifi.WIFI_WPA2, PASSWORD) timestamp = int(json.loads(requests.get("http://now.zerynth.com/").content)['now']['epoch']) rtc.set_utc(timestamp) wifi.unlink() break except Exception as e: mcu.reset()
def cmd_parser(input): if input == 'list': return mcu.img_list(name) elif input == 'erase': return mcu.img_erase(name) elif input == 'upload': return mcu.img_upload(name, path) elif input == 'test': return mcu.img_test(name, img) elif input == 'confirm': return mcu.img_confirm(name, img) elif input == 'reset': return mcu.reset() elif input == 'list_bin': chose_file() elif input == 'quit': print 'Bye bye!' else: print 'Try again!'
def read_event_handler(): global ready while True: try: # Sync ready = True core_sample_lock.acquire() ready = False print("======== reading") # Read from 4-20mA channel1, resistive channel1, power channel1 analog_val = fzbox.read_420(1) temperature = fzbox.read_resistive(1) power = fzbox.read_power(1) print(" - analog:", analog_val) print(" - temp:", temperature) print(" - power:", power) print("======== done") # reverse green blink each cycle fzbox.reverse_pulse('G',100) except Exception as e: print("Generic Error:", e) fzbox.error_cloud() mcu.reset()
try: print("Polaris default app") polaris.init() print("MCU UID:", [hex(b) for b in mcu.uid()]) print("VM info:", vm.info()) print("FW version:", fw_version) print("Watchdog was triggered:", sfw.watchdog_triggered()) polaris.ledRedOn() polaris.ledGreenOff() except Exception as e: print("Failed polaris init with", e) sleep(500) mcu.reset() # INIT HW try: print("Initializing Modem...") modem = modem.init() print("Initializing GNSS...") gnss = gnss.init() # verify preconditions and start utility thread utils.start() print("Starting Accelerometer...") import accel accel.start()
def main(): utils.debug('\n\n******OTA TEST******\n') # Steps to TRACKR_PATH which contains mcumgr os.chdir(os.environ['TRACKR_PATH']) try: # Queries device for its current image list img_list = mcu.img_list(p_name) time.sleep(0.5) # Erases image in slot 1 if exist if 'slot=1' in img_list: mcu.img_erase(p_name) time.sleep(0.5) # Uploads new image to DUT os.environ['OTA_FW_PATH'] = utils.find_bin_file( os.environ['TRACKR_PATH']) mcu.img_upload(p_name, os.environ['OTA_FW_PATH']) # Checks current image list curr_img_list = mcu.img_list(p_name) time.sleep(0.5) if 'slot=1' in curr_img_list: utils.debug('Image is successfully uploaded to slot 1\n') # Extracts slot1's hash from the current image list slot1_str = curr_img_list.split('slot=1')[1] slot1_hash = slot1_str.split('hash: ')[1].split('\n')[0] slot1_hash = slot1_hash.replace('\n', '') else: utils.debug('FAIL to upload image!\n') # Tells DUT to run the new image on its next boot mcu.img_test(p_name, slot1_hash) # Makes the image swap permanent mcu.img_confirm(p_name, slot1_hash) time.sleep(0.5) # Resets DUT mcu.reset(p_name) time.sleep(5) # Checks the image list after reset curr_img_list = mcu.img_list(p_name) time.sleep(1) slot0_str = curr_img_list.split('slot=1')[0] slot0_hash = slot0_str.split('hash: ')[1] slot0_hash = slot0_hash.replace('\n', '') if ' ' in slot0_hash: slot0_hash = slot0_hash.replace(' ', '') if (slot0_hash == slot1_hash): utils.debug('FW upgrade successful\n') utils.test_report('\n\nFW upgrade successful\n\n') else: utils.debug('Failed to upgrade FW!!!\n') utils.test_report('\n\nFailed to upgrade FW!!!\n\n') # Erases the image in slot 1 mcu.img_erase(p_name) curr_img_list = mcu.img_list(p_name) time.sleep(0.5) if os.path.exists(os.environ['OTA_FW_PATH']): os.remove(os.environ['OTA_FW_PATH']) except (subprocess.CalledProcessError, UnboundLocalError) as detail: traceback.format_exc() utils.debug(str(detail)) utils.debug('Failed to upgrade FW!!!\n') utils.test_report('\n\nFailed to upgrade FW!!!\n\n') except KeyboardInterrupt: utils.debug('\nAborted by user\n')
def reset(client, data): print("reset: " + data['message'].payload) client.publish("iot/Actor-1/status", "Actor-1 is reset.") mcu.reset()
def _readloop(self): while True: while self.reconnecting: sleep(1000) try: msg = self._getmsg() if "cmd" in msg and msg[ "cmd"] == "CALL" and "method" in msg and msg[ "method"] in self.rpc and "id" in msg: if "args" in msg: args = msg["args"] else: args = [] ret = False if "ret" in msg: ret = msg["ret"] try: self.log("calling", msg["method"]) res = self.rpc[msg["method"]](*args) #print(timers.now(),"called",msg["method"]) except Exception as e: self.log("Exception in rpc", e) if ret: self.send({ "cmd": "RETN", "id": msg["id"], "error": str(e) }) else: if ret: self.send({ "cmd": "RETN", "id": msg["id"], "res": res }) res = None elif "terminate" in msg: self.log("Terminating...") self._closeall() elif "cmd" in msg and msg["cmd"] == "OTA": self.log("OTA message") try: rec = fota.get_record() except: self.log("OTA unsupported") self._ota_fail("OTA unsupported") continue if "chunk" in msg: self.chunk = msg["chunk"] self.vmsize = msg["vmsize"] self.bcsize = msg["bcsize"] self.bcslot = msg["bc"] self.vmslot = msg["vm"] if self.bcslot == rec[4] or (self.vmsize and self.vmslot == rec[1]): self.log("Invalid OTA request!") self._ota_fail("Bad slots") continue if self.vmsize <= 0: self.ota_type = __OTA_ONLY_BC self.next_bcaddr = fota.find_bytecode_slot() self.next_vmaddr = -1 else: self.ota_type = __OTA_BC_AND_VM self.next_vmaddr = fota.find_vm_slot() self.next_bcaddr = fota.find_bytecode_slot() if self.fota_callback and not self.fota_callback(0): self.log("OTA", 0, "stopped by callback") self._ota_fail("stopped by callback") continue if self.next_bcaddr > 0: self.log("ERASE BC SLOT", hex(self.next_bcaddr), self.bcsize) fota.erase_slot(self.next_bcaddr, self.bcsize) if self.next_vmaddr > 0: self.log("ERASE VM SLOT", hex(self.next_vmaddr), self.vmsize) fota.erase_slot(self.next_vmaddr, self.vmsize) self.ota = __OTA_RECEIVING_BC self.cblock = 0 self.csize = 0 self.send({ "cmd": "OTA", "payload": { "b": 0, "t": "b" } }) elif "bin" in msg and (self.ota == __OTA_RECEIVING_BC or self.ota == __OTA_RECEIVING_VM): thebin = base64.standard_b64decode(msg["bin"]) if self.ota == __OTA_RECEIVING_BC: if msg["t"] != "b": self.log("Bad OTA message!") self._ota_fail("BC only ota") continue addr = self.next_bcaddr tsize = self.bcsize elif self.ota == __OTA_RECEIVING_VM and self.ota_type == __OTA_BC_AND_VM: addr = self.next_bcaddr if msg[ "t"] == "b" else self.next_vmaddr tsize = self.bcsize if msg[ "t"] == "b" else self.vmsize self.log("WRITING BLOCK", self.cblock, "at", hex(addr + self.chunk * self.cblock), len(thebin)) fota.write_slot(addr + self.chunk * self.cblock, thebin) self.cblock += 1 self.csize += len(thebin) if self.csize < tsize: #keep sending blocks self.send({ "cmd": "OTA", "payload": { "b": self.cblock, "t": msg["t"] } }) else: #ask for crc self.ota = __OTA_RECEIVING_BC_CRC if msg[ "t"] == "b" else __OTA_RECEIVING_VM_CRC self.send({ "cmd": "OTA", "payload": { "c": 0, "t": msg["t"] } }) elif "crc" in msg: if msg["t"] == "b": chk = fota.checksum_slot(self.next_bcaddr, self.bcsize) fota.close_slot(self.next_bcaddr) else: chk = fota.checksum_slot(self.next_vmaddr, self.vmsize) fota.close_slot(self.next_vmaddr) if not chk: self.log("Skipping CRC") for i, b in enumerate(chk): k = int(msg["crc"][i * 2:i * 2 + 2], 16) if k != b: self.log("Bad crc!") self._ota_fail("Bad CRC") break else: self.log("OTA OK") if msg["t"] == "b" and self.ota_type == __OTA_BC_AND_VM: #start VM download self.send({ "cmd": "OTA", "payload": { "b": 0, "t": "v" } }) self.ota = __OTA_RECEIVING_VM self.cblock = 0 self.csize = 0 self.log("Vm begin") else: # try OTA! if self.fota_callback and not self.fota_callback( 1): self.log("OTA", 1, "stopped by callback") self._ota_fail("stopped by callback") continue fota.attempt(self.bcslot, self.vmslot) if self.fota_callback and not self.fota_callback( 2): self.log("OTA", 2, "stopped by callback") self._ota_fail("stopped by callback") continue self._closeall() self.log("resetting...") sleep(1000) mcu.reset() elif "ok" in msg: if msg["bc"] == rec[4] and msg["vm"] == rec[1]: self.send({"cmd": "OTA", "payload": {"ok": 1}}) else: self._ota_fail("not ready") except Exception as e: self.log("Exception in readloop", e) self._reconnect()
def get_packets(sleep_time, iterations_per_channel, activity_percentage, scan_time_interval): print("Sniffing...") count = 0 while True: sfw.kick() payloads = [] if count % 60 == 0: print("Initializing RTC") init_rtc() sfw.kick() count = (count + 1) % 60 # If timer has reached the interval, perform another scan if t.get() >= scan_time_interval: t.reset() print() scan_for_active_channels(1000, 2) # Else, get packets else: try: for channel in range(1, number_of_channels + 1): print("Checking channel", channel) if channel_activity_stats[channel - 1] >= activity_percentage: print("Starting sniffer on channel", channel) wifi_driver.start_sniffer( packet_types=[wifi_driver.WIFI_PKT_MGMT], channels = [channel], mgmt_subtypes=[wifi_driver.WIFI_PKT_MGMT_PROBE_REQ], direction = wifi_driver.WIFI_DIR_TO_NULL_FROM_NULL, pkt_buffer=32, max_payloads=0, hop_time=2000) print("Start acquisition for", iterations_per_channel, "seconds") for iteration in range(iterations_per_channel): print(gc.info()) # Sleep for a given time sleep(sleep_time) # Sniff packets pkts = wifi_driver.sniff() now = rtc.get_utc() for pkt in pkts: payloads.append({ 'scanner_id': mac_addr, 'type': pkt[0], 'subtype': pkt[1], 'mac1': pkt[7], 'mac2': pkt[8], 'mac3': pkt[9], 'mac4': pkt[10], 'rssi': pkt[11], 'channel': pkt[12], 'timestamp': now.tv_seconds + (now.tv_microseconds/1000000) #mantenere solo i secondi }) print("Sniffed", len(pkts), "in channel", channel) # Stop sniffer print("STOP") wifi_driver.stop_sniffer() sfw.kick() print("STOPPED") sleep(500) print("Connecting to Wi-Fi network") try: sfw.kick() for j in range(3): try: wifi.link(SSID, wifi.WIFI_WPA2, PASSWORD) break except Exception as e: print("Can't link",e) sleep(100) else: mcu.reset() sleep(100) sleep(100) print(gc.info()) print("Storing", len(payloads), "packets in database") sfw.kick() page = 0 page_size = 5 page_num = math.ceil(len(payloads) / page_size) device.connect() page = 0 page_size = 5 page_num = math.ceil(len(payloads) / page_size) while page < page_num: print(page + 1, "/", page_num) for j in range(3): try: data=json.dumps({"data":payloads[page*page_size:(page+1)*page_size]}) device.publish(data,TAG) break except Exception as e: print("Can't post data",e) sleep(100) else: mcu.reset() page = page + 1 sfw.kick() sleep(5000) wifi.unlink() except Exception as e: print("Error!", e) sleep(100) except Exception as e: print("Error while sniffing:", e)