# This is used to recive words from Device 1 # protocol is: # First the sender device led will be off # to notify this unit to be ready to recive the sender device will turn on LED for 5 sec Followed by the message. # The message will be send one bit at a time were # no ligth for one sec means 0 # light for one sec means 1 # Each letter is 8 bits! # the message will end with the LED being turn off for 8 sec # From:https://github.com/pycom/pycom-libraries from LTR329ALS01 import LTR329ALS01 from SI7006A20 import SI7006A20 from pytrack import Pytrack py = Pytrack() lightsensor = LTR329ALS01() humiAndTempSensor = SI7006A20() isRunning = True isReciving = False ligthThreshold = 200 #Metode to decode a lettere from a byte def getWordvalue(bits): word = "" word = EncoderDecoder.dataDecoding[bits] return word #Method to recive the ligth intensity, the board have 2 sensor which is add and then returned
pycom.heartbeat(False) # Led orange pycom.rgbled(config.LED_COLOR_WARNING) log.info('Start InnovateNow Outdoor Tracker version {}', VERSION) log.debug('Memory allocated: ' + str(gc.mem_alloc()) + ' ,free: ' + str(gc.mem_free())) # Set watchdog 5min wdt = machine.WDT(timeout=300000) try: # Init pytrack board py = Pytrack() wdt.feed() # Feed # Start network start_network() wdt.feed() # Feed # Init gps gps = GPS(i2c=py.i2c) # Init environmental sensor environ = Environment(i2c=py.i2c) # Led off
#wlan = WLAN(mode=WLAN.STA) #wlan.scan() # scan for available networks #wlan.connect(ssid='Red', auth=(WLAN.WPA2, '12345678')) #while not wlan.isconnected(): # pass # print(wlan.ifconfig()) # setup rtc # rtc = machine.RTC() # rtc.ntp_sync("pool.ntp.org") # utime.sleep_ms(1000) # print('\nRTC Set from NTP to UTC:', rtc.now()) # utime.timezone(25200) # print('Adjusted from UTC to EST timezone', utime.localtime(), '\n') py = Pytrack() l76 = L76GNSS(py, timeout=30) accelerometer = LIS2HH12(py) # display the reset reason code and the sleep remaining in seconds # possible values of wakeup reason are: # WAKE_REASON_ACCELEROMETER = 1 # WAKE_REASON_PUSH_BUTTON = 2 # WAKE_REASON_TIMER = 4 # WAKE_REASON_INT_PIN = 8 print("Wakeup reason: " + str(py.get_wake_reason())) print("Approximate sleep remaining: " + str(py.get_sleep_remaining()) + " sec") time.sleep(5) # enable wakeup source from INT pin
import pycom import lteHelper import machine import pytrackHelper from pytrack import Pytrack from LIS2HH12 import LIS2HH12 import time import gc # *********************************************************** # Project used to test out LTE communication (LTE-M & NB-IOT) # *********************************************************** pycom.heartbeat(False) py = Pytrack() acc = LIS2HH12() print("") DEEP_SLEEP_SECONDS = 600 # Set deep sleep parameters py.setup_int_wake_up(True, False) # Turn off accelerometer acc.set_odr(0) # Get GPS data from pytrack board gc.collect() gps = pytrackHelper.getGPS(py, 300) if (gps[0] is not None and gps[1] is not None): # Create a list of key value pairs to be # sent by LTE to hologram dataList = []
from LIS2HH12 import LIS2HH12 from pytrack import Pytrack import pycom import socket import binascii import struct import pycom import network import cayenneLPP import time from deepsleep import DeepSleep import deepsleep ds = DeepSleep() gc.enable() py = Pytrack() l76 = L76GNSS() acc = LIS2HH12() l76 = L76GNSS(py, timeout=10) pycom.heartbeat(False) #lora_packet.decrypt(packet, AppSKey, NwkSKey).toString('hex') lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, adr=False, tx_retries=0, device_class=LoRa.CLASS_A) dev_addr = struct.unpack( ">l", binascii.unhexlify('ASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'))[0] nwk_swkey = binascii.unhexlify('ASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA') app_swkey = binascii.unhexlify('ASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
class PytrackSensor(AbstractSensor): """A Pytrack sensor component.""" def __init__(self): super().__init__() # The driver instance. self.readings = None self.bus = None self.sensor = None self.l76 = None self.lis2hh12 = None def start(self): """Getting the bus""" if self.bus is None: raise KeyError("I2C bus missing") # Initialize the hardware driver. try: from pytrack import Pytrack self.sensor = Pytrack(i2c=self.bus.adapter) except Exception as ex: log.exc(ex, 'Pytrack hardware driver failed') raise # Initialize the L76GNS sensor driver. try: from L76GNSV4 import L76GNSS self.l76 = L76GNSS(pytrack=self.sensor, timeout=5) except Exception as ex: log.exc(ex, 'Pytrack L76GNSS hardware driver failed') raise # Initialize the LIS2HH12 sensor driver. try: from LIS2HH12 import LIS2HH12 self.lis2hh12 = LIS2HH12(pysense=self.sensor) except Exception as ex: log.exc(ex, 'Pytrack LIS2HH12 hardware driver failed') raise def read(self): """ """ data = {} #log.info('Acquire reading from Pytrack') data['battery_voltage'] = float(self.sensor.read_battery_voltage()) # TODO: Add more data here. l76_data = self.read_l76gns() data.update(l76_data) lis2hh12_data = self.read_lis2hh12() data.update(lis2hh12_data) log.info("Pytrack data: {}".format(data)) return data def read_lis2hh12(self): """ """ data = {} try: data['roll'] = float(self.lis2hh12.roll()) data['pitch'] = float(self.lis2hh12.pitch()) except Exception as e: print('No Roll/Pitch Data:', e) return data def read_l76gns(self): """ """ data = {} # Call this to start the machinery and actually get a fix. try: self.l76.coordinates() except Exception as ex: log.exc(ex, "Could not read coordinates") raise # Only read values when having a fix. if not self.l76.fixed(): return data # Read speed and orientation. try: speed = self.l76.get_speed() data['speed'] = float(speed.get('speed')) data['cog'] = float(speed.get('COG')) except Exception as e: log.warning("Could not read Speed. Error:", e) # Read position. try: location = self.l76.get_location(MSL=True) except Exception as ex: log.exc(ex, "Could not read location from L76 GNSS") try: data['longitude'] = float(location.get('longitude')) data['latitude'] = float(location.get('latitude')) data['altitude'] = float(location.get('altitude')) except Exception as e: log.warning('No GPS Data') return data
from network import LoRa import struct import binascii import socket import time import uos import array import machine from pytrack import Pytrack py = Pytrack() def convert_latlon(latitude, longitude): # latitude = -37.8597 # longitude = 144.8126 lat = int((latitude + 90) * 10000) lon = int((longitude + 180) * 10000) coords = array.array('B', [0, 0, 0, 0, 0, 0]) coords[0] = lat coords[1] = (lat >> 8) coords[2] = (lat >> 16) coords[3] = lon coords[4] = (lon >> 8) coords[5] = (lon >> 16) return coords
from pytrack import Pytrack from LIS2HH12 import LIS2HH12 import time py = Pytrack() # display the reset reason code and the sleep remaining in seconds # possible values of wakeup reason are: # WAKE_REASON_ACCELEROMETER = 1 # WAKE_REASON_PUSH_BUTTON = 2 # WAKE_REASON_TIMER = 4 # WAKE_REASON_INT_PIN = 8 print("Wakeup reason: " + str(py.get_wake_reason())) print("Approximate sleep remaining: " + str(py.get_sleep_remaining()) + " sec") time.sleep(0.5) # enable wakeup source from INT pin py.setup_int_pin_wake_up(False) acc = LIS2HH12() # enable activity and also inactivity interrupts, using the default callback handler py.setup_int_wake_up(True, True) # set the acceleration threshold to 2000mG (2G) and the min duration to 200ms acc.enable_activity_interrupt(2000, 200) # go to sleep for 5 minutes maximum if no accelerometer interrupt happens py.setup_sleep(300) py.go_to_sleep()
def setup_array(): if (lib.get_number('cycle') != None): #Als de waarde in het geheugen bestaat, deze uitlezen. lijstBytes[11] = lib.get_number( 'cycle') #opvragen van de waarde in het geheugen. else: lijstBytes[11] = 0 return bytearray(lijstBytes) #array van bytes teruggeven. #heartbeat uitschakelen om de led aan te kunnen sturen. pycom.heartbeat(False) #instantie aanmaken van de pytrack (voor deepsleep) #instantie aanmaken van de accelerometer. py = Pytrack() acc = LIS2HH12() # display the reset reason code and the sleep remaining in seconds # possible values of wakeup reason are: WAKE_REASON_ACCELEROMETER = 1 WAKE_REASON_PUSH_BUTTON = 2 WAKE_REASON_TIMER = 4 WAKE_REASON_INT_PIN = 8 wakeReason = py.get_wake_reason() #reden van wakeup opvragen cycliInGeheugen = lib.get_number('cycle') print( " Cycle: " + '{}'.format(cycliInGeheugen) ) #uitprinten van het aantal cycli in het geheugen, voordat er een nieuwe waarde bijgeteld wordt.
import os import time import utime from pytrack import Pytrack from machine import RTC from machine import SD from machine import Timer import config # Set up garbage collection import gc gc.enable() # Find reason for boot py = Pytrack() if py.get_wake_reason() == 2: isInteractive = True else: isInteractive = False # Prepare for next deepsleep def sleep(): print('Setting up a sleeptime of', config.DStime, 'seconds.', flush=True) if not isInteractive: py.setup_sleep(config.DStime - (time.ticks_ms() / 1000)) else: py.setup_sleep(config.DStime) py.go_to_sleep()
import gc import sys # GPS l76 = 1 micropygps = 2 # https://github.com/inmcm/micropyGPS l762 = 3 # https://github.com/andrethemac/L76GLNSV4 active_gps = l762 # vars sent, searched = 0, 0 # number of time coords have been sent and searched (l76) max_search = 120 # max amount of gps lookup when coords not found (l76) or max amount of time gps lookup when coords not found (micropygps) sleep = 660 # seconds to sleep after successfull send (11 minutes) # pytrack py = Pytrack() # gps if active_gps == micropygps: i2c = machine.I2C(0, I2C.MASTER, pins=('P22', 'P21')) GPS_I2CADDR = const(0x10) # write to address of GPS (16) raw = bytearray(1) i2c.writeto(GPS_I2CADDR, raw) gps = MicropyGPS(0, location_formatting='dd') elif active_gps == l76: gps = L76GNSS(py, timeout=30) elif active_gps == l762: gps = L76GNSS(pytrack=py) gps.setAlwaysOn() # network
#py.setup_int_pin_wake_up(False) # enable activity and also inactivity interrupts, using the default callback handler py.setup_int_wake_up(True, True) # go to sleep for mins duration if no accelerometer interrupt happens py.setup_sleep(config["SLEEP_MIN"] * 60) py.go_to_sleep(gps=True) return pycom.heartbeat(False) pycom.rgbled(0x00FF00) time.sleep(2) pycom.rgbled(0x000000) gc.enable() py = Pytrack() l76 = L76GNSS(py, timeout=30) li = LIS2HH12(py) # display the reset reason code. Possible values of wakeup reason are: # WAKE_REASON_POWER_ON = 0 # WAKE_REASON_ACCELEROMETER = 1 # WAKE_REASON_PUSH_BUTTON = 2 # WAKE_REASON_TIMER = 4 # WAKE_REASON_INT_PIN = 8 wake = py.get_wake_reason() print("Wakeup reason: " + str(wake)) sd = machine.SD() try: os.mount(sd, "/sd")
OFF = const(0x000000) VIOLET = const(0x9400D3) INDIGO = const(0x4B0082) BLUE = const(0x0000FF) GREEN = const(0x00FF00) YELLOW = const(0xFFFF00) ORANGE = const(0xFF7F00) RED = const(0xFF0000) pycom.wifi_on_boot(False) pycom.wdt_on_boot(False) pycom.heartbeat(False) if DEBUG: pycom.rgbled(VIOLET) print("Collecting environment data") py = Pytrack() gps = MicropyGPS(location_formatting='dd') # Stop logging to local flash of GPS py.i2c.writeto(GPS_I2CADDR, "$PMTK185,1*23\r\n") py.i2c.writeto(GPS_I2CADDR, bytes([0])) # Use GPS, GONASS, GALILEO and GALILEO Full satellites, disable Beidou py.i2c.writeto(GPS_I2CADDR, "$PMTK353,1,1,1,1,0*2B\r\n") py.i2c.writeto(GPS_I2CADDR, bytes([0])) # Increase output rate to 5Hz (max with currently activated satellites) py.i2c.writeto(GPS_I2CADDR, "$PMTK220,200*2C\r\n") py.i2c.writeto(GPS_I2CADDR, bytes([0])) if DEBUG: pycom.rgbled(VIOLET) print("reading GPS data...")
import pycom import os import machine from L76GNSS import L76GNSS from pytrack import Pytrack from network import WLAN from machine import SD # Disable default LED heartbeat pycom.heartbeat(False) # Initialize GPS / GLONASS pytrk = Pytrack() t = 30 # maximum time (s) for GPS fix # wait for GPS uplink while True: pycom.rgbled(0xFF0000) # light LED red while waiting for GPS gps = L76GNSS(pytrk, timeout=t) if gps.coordinates()[0] is not None: pycom.rgbled(0x000000) # disable LED once we have GPS, break # Load WLAN module in station mode wlan = WLAN(mode=WLAN.STA) # Initialize RTC rtc = machine.RTC() # todo properly init RTC (GPS) - now only epoch start # rtc.ntp_sync('pool.ntp.org') # server to use for RTC synchronization # set variables for file management
from L76GNSS_fork import L76GNSS from pytrack import Pytrack from network import WLAN from network import LTE from LIS2HH12 import LIS2HH12 #from mqtt import MQTTClient from ubinascii import b2a_base64 from network import Server import string import config lte = None wlan = None server = None current_jwt = None py = Pytrack() l76 = L76GNSS(py, timeout=30) acc = LIS2HH12() sd = SD() os.mount(sd, '/sd') TOKEN_VALIDITY = 3600 MEASURE_INTERVAL = 60 def debugprint(string): now = machine.RTC().now() isodatetime = "{}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}+00:00 - ".format( now[0], now[1], now[2], now[3], now[4], now[5], now[6]) print(isodatetime + string) debuglog = open('/sd/debuglog.txt', 'a') debuglog.write(isodatetime + string + '\n')
import pycom import gc import struct from pytrack import Pytrack from network import LoRa from L76GNSS import L76GNSS import sys import os # Disable default blue LED blink pycom.heartbeat(False) # Pytrack GPS time.sleep(2) # enable garbage collector gc.enable() # Enable pytrack shield py = Pytrack() fw_version = py.read_fw_version() print("Pytrack firmware version: " + str(fw_version)) counter = 0 while(True): #print(input()) lora_data=input() if lora_data=="1": print('envoi 1') # make the socket blocking s.setblocking(True) # send some data s.send(bytes([1])) # make the socket non-blocking # (because if there's no data received it will block forever...) s.setblocking(False)
def __init__(self): self.pytrack = Pytrack() self.gps = GNSS(self.pytrack, timeout=1)
import machine # pour pouvoir géré des fichier import pycom # pour le gestion du module pycom (dans notre cas la led) import time # pour la gestion des temps d'attente from L76GNSS import L76GNSS # pour le module gps from pytrack import Pytrack # shield du modul gps import _thread py = Pytrack() # initialisation du shield l76 = L76GNSS(py, timeout=5) # initialisation GPS time.sleep(2) # pour pas brusquer coord = () def listenGPS(): while True: global coord coord = l76.coordinates( ) #récupération des coordoné GPS#random.randrange(1000)# _thread.start_new_thread(listenGPS, ())
import time import pycom import gc from pytrack import Pytrack from network import LoRa from L76GNSS import L76GNSS from LIS2HH12 import LIS2HH12 from CayenneLPP import CayenneLPP py = Pytrack() fw_version = py.read_fw_version() print("Pytrack firmware version: " + str(fw_version)) # Pytrack GPS time.sleep(2) # enable garbage collector gc.enable() coord = None dl_data = "" counter = 0 mvt = False # Init GPS gps = L76GNSS(py, timeout=10) coord = None lpp = CayenneLPP() acc = LIS2HH12() # enable the activity/inactivity interrupts
def setup_gps(): py = Pytrack() l76 = L76GNSS(py, timeout=30) return l76
from gps import GPS import time from pytrack import Pytrack from connection_otaa import Connection from LIS2HH12 import LIS2HH12 import pycom conn = Connection('70B3D57ED0015419', 'CA137963FA80E48A44B17973DED1977A') py = Pytrack() gps = GPS(py, 120) counter = 0 while counter < 20: if gps.hasGPS() == True: break else: time.sleep(2) gps.printGPS() counter += 1 gps.printGPS() print("Wakeup reason: " + str(py.get_wake_reason()) + "; Aproximate sleep remaining: " + str(py.get_sleep_remaining()) + " sec") time.sleep(0.5) # enable wakeup source from INT pin py.setup_int_pin_wake_up(False)
MAX_TIMEOUT = 20 # time in seconds to wait if nothing happens, then go to go to sleep TIME_TO_SLEEP = 60 # time to sleep in seconds, then wake up. print("Connecting to WiFi %s.."%SSID) wlan = WLAN(mode=WLAN.STA) wlan.antenna(WLAN.EXT_ANT) wlan.connect(SSID, auth=(WLAN.WPA2, PASS), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to Wifi %s"%SSID) queue = MessageBuffer(broker=BROKER, topic=TOPIC) py = Pytrack() # display the reset reason code and the sleep remaining in seconds # possible values of wakeup reason are: # WAKE_REASON_ACCELEROMETER = 1 # WAKE_REASON_PUSH_BUTTON = 2 # WAKE_REASON_TIMER = 4 # WAKE_REASON_INT_PIN = 8 message = "Wake up reason: " + str(py.get_wake_reason()) print(message) queue.push(message) print("Approximate sleep remaining: " + str(py.get_sleep_remaining()) + " sec") time.sleep(0.5) # enable wakeup source from INT pin py.setup_int_pin_wake_up(False)
import pycom import time import os import micropython import state import audiovisual from state import State from pytrack import Pytrack from LIS2HH12 import LIS2HH12 from audiovisual import AV # set aside mem for emergancy buffer #micropython.alloc_emergency_exception_buf(100) py = Pytrack() state = State() av = AV() def main(): # default sleep = 10 hours config = state.getState() if config['state'] >= 1: if config['state'] == 1: av.warning() state.trigger() else: if config['state'] == 2: state.notify() av.alarm() else:
# TTN join configuration parameters dev_addr = struct.unpack(">l", binascii.unhexlify('26011D16'))[0] nwk_swkey = binascii.unhexlify('65C01B23EEA4F2FC3423D6EC966718FC') app_swkey = binascii.unhexlify('9107395CE10B8D09185D6D3D33659F4D') # # delay in msec to repeat loop DelayLoopLogger = 20000 # wait 20sec for logger loop #---------------------------------------------- # START GPS LOGGER #---------------------------------------------- # gc.enable() # enable GC #---------------------------------------------- py = Pytrack() # Start GPS, you need this line # Start a microGPS object, you need this line my_gps = MicropyGPS(location_formatting='dd') # Start the L76micropyGPS object, you need this line L76micropyGPS = L76micropyGPS(my_gps, py) # Start the thread, you need this line gpsThread = L76micropyGPS.startGPSThread() print("startGPSThread thread id is: {}".format(gpsThread)) #start rtc rtc = machine.RTC()
def __init__(self, queue, period): self._gps = L76GNSS(Pytrack()) PeriodicSensor.__init__(self, queue, period) self.value = (None, None) # latitude, longitude
import time import gc from L76GNSS import L76GNSS from pytrack import Pytrack time.sleep(2) gc.enable() py = Pytrack() print(py.read_fw_version()) l76 = L76GNSS(py, timeout=30) while (True): coord = l76.coordinates() print("{} - {} - {}".format(coord, time.time(), gc.mem_free()))
# This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information # see the Pycom Licence v1.0 document supplied with this file, or # available at https://www.pycom.io/opensource/licensing # from pytrack import Pytrack from LIS2HH12 import LIS2HH12 from network import LoRa import machine import pycom import socket import time import ubinascii py = Pytrack() acc = LIS2HH12() # unique id (last 4 of mac) for message id = ubinascii.hexlify(machine.unique_id()).decode()[8:12] # type of sensor type = "accel" pycom.heartbeat(False) # checks to see if system woke up because of the Accelerometer if py.get_wake_reason() == 1: #test decode pycom.rgbled(0xffffff) time.sleep(1)
from pytrack import Pytrack #from pysense import Pysense from LIS2HH12 import LIS2HH12 import pycom import time pycom.heartbeat(False) py = Pytrack() # py = Pysense() # enable activity and also inactivity interrupts, using the default callback handler py.setup_int_wake_up(True, True) acc = LIS2HH12() # enable the activity/inactivity interrupts # set the accelereation threshold to 2000mG (2G) and the min duration to 200ms acc.enable_activity_interrupt(2000, 200) # check if we were awaken due to activity if acc.activity(): pycom.rgbled(0xFF0000) else: pycom.rgbled(0x00FF00) # timer wake-up time.sleep(0.1) # go to sleep for 5 minutes maximum if no accelerometer interrupt happens py.setup_sleep(300) py.go_to_sleep()
import gc import math #Enable garbage collection: gc.enable() gc.collect() #Close Unnecessary functions: ds = DeepSleep() ds.enable_auto_poweroff() #enable auto power off then li-po can't supply 3.3v bt = Bluetooth() bt.deinit() #close bluetooth wlan = network.WLAN() #close wlan wlan.deinit() py = Pytrack() acc = LIS2HH12() l76 = L76GNSS(py, timeout=10) pycom.heartbeat(False) ds.enable_auto_poweroff() #lora_packet.decrypt(packet, AppSKey, NwkSKey).toString('hex') #Lora settings: lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, adr=False, tx_retries=0, device_class=LoRa.CLASS_A) dev_addr = struct.unpack(">l", binascii.unhexlify('26011327'))[0] nwk_swkey = binascii.unhexlify('93896830809D21A62C175C8A772053C3')