database websocket connection documentation.

This commit is contained in:
Bram Barbieri
2024-03-14 18:05:38 +01:00
parent 28ff778ce8
commit 6c60a184b8

View File

@@ -0,0 +1,65 @@
## Python code + explaination
```js
// Here different librarys are imported to
// 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
//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="*******"
)
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()
//here the connection to the websocked is made
async def receive_data():
uri = "ws://145.92.8.114/ws"
try:
async with websockets.connect(uri) as websocket:
while True:
// the data collected from the websocket is.
data = await websocket.recv()
// dara 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())
```