Files
J1B3-Sensor-boxes/server/web-data-connection/sensorNodeClassFile.md
2024-04-02 21:13:27 +02:00

56 lines
2.2 KiB
Markdown

## Sensor Node class
This class is made to get the info of the sensor-nodes and send this to the database.
This is done this way to make the code more clear and readable.
```py
#Import library's
import mysql.connector
import json
#Import classes and functions from different files.
from classes_data import Node
from classes_data import dbLogin
```
After this the "__init__"function is called.
(In javascript this is known as the "constructor".
For further information visit https://www.w3schools.com/python/gloss_python_class_init.asp)
```py
#A class to send data to the database. child class of "Node"
class SensorNode(Node):
#A private query only to be used in this class.
__query = "INSERT INTO `Measurement` (NodeID, Type, Value) VALUES (%s, %s, %s)"
#All variables to be used.
def __init__(self, macAdress, temp, humi, eCO2, TVOC):
super().__init__(macAdress)
self.temperature = temp
self.humidity = humi
self.eCO2 = eCO2
self.TVOC = TVOC
#A function to connect to the database, grab the info which is given, and push this to the database.
async def processSensorNodeData(data, nodeID):
try:
mydb = dbLogin()
cursor = mydb.cursor()
processedData = json.loads(data)
#The variables to give to the database.
SensorNode.temperature = (processedData['Temp'])
SensorNode.humidity = (processedData['Humi'])
SensorNode.eCO2 = (processedData['eCO2'])
SensorNode.TVOC = (processedData['TVOC'])
#A array of the info to be given to the database in the correct format.
pushingDataArray = [(nodeID, "Temp", SensorNode.temperature), (nodeID, "Humi", SensorNode.humidity), (nodeID, "eCO2", SensorNode.eCO2), (nodeID, "TVOC", SensorNode.TVOC)]
#Go along all files of the array, and push it out to the database following the query.
for i in pushingDataArray:
cursor.execute(SensorNode.__query, i)
mydb.commit()
except mysql.connector.Error as err:
print("MySQL Error:", err)
finally:
cursor.close()
mydb.close()
```