---
# System prepended metadata

title: IoT Bike Lock
tags: [IoT, MQTT, FiPy, Pysense2, Node-Red]

---

IoT Bike Lock
===

###### tags: `IoT` `FiPy` `Pysense2` `Node-Red` `MQTT`
###### author: `Matas Pipiras` mp223gr@student.lnu.se

## Overview

- Bicycle lock witch gathers sensor data and triggers an alarm if disturbed
- If the device is disturbed \(motion detected\):
  - Alert is sent to a MQTT server 
  - The LED flashes
  - Sensor data is sent move frequently
  - GPS position is being tracked*
- Can be turned off remotely
- Project should take around 3 days


:books: Motivation
---
- Due to delays in hardware, options were limited
- I tried to use the hardware that I got to the best of its' potential, while setting up an environment for easy expansion
- Limited battery life was one of a constraints I was interested in
- This would give me insights about how to communicate between devices if one of them is actually off-line and saving battery power

:dart: Objective
---
- Create a descrete device that can be attached to a vehicle to prevent theft
- Easy to expand with additional sensors
- Store and present sensor data
- Long baterry life

:mag: Material
---


| Device                                                                                          | Cost | Description                                                                                |
| ----------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------------------------ |
| [FiPy](https://pycom.io/product/fipy/)                                                          | €65  | The main computer of the board, 5 different connectivity options, comes with 1NCE SIM card |
| [Pysense 2.0 X](https://pycom.io/product/pysense-2-0-x/)                                        | €30  | An expansion board for FiPy, 5 in-built sensors                                            |
| [Pytrack 2.0 X](https://pycom.io/product/pytrack-2-0-x/)                                        | €40  | An alternative to Pysense, allowing for GPS tracking                                  |
| [Battery holder]((https://www.electrokit.com/en/product/battery-holder-3xaa-wire-connection/) ) | €1   | Battery holder with a cable that can provide power to FiPy and Pysense                     |

![](https://i.imgur.com/Ni2EwKu.jpg)



:computer: Computer Setup
--
### List of Software
- Node.js
- Atom
- Pymakr package for Atom
- Pycom firmware updater
- Node-Red client
- PostgreSQL client
- Mosquitto client

### Steps
 - At first, we want to try to upload a simple program to our device to make sure everything works correctly 
     - Node.js is the first thing to be installed, since it's used in Atom to install plugins 
     - Atom comes next, it's the IDE i chose for the project. It's used to write and upload code to the device
     - Pymakr is a plugin for Atom which allows for compilation of code using micropython, which is used in IoT devices. It can be found in Atom under File > Settings > Install
     - Finally, Pycom firmware updater is required, to flash the device with firmware and is also useful if you want to factory reset the device
     - Once everything is installed, a simple application can be run. Create a new project and a file named main.py
     - Inside main.py paste the code bellow
     - Make sure to select the project and the connection, just above the console. Once you hit the upload button the device should be flashed with the code
     - ![](https://i.imgur.com/QhoqUOa.png)

```
import pycom 
import time

pycom.heartbeat(False)

 while True: 
 
    pycom.rgbled(0xFF0000)  # Red
    time.sleep(1) #sleep for 1 second
    
    pycom.rgbled(0xFF3300)  # Orange
    time.sleep_ms(1000) #sleep for 1000 ms
    
    pycom.rgbled(0x00FF00)  # Green
    time.sleep(1)
``` 
- After that is working it's time to install the rest of the things
    - Begin by installing Node-Red client. Once installed, typing node-red in cmd will start the node-red server. It can be accesssed in http://localhost:1880/
    - Afterwards install PostgreSQL client. This is database used to store data. Open the SQL Shell\(psql\), type in your password and you should be set here are some commands:
        - CREATE DATABASE measurements; - create a DB named measurements
        -  \l - list all available databases
        -  \c measurements - connect to database measurements
        -  CREATE TABLE temperature \( temp varchar(50)\); - Create a table named temperature with it's field(s) beeing temp
        -  \d - list the tables in the database
        -  SELECT * FROM temperature; - print the contents of the table temperature
    - Install a pallete \(ctrl+shift+P\) for Node-red named "node-red-contrib-re-postgres" This will allow functionality between Node-red and PostgreSQL
    - Finally install Mosquitto client. In CMD navigate to the installation folder and begin host a MQTT Broker by typing: mosquitto -v

## Putting everything together
- I have decided that for a project like this, a breadboard would be too clunky
- There are enough sensors on the Pysense 2.0 expansion board and without a breadboard they neatly tie together with eachother
- However, I still need to be aware of funtions provided by  pins of Pysense. They will be used to wake the device from accelerometer input.
- ![](https://i.imgur.com/Cyw7kYu.png)
- The diagram above displays the pinout of the Pysense 2.0
- We can notice that pin13 is the Accelerometer Interrupt. I use that in my code to wake the device up when it's disturbed

## Platform

- For my platform i chose Node-Red because it allows true flexibility with what you want to acomplish. It provides function nodes, networking options and has "pallets" which are basically plugins for extra functionality. It is also a really nice way to display the flow of the code and serves as a nice dashboard
- For MQTT connectivity i chose to host the Broker on my PC instead of using a cloud one. This takes a bit longer to set up, but in return gives me full control of the functionality, including a configuration file
- Both of these platforms well suited for scalability 

## The code

- The hardest part of writing the code was figuring out how to make the device sleep, trigger an alarm and turn off
- Once it estabilishes WiFi and MQTT boker connections, it subscribes to a topic named "connection"
```
# connect to MQTT broker
client = MQTTClient("FiPy", "xxx.xxx.xxx.xxx",user="admin", password="123", port=1883, keepalive=30)
client.set_callback(sub_cb)
client.connect()

client.subscribe(topic="connection")
```
- It then pusblishes a message according to its wakeup reason
```
(wake_reason, gpio_list) = machine.wake_reason()
if wake_reason == machine.PWRON_WAKE:
    client.publish(topic="hello", msg="Hello FiPy - reset")
elif wake_reason == machine.PIN_WAKE:
    client.publish(topic="hello", msg="Hello FiPy - alarm")
elif wake_reason == machine.RTC_WAKE:
    client.publish(topic="hello", msg="Hello FiPy - measure")
```
- Node-Red is subscribed to topic "hello" and therefore recieves the published message
![](https://i.imgur.com/plJAzVH.png)
![](https://i.imgur.com/ncqnuzK.png)
- Node-Red then publishes a message to topic "connection" with the status code, 0 being OFF, 1 being ON
![](https://i.imgur.com/DxtifDr.png)
- The Device status can be configured by a toggle switch in Node-Red:
![](https://i.imgur.com/mJGJ4Zl.png)
- If the returned status is 0, the device goes to permanent sleep
```
if message == "0":
    print("Code:0, shutting down")
    py.go_to_sleep(pycom_module_off=True, accelerometer_off=True, wake_interrupt=False)
    machine.deepsleep()
```
- If the status is 1, the device publishes the temperature sensor data, which is picked up in Node-Red, formatted to SQL code and inserted into a Database
![](https://i.imgur.com/21Ptcqa.png)
```
msg.payload = "INSERT INTO public.measurements " +
"(date, temp) " +
"VALUES("+current+")"
return msg;
```
- The device then enters a deepsleep for a selected period\(1 minute) and restarts
- If wakeup_reason comes from an accelerometer, it instead enters an endless loop where it sends its data every 5 seconds and never sleeps. It still is subscribed to connection so if it recieves a status = 0, it then shuts off

## Transmitting the data / connectivity

- The data is sent every 1 minute
- If an alarm is triggered, it is instead sent every 5 seconds
- Originally the plan was to use LTE for connectivity, but the provided SIM card was never activated, so I had to settle with WiFi, even though it does not really make sense for a device like this
- The selected transport protocol is MQTT as it allows for simple, lightweight communication, which is easy to scale for multiple devices

## Presenting the data

- The dashboard is supplied by Node-Red
![](https://i.imgur.com/0FlFLXd.png)
- The debug nodes can be activated to catch the traffic going through the system
![](https://i.imgur.com/Gm4ZRXw.png)
- The measurements are immediatelly stored in the database, which can be accessed via a Postgres client or an **SQL Shell**
![](https://i.imgur.com/YtT7P9j.png)

## Finalizing the design
- The results of the project are satisfactory
- I managed to host a Node-Red, MQTT and a Databse client on my PC
- If I were to do it again, I would instead get a Pytrack expansion board instead of Pysense, which would allow me to track the GPS coordinates of the device
- It's a shame that the SIM card was not activated, because for a project like this being able to connect anywhere is crucial. WiFi is probably one of the worst options when it comes to real world scenarios
![](https://i.imgur.com/xs7ENOj.jpg)





