Files
J1B3-Sensor-boxes/docs/rpi-documentation/Databaseconnection.md
Bram Barbieri a2ff97d7fb database websocket
documentation
2024-03-14 18:46:46 +01:00

2.6 KiB

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:

// 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.

//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())