def lte_connect(): lte = LTE() lte.init() #some carriers have special requirements, check print(lte.send_at_cmd("AT+SQNCTM=?")) to see if your carrier is listed. #when using verizon, use #lte.init(carrier=verizon) #when usint AT&T use, #lte.init(carrier=at&t) #some carriers do not require an APN #also, check the band settings with your carrier lte.attach(band=2, apn="vzwinternet") print("attaching..", end='') while not lte.isattached(): time.delay(0.25) print('.', end='') print(lte.send_at_cmd('AT!="fsm"')) # get the System FSM print("attached!") lte.connect() print("connecting [##", end='') while not lte.isconnected(): time.sleep(0.25) print('#', end='') #print(lte.send_at_cmd('AT!="showphy"')) print(lte.send_at_cmd('AT!="fsm"')) print("] connected!") print(socket.getaddrinfo('pycom.io', 80)) lte.deinit()
def get_device_id(self): #TODO For Wifi, change this to something like the mac address instead of SIM ICCID """Get an identifier for the device used in server requests In this case, we return the SHA256 hash of the SIM ICCID prefixed with 'ID:' and then prepend an 'IC' (for ICCID) so the result is e.g. devid = 'IC' + SHA256("ID:12345678901234567890") = IC27c6bb74efe9633181ae95bade7740969df13ef15bca1d72a92aa19fb66d24c9""" try: lte = LTE() iccid = lte.iccid() except Exception as e: print("Getting device ID failed:") print(e) return "ICERROR" hasher = None try: hasher = uhashlib.sha256("ID:" + iccid) hashvalue = hasher.digest() except Exception as e: if hasher is not None: hasher.digest( ) #make sure hasher is closed, as only one is allowed at a time by the hardware raise e devid = "IC" + ubinascii.hexlify(hashvalue).decode('utf-8') return devid
def whoami(verbose=False, veryverbose=False): import machine import binascii import os uid = binascii.hexlify(machine.unique_id()) name = os.uname().sysname.lower() + '-' + uid.decode("utf-8")[-4:] print(name) print(os.uname()) if verbose: print("type", fw_type()) for attr in dir(os.uname()): if attr[0] != '_': # filter out __class__ print(attr, getattr(os.uname(), attr)) if veryverbose: if os.uname().nodename == 'GPy' or os.uname().nodename == 'FiPy': from network import LTE lte = LTE() ver = lte.send_at_cmd('ATI1').split('\r\n')[2] prot = 'unknown' import re if re.search('^LR5', ver): prot = 'CAT-M1' elif re.search('^LR6', ver): prot = 'NB-IoT' print('Sequans FW', ver, prot)
def power_off_lte_modem(self): """ We don't use LTE yet. https://community.hiveeyes.org/t/lte-modem-des-pycom-fipy-komplett-stilllegen/2161 https://forum.pycom.io/topic/4877/deepsleep-on-batteries/10 """ import pycom """ if not pycom.lte_modem_en_on_boot(): log.info('Skip turning off LTE modem') return """ log.info('Turning off LTE modem') try: from network import LTE # Invoking this will cause `LTE.deinit()` to take around 6(!) seconds. #log.info('Enabling LTE modem on boot') #pycom.lte_modem_en_on_boot(True) log.info('Turning off LTE modem on boot') pycom.lte_modem_en_on_boot(False) log.info('Invoking LTE.deinit()') lte = LTE() lte.deinit() except: log.exception('Shutting down LTE modem failed')
def init_lte_modem(self): """ initialise the LTE modem """ try: # check if self.lte is already initialised/initialise it if not self.lte: self.lte = LTE() if not self.modem: self.modem = Modem(self.lte) # reset the LTE modem (ensure that it is in a usable state) log.info("Resetting the LTE modem") self.modem.reset() log.info("Done resetting the LTE modem") # get/log the IMSI log.info("Reading the IMSI from the SIM") self.sim_imsi = self.modem.get_imsi() log.info("SIM IMSI: %s" % str(self.sim_imsi)) except Exception as e: log.exception("Failed to set up the LTE Modem: %s" % str(e)) # idle until the watchdog resets the system while True: machine.idle() return
def lte_init_psm_off(): global l print("lte_init_psm_off") try: l = LTE(psm_period_value=1, psm_period_unit=LTE.PSM_PERIOD_DISABLED, psm_active_value=5, psm_active_unit=LTE.PSM_ACTIVE_DISABLED, debug=lte_debug) except Exception as e: print("Exception:", e) print("try without psm args") try: l = LTE(debug=lte_debug) except Exception as e: print("Exception:", e) print("try without debug") l = LTE() return l
class LTEManager(CommManager): logger = logging.getLogger(__name__) lte = LTE() def isconnected(self): return self.lte.isconnected() def scan(self): return True def connect(self): attempts = 0 if not self.lte_attach(): print("LTE attach failed") return False while not self.lte.isconnected(): print("Connecting to LTE, attempt " + str(attempts) + "/3") if self.lte_connect_attempt(): break if attempts < 3: attempts += 1 else: break if self.lte.isconnected(): print("Connected to LTE\n") pycom.rgbled(0x0000FF) return True return False def lte_connect_attempt(self): counter = 0 self.lte.connect() while not self.lte.isconnected(): time.sleep(1) counter += 1 if counter == 5: return False return True def lte_attach(self): counter = 0 print("Attaching to LTE") self.lte.attach() while not self.lte.isattached(): time.sleep(1) counter += 1 if counter == 15: return False return True def disconnect(self): if self.lte.isconnected(): self.lte.disconnect() if self.lte.isattached(): self.lte.dettach() return True
def attachLte(): global lte lte = LTE() lte.init() lte.attach(band=12, apn="soracom.io") while not lte.isattached(): time.sleep(0.25) print('.',end='') print("attached!")
def lte_init_psm_on(): global l print("lte_init_psm_on") l = LTE(psm_period_value=12, psm_period_unit=LTE.PSM_PERIOD_1H, psm_active_value=5, psm_active_unit=LTE.PSM_ACTIVE_2S, debug=lte_debug) return l
def __init__(self): try: self.lte = LTE() time.sleep(4) except: print("initialize LTE object?") self.lte.reset() time.sleep(4) print("delay 4 secs")
def check_OTA_update(): # Configuration (if you are looking for the server pubkey: it's in the OTA class) #TODO: Change server URL and Pubkey to non-testing versions SERVER_URL = "ota.iot.wheelmap.pro" SERVER_PORT = 80 NBIOT_APN = "iot.1nce.net" NBIOT_BAND = None #None = autoscan NBIOT_ATTACH_TIMEOUT = 15 * 60 #seconds NBIOT_CONNECT_TIMEOUT = 15 * 60 #seconds WATCHDOG_TIMEOUT = 15 * 60 * 1000 #milliseconds #setup watchdog wdt = machine.WDT(timeout=WATCHDOG_TIMEOUT) wdt.feed() #initialize ota object variable for proper exception handling ota = None try: # # Setup Wifi OTA # from ota_wifi_secrets import WIFI_SSID, WIFI_PW # ota = WiFiOTA(WIFI_SSID, # WIFI_PW) # Setup NB-IoT OTA print("Initializing LTE") lte = LTE() lte.reset() lte.init() ota = NBIoTOTA(lte, NBIOT_APN, NBIOT_BAND, NBIOT_ATTACH_TIMEOUT, NBIOT_CONNECT_TIMEOUT) #start the update itself print("Current version: ", ota.get_current_version()) ota.connect(url=SERVER_URL, port=SERVER_PORT) ota.update() # the update did not fail, proceed to check file integrity n = ota.check_stored_files() if n > 0: print("%d corrupted files detected and reloaded! Rebooting ..." % n) time.sleep(0.5) machine.reset() except Exception as e: raise (e) #let top level loop handle exception finally: if ota is not None: ota.clean_up() # before leaving, set watchdog to large value, so we don't interfere # with code in main.py (wdt can never be disabled after use) wdt = machine.WDT(timeout=10 * 24 * 60 * 60 * 1000) wdt.feed()
def sendData(dataList, deviceKey): # ******************** Hologram endpoint Definition HOST = "cloudsocket.hologram.io" PORT = 9999 TOPIC = "SENSOR_DATA" blink(1, 0xffffff) # blink white # Set up LTE connection lte = LTE() lte.init() print("Resetting LTE modem ... ", end="") lte.send_at_cmd('AT^RESET') print("Reset OK") time.sleep(1) # While the configuration of the CGDCONT register survives resets, # the other configurations don't. So just set them all up every time. print("Configuring LTE ", end='') # Changed this from origninal lte.send_at_cmd('AT+CGDCONT=1,"IP","hologram"') print(".", end='') # changed band from 28 to 4. I dont know what earfcn=9410 is; lte.send_at_cmd('AT!="RRC::addscanfreq band=4 dl-earfcn=9410"') print(".", end='') # lte.send_at_cmd # Do the attach (Enable radio functionality and attach to the LTE network authorized by the inserted SIM card) lte.attach() print("attaching..", end='') while not lte.isattached(): blink(1, 0x0000ff) # blue print('.', end='') # print(lte.send_at_cmd('AT!="fsm"')) # get the System FSM print("attached!") # Do the connect (Start a data session and obtain and IP address) lte.connect() print("connecting [##", end='') while not lte.isconnected(): time.sleep(1) print('#', end='') print("] connected!") blink(1, 0x00ff00) # Green # **** Send data to hologram bodyData = buildData(dataList) lteSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lteSocket.connect(socket.getaddrinfo(HOST, PORT)[0][-1]) data = '{"k": "%s", "d": "{%s}", "t": "%s"}' % (deviceKey, bodyData, TOPIC) print("Send Data:", data) lteSocket.send(data) # Clean up and close connection lteSocket.close() lte.deinit() print("Disconnected") blink(1, 0xff0000) # red
def __init__(self): self._lte = LTE() self._lte.attach() while not self._lte.isattached(): time.sleep(1) self._lte.connect() while not self._lte.isconnected(): time.sleep(1) print(self._lte.isattached()) print(self._lte.isconnected())
def __init__(self, network_manager, settings): self.network_manager = network_manager self.settings = settings from network import LTE self.lte = LTE() import machine self.chrono = machine.Timer.Chrono() self.chrono.start()
def __init__(self): self.message_storage = 'AT+CPMS="SM", "SM", "SM"' gc.collect() try: self.lte = LTE() time.sleep(4) except: print("initialize LTE object?") self.lte.reset() time.sleep(4) print("delay 4 secs")
def __init__(self, network=LTE_M): self._network = network self.lte = LTE() try: self.lte.deinit() self.lte.reset() except: pass sleep(5) self.lte.init() sleep(5) self._assure_modem_fw()
def get_LTE(): global lte if lte == None: lte = LTE() if lte.isconnected(): return True # lte.reset() # lte.send_at_cmd('AT+CGDCONT=1,"IP","nbiot.iot"') if (not lte.isattached()): lte.attach(band=20, apn="nbiot.iot") while not lte.isattached(): debugprint('Attaching...') time.sleep(1) debugprint('LTE is attached') return True
def connect_lte(self, reconnect=True, check_interval=0.5): self.__initialise_watchdog() lte_cfg = self.__conf.get('lte') if lte_cfg is not None: if (os.uname()[0] not in ['FiPy', 'GPy']): print("You need a device with FiPy or GPy firmware to connect via LTE") return False try: from network import LTE time.sleep(3) print_debug(1, 'LTE init(carrier={}, cid={})'.format(lte_cfg.get('carrier'), lte_cfg.get('cid', 1))) self.lte = LTE(carrier=lte_cfg.get('carrier')) # instantiate the LTE object print_debug(1, 'LTE attach(band={}, apn={}, type={})'.format(lte_cfg.get('band'), lte_cfg.get('apn'), lte_cfg.get('type'))) self.lte.attach(band=lte_cfg.get('band'), apn=lte_cfg.get('apn'), type=lte_cfg.get('type')) # attach the cellular modem to a base station while not self.lte.isattached(): time.sleep(0.25) time.sleep(1) print_debug(1, 'LTE connect()') self.lte.connect() # start a data session and obtain an IP address print_debug(1, 'LTE is_connected()') while not self.lte.isconnected(): time.sleep(0.25) print("LTE connection established") self.__network_type = constants.__NETWORK_TYPE_LTE self.__mqtt_check_interval = check_interval try: self.__connection = MQTTClient(self.__device_id, self.__host, self.__mqtt_download_topic, user=self.__user_name, password=self.__device_id, reconnect=reconnect, ssl=self.__ssl, ssl_params = self.__ssl_params) self.__connection.connect() self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE self.__pybytes_protocol.start_MQTT(self, check_interval, constants.__NETWORK_TYPE_WIFI) print("Connected to MQTT {}".format(self.__host)) return True except Exception as ex: if '{}'.format(ex) == '4': print('MQTT ERROR! Bad credentials when connecting to server: "{}"'.format(self.__host)) else: print("MQTT ERROR! {}".format(ex)) return False except Exception as ex: print("Exception connect_lte: {}".format(ex)) return False else: print("Error... missing configuration!") return False
def __init__(self, pytrack=None, debug=False): if pytrack is not None: self.pytrack = pytrack else: self.pytrack = Pytrack() self.debug = debug # Instantiate and hold state for sensors (accelerometer, lte, gps, etc) self.accel = LIS2HH12() self.lte = LTE() self.gps = None # Holds the mqtt client to send messages to self.mqttClient = None # If after wakeup, we are in continuous GPS logging state self.continueGPSRead = False # Flag for handling wakeup and logging logic differently if owner is nearby self.checkOwnerNearby = True self.wlan = WLAN() #TODO remove
def lte_connect(): print("init") t = time.time() try: # try to detach, in case the script was Ctrl-C-ed and is rerun detach(lte) print("detached") except: pass lte = LTE() # debug=True) # carrier=None, cid=1) # print("imei", lte.imei()) attach(lte) # lte.init(debug=True) connect(lte) # host = 'google.com' # print(host, socket.getaddrinfo(host,80)) return True
def power_off_lte_modem(self): """ We don't use LTE yet. Important ========= Once the LTE radio is initialized, it must be de-initialized before going to deepsleep in order to ensure minimum power consumption. This is required due to the LTE radio being powered independently and allowing use cases which require the system to be taken out from deepsleep by an event from the LTE network (data or SMS received for instance). Note ==== When using the expansion board and the FiPy together, the RTS/CTS jumpers MUST be removed as those pins are being used by the LTE radio. Keeping those jumpers in place will lead to erratic operation and higher current consumption specially while in deepsleep. -- https://forum.pycom.io/topic/3090/fipy-current-consumption-analysis/17 See also ======== - https://community.hiveeyes.org/t/lte-modem-des-pycom-fipy-komplett-stilllegen/2161 - https://forum.pycom.io/topic/4877/deepsleep-on-batteries/10 """ log.info('Turning off LTE modem') try: import pycom from network import LTE log.info('Turning off LTE modem on boot') pycom.lte_modem_en_on_boot(False) # Disables LTE modem completely. This presumably reduces the power # consumption to the minimum. Call this before entering deepsleep. log.info('Invoking LTE.deinit()') lte = LTE() lte.deinit(detach=False, reset=True) except Exception as ex: log.exc(ex, 'Shutting down LTE modem failed')
def sleep(): global client client.disconnect() # Disconnects from Ubidots server. client = None print("Disconnected from Ubidots.") lte = LTE() lte.deinit( ) # Disables the LTE modem to lower the power consumption during deepsleep. global chrono time = 300 - chrono.read( ) # Calculates the time in seconds for how long the deepsleep will be active. print("Going to sleep for %s seconds." % (time)) sleepTime = int( time * 1000) # Converts the time to milliseconds and the data type to int. machine.deepsleep( sleepTime ) # Turns deepsleep on. When time has passed the FipY will reboot and read the code from the top of the file.
def connect(timeout=30, lte=None): if lte is None: lte = LTE() # instantiate the LTE object lte.attach() # attach the cellular modem to a base station cycles = 0 while not lte.isattached(): sleep(1) cycles += 1 if cycles > timeout: raise Exception("Failed to attach cellular modem to base station") lte.connect() # start a data session and obtain an IP address cycles = 0 while not lte.isconnected(): sleep(1) cycles += 1 if cycles > timeout: raise Exception("Failed to obtain cellular data session") return lte
def connect(): global lte lte = LTE() # instantiate the LTE object # Change this if you are using the M1 network (comment out the next 6 lines) lte.send_at_cmd('AT+CFUN=0') lte.send_at_cmd('AT+CEMODE=0') lte.send_at_cmd('AT+CEMODE?') lte.send_at_cmd('AT!="clearscanconfig"') lte.send_at_cmd('AT!="addscanfreq band=20 dl-earfcn=6352"') lte.send_at_cmd('AT+CFUN=1') # End change this .... lte.attach() # attach the cellular modem to a base station while not lte.isattached(): time.sleep(0.25) print("attatched") lte.connect() # start a data session and obtain an IP address while not lte.isconnected(): time.sleep(0.25) print("connected")
def __init__(self): print("Init: Initialization of Gateway class...") # Machine machine.callback( trigger=(machine.PYGATE_START_EVT | machine.PYGATE_STOP_EVT | machine.PYGATE_ERROR_EVT), handler=self.machine_callback) self.machine_state = 0 # LTE self.lte = LTE() self.lte_connection_state = 0 # RTC self.rtc = RTC() # Gateway # Read the GW config file from Filesystem self.gateway_config_file = None # Timers self.rgb_breathe_timer = Timer.Chrono()
def __init__(self): self.logger = logging.get_logger(__name__) self.lte = LTE()
from network import LTE def send_at_cmd_pretty(cmd): response = lte.send_at_cmd(cmd).split('\r\n') for line in response: if (len(line) > 0): print(line) lte = LTE() print("imei", lte.imei()) print("is_connected", lte.isconnected()) print("ue_coverage", lte.ue_coverage()) print("iccid", lte.iccid()) print("time", lte.time()) send_at_cmd_pretty('AT+CGMI') # PYCOM send_at_cmd_pretty('AT+CGMM') # FiPy send_at_cmd_pretty('AT+CGMR') # UE5.0.0.0d send_at_cmd_pretty('AT+CGSN=0') send_at_cmd_pretty('AT+CGSN=1') send_at_cmd_pretty('AT+CGSN=2') send_at_cmd_pretty('AT+CGSN=3') # +CGSN: "00"
def connect_lte(self, activation_info=False, start_mqtt=True): if activation_info: lte_cfg = activation_info else: lte_cfg = self.__conf.get('lte') self.__initialise_watchdog() if lte_cfg is not None: if (os.uname()[0] not in ['FiPy', 'GPy']): print("You need a device with FiPy or GPy firmware to connect via LTE") # noqa return False try: from network import LTE time.sleep(3) if lte_cfg.get('carrier', 'standard') == 'standard': carrier = None else: carrier = lte_cfg.get('carrier') print_debug(1, 'LTE init(carrier={}, cid={})'.format(carrier, lte_cfg.get('cid', 1))) # noqa # instantiate the LTE object self.lte = LTE(carrier=carrier, cid=lte_cfg.get('cid', 1)) try: lte_type = lte_cfg.get('type') if len(lte_cfg.get('type')) > 0 else None except: lte_type = None try: lte_apn = lte_cfg.get('apn') if len(lte_cfg.get('type')) > 0 else None except: lte_apn = None try: lte_band = int(lte_cfg.get('band')) except: lte_band = None print_debug( 1, 'LTE attach(band={}, apn={}, type={})'.format( lte_band, lte_apn, lte_type ) ) self.lte.attach(band=lte_band, apn=lte_apn, type=lte_type) # noqa # attach the cellular modem to a base station while not self.lte.isattached(): time.sleep(0.25) time.sleep(1) print_debug(1, 'LTE connect()') # start a data session and obtain an IP address self.lte.connect() print_debug(1, 'LTE is_connected()') while not self.lte.isconnected(): time.sleep(0.25) print("LTE connection established") self.__network_type = constants.__NETWORK_TYPE_LTE if start_mqtt: try: self.__connection = MQTTClient( self.__device_id, self.__host, self.__mqtt_download_topic, self.__pybytes_protocol, user=self.__user_name, password=self.__device_id ) self.__connection.connect() self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE # noqa self.__pybytes_protocol.start_MQTT( self, constants.__NETWORK_TYPE_LTE ) print("Connected to MQTT {}".format(self.__host)) return True except Exception as ex: if '{}'.format(ex) == '4': print('MQTT ERROR! Bad credentials when connecting to server: "{}"'.format(self.__host)) # noqa else: print("MQTT ERROR! {}".format(ex)) return False except Exception as ex: print("Exception connect_lte: {}".format(ex)) sys.print_exception(ex) return False else: print("Error... missing configuration!") return False
from io_control import set_io_i2c, init_io, led_rd_on, measure_vbatt from io_control import pmic_ce, get_charger_status from network import LTE pycom.heartbeat(False) while False: pycom.rgbled(0xFF0000) # Red time.sleep(1) pycom.rgbled(0x00FF00) # Green time.sleep(1) pycom.rgbled(0x0000FF) # Blue time.sleep(1) if False: lte = LTE(carrier="verizon") imei = lte.imei() print(imei) if False: adc = machine.ADC() # create an ADC object apin = adc.channel(pin='P13',attn=machine.ADC.ATTN_0DB) # create an analog pin on P13 val = apin() # read an analog value print(val) volt = apin.voltage() print(volt) if False: #i2c = I2C(0, pins=('P9','P10')) # create and use non-default PIN assignments (P9=SDA, P10=SCL) #i2c.init(I2C.MASTER, baudrate=1000) # init as a master i2c = I2C(0)
import time from network import LoRa from certification import Compliance import pycom import machine import os # disable WiFi if pycom.wifi_on_boot(): pycom.wifi_on_boot(False) # disable LTE try: if 'FiPy' in os.uname().machine: from network import LTE LTE().deinit() except: pass time.sleep(5) regions_str = ['EU868', 'AS923', 'US915', 'AU915'] activations_str = ['OTAA', 'ABP'] region = None activation = None region_in = -1 activation_in = -1 print('<<< Device ready for LoRaWAN certification testing >>>')