Build an End-to-End Sigfox GPS Tracker Using Wia and Pycom
Tags: iot, sigfox, gps, pycom
Published: 2018-05-24 13:11:31

---
title: Build an End-to-End Sigfox GPS Tracker Using Wia and Pycom
published: true
description: Learn how to create a Sigfox GPS tracker using Wia and the Pycom SiPy.
tags: #Iot #sigfox #gps #pycom
---

![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-05-14/1526299660-249518-pycom-smartphone-illustration.png)

Hi folks,

Today I’m going to show you how to create a Sigfox GPS tracker using Wia and the Pycom SiPy.

This tutorial assumes that you have already connected Sigfox to Wia if you haven’t, please click [here](https://developers.wia.io/v1.0/docs/pycom-sipy) to find a tutorial for initial Sigfox setup and publishing data to Wia.


###**Components**
* [Pycom SiPy](https://pycom.io/hardware/sipy-specs/)
* [Pytrack Expansion Board](https://pycom.io/product/expansion-board-3-0/)
* Sigfox compatible antenna
* Mobile device (iOS or Android)

###**Setup your board**
If you haven’t already, you’ll need to upgrade the firmware on your Pytrack Expansion Board.

You can follow the instructions [here].(https://docs.pycom.io/chapter/pytrackpysense/installation/firmware.html)

* Connect the SiPy to the Pytrack board. (The RGB LED on the SiPy should be on the side of the usb port on the Pytrack board)
* Connect the Sigfox antenna to the SiPy. (The connection is just left of RGB LED)


###**Setup Your Project**
* Create a new folder for your project. I'm going to call mine pycom-pytrack
* In [Atom](https://atom.io/), go to `File > New Window` to open a new window
* Add your newly created folder by clicking `File > Add Project Folder` and navigating to it
* If the [Pymakr](https://atom.io/packages/pymakr) plugin is not open at the bottom of your Atom window, click on the arrow on the right hand side to open it
* Select `Settings > Project Settings`. In the address field replace the value with the device name from the step above e.g. `/dev/tty.usbmodemPy343431` (Mac OS X), `COM3` (Windows), `/dev/ttyACM0` (Linux) then save the file


###**Add required libraries**
* Right click on the folder name in Atom and click `Add Folder`. Enter lib as the folder name
* Right click on the lib folder and click New File. Enter urequests.py as the file name
* Click on the file then copy and paste the code from [here](https://raw.githubusercontent.com/wiaio/wia-board-examples/master/Pycom/LoPy/PublishEventWifi/lib/urequests.py) into that file then save it.
* For Pytrack, additional libraries must also be added to the lib folder, these can be found [here](https://github.com/pycom/pycom-libraries/tree/master/pytrack/lib)


###**Publish A Location Event**
* We'll need two files for our application:
  * `boot.py` which is run when the device is powered up
  * `main.py` which is where our main code is
* In Atom, right click on your project and click `New File`. Enter `boot.py` as the filename
* Copy and paste the code below into the file
```
from machine import UART
from network import Sigfox
import binascii
import machine
import os

# initalise Sigfox for RCZ1 (Europe) (You may need a different RCZ Region)
sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1)

# print Sigfox Device ID
print("ID: ", binascii.hexlify(sigfox.id()))

# print Sigfox PAC number
print("PAC: ", binascii.hexlify(sigfox.pac()))

uart = UART(0, baudrate=115200)
os.dupterm(uart)

machine.main('main.py')

```
* Right click on your project and click New File. Enter `main.py` as the filename
* Copy and paste the code below into the file

```
from network import Sigfox
from pytrack import Pytrack
import urequests as requests
from L76GNSS import L76GNSS
import socket
import time
import pycom
import struct

py = Pytrack()
gps = L76GNSS(py, timeout=60)

init_timer = time.time()

print("connecting to Sigfox")
# init Sigfox for RCZ1 (Europe)
sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1)

# create a Sigfox socket
s = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW)
# make the socket blocking
s.setblocking(True)

s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)

# Post an location to the Wia cloud via Sigfox backend
def post_location(latitude, longitude):
    try:
        print(str(latitude), ":", str(longitude))
        s.send(struct.pack('f',float(latitude)) + struct.pack('f',float(longitude)))
    except:
        pass

# main loop
while True:
    final_timer = time.time()
    diff = final_timer - init_timer
    # Get coordinates from pytrack
    coord = gps.coordinates()

    # If the GPS has coordinates and 15 minites has past. Post the location data
    if not coord == (None, None) and diff < 900:
        lat, lng = coord
        post_location(lat, lng))
        init_timer = time.time()
```

Your folder structure should now look like this:

`lib`
  * `urequests.py`
  * `L76GNSS.py`
  * `LIS2HH12.py`
  * `pytrack.py`
* `boot.py`
* `main.py`

Click `Upload` in the Pymakr plugin at the bottom of your window in Atom and send the code to your Pycom board. Now go to the Wia dashboard and you should see data appearing in the debugger section of your dashboard.

Note: It may take a few minutes before the Pytrack finds a GPS signal, also the Pytrack isn't suitable for indoor use.


###**Parsing the Data**
Now for the next step, we must parse the data we received from Sigfox and do something useful with it. For this we need to build a Flow.

Head over to your Wia dashboard and in the Space where your Sigfox device is held. From there click on the Flow icon in the left hand menu to go your Flows.

![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-05-14/1526284386-778692-flow.png)


Now to create your Flow, you can name it whatever you like. Once you have created a Flow, you should be taken to the Flow studio.

In the Flow studio:

* Drag the `trigger event node` from the left hand side onto the canvas

* Click on the node and enter `sigfoxDataUplink` as the event name

* Enable your Sigfox Device as the event source

* Now add a function node from the logic section (We’ll parse the data here)

* Add a location node from the `output` section

Click on the function node and add the following code:

```
if (input.body) {
  let latLong = parseSigfoxLocation(input.body.data.sigfoxData);
  output.body.latitude = latLong.latitude;
  output.body.longitude = latLong.longitude;
}

function parseSigfoxLocation(sigfoxData) {
  let latHex = sigfoxData.slice(0, 8);
  let longHex = sigfoxData.slice(8);
  let result = {
    latitude: Buffer(latHex, 'hex').readFloatLE(0).toFixed(6),
    longitude: Buffer(longHex, 'hex').readFloatLE(0).toFixed(6)
  };

  return result;
}
```
This code parses the Sigfox data from hexadecimal format to latitude and longitude in floating point.

* The Sigfox data comes in a 12 byte hexadecimal string
* Each of GPS coordinates is 32 bits or 4 bytes of data
* They are 2 characters that can fit into 1 byte of data, hence why we split our hexadecimal string by 8

###**Send a Push Notification**
Currently the Flow takes in the data from Sigfox, parses it and outputs a location. Now we are going to go one step further and get a notification of the newly created location so we can view it on a map on our phones. To do this, you will require the Wia mobile app. You can download it for iOS [here](https://itunes.apple.com/us/app/wia-talk-to-your-things/id1320616870?ls=1&mt=8) and Android [here](https://play.google.com/store/apps/details?id=io.wia.wia).

![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-05-14/1526284470-725433-flow-left.png)

In the Flow Studio editor:

* Drag over a location node from the trigger section now. With this we can capture the node created from the previous Flow chain
* Add the same Device as earlier to the location trigger node
* Drag over a notification node and enter the following text

 `GPS Coordinates: ${input.body.latitude}, ${input.body.longitude}`

![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-05-14/1526299594-582357-selection-112.png)

Now you should receive Sigfox data to your mobile device.

![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-05-14/1526303292-200022-track-push.jpeg)