Example #1
0
File: main.py Project: darox/Pycom
from network import LTE
from mqtt import MQTTClient
from machine import I2C
import bme280
import json
import utime
import re


def send_at_cmd_pretty(cmd):
    response = lte.send_at_cmd(cmd).split('\r\n')
    for line in response:
        print(line)


lte = LTE()
send_at_cmd_pretty('AT+CFUN=0')
send_at_cmd_pretty('AT!="clearscanconfig"')
send_at_cmd_pretty('AT!="addscanfreq band=20 dl-earfcn=6300"')
send_at_cmd_pretty('AT!="zsp0:npc 1"')
send_at_cmd_pretty('AT+CGDCONT=1,"IP","iot.swisscom.ch"')
send_at_cmd_pretty('AT+CFUN=1')

pycom.heartbeat(False)

while not lte.isattached():
    pycom.rgbled(0x7f0000)
    time.sleep(0.1)
    pycom.rgbled(0x000000)
    time.sleep(0.5)
    send_at_cmd_pretty('AT!="showphy"')
Example #2
0
from network import LTE
import urequests as requests
lte = LTE()

def send_at_cmd_pretty(cmd):
    response = lte.send_at_cmd(cmd).split('\r\n')
    for line in response:
        print(line)


print("Main ..............................")

print("gps is")
print(lat,lon)
print("Mac ID is ..")
print(dev_id)
print("Wakeup reason")
print(reason)
print("Voltage is ..")
print(voltage)


send_at_cmd_pretty('AT+CFUN=0')
send_at_cmd_pretty('AT!="clearscanconfig"')
send_at_cmd_pretty('AT!="addscanfreq band=28 dl-earfcn=9410"')
send_at_cmd_pretty('AT+CGDCONT=1,"IP","telstra.m2m"')
send_at_cmd_pretty('AT+CEREG=2')
send_at_cmd_pretty('AT+CFUN=1')


lteAttachAttemptCount = 0
Example #3
0
import ufirebase as firebase
import ws2812
from network import LTE
import json
import ledConf
from machine import CAN

#Creating socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

pycom.heartbeat(False)

# Need to use global variables.
# If in each function you delare a new reference, functionality is broken
lte = LTE()


# Returns a network.LTE object with an active Internet connection.
def getLTE():

    # If already used, the lte device will have an active connection.
    # If not, need to set up a new connection.
    if lte.isconnected():
        return lte

    # Modem does not connect successfully without first being reset.
    print("Resetting LTE modem ... ", end='')
    lte.send_at_cmd('AT^RESET')
    print("OK")
    time.sleep(1)
Example #4
0
 def __init__(self):
     from network import LTE
     self.lte = LTE()
     self.at('RRC:setDbgPerm full')
Example #5
0
from ubirch import SimProtocol

print("\n- - - UBIRCH protocol (SIM) - - -\n")

# load some necessary config (request API keys from ubirch)
with open("config.json") as f:
    cfg = json.load(f)

UPP_SERVER = 'niomon.{}.ubirch.com'.format(cfg["env"])
KEY_SERVER = 'key.{}.ubirch.com'.format(cfg["env"])
BOOT_SERVER = 'api.console.{}.ubirch.com'.format(cfg["env"])

device_name = "ukey"
cert_id = "ucrt"

lte = LTE()

if machine.reset_cause() != machine.DEEPSLEEP_RESET:
    #if we are not coming from deepsleep, the modem is probably in a strange state -> reset
    print("Not coming from sleep, resetting modem to be safe...")
    reset_modem(lte,debug_print=cfg.get("debug", False))

if 'wifi' in cfg:
    nb_iot_connection = False
    func_lvl = 4  # disable modem transmit and receive RF circuits
else:
    nb_iot_connection = True
    func_lvl = 1  # full modem functionality

# set up modem
try:
 def reconnect_uart():
     if hasattr(LTE, 'reconnect_uart'):
         LTE.reconnect_uart()
 def uart_mirror(self, color):
     import pycom
     pycom.heartbeat(False)
     time.sleep(.5)
     pycom.rgbled(color)
     LTE.modem_upgrade_mode()
Example #8
0
class Connection:
    def __init__(self):
        self.lte = LTE()

    def nb_connect(self, band=20, apn="nb.inetd.gdsp"):
        counter1 = 0
        counter2 = 0

        if not self.lte.isattached():
            print("Attaching to LTE...")
            self.lte.attach(band=band, apn=apn)
            while not self.lte.isattached():
                counter1 += 1
                print(str(counter1) + ' seconds elapsed')
                if counter1 >= 50:
                    import machine
                    machine.reset()
                time.sleep(1)

        if not self.lte.isconnected():
            print("Obtaining IP address...")
            self.lte.connect()
            while not self.lte.isconnected():
                counter2 += 1
                print(str(counter2) + ' seconds elapsed')
                time.sleep(0.25)

        print("Network ready ...")

    def nb_disconnect(self):
        if self.lte.isconnected():
            self.lte.disconnect()
        while self.lte.isattached():
            try:
                self.lte.dettach()
            except OSError as e:
                print(e, type(e))
            else:
                print("Network is now disconnected")
Example #9
0
 def __init__(self):
     self.lte = LTE()
Example #10
0
import socket
import ssl
import time
from network import LTE
import binascii
import machine
import os

uid = binascii.hexlify(machine.unique_id())
name = os.uname().sysname.lower() + '-' + uid.decode("utf-8")[-4:]
print(name, "lte_simple.py")

print("init")
t = time.time()
lte = LTE(debug=True)

# lte.send_at_cmd('AT+COPS=?')
# '\r\n+COPS: (2,"Vodafone@","VF","20404",9),,(0,1,2,3,4),(0,1,2)\r\n\r\nOK\r\n'

print("attach")
#### amarisoft (the "anritsu" or the "blank" sim)
# lte.attach()
# lte.attach(band=20)
# lte.attach(band=20)
# lte.attach(apn="Internet")
#### pycom vodafone
# lte.attach(apn="pycom.io", band=20)
# lte.attach(apn="pycom.io")
#### vodafone
# lte.attach()
# lte.attach(cid=1, band=20, apn="spe.inetd.vodafone.nbiot", type=LTE.IP)
Example #11
0
class Tracker:
    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 init(self, bInitLTE=False):
        '''
        Initialize local variables used within the script. Checks for network connectivity. If not able to connect after
        a timeout, resets the machine in order to try and conenct again. 
        Initializes MQTTClient and checks if we are in a continuous GPS read state after wakeup (saved to self instance variables)
        '''
        # Check if network is connected. If not, attempt to connect
        if bInitLTE:
            self.initLTE()
        else:
            #TODO remove
            # Check if network is connected. If not, attempt to connect
            counter = 0
            while not self.wlan.isconnected():
                # If we surpass some counter timeout and network is still not connected, reset and attempt to connect again
                if counter > 100000:
                    machine.reset()
                machine.idle()
                counter += 1

        # Initialize mqttClient
        self.mqttClient = self._getMqttClient(self.debug)

        # Check to see if we are in continued gps read (went to sleep and want to continue reading GPS data)
        if self._getNVS(ConfigGPS.NVS_SLEEP_CONTINUE_GPS_READ) is not None:
            self.continueGPSRead = True
            # Erase this key from NVS
            pycom.nvs_erase(ConfigGPS.NVS_SLEEP_CONTINUE_GPS_READ)

    @staticmethod
    def _getRTC():
        '''
        Syncs the real time clock with latest time and returns RTC instance
        '''
        rtc = machine.RTC()
        if not rtc.synced():
            # Sync real time clock
            rtc.ntp_sync("pool.ntp.org")
        return rtc

    @staticmethod
    def _getNVS(key):
        '''
        Looks up at the non volatile storage for a specified key. If it exists, returns the value stored
        for that key. Otherwise, returns None
        '''
        try:
            if pycom.nvs_get(key) is not None:
                return pycom.nvs_get(key)
        except Exception:
            # Do nothing, key doesnt exist
            pass
        return None

    @staticmethod
    def _decodeBytes(data):
        '''
        Attempts to decode a byte array to string format. If not a byte type,
        just returns the original data
        '''
        try:
            return data.decode()
        except (UnicodeDecodeError, AttributeError):
            pass
        return data

    def _getMqttClient(self, debug):
        # Initialize mqttClient
        state = False
        count = 0
        mqttClient = None

        while not state and count < 5:
            try:
                count += 1
                mqttClient = MQTTClient(ConfigMqtt.CLIENT_ID,
                                        ConfigMqtt.SERVER,
                                        port=ConfigMqtt.PORT,
                                        user=ConfigMqtt.USER,
                                        password=ConfigMqtt.PASSWORD)
                # Set the callback method that will be invoked on subscription to topics
                mqttClient.set_callback(self.mqttCallback)
                mqttClient.connect()
                state = True
            except Exception as e:
                if debug:
                    print("Exception on initialize mqtt client: {}".format(e))
                time.sleep(0.5)

        #Subscribe to the disable tracking topic
        mqttClient.subscribe(topic=ConfigMqtt.TOPIC_TRACKING_STATE)
        time.sleep(0.5)
        if self.debug:
            print("Checking MQTT messages")

        mqttClient.check_msg()

        if self.debug:
            print("Messages checked. Returning MQTT client")

        return mqttClient

    def initLTE(self):
        #TODO remove
        return
        '''
        If already used, the lte device will have an active connection.
        If not, need to set up a new connection.
        '''
        lte = self.lte
        debug = self.debug

        if lte.isconnected():
            return

        # Modem does not connect successfully without first being reset.
        if debug:
            print("Resetting LTE modem ... ", end='')
        lte.send_at_cmd('AT^RESET')
        if debug:
            print("OK")
        time.sleep(5)
        lte.send_at_cmd('AT+CFUN=0')
        time.sleep(5)

        #send_at_cmd_pretty('AT!="fsm"')
        # While the configuration of the CGDCONT register survives resets,
        # the other configurations don't. So just set them all up every time.
        if debug:
            print("Configuring LTE ", end='')
        lte.send_at_cmd('AT!="clearscanconfig"')

        if debug:
            print(".", end='')
        lte.send_at_cmd('AT!="RRC::addScanBand band=26"')

        if debug:
            print(".", end='')
        lte.send_at_cmd('AT!="RRC::addScanBand band=18"')

        if debug:
            print(".", end='')
        lte.send_at_cmd('AT+CGDCONT=1,"IP","soracom.io"')

        if debug:
            print(".", end='')
        lte.send_at_cmd('AT+CGAUTH=1,1,"sora","sora"')
        print(".", end='')

        if debug:
            lte.send_at_cmd('AT+CFUN=1')
        print(" OK")

        # If correctly configured for carrier network, attach() should succeed.
        if not lte.isattached():
            if debug:
                print("Attaching to LTE network ", end='')
            lte.attach()

            while True:
                if lte.isattached():
                    #send_at_cmd_pretty('AT+COPS?')
                    time.sleep(5)
                    break

                if debug:
                    print('.', end='')
                    pycom.rgbled(0x0f0000)
                time.sleep(0.5)
                if debug:
                    pycom.rgbled(0x000000)
                time.sleep(1.5)

        # Once attached, connect() should succeed.
        if not lte.isconnected():
            if debug:
                print("Connecting on LTE network ", end='')
            lte.connect()
            while True:
                if lte.isconnected():
                    break
                if debug:
                    print('.', end='')
                time.sleep(1)

        # Once connect() succeeds, any call requiring Internet access will
        # use the active LTE connection.
        self.lte = lte

    def isContinueGPSRead(self):
        '''
        Returns true or false - whether or not we are in a continued gps read state after power cycle / deep sleep.
        If true, we should jump right to gps read. False if we should execute normal wakeup flow
        '''
        return self.continueGPSRead

    def getWakeReason(self):
        '''
        Returns the reason why the device was woken up.
        Return values are from the ConfigWakeup scope
        '''
        if self.continueGPSRead:
            return ConfigWakeup.WAKE_CONTINUE_GPS
        elif self.pytrack.get_wake_reason() == WAKE_REASON_ACCELEROMETER:
            return ConfigWakeup.WAKE_REASON_ACCELEROMATER
        else:
            return ConfigWakeup.WAKE_REASON_TIMEOUT

    def setCheckOwnerNearby(self, bOwnerNearby=True):
        '''
        If bOnwerNearby is set to true (defaults to true here and constructor instantiation), we handle
        logic for wakup and actively logging location and pushing mqtt messages differently.
        If checkowner flag is true and owner is detected nearby on device wakeup, we are much less active
        in wakeups and monitoring
        '''
        self.checkOwnerNearby = bOwnerNearby

    def isOwnerNearby(self):
        '''
        Logic here checks if a known BLE device is broadcasting nearby.
        If they are, return true. Else, return false
        '''
        # TODO remove
        return False
        bt = Bluetooth()
        bt.start_scan(ConfigBluetooth.SCAN_ALLOW_TIME)  # Scans for 10 seconds

        while bt.isscanning():
            adv = bt.get_adv()
            if adv and binascii.hexlify(adv.mac) == ConfigBluetooth.MAC_ADDR:
                try:
                    if self.debug:
                        print("Owner device found: {} Mac addr {}".format(
                            bt.resolve_adv_data(adv.data,
                                                Bluetooth.ADV_NAME_CMPL),
                            ConfigBluetooth.MAC_ADDR))
                    conn = bt.connect(adv.mac)
                    time.sleep(0.05)
                    conn.disconnect()
                    bt.stop_scan()
                except Exception:
                    bt.stop_scan()

                return True

            time.sleep(0.050)

        return False

    def handleOwnerNearby(self):
        '''
        If owner is determined to be nearby, puts device in deep sleep for specified amount
        of time without acceleration wakeup
        '''
        # Current time and last time we wokeup with owner nearby was less than 2 minutes apart.
        # Go to deep sleep for specified amount of time without accelerometer wakeup
        self.pytrack.setup_sleep(ConfigWakeup.SLEEP_TIME_OWNER_NEARBY)
        self.pytrack.go_to_sleep()

    def mqttCallback(self, topic, msg):
        '''
        Method to handle callbacks of any mqtt topics that we subscribe to.
        For now, only subscribes to bypass topic which is used to disable gps monitoring and accelerometer wakeup detection.
        topic - MQTT topic that we are subscribing to and processing the request for 
        msg - Message received from the topic
        '''
        if self.debug:
            print("In MQTT subscription callback")

        # Attempt to decode the topic and msg if in byte format
        topic = self._decodeBytes(topic)
        msg = self._decodeBytes(msg)

        # Handle mqtt topic for disabiling the monitoring
        if topic == ConfigMqtt.TOPIC_TRACKING_STATE:
            try:
                bSleep = False
                sleepTime = ConfigMqtt.SLEEP_TIME_MQTT_DISABLE

                # First check if this is a plaintext msg (not json format)
                if msg == ConfigMqtt.ENABLE_TRACKING_MSG:
                    # Tracking is enabled, continue
                    bSleep = False

                elif msg == ConfigMqtt.DISABLE_TRACKING_MSG:
                    # If tracking is disabled, go to sleep with configured sleep time
                    bSleep = True

                else:
                    # Structure of the message will be in json format:
                    # { msg: "XXX", "time": 123} where msg value is ON/OFF for disable (OFF) or enable(ON)
                    # and time value is time to disable tracking (will automatically be re-enabled after
                    # time surpasses if this value is present)
                    jMsg = ujson.loads(msg)
                    # Check if the msg is Y. If so, need to stop tracking
                    if jMsg['msg'] == ConfigMqtt.DISABLE_TRACKING_MSG:
                        # Requested to go to sleep, so set the flags
                        bSleep = True
                        # If theres a time with the disable flag, go to sleep for that amount of time
                        if jMsg['time'] and jMsg['time'] is not None:
                            sleepTime = jMsg['time']

                # If the flag was set, go to sleep
                if bSleep:
                    if self.debug:
                        print("Disable tracking from mqtt. Sleeping for {}".
                              format(sleepTime))
                    self.goToSleep(sleepTime=sleepTime)

            except ValueError:
                if self.debug:
                    print('Exception parsing disable tracking mqtt msg')

    def sendMQTTMessage(self, topic, msg, retain=False):
        '''
        Sends an MQTT message to the specified topic
        topic - Topic to send to
        msg - Message to send to topic
        mqttClient - MQTT Client used to send the message. If not defined, sends to default configured mqtt client in configuration
        '''
        debug = self.debug

        # If LTE is not setup, initialize it so we can send messages
        #self.initLTE()

        if self.mqttClient is None:
            try:
                # Instantiate a new MQTTClient
                self.mqttClient = self._getMqttClient(debug)
            except:
                self.mqttClient = None

        try:
            if self.mqttClient is not None:
                # Send the message topic
                self.mqttClient.publish(topic=topic, msg=msg, retain=retain)
        except:
            if debug:
                print(
                    "Exception occurred attempting to connect to MQTT server")

    def goToSleep(self, sleepTime=60, bWithInterrupt=False, bSleepGps=True):
        '''
        Puts the py to deepsleep, turning off lte in order to reduce battery consumption.
        By default, sleeps for 60 seconds and powers down gps.
        sleepTime - specifies the time (in seconds) to put the device in deep sleep before waking up
        bWithInterrupt - if True, will wakeup for both timer timeout as well as acceleration interrupt
        bSleepGps - If True, puts the gps in deepsleep state as well (will take longer to reinitialize and refix gps signal)
        '''
        # Enable wakeup source from INT pin
        self.pytrack.setup_int_pin_wake_up(False)

        # Enable activity and inactivity interrupts with acceleration threshold and min duration
        if bWithInterrupt:
            self.pytrack.setup_int_wake_up(True, True)
            self.accel.enable_activity_interrupt(
                ConfigAccelerometer.INTERRUPT_THRESHOLD,
                ConfigAccelerometer.INTERRUPT_DURATION)

        # If mqttClient is defined, disconnect
        if self.mqttClient is not None:
            try:
                self.mqttClient.disconnect()
            except:
                if self.debug:
                    print("Exception occurred disconnecting from mqtt client")

        # Disconnect lte
        if self.lte is not None and self.lte.isconnected():
            try:
                self.lte.disconnect()
                time.sleep(1)
                self.lte.dettach()
            except:
                if self.debug:
                    print("Exception disconnecting from lte")

        # Go to sleep for specified amount of time if no accelerometer wakeup
        if self.debug:
            print("Sleeping for {} seconds with accel interrupt? {}".format(
                sleepTime, bWithInterrupt))
            time.sleep(0.5)

        time.sleep(0.1)
        self.pytrack.setup_sleep(sleepTime)
        self.pytrack.go_to_sleep(gps=bSleepGps)

    def _getGpsFix(self):
        '''
        Attempts to lock on a signal to the gps.
        Returns true if signal is found, false otherwise
        '''
        # Attempt to get the gps lock for X number of attempts (defined in config)
        maxTries = max(ConfigGPS.LOCK_FAIL_ATTEMPTS, 1)
        signalFixTries = maxTries
        while signalFixTries > 0:
            signalFixTries -= 1
            if self.debug:
                print("On GPS fix try number {} of {}".format(
                    maxTries - signalFixTries, maxTries))
            self.gps.get_fix(debug=False)
            pycom.heartbeat(False)
            bIsFixed = False

            if self.gps.fixed():
                # Got the GPS fix, exit out of this while condition
                if self.debug:
                    pycom.rgbled(0x000f00)
                bIsFixed = True
            else:
                # If couldnt get a signal fix, try again
                if self.debug:
                    pycom.rgbled(0x0f0000)

        return bIsFixed

    def monitorLocation(self, bWithMotion=True):
        '''
        Sends GPS location to Mqtt topic. Continues sending data as long as motion is detected
        bWithMotion - If true, continues to monitor and send GPS location to topic as long as accelerometer activity is
            detected. If false, only publishes location once
        '''
        if self.debug:
            print("Monitoring Location")
        self.gps = L76GNSS(self.pytrack,
                           timeout=ConfigGPS.LOCK_TIMEOUT,
                           debug=False)
        self.gps.setAlwaysOn()

        if not self._getGpsFix():
            # Couldnt get a signal so send message to topic for gps not available and exit (go back to sleep)
            if self.debug:
                print("Couldnt get a GPS signal after {} attempts".format(
                    ConfigGPS.LOCK_FAIL_ATTEMPTS))
            self.sendMQTTMessage(ConfigMqtt.TOPIC_GPS_NOT_AVAILABLE, "-1")
            return

        # Otherwise we have a gps signal, so get the coordinates and send to topic
        coordinates = self.gps.coordinates()
        self.sendMQTTMessage(ConfigMqtt.TOPIC_GPS, coordinates)

        # Save current timestamp of log time
        self._getRTC()  # Syncs rtc
        pycom.nvs_set(ConfigGPS.NVS_LAST_LOCATION_LOG_TIME, utime.time())

        # If we want to monitor with motion (send multiple gps coordinates as long as there is motion), start monitoring
        if bWithMotion & self.accelInMotion():
            # Go to sleep for a specified amount of time (keeping GPS alive) to conserve some battery
            # TODO - check if this is better than setPeriodicMode
            if self.debug:
                print("Putting gps in low power and going to sleep")
            #Save state to nvs (non volatile storage)
            pycom.nvs_set(ConfigGPS.NVS_SLEEP_CONTINUE_GPS_READ, 1)
            self.goToSleep(sleepTime=ConfigGPS.SLEEP_BETWEEN_READS,
                           bWithInterrupt=False,
                           bSleepGps=False)

    def accelInMotion(self, numReads=10):
        '''
        Takes numReads measurements of accelerometer data to detect if there is motion.
        numReads - Number of measurements to take to detect motion
        Returns true if delta sensor data is above a threshold (meaning there is active motion), false otherwise
        '''
        accel = self.accel
        xyzList = list()
        xyzList.append(accel.acceleration())
        for index in range(0, numReads):
            # Print change from last reading
            time.sleep(0.5)
            xyzList.append(accel.acceleration())
            deltas = list(
                map(lambda b, a: abs(b - a), xyzList[-1], xyzList[-2])
            )  # Get last element (with -1) and subtract previous element (-2)
            # If max delta is greater than threshold, return true
            if max(deltas) >= ConfigAccelerometer.MOTION_CHECK_MIN_THRESHOLD:
                return True

        # Get the largest change in x, y, and z and see if that surpasses the threshold
        minVals = list()
        maxVals = list()
        for i in range(3):
            minVals.append(min(map(lambda a, i=i: a[i], xyzList)))
            maxVals.append(max(map(lambda a, i=i: a[i], xyzList)))

        # Get the maximum delta for x, y, z for all logged points
        deltas = list(map(lambda b, a: b - a, maxVals, minVals))
        if self.debug:
            print("Deltas accel motion {}".format(deltas))
        # If any x, y, or z axis in deltas array have a total delta change past the allowed threshold, return true. Otherwise return false
        return max(deltas) >= ConfigAccelerometer.MOTION_CHECK_MIN_THRESHOLD

    def logRegularCoordinates(self):
        '''
        On regular timed wakeups, we still log our location every so often. Check the last time the location was
        logged and if the time is greater than the surpassed time defined in config, log coordinates again
        '''
        lastLogTime = self._getNVS(ConfigGPS.NVS_LAST_LOCATION_LOG_TIME)
        self._getRTC()  # Updates RTC

        # Compare the last log time with current rtc to see if threshold has passed
        if (lastLogTime is None or
            (utime.time() - lastLogTime > ConfigGPS.LOCATION_LOG_INTERVAL)):
            # Need to update gps as time has elapsed since last log
            self.monitorLocation(bWithMotion=False)  # Only log once

    def accelWakeup(self):
        '''
        Logic to handle board wakeup interruption due to accelerometer.
        Sends mqtt messages for wakeup if client is defined.
        '''
        debug = self.debug
        if debug:
            print("Accelerometer wakeup")

        # Check if the owner is nearby (owner moving device). If so, handle differently
        if self.checkOwnerNearby and self.isOwnerNearby():
            # Owner is nearby. If last wake is with 2 minutes, we are most likely riding
            # so go to sleep for longer time without wakeup
            self.handleOwnerNearby()

        # Check the accelerometer is still active (preventing false negatives for alerting of theft)
        # If we dont ready any new accelerometer motion, exit this function and dont send any accelerometer wakeup or gps msgs
        if not self.accelInMotion():
            if debug:
                print("Not currently in motion, going back to sleep")
            return
        else:
            if debug:
                print("Motion detected after wakeup...")

        # Not a false wakeup, so send a message to the initial accelerometer wakeup topic
        self.sendMQTTMessage(ConfigMqtt.TOPIC_ACCEL_WAKEUP, "1")

        # Send GPS updates while there has been continued motion for some time
        self.monitorLocation(bWithMotion=True)
Example #12
0
    print(lora.frequency())
    print(lora.has_joined())
    print(lora.tx_power())
    print(lora.power_mode())
    #print(lora.stats())
except:
    pass

try:
    print("===== sigfox =====================================")
    from network import Sigfox
    sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1)
    print("id", ubinascii.hexlify(sigfox.id()))
    print("mac", ubinascii.hexlify(sigfox.mac()))
    print("pac", ubinascii.hexlify(sigfox.pac()))
    print("frequencies", sigfox.frequencies())
except:
    pass

try:
    print("===== lte ========================================")
    from network import LTE
    lte = LTE()
    print("imei", lte.imei())
    print("iccid", lte.iccid())
    print("is_connected", lte.isconnected())
    print("ue_coverage", lte.ue_coverage())
    # print("time", lte.time())
except:
    pass
Example #13
0
""" Meerkat Pycom LTE module
Note: Use global variables, if in each function you delare a new reference,
functionality is broken.

Refactored from post by user mattliddle at:
https://forum.pycom.io/topic/3021/gpy-with-hologram-io-sim?page=1
"""

import socket
import time
import pycom
from network import LTE


lte_modem = LTE()

def LTE_init(verbose=False):
    """Connect to LTE network using hologram.io SIM. If network connection
    is already in use, returns the LTE device's connection, otherwise will
    set up a new connection.

    Parameters
    ----------
    verbose : bool, print debug statements

    Returns
    -------
    network.LTE object with an active Internet connection
    """
    if lte_modem.isconnected():
        if verbose: print('LTE Modem already connected.')
Example #14
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