Files
J1B3-Sensor-boxes/docs/rpi-documentation/Databaseconnection.md
2024-03-15 12:13:51 +01:00

81 lines
3.3 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
cursor = mydb.cursor()
// the segments in wich the infromation will be sent.
query = "INSERT INTO `Measurement` (NodeID, Type, Value) VALUES (%s, %s, %s)"
// the json data collected from the websocket gets collected and transformed into data usable by python.
mrdata = json.loads(data)
//variables get the different types of data.
mrtemp = (mrdata['Temp'])
mrhumi = (mrdata['Humi'])
mrco = (mrdata['eCO2'])
mrtvoc = (mrdata['TVOC'])
mrnode = (mrdata['node'])
//an array is made to holster the different information clusters, for the time being it holds the infromation of one node.
mrarray = [(1, "Temp", mrtemp), (1, "Humi", mrhumi), (1, "eCO2", mrco), (1, "TVOC", mrtvoc)]
// a for statement to go trough the array.
for i in mrarray:
print(query ,i)
cursor.execute(query, i)
//commit the information to the database.
mydb.commit()
// if the connection to the database can't be made this error wil show with further information.
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())
```