Connect Your Plant to the Cloud
by steffenvandegaer in Circuits > Arduino
950 Views, 1 Favorites, 0 Comments
Connect Your Plant to the Cloud
In our office there is a cactus that wasn't getting the attention it deserved. Since I work at an IT company and wanted to experiment with LoRa, serverless solutions and AWS, I named our cactus Steeve and connected him to the cloud. You can now monitor Steeve from just about anywhere in the world using the webpage I made for him: Steeve's web interface.
Supplies
1 cactus / your favourite plant
1 Arduino MKR WAN 1300 (Arduino store)
1 868mHz/914mHz (depends on your location) antenna (Amazon)
1 LoRa Gateway when not in range of one (Amazon)
2 AA batteries
1 TMP102 sensor (Amazon)
1 soil moisture sensor (Amazon)
Conductive cables (Amazon)
soldering iron
Battery holder (Amazon)
case
optional: 3D printer (if you can use a 3d printer then you don't need a battery holder or a case)
Printing the Case (Optional)
Download this zip file, unzip it and print the files. The files are marked with the need amount of the item.
Feel free to add something to the lid like I did.
I printed these using a layer height of 0.2mm and 15% infill.
The boxhooks can be attached using m3 screws.
When the box is printed you can use some wire to make the needed connections on the battery holder. You can use the provided picture as reference.
Wiring
- Before powering on the arduino make sure the antenna is connected, powering up the arduino without the antenna may cause damage.
- Connect everything according to the provided wiring diagram.
- If you are soldering these wires, make sure you don't bridge any pins on the sensors or the arduino!
Create an App on the Things Network
- Go to https://www.thethingsnetwork.org/ and if you don't have an account yet, make one.
- Once you have an account and are logged in you can go to the console ( top right corner, click your username and then on console).
- Click on applications.
- Once the page loads you should be able to click on "add application".
- Fill in the form and choose the correct region at the bottom. Click on "add application".
- Congratulations, you have just created an application on the things network. =D
Connecting the Arduino to the Things Network
To program the arduino I advise you to use the online arduino ide, this makes loading in the needed library's very easy.
- Open your application on the things network.
- There should be a field titled devices, click on register device.
- you will see a field called Device Id. this is the name you want to give your sensor. There should be another one labeled Device EUI, this is the unique key your arduino uses to authenticate itself.
- To get this key we need to flash the arduino with a specific sketch. The sketch can be found overhere. This sketch should run and over the serial monitor is should send the eui. Copy the eui from the serial monitor to the Device EUI field on the things network.
- Click register.
- Now we have registered our arduino to the cloud. It is time to start sending messages.
- You should have been redirected to a page called device overview. Here you can see your device eui, app eui and app key.
- To continue we need to flash the final sketch to the arduino. The sketch can be found here.
- When you open this link you will see there are multiple tabs. Open the secrets tab. There are 2 keys you need to cope from the things network to the secrets file.
- Once these keys are filled in you can flash the arduino. It will start sending data to the things network once every hour.
- If everything went right you should be able to see messages comming in in the Data tab on the things network upon resetting the arduino (the only button on the board).
- If there is no data appearing overhere, this might mean you are not in range of a correct LoRa gateway. You can check a map with all the available gateways on https://thethingsnetwork.org. The single channel LoRa gateways will not work with the recommended arduino.
- If you are not in range of a gateway then you can couple your own gateway to the things network. These gateways usually have fairly good tutorials on how to connect them. Look in the supply list for the recommended gateway.
Interpreting the Data on the Things Network
- To get usable data from the messages on the things network we need to decode the bytestream.
- On the things network go to your application.
- There should be a tab labeled "Payload formats", click this tab.
- There are 4 buttons next to eachother: "decoder", "converter", "validator", "encoder".
- Click on decoder.
- Paste the following code there.
function Decoder(bytes, port) {<br> // Decode an uplink message from a buffer // (array) of bytes to an object of fields. var stringToDecode=bin2String(bytes); var res=stringToDecode.split(" "); var temp=res[1];<br> var moist= res[3];<br> var bat= res[5];<br> var decoded = {"temperature":temp, "moisture":moist, "battery":bat}; return decoded; <br>} function bin2String(array) {<br> var result = "";<br> for(var i = 0; i < array.length; ++i){ result+= (String.fromCharCode(array[i])); <br> }<br> return result;<br>}
- Click save.
- When you reset the arduino and view your data tab, you should see a nicely formatted json object you can easely read.
Connecting Your App to AWS
We are going to use AWS to store and use the data from the things network. All the resources we are going to use are covered under the free tier of AWS.
- Go to AWS https://aws.amazon.com/.
- Log in or create an account.
- To connect your application on the things network to AWS I recommend following this tutorial: https://www.thethingsnetwork.org/docs/applications/aws/quick-start.html
- Once you have completed this tutorial, navigate in the aws console to the IoT-Core segment.
- In the left menubar there is a label "Manage", click this.
- You should now see a card with the name of your sensor in it.
- Again in the left menubar click "Act"
- If there is a card labeled Store, you are good to go.
- If not, click on "Create".
- Fill in the name "Store".
- You can add a description if you want to.
- As a query statement fill in the following code:
SELECT dev_id, metadata.time, payload_fields.temperature, payload_fields.moisture, payload_fields.battery FROM 'cactus_network/devices/+/up'. - Under "Set one or more actions" click add action.
- Select "Split message into multiple columns of a DynamoDb table (DynamoDBv2)".
- Click configure action
- Click create new resource.
- Click create table an give your table a name.
- Under primary key fill in "dev_id".
- Click add sort key
- Fill in "time".
- Click create.
- If all went well, you should be be back on the configure action page.
- There is a slightly greyed out area under "Choose or create a role to grant AWS IoT access to perform this action."
- Click create Role and give this role a name.
- Click create role.
- Click add action.
- Click create rule.
- You should now have a rule that automatically stores all the incoming messages from the things network in DynamoDb.
- You can check if this is working by resetting the arduino and go look into the DynamoDb table you just created.
- There should be a record with the message.
Creating a Lambda
To read the data from DynamoDB we are going to write an AWS lambda.
- In the AWS management console under services there is a link labeled "Lambda", click this one.
- Click create function.
- Choose a name.
- Set runtime to python 3.7.
- Click create function.
- Paste this code in the integrated IDE.
import json import boto3 import time from datetime import datetime, timedelta from boto3.dynamodb.conditions import Key, Attr def lambda_handler(event, context): return retreive_data() def retreive_data(): # Get the service resource. dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('TABLE NAME HERE') now = datetime.now() yesterday = now - timedelta(hours=24) fe = Key('time').between(yesterday.isoformat(),now.isoformat()) fed =Key('time').lt(yesterday.isoformat()) response = table.scan(FilterExpression=fe) recordsToDelete=table.scan(FilterExpression=fed) for f in recordsToDelete['Items']: #print(f) table.delete_item( Key={'dev_id':f['dev_id'], 'time':f['time']} ) data = response['Items'] return data
- Change the table name to the one you choose.
- Scroll down to execution role.
- Click create a new role from aws policy templates.
- Choose a name.
- Under policy templates select "Test harness permissions" and "Simple microservice permissions".
- Click save.
- Click test.
- A popup might appear, just choose a name and save.
- Click test again.
- At the top there should be a green banner that says "Execution result: succeeded".
- When you click this banner you should see the output of this function, this should be a list af sensordata.
- Please be aware that this script deletes all the data that is older than 24 hours.
- In case your banner is not green but red, you have missed something and clicking this banner will give you the full errormessage. In this case google is your best friend.
Creating an API Endpoint
- In the AWS management console under services there is a link labeled "api-gateway", click this one.
- Click create API.
- Make sure "REST" and "New API" are both selected.
- Choose a name for your api.
- Click create API.
- There should be a button labeled actions on screen now, click it.
- Then click create Resource.
- As resource name you should tke something simple like "plant" or "plant-data".
- Click create Resource.
- On the left there should now be the name you just entered. click this name.
- Now click actions again and now click add method.
- Select GET.
- Click the check mark.
- There should be a textbox labeled Lambda Function.
- Enter the name you gave you lambda function here.
- Click save.
- There may be a popup that warns you that it is creating extra permissions.
- Accept this popup.
- Now under actions click enable cors.
- Click "enable CORS and replace existing CORS headers".
- Click "yes, ...".
- Click actions again and click Deploy API.
- Under deployment stage select [New Stage].
- Choose a name.
- Click deploy.
- You have now published your api online to the world.
- On the screen where you have arrived now click the "GET" ander the resource you just created.
- There should be a link on top labeled "invoke URL".
- Copy this link.
- Paste it in a browser and hit enter.
- You should see the data that is in the database.
Connect Your Plant to the Social Plant Network
- Go to http://bit.ly/social_plant_network.
- Click "Login".
- Click create account.
- Fill in the form to create your account.
- Please note that the user name also has to be your email.
- Click create account.
- You may have to verify your email before you can continue.
- Make sure you are logged in.
- Ga back to the home page (click the logo in the top left corner).
- Glick the settings button.
- Fill out the form, you should fill out every field.
- The link to the api is the link you saved after you created the API endpoint.
- When everything is filled in click the save plant button. the system will now verify the api link you entered and if this is correct it will save your plant in the network.
- Go back to the homepage.
- You can now click on all plants, you should be able to see all the registered plants. your plant should also be in there. click the card and you will be taken to an overview page of your plant, it will also display advice based on thevalues you set in settings.
Lean Back and Pat Yourself on the Back
You have just connected a plant to the internet. Pretty impressive, right?