From 6c60a184b811959eba8a467122d3a44d53c73368 Mon Sep 17 00:00:00 2001 From: Bram Barbieri Date: Thu, 14 Mar 2024 18:05:38 +0100 Subject: [PATCH] database websocket connection documentation. --- docs/rpi-documentation/Databaseconnection.md | 65 ++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 docs/rpi-documentation/Databaseconnection.md diff --git a/docs/rpi-documentation/Databaseconnection.md b/docs/rpi-documentation/Databaseconnection.md new file mode 100644 index 0000000..0372d01 --- /dev/null +++ b/docs/rpi-documentation/Databaseconnection.md @@ -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()) +``` \ No newline at end of file