コード例 #1
0
def test():
    s = setup_node()
    py = Pytrack()
    acc = LIS2HH12()

    for i in range(200):
        pitch = acc.pitch()
        roll = acc.roll()
        pitch_data = struct.pack('>f', pitch)
        roll_data = struct.pack('>f', roll)
        print("Pitch data: ", pitch_data)
        print("Roll data: ", roll_data)
        pkt = pitch_data + roll_data
        # pkt = b'PKT #' + bytes([i])
        print('Sending:', pkt)
        s.send(pkt)
        time.sleep(4)
        # rx, port = s.recvfrom(256)
        rx = s.recv(256)
        print(rx)
        if rx:
            # print('Received: {}, on port: {}'.format(rx, port))
            print('Received: {}, on port:'.format(rx))
        time.sleep(6)


# while True:
#     #s.send(b'Hola LORAWAN')
#     s.send(bytes([0xFF,0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]))#Send some sample Bytes
#     print("packet send")
#     time.sleep(4)
#     time.sleep(4)
#     time.sleep(4)
#     time.sleep(4)
コード例 #2
0
ファイル: gps_setup.py プロジェクト: Kbman99/Lopy-Quickstart
def setup_gps():
    time.sleep(2)
    gc.enable()

    rtc = RTC()
    rtc.ntp_sync("pool.ntp.org")
    utime.sleep_ms(750)
    print('\nRTC Set from NTP to UTC:', rtc.now())
    utime.timezone(7200)
    print('Adjusted from UTC to EST timezone', utime.localtime(), '\n')
    if rtc.now()[0] == 1970:
        print("Datetime could not be automatically set")
        date_str = (input(
            'Enter datetime as list separated by commas (y, m, d, h, min, s): '
        )).split(',')
        date_str = tuple([int(item) for item in date_str])
        try:
            rtc.init(date_str)
            print('Time successfully set to ', rtc.now(), '\n')
        except Exception:
            print("Failed to set time...")
    py = Pytrack()
    l76 = L76GNSS(py, timeout=30)
    print("GPS Timeout is {} seconds".format(30))
    chrono = Timer.Chrono()
    chrono.start()

    # while (True):
    #     coord = l76.coordinates(debug=True)
    #     print("{} - {} - {}".format(coord, rtc.now(), gc.mem_free()))
    return l76
コード例 #3
0
 def __init__(self):
     self.gps = L76GNSS.L76GNSS(pytrack=Pytrack(),
                                sda='P22',
                                scl='P21',
                                timeout=5)
     self.lon = -1
     self.lat = -1
コード例 #4
0
    def __init__(self,
                 queue,
                 period,
                 wait_before_sleep=WAIT_BEFORE_SLEEP,
                 time_to_sleep=TIME_TO_SLEEP):

        self._wait_before_sleep = wait_before_sleep
        self._time_to_sleep = time_to_sleep
        self._queue = queue
        self._py = Pytrack()
        message = "Wake up reason: " + str(self._py.get_wake_reason())
        # 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
        self.printout(message)
        time.sleep(0.5)
        # enable wakeup source from INT pin
        self._py.setup_int_pin_wake_up(False)
        self.value = 0
        # enable activity and also inactivity interrupts, using the default callback handler
        self._py.setup_int_wake_up(True, True)
        PeriodicSensor.__init__(self, queue, period)
コード例 #5
0
    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
コード例 #6
0
def getGPS():
    py = Pytrack()
    l76 = L76GNSS(py, timeout=30)
    global coord
    coord = l76.coordinates()

    global latitude
    global longitude

    try:
        print(coord)

        if type(coord[1]) == "NoneType":
            pycom.rgbled(0xFF0000)
            latitude = round(0, 5)
        else:
            latitude = round(coord[1], 5)

        if type(coord[0]) == "NoneType":
            pycom.rgbled(0xFF0000)
            longitude = round(0, 5)
        else:
            longitude = round(coord[0], 5)
    except:
        pass
        print("can't get signal")
        longitude = 999
        latitude = 999

    global remote_address
    remote_address = remote_address_base
    remote_address += "?lat="
    remote_address += str(latitude)
    remote_address += "&lon="
    remote_address += str(longitude)
コード例 #7
0
def sync_time_from_GPS(verbose=False):
    #Start GPS
    py = Pytrack()
    l76 = L76GNSS(py, timeout=600)
    #start rtc
    rtc = machine.RTC()
    if verbose:
        print('Aquiring GPS signal....')
    set_LED_red()
    while (True):
       gps_datetime = l76.get_datetime()
       #case valid readings
       if gps_datetime[3]:
           day = int(gps_datetime[4][0] + gps_datetime[4][1] )
           month = int(gps_datetime[4][2] + gps_datetime[4][3] )
           year = int('20' + gps_datetime[4][4] + gps_datetime[4][5] )
           hour = int(gps_datetime[2][0] + gps_datetime[2][1] )
           minute = int(gps_datetime[2][2] + gps_datetime[2][3] )
           second = int(gps_datetime[2][4] + gps_datetime[2][5] )
           print("Current location: {}  {} ; Date: {}/{}/{} ; Time: {}:{}:{}".format(gps_datetime[0],gps_datetime[1], day, month, year, hour, minute, second))
           rtc.init( (year, month, day, hour, minute, second, 0, 0))
           break
    #Stop GPS
    set_LED_green()
    l76.stop(py)
    if verbose:
        print('RTC Set from GPS to UTC:', rtc.now())
    time.sleep(2)
    set_LED_off()
コード例 #8
0
def setup():
    global l76, lora
    if pycom.wifi_on_boot():  ## attempt to save battery
        pycom.wifi_on_boot(False)
    pycom.heartbeat(False)
    py = Pytrack()
    l76 = L76GNSS(py, timeout=30)
    lora = LoRa(mode=LoRa.LORAWAN)
コード例 #9
0
def getGPSCoord():
    py = Pytrack()
    l76 = L76GNSS(py, timeout=30)
    coord = l76.coordinates(debug=True)
    while coord == (None, None):
        coord = l76.coordinates(debug=True)
        print(coord)
    return coord
コード例 #10
0
 def __init__(self, logger):
     gc.enable()
     self.acc = LIS2HH12(pysense = None, sda = "P22", scl = "P21")
     py = Pytrack()
     self.gps = L76GNSS(py, timeout=30)
     self.py = Pycoproc()
     self.batteryTrack = 0
     self.Logger = logger
コード例 #11
0
def gnss_position2():
    #Obtain current GNSS position.
    #If a position has been obtained, returns an instance of NmeaParser
    #containing the data. Otherwise, returns None.

    py = Pytrack()
    l76 = L76GNSS(py, timeout=30)

    return l76.coordinates()
コード例 #12
0
 def init_static():
     is_pytrack = True
     try:
         py = Pytrack()
         Gps.l76 = L76GNSS(py, timeout=30)
         #l76.coordinates()
         Gps._timer = Timer.Alarm(Gps.gps_periodic, 30, periodic=True)
         print("Pytrack detected")
     except:
         is_pytrack = False
         print("Pytrack NOT detected")
     #TODO: how to check if GPS is conencted
     return is_pytrack
コード例 #13
0
def deep_sleep(time_to_deep_sleep):
    """
    Function to set Pytrack in ultra low power (deep sleep) during x time.

    Returns
    -------
        time_to_deep_sleep: int
            seconds to stay in deep sleep
    """
    i2c = machine.I2C(0, mode=I2C.MASTER, pins=('P22', 'P21'))
    py = Pytrack(i2c=i2c)
    py.setup_sleep(time_to_deep_sleep)
    py.go_to_sleep(gps=True)
    i2c.deinit()
コード例 #14
0
def get_battery_status():
    """
    Function to get the battery voltage

    Returns
    -------
        volt: int
            voltage from battery
    """
    i2c = machine.I2C(0, mode=I2C.MASTER, pins=('P22', 'P21'))
    py = Pytrack(i2c=i2c)
    volt = py.read_battery_voltage()
    i2c.deinit()

    return volt
コード例 #15
0
    def setup(self):
        time.sleep(2)
        gc.enable()

        # setup rtc
        rtc = machine.RTC()
        rtc.ntp_sync("pool.ntp.org")
        utime.sleep_ms(750)
        utime.timezone(7200)

        py = Pytrack()
        self.gnss = L76GNSS(py, timeout=30)

        print("Waiting for GNSS connection...")
        # Unfortunately, the tuple comparison method - cmp() - is not available in MicroPython
        while(self.gnss.coordinates()[0] == None and self.gnss.coordinates()[1] == None):
            pass

        print("GNSS connection acquired")
コード例 #16
0
ファイル: ServiceLib.py プロジェクト: robfloyd74/Laterlite-Sw
def GPSInit(max_time_wait=20):
    py = Pytrack()
    l76 = L76GNSS(py, timeout=5)
    ciclo1 = 0
    getsat = True

    while getsat and (ciclo1 < max_time_wait):
        ciclo1 = ciclo1 + 1
        print(ciclo1)
        print('TASK 1: Looking for GPS SAT')
        coord = l76.coordinates()
        data = l76.getUTCDateTimeTuple()
        print(data)
        time.sleep(1)
        if data == None:
            time.sleep_ms(50)
        else:
            getsat = False
    if (getsat == False):
        print('TASK 1: got GPS SAT', coord, data)
        return coord, data, True
    else:
        print('TASK 1: not got GPS SAT', coord, data)
        return coord, data, False
コード例 #17
0
def get_time():
    try:
        py = Pytrack()
        l76 = L76GNSS(py, timeout=120)
        timeout = time() + 30 #timeout in 30 seconds from now


        while timeout  > time(): # try until timeout
            date_time=l76.getUTCDateTime()  # get time from L76

            # 2080 is default year returned by L76 when no GPS signal detected
            if date_time[:4] != '2080': # prevents default value from L76 for date_time
                break
            sleep(2)  # wait before checking L76 time again
        else:
            date_time = '2000-01-01T00:00:00+00:00' # set to a vale if timeout occurs
            print('GPS time not found.  Setting clock to 01/01/2000')
        print(date_time)
        rtc = RTC()  # create real time clock
        #  init RTC with GPS UTC date & time
        rtc.init((int(date_time[0:4]),int(date_time[5:7]),int(date_time[8:10]),int(date_time[11:13]),int(date_time[14:16])))

    except:
        print('Unable to set time.')
コード例 #18
0
 def __init__(self):
     self.gps = gps = L76GNSS.L76GNSS(pytrack=Pytrack(),
                                      sda='P22',
                                      scl='P21')
コード例 #19
0
import machine  # pour pouvoir géré des fichier
import pycom  # pour le gestion du module pycom (dans notre cas la led)
import socket  # pour lire les message recus
import time  # pour la gestion des temps d'attente
from network import LoRa  #pour etre en mode LoRa
from L76GNSS import L76GNSS  # pour le module gps
from pytrack import Pytrack  # shield du modul gps

lora = LoRa(mode=LoRa.LORA,
            region=LoRa.EU868,
            bandwidth=LoRa.BW_250KHZ,
            preamble=20,
            sf=12)  #configuration initiale
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
py = Pytrack()  # initialisation du shield
l76 = L76GNSS(py, timeout=10)  # initialisation GPS

pycom.heartbeat(
    False)  # on stop les pulsations indiquant que le module est allumé
pycom.rgbled(0x7f0000)  # on initialise la led en rouge

with open(
        'data.txt', 'a'
) as datafile:  #création de du fichier data.txt sur le module si il n'est pas present, ou sinon on l'ouvre en mode ajout de data.
    datafile.write(
        "\n\n\n")  # 3 saut à la ligne pour diferentier les data precedentes
datafile.close()  # on referme le fichier

while (True):
    s.setblocking(False)  # module en position d'écoute
    data = s.recv(64)  # data avec un buffer de 64
コード例 #20
0
ファイル: main.py プロジェクト: fossabot/LoRaTracker
time_since_fix = 0
crc = 0
altitude = 0
speed = 0
course = 0
vBatt = 0
current_rate = norm_rate
last_batt_check = 0
last_send_time = 0
last_LED_check = 0
LED_count = 0

# instantiate libraries
try:
    # Initialize PyTrack
    pytrack = Pytrack()
except Exception as e:
    print("Pytrack initialisation: ERROR")
    time.sleep(0.5)
    machine.reset()
l76 = L76GNSS(pytrack)
acc = LIS2HH12()
gps = MicropyGPS(location_formatting='dd')  # return decimal degrees from GPS
wdt = WDT(timeout=WDtimeout)  # enable a Watchdog timer with a specified timeou
rtc = machine.RTC()
led = RGBLED(10)


def update_LED():
    # continuously update the status of the unit via the onboard LED
    global gps
コード例 #21
0
 def __init__(self, queue, period):
     self._gps = L76GNSS(Pytrack())
     PeriodicSensor.__init__(self, queue, period)
     self.value = (None, None)  # latitude, longitude
コード例 #22
0
ファイル: main.py プロジェクト: palladionIT/warpy
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
コード例 #23
0
def setup_gps():
    py = Pytrack()
    l76 = L76GNSS(py, timeout=30)

    return l76
コード例 #24
0
# 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()
コード例 #25
0
ファイル: main.py プロジェクト: vladirares/beialand
import time
#import gc
import ubinascii
#from deepsleep import DeepSleep
import deepsleep
from LIS2HH12 import LIS2HH12
from pytrack import Pytrack

ds = DeepSleep()

# Wireless network
WIFI_SSID = "LANCOMBEIA"
WIFI_PASS = "******"

#  Use on-board accelerometer
py = Pytrack()
acc = LIS2HH12()

# MQTT configuration
AIO_SERVER = "mqtt.beia-telemetrie.ro"
AIO_PORT = 1883
AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id())  # Can be anything

wlan = WLAN(mode=WLAN.STA)
wlan.connect(WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS), timeout=5000)

while not wlan.isconnected():
    machine.idle()

print("Connected to Wifi\n")
client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT)
コード例 #26
0
ファイル: GPSFIX.py プロジェクト: ASYNOU/BasicPython
 def __init__(self):
     self.pytrack = Pytrack()
     self.gps = GNSS(self.pytrack, timeout=1)