Beispiel #1
0
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()
Beispiel #2
0
def reset_modem(lte: LTE, debug_print=False):
    function_level = "1"
    cereg_level = "0"

    if debug_print: print("\twaiting for reset to finish")
    lte.reset()
    lte.init()

    if debug_print: print("\tsetting function level")
    for tries in range(5):
        _send_at_cmd(lte, "AT+CFUN=" + function_level)
        result = _send_at_cmd(lte, "AT+CFUN?")
        if result[0] == '+CFUN: ' + function_level:
            break
    else:
        raise Exception("could not set modem function level")

    if debug_print: print("\twaiting for SIM to be responsive")
    for tries in range(10):
        result = _send_at_cmd(lte, "AT+CIMI")
        if result[-1] == 'OK':
            break
    else:
        raise Exception("SIM does not seem to respond after reset")

    if debug_print: print("\tdisabling CEREG messages")
    # we disable unsolicited CEREG messages, as they interfere with AT communication with the SIM via CSIM commands
    # this also requires to use an attach method that does not require cereg messages, for pycom that is legacyattach=false
    for tries in range(5):
        _send_at_cmd(lte, "AT+CEREG=" + cereg_level)
        result = _send_at_cmd(lte, "AT+CEREG?")
        if result[0][0:9] == '+CEREG: ' + cereg_level:
            break
    else:
        raise Exception("could not set CEREG level")
Beispiel #3
0
def lte_setup(lte: LTE, connect: bool, apn: str or None):
    print(">> initializing LTE")
    lte.init()
    if connect:
        if not lte.isattached():
            nb_iot_attach(lte, apn)
        if not lte.isconnected():
            nb_iot_connect(lte)
Beispiel #4
0
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!")
Beispiel #5
0
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
Beispiel #6
0
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 connect_lte(timeout=30):
    lte = LTE()  # instantiate the LTE object
    lte.deinit()
    lte.init()

    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
Beispiel #8
0
    start_time_activation = utime.ticks_ms()

    lte.send_at_cmd('AT+CFUN=1')
    while not lte.isattached() and (utime.ticks_ms() - start_time_activation <
                                    timeout):
        print(".", end="")
        utime.sleep_ms(10)

    print("")
    return lte.isattached()


print("Initializing LTE...")
lte = LTE()
lte.init()

attached = attachCellular(_NBIOT_MAX_CONNECTION_TIMEOUT_MSEC)
print("LTE ok: " + str(attached))

if (attached):
    #message as bytes
    data = bytearray('{data:"testmessage"}')

    # create socket instance providing the instance of the LTE modem
    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    sock.setModemInstance(lte)

    # set that the incoming/outgoing data are bytes in hex
    # the following cal can be omitted as default format for socket is SOCKET_MESSAGE_BYTE
    #socket.setMessageFormat(MicroATSocket.SOCKET_MESSAGE_FORMAT.SOCKET_MESSAGE_BYTE)
Beispiel #9
0
class StartIoT:
  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 _assure_modem_fw(self):
    response = self.lte.send_at_cmd('ATI1')
    if response != None:
      lines = response.split('\r\n')
      fw_id = lines[1][0:3]
      is_nb = fw_id == 'UE6'
      if is_nb:
        print('Modem is using NB-IoT firmware (%s/%s).' % (lines[1], lines[2]))
      else:
        print('Modem in using LTE-M firmware (%s/%s).' % (lines[1], lines[2]))
      if not is_nb and self._network == NB_IOT:
        print('You cannot connect using NB-IoT with wrong modem firmware! Please re-flash the modem with the correct firmware.')
        raise WrongNetwork
      if is_nb and self._network == LTE_M:
        print('You cannot connect using LTE-M with wrong modem firmware! Please re-flash the modem with the correct firmware.')
        raise WrongNetwork
    else:
      print('Failed to determine modem firmware. Rebooting device...')
      reset() # Reboot the device


  def send_at_cmd_pretty(self, cmd):
    print('>', cmd)
    response = self.lte.send_at_cmd(cmd)
    if response != None:
      lines = response.split('\r\n')
      for line in lines:
        if len(line.strip()) != 0:
          print('>>', line)
    else:
      print('>> No response.')
    return response

  def connect(self):
    # NB-IoT
    if (self._network == NB_IOT):
      self.send_at_cmd_pretty('AT+CFUN=0')
      self.send_at_cmd_pretty('AT+CEMODE=0')
      self.send_at_cmd_pretty('AT+CEMODE?')
      self.send_at_cmd_pretty('AT!="clearscanconfig"')
      self.send_at_cmd_pretty('AT!="addscanfreq band=%s dl-earfcn=%s"' % (BAND, EARFCN))
      self.send_at_cmd_pretty('AT+CGDCONT=1,"IP","%s"' % APN)
      self.send_at_cmd_pretty('AT+COPS=1,2,"%s"' % COPS)
      self.send_at_cmd_pretty('AT+CFUN=1')

    # LTE-M (Cat M1)
    else:
      self.send_at_cmd_pretty('AT+CFUN=0')
      self.send_at_cmd_pretty('AT!="clearscanconfig"')
      self.send_at_cmd_pretty('AT!="addscanfreq band=%s dl-earfcn=%s"' % (BAND, EARFCN))
      self.send_at_cmd_pretty('AT+CGDCONT=1,"IP","%s"' % APN)
      self.send_at_cmd_pretty('AT+CFUN=1')
      self.send_at_cmd_pretty('AT+CSQ')

    # For a range scan:
    # AT!="addscanfreqrange band=20 dl-earfcn-min=3450 dl-earfcn-max=6352"

    print('Attaching...')
    seconds = 0
    while not self.lte.isattached() and seconds < attach_timeout:
      sleep(0.25)
      seconds += 0.25
    if self.lte.isattached():
      print('Attached!')
    else:
      print('Failed to attach to LTE (timeout)!')
      raise AttachTimeout
    self.lte.connect()

    print('Connecting...')
    seconds = 0
    while not self.lte.isconnected() and seconds < connect_timeout:
      sleep(0.25)
      seconds += 0.25
    if self.lte.isconnected():
      print('Connected!')
    else:
      print('Failed to connect to LTE (timeout)!')
      raise ConnectTimeout

  def disconnect(self):
    if self.lte.isconnected():
      self.lte.disconnect()

  def dettach(self):
    if self.lte.isattached():
      self.lte.dettach()
class SQNS:
    """
    Synopsis::
    
        sq = SQNS()
        sq.info()
        sq.firmware_info()
    
        sq.at('showphy')

    See also:
    - https://git.cicer.de/autonome-zelle/fipy-nbiot-rtd/blob/master/main.py

    """
    def __init__(self):
        from network import LTE
        self.lte = LTE()
        self.at('RRC:setDbgPerm full')

    def connect(self):
        self.lte.init()

    def attach(self):
        self.lte.attach(band=8, apn="iot.1nce.net")
        while not self.lte.isattached():  # do we have a timeout?
            time.sleep(1)
            try:
                csq_at = self.lte.send_at_cmd("AT+CSQ")
                csq_line_regex = ure.compile("\n")
                csq_line = csq_line_regex.split(csq_at)
                csq_string_regex = ure.compile(" ")
                csq_string = csq_string_regex.split(csq_line[1])
                csq_comma = csq_string[1]
                csq_num_regex = ure.compile(",")
                csq_num = csq_num_regex.split(csq_comma)
                csq = csq_num[0]
                print("[LTE   ]   ... still attaching ... (CSQ: " + csq + ")")
            except:
                csq = "-999.0"
                print(
                    "[LTE   ]   ... no CSQ recevied, let us hope I am still attaching "
                    + csq)

    def at(self, command):
        """

        :param command: 

        """
        self.raw('AT!="{}"'.format(command))

    def raw(self, command):
        """

        :param command: 

        """
        print('Sending command {}'.format(command))
        print(self.lte.send_at_cmd(command))

    def imei(self):
        """ """
        self.at('AT+CGSN=1')

    def info(self):
        """ """
        # https://forum.pycom.io/topic/4022/unable-to-update-gpy-modem-firmware/8
        self.at('AT')
        self.at('ATI')
        self.at('ATZ')

    def firmware_info(self):
        """ """
        import sqnsupgrade
        sqnsupgrade.info(verbose=True, debug=True)

    def unbrick(self):
        """ """
        raise NotImplementedError(
            'https://forum.pycom.io/topic/4022/unable-to-update-gpy-modem-firmware/21'
        )
class DatacakeGateway:
    def machine_callback(self, arg):
        evt = machine.events()
        if (evt & machine.PYGATE_START_EVT):
            self.machine_state = config.GATEWAY_STATE_OK
            pycom.rgbled(config.RGB_GATEWAY_OK)
        elif (evt & machine.PYGATE_ERROR_EVT):
            self.machine_state = config.GATEWAY_STATE_ERROR
            pycom.rgbled(config.RGB_GATEWAY_ERROR)
        elif (evt & machine.PYGATE_STOP_EVT):
            self.machine_state = config.GATEWAY_STATE_STOP
            pycom.rgbled(config.RGB_GATEWAY_STOP)

    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()

        # Startup
        # Should be called outside init
        # self.start_up()

    def lte_event_callback(self, arg):
        #self.blink_rgb_led(5, 0.25, config.RGB_LTE_ERROR)
        #self.lte.deinit()
        #machine.reset()
        print(
            "\n\n\n#############################################################"
        )
        print("CB LTE Callback Handler")
        ev = arg.events()  # NB: reading the events clears them
        t = time.ticks_ms()
        print("CB", t, time.time(), ev, time.gmtime())
        self.blink_rgb_led(3, 0.25, config.RGB_LTE_ERROR)
        if ev & LTE.EVENT_COVERAGE_LOSS:
            print("CB", t, "coverage loss")
        if ev & LTE.EVENT_BREAK:
            print("CB", t, "uart break signal")
        try:
            self.lte.pppsuspend()
            if not self.lte.isattached():
                print("not attached ... reattach")
                self.lte.detach()
                self.init_lte()
            else:
                print("attached ... resume")
                self.lte.pppresume()
        except Exception as ex:
            sys.print_exception(ex)
        print(
            "#############################################################\n\n\n"
        )

    def init_gateway(self):
        print("Init GW: Starting LoRaWAN Concentrator...")
        try:
            self.gateway_config_file = open(config.GW_CONFIG_FILE_PATH,
                                            'r').read()
        except Exception as e:
            print("Error opening Gateway Config: {}".format(e))
            # TODO: Handle Error
            return False
        else:
            machine.pygate_init(self.gateway_config_file)
            print("Init GW: LoRaWAN Concentrator UP!")
            return True

    def init_rtc(self):
        print("Init RTC: Syncing RTC...")
        try:
            self.rtc.ntp_sync(server="pool.ntp.org")
            while not self.rtc.synced():
                self.blink_rgb_led(1,
                                   0.25,
                                   config.RGB_RTC_IS_SYNCING,
                                   delay_end=False)
            self.blink_rgb_led(3, 0.1, config.RGB_RTC_IS_SYNCING)
        except Exception as e:
            print("Exception syncing RTC: {}".format(e))
            return False
        else:
            print("Init RTC: Synced!")
            return True

    def init_lte(self):

        self.lte_connection_state = 0
        self.lte.init()
        #self.lte.lte_callback(LTE.EVENT_COVERAGE_LOSS, self.lte_event_callback)
        self.lte.lte_callback(LTE.EVENT_BREAK, self.lte_event_callback)

        while True:

            # attach LTE
            if self.lte_connection_state == 0:
                print("Init LTE: Attaching LTE...")
                self.lte.attach(band=config.LTE_BAND, apn=config.LTE_APN)
                while not self.lte.isattached():
                    self.blink_rgb_led(1,
                                       0.25,
                                       config.RGB_LTE_IS_ATTACHING,
                                       delay_end=False)
                self.blink_rgb_led(3, 0.1, config.RGB_LTE_IS_ATTACHING)
                self.lte_connection_state += 1
                print("Init LTE: Attached!")

            # connect LTE
            if self.lte_connection_state == 1:
                print("Init LTE: Connecting LTE...")
                self.lte.connect()
                while not self.lte.isconnected():
                    self.blink_rgb_led(1,
                                       0.25,
                                       config.RGB_LTE_IS_CONNECTING,
                                       delay_end=False)
                self.blink_rgb_led(3, 0.1, config.RGB_LTE_IS_CONNECTING)
                self.lte_connection_state += 1
                print("Init LTE: Connected!")

            # done
            if self.lte_connection_state == 2:
                return True

    def blink_rgb_led(self,
                      times,
                      speed,
                      color_on,
                      color_off=config.RGB_OFF,
                      delay_end=True):
        for index in range(times):
            pycom.rgbled(config.RGB_OFF)
            time.sleep(speed)
            pycom.rgbled(color_on)
            time.sleep(speed)
        pycom.rgbled(config.RGB_OFF)
        if delay_end is True:
            time.sleep(0.1)

    def start_up(self):
        print("Start Up: Now starting up Gateway...")
        self.init_lte()
        self.init_rtc()
        self.init_gateway()
        #self.main_loop()

    def main_loop(self):

        # Start Timers
        self.rgb_breathe_timer.start()

        while True:

            if self.rgb_breathe_timer.read(
            ) > config.TIMER_RGB_BREATHE_INTERVAL:
                self.rgb_breathe_timer.reset()
Beispiel #12
0
class StartIoT:
    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 _assure_modem_fw(self):
        response = self.lte.send_at_cmd('ATI1')
        if response != None:
            lines = response.split('\r\n')
            fw_id = lines[1][0:3]
            is_nb = fw_id == 'UE6'
            if is_nb:
                print('Modem is using NB-IoT firmware (%s/%s).' %
                      (lines[1], lines[2]))
            else:
                print('Modem in using LTE-M firmware (%s/%s).' %
                      (lines[1], lines[2]))
            if not is_nb and self._network == NB_IOT:
                print(
                    'You cannot connect using NB-IoT with wrong modem firmware! Please re-flash the modem with the correct firmware.'
                )
                raise WrongNetwork
            if is_nb and self._network == LTE_M:
                print(
                    'You cannot connect using LTE-M with wrong modem firmware! Please re-flash the modem with the correct firmware.'
                )
                raise WrongNetwork
        else:
            print('Failed to determine modem firmware. Rebooting device...')
            reset()  # Reboot the device

    def _get_assigned_ip(self):
        ip_address = None
        try:
            self.lte.pppsuspend()
            response = self.send_at_cmd_pretty('AT+CGPADDR=1')
            self.lte.pppresume()
            lines = response.split('\r\n')
            sections = lines[1].split('"')
            ip_address = sections[1]
        except:
            print('Failed to retrieve assigned IP from LTE network.')

        return ip_address

    def send_at_cmd_pretty(self, cmd):
        print('>', cmd)
        response = self.lte.send_at_cmd(cmd)
        if response != None:
            lines = response.split('\r\n')
            for line in lines:
                if len(line.strip()) != 0:
                    print('>>', line)
        else:
            print('>> No response.')
        return response

    def connect(self):
        # NB-IoT
        if (self._network == NB_IOT):
            self.send_at_cmd_pretty('AT+CFUN=0')
            self.send_at_cmd_pretty('AT+CEMODE=0')
            self.send_at_cmd_pretty('AT+CEMODE?')
            self.send_at_cmd_pretty('AT!="clearscanconfig"')
            self.send_at_cmd_pretty('AT!="addscanfreq band=%s dl-earfcn=%s"' %
                                    (BAND, EARFCN))
            self.send_at_cmd_pretty('AT+CGDCONT=1,"IP","%s"' % APN)
            self.send_at_cmd_pretty('AT+COPS=1,2,"%s"' % COPS)
            self.send_at_cmd_pretty('AT+CFUN=1')

        # LTE-M (Cat M1)
        else:
            self.send_at_cmd_pretty('AT+CFUN=0')
            self.send_at_cmd_pretty('AT!="clearscanconfig"')
            self.send_at_cmd_pretty('AT!="addscanfreq band=%s dl-earfcn=%s"' %
                                    (BAND, EARFCN))
            self.send_at_cmd_pretty('AT+CGDCONT=1,"IP","%s"' % APN)
            self.send_at_cmd_pretty('AT+CFUN=1')
            self.send_at_cmd_pretty('AT+CSQ')

        # For a range scan:
        # AT!="addscanfreqrange band=20 dl-earfcn-min=3450 dl-earfcn-max=6352"

        print('Attaching...')
        seconds = 0
        while not self.lte.isattached() and seconds < attach_timeout:
            sleep(0.25)
            seconds += 0.25
        if self.lte.isattached():
            print('Attached!')
        else:
            print('Failed to attach to LTE (timeout)!')
            raise AttachTimeout
        self.lte.connect()

        print('Connecting...')
        seconds = 0
        while not self.lte.isconnected() and seconds < connect_timeout:
            sleep(0.25)
            seconds += 0.25
        if self.lte.isconnected():
            print('Connected!')
        else:
            print('Failed to connect to LTE (timeout)!')
            raise ConnectTimeout

        print('Retrieving assigned IP...')
        ip_address = self._get_assigned_ip()

        print("Device IP: {}".format(ip_address))
        print(ip_address)

        # Initialise the CoAP module
        Coap.init(ip_address)

        # Register the response handler for the requests that the module initiates as a CoAP Client
        Coap.register_response_handler(self.response_callback)

        # A CoAP server is needed if CoAP push is used (messages are pushed down from Managed IoT Cloud)
        # self.setup_coap_server()

    def setup_coap_server(self):
        # Add a resource with a default value and a plain text content format
        r = Coap.add_resource('',
                              media_type=Coap.MEDIATYPE_APP_JSON,
                              value='default_value')
        # Configure the possible operations on the resource
        r.callback(
            Coap.REQUEST_GET | Coap.REQUEST_POST | Coap.REQUEST_PUT
            | Coap.REQUEST_DELETE, True)

        # Get the UDP socket created for the CoAP module
        coap_server_socket = Coap.socket()
        # Create a new poll object
        p = uselect.poll()
        # Register the CoAP module's socket to the poll
        p.register(coap_server_socket,
                   uselect.POLLIN | uselect.POLLHUP | uselect.POLLERR)
        # Start a new thread which will handle the sockets of "p" poll
        _thread.start_new_thread(socket_thread, (p, coap_server_socket))

        print('CoAP server running!')

    # The callback that handles the responses generated from the requests sent to a CoAP Server
    def response_callback(self, code, id_param, type_param, token, payload):
        # The ID can be used to pair the requests with the responses
        print('ID: {}'.format(id_param))
        print('Code: {}'.format(code))
        print('Type: {}'.format(type_param))
        print('Token: {}'.format(token))
        print('Payload: {}'.format(payload))

    def disconnect(self):
        if self.lte.isconnected():
            self.lte.disconnect()

    def dettach(self):
        if self.lte.isattached():
            self.lte.dettach()

    def send(self, data):
        if not self.lte.isconnected():
            raise Exception('Not connected! Unable to send.')

        id = Coap.send_request(IOTGW_IP,
                               Coap.REQUEST_POST,
                               uri_port=IOTGW_PORT,
                               uri_path=IOTGW_ENDPOINT,
                               payload=data,
                               include_options=True)
        print('CoAP POST message ID: {}'.format(id))

    def pull(self, uri_path='/'):
        if not self.lte.isconnected():
            raise Exception('Not connected! Unable to pull.')

        id = Coap.send_request(IOTGW_IP,
                               Coap.REQUEST_GET,
                               uri_port=IOTGW_PORT,
                               uri_path=uri_path,
                               include_options=True)
        Coap.read()
        print('CoAP GET message ID: {}'.format(id))
Beispiel #13
0
class SequansLTE:
    """
    Synopsis::

        sq = SequansLTE()
        sq.info()
        sq.firmware_info()

        sq.at('showphy')

    See also:
    - https://git.cicer.de/autonome-zelle/fipy-nbiot-rtd/blob/master/main.py

    """
    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 start(self):
        self.lte.init()
        self.attach()
        self.connect()

    def stop(self):
        self.lte.disconnect()
        time.sleep(0.25)

        self.lte.deinit()
        time.sleep(0.25)

    def attach(self):
        log.info('Attaching to LTE')
        self.lte.attach(band=self.settings.get('networking.lte.band'),
                        apn=self.settings.get('networking.lte.apn'))

        self.chrono.reset()
        while True:

            log.info('Signal strength: {}'.format(self.get_signal_strength()))

            if self.lte.isattached():
                break

            if self.chrono.read() > self.settings.get(
                    'networking.lte.attach_timeout'):
                raise Exception('Attaching to LTE timed out')

            time.sleep(0.25)

    def connect(self):
        log.info('Connecting to LTE')
        self.lte.connect()

        self.chrono.reset()
        while True:

            if self.lte.isconnected():
                break

            if self.chrono.read() > self.settings.get(
                    'networking.lte.connect_timeout'):
                raise Exception('Connecting to LTE timed out')

            time.sleep(0.25)

    def imei(self):
        """
        Return IMEI.
        """
        return self.at('AT+CGSN=1')

    def info(self):
        """
        Get infos from Modem.
        """

        log.info('Signal strength: {}'.format(self.get_signal_strength()))

        self.at('RRC:setDbgPerm full')
        self.at('RRC:showcaps')
        self.at('showver')

        # https://forum.pycom.io/topic/4022/unable-to-update-gpy-modem-firmware/8
        #self.at('AT')
        #self.at('ATI')
        #self.at('ATZ')

    def get_signal_strength(self):
        csq_at = self.lte.send_at_cmd("AT+CSQ")
        csq_line_regex = ure.compile("\n")
        csq_line = csq_line_regex.split(csq_at)
        csq_string_regex = ure.compile(" ")
        csq_string = csq_string_regex.split(csq_line[1])
        csq_comma = csq_string[1]
        csq_num_regex = ure.compile(",")
        csq_num = csq_num_regex.split(csq_comma)
        csq = csq_num[0]
        return csq

    def at(self, command):
        """

        :param command:

        """
        return self.raw('AT!="{}"'.format(command))

    def raw(self, command):
        """

        :param command:

        """
        log.info('Sending: {}'.format(command))
        answer = self.lte.send_at_cmd(command)
        log.info('Answer:  {}'.format(answer))
        return answer

    def firmware_info(self):
        """ """
        import sqnsupgrade
        sqnsupgrade.info(verbose=True, debug=True)

    def unbrick(self):
        """ """
        raise NotImplementedError(
            'https://forum.pycom.io/topic/4022/unable-to-update-gpy-modem-firmware/21'
        )