97 lines
3.9 KiB
Markdown
97 lines
3.9 KiB
Markdown
## Python code + explaination
|
|
We wanted to make a working connection between our websocket wich runs all the data gatherd by our nodes and a live feed to our database.
|
|
So we set out to make this connection using python.
|
|
|
|
At first we needed to import the folowing librarys:
|
|
```js
|
|
// everything is running async so the code can run together and not interfere with eachother.
|
|
import asyncio
|
|
import websockets
|
|
// a library to connect to the database.
|
|
import mysql.connector
|
|
import json
|
|
```
|
|
Then we began the process of connecting with both the websocket and the database.
|
|
|
|
First-off, we began making a connection to the database by using a mysql library in wich we gave the log in in order to connect to our ow database.
|
|
```js
|
|
//the data that has to be pushed needs to be
|
|
async def process_data(data):
|
|
try:
|
|
mydb = mysql.connector.connect(
|
|
host="localhost",
|
|
user="*****",
|
|
password="*********",
|
|
database="*******"
|
|
)
|
|
```
|
|
Then after this we code in the infromation we want to put inside of the database.
|
|
The data collected from the websocket is json data, so this has to be changed.
|
|
```js
|
|
//Making a variable for the database connection
|
|
cursor = mydb.cursor()
|
|
//Making a variable for the database connection
|
|
MACDataReading = mydb.cursor()
|
|
//find the correct section and interact with it.
|
|
MACDataReading.execute("SELECT MAC FROM Node")
|
|
//the query for what needs to be inserted into the database ( atleast where it has to go).
|
|
query = "INSERT INTO `Measurement` (NodeID, Type, Value) VALUES (%s, %s, %s)"
|
|
//the recieved data from the websocket is json data so needs to be changed.
|
|
processedData = json.loads(data)
|
|
//variables about the recieved data points.
|
|
processedTemp = (processedData['Temp'])
|
|
processedHumi = (processedData['Humi'])
|
|
processedECo = (processedData['eCO2'])
|
|
processedTvoc = (processedData['TVOC'])
|
|
processedMAC = (processedData['node'])
|
|
//change the recieved macadress to a tuple.
|
|
MACTuple = (processedMAC,)
|
|
//fetch the data from the database an[d put it in an array.
|
|
MACDataFetching = MACDataReading.fetchall()
|
|
MACArray = list(MACDataFetching)
|
|
|
|
//see if the fetched data is not in the gotten array.
|
|
//otehrwise insert it into the database directly.
|
|
if MACTuple not in MACArray:
|
|
addingNode = "INSERT INTO `Node` (MAC) VALUES (%s)"
|
|
cursor.execute(addingNode, MACTuple)
|
|
mydb.commit()
|
|
//the websocket data that needs to be sent to the database.
|
|
pushingDataArray = [(1, "Temp", processedTemp), (1, "Humi", processedHumi), (1, "eCO2", processedECo), (1, "TVOC", processedTvoc)]
|
|
// forloop, go allong the array.
|
|
for i in pushingDataArray:
|
|
print(query ,i)
|
|
cursor.execute(query, i)
|
|
mydb.commit()
|
|
// show me the error it there is one.
|
|
except mysql.connector.Error as err:
|
|
print("MySQL Error:", err)
|
|
finally:
|
|
cursor.close()
|
|
mydb.close()
|
|
```
|
|
After fully connecting t othe database, making statements of what to put there and telling the code what to do, we ofcourse need to write the code to connect to the weebsocket.
|
|
We begin by telling our websocket id and what type of port we are using.
|
|
Then we will collect live data from the conected websocket, store it in a variable, and then in the previous code
|
|
```js
|
|
//here the connection to the websocked is made
|
|
async def receive_data():
|
|
uri = "****************"
|
|
|
|
try:
|
|
async with websockets.connect(uri) as websocket:
|
|
while True:
|
|
// the data collected from the websocket is.
|
|
data = await websocket.recv()
|
|
// data recieved: conformation.
|
|
print(f"Received data: {data}")
|
|
await process_data(data)
|
|
// error sowing.
|
|
except websockets.ConnectionClosedError as e:
|
|
print("WebSocket connection closed:", e)
|
|
|
|
async def main():
|
|
await receive_data()
|
|
|
|
asyncio.run(main())
|
|
``` |