156 lines
5.9 KiB
Markdown
156 lines
5.9 KiB
Markdown
## The websocket -> database connection classes.
|
|
I have made several classes to make the database connection more clear and easyer to overlook.
|
|
This here is the main file where the data for each function is collected and ready to be sent to the database.
|
|
|
|
In the file : "data.py" the primary connections are made to the websocket and the data recieved is split off to see which type of node came back.
|
|
|
|
These types can be the "sensorNode"(the nodes that are located around the school) and the "enqueteNode"(a questionaire node which also collects data.).
|
|
|
|
```py
|
|
#Importing all different files from all the nodes which are on different pages
|
|
import asyncio
|
|
import websockets
|
|
import json
|
|
from class_SensorNode import SensorNode
|
|
from class_enqueteNode import EnqueteNode
|
|
from classes_data import dbLogin
|
|
|
|
#Making global variables
|
|
sensorNodeArray = []
|
|
enqueteNodeArray = []
|
|
```
|
|
These array's need to be global because of the several uses later in the code. These cannot be bound to a singular function.
|
|
|
|
The following function is meant to connect to the websocket and after this, process the gained Json data from the socket.
|
|
|
|
Once this is done get the info if the data comming from the websocket is from a "sensor-node" or a "questionairre-node".
|
|
|
|
once this information is gained, decide if this new node is a not yet existing connection with the database or if it was already inserted.
|
|
|
|
In the case that the node didn't connect to the database, a new node is made with this new MAC address.
|
|
|
|
These functions are put in different classes for a better overview of the whole project and a better understanding of what function is supposed to do what.
|
|
```py
|
|
#Connection making with the websocket
|
|
async def receive_data():
|
|
uri = "ws://145.92.8.114/ws"
|
|
try:
|
|
async with websockets.connect(uri) as websocket:
|
|
while True:
|
|
print("true")
|
|
data = await websocket.recv()
|
|
print(f"Received data: {data}")
|
|
|
|
processedData = json.loads(data)
|
|
macAdress = processedData['node']
|
|
|
|
#A function to see if the node is one of two types.
|
|
if "Temp" in processedData:
|
|
type = 'sensor'
|
|
else:
|
|
type = 'enquete'
|
|
|
|
await getNodeInfo('sensor')
|
|
await getNodeInfo('enquete')
|
|
|
|
#Get the node id and use it in functions seperate from this file.
|
|
if macAdress in sensorNodeArray:
|
|
nodeID = await getNodeID(macAdress)
|
|
await SensorNode.processSensorNodeData(data, nodeID)
|
|
elif macAdress in enqueteNodeArray:
|
|
nodeID = await getNodeID(macAdress)
|
|
await EnqueteNode.processEnqueteNodeData(data, nodeID)
|
|
else:
|
|
await newNode(macAdress, type)
|
|
# Error message if smth went wrong
|
|
except websockets.ConnectionClosedError as e:
|
|
print("WebSocket connection closed:", e)
|
|
|
|
#Wait for data to come in.
|
|
async def main():
|
|
await receive_data()
|
|
```
|
|
The following function is made to set the different node types appart, this is done by putting down these global variables.
|
|
These variables are doen this way because the python-scope could not reach inside some parts of the files.
|
|
|
|
A bit further a array is made to holde the node info. this is so the information of the node can be sepperated and held.
|
|
|
|
After the array, a type tuple is made. (A tuple is a type of info which acts in a way like a array. For more info visit https://www.w3schools.com/python/python_tuples.asp)
|
|
|
|
Then another connection to the database is made to gather all existing mac-addresses.
|
|
|
|
Then a for-loop is made to see if the incomming MAC is existing, if this isn't the case, add it to the array.
|
|
|
|
After, if the given type from the previous function is a sensor-, or questionaire-node
|
|
```py
|
|
#By python's scuffed we had to use global variables.
|
|
async def getNodeInfo(type):
|
|
print("getNodeINfo")
|
|
global sensorNodeArray
|
|
global enqueteNodeArray
|
|
|
|
#New array which is needed.
|
|
nodeInfoArray = []
|
|
|
|
# make a connection to the databasse, then gather all MAC-adresses from it.
|
|
id = (type,)
|
|
mydb = dbLogin()
|
|
cursor = mydb.cursor()
|
|
cursor.execute("""SELECT MAC FROM Node WHERE Type = %s""", id)
|
|
#Fetch all info(get all info)
|
|
nodeInfo = cursor.fetchall()
|
|
|
|
#Go along each tuple in nodeinfo and each item in tuple, append(item)
|
|
for tuples in nodeInfo:
|
|
for item in tuples:
|
|
nodeInfoArray.append(item)
|
|
|
|
cursor.close()
|
|
mydb.close()
|
|
|
|
#If the type is a sensor do this,
|
|
if type == 'sensor':
|
|
sensorNodeArray = nodeInfoArray
|
|
return sensorNodeArray
|
|
|
|
#Else, this if statement
|
|
elif type == 'enquete':
|
|
enqueteNodeArray = nodeInfoArray
|
|
return enqueteNodeArray
|
|
```
|
|
The next function acts as a node ID fetcher, it searches the database for information regarding the nodeID's.
|
|
|
|
Like the previous function, It adds the new ID id this is not yet existent.
|
|
```py
|
|
async def getNodeID(macAdress):
|
|
id = (macAdress,)
|
|
mydb = dbLogin()
|
|
cursor = mydb.cursor()
|
|
cursor.execute("""SELECT nodeID FROM Node WHERE MAC = %s""", id)
|
|
data = cursor.fetchall()
|
|
|
|
#Again, all tuples in data, all items for all tuples, nodeID
|
|
for tuples in data:
|
|
for item in tuples:
|
|
nodeID = item
|
|
|
|
return nodeID
|
|
```
|
|
The following function will take the previous information and process it and push it to the database.
|
|
|
|
First the connection, then the query, then insert the data into the query and send it off.
|
|
```py
|
|
async def newNode(mac, type):
|
|
id = (mac, type)
|
|
mydb = dbLogin()
|
|
|
|
cursor = mydb.cursor()
|
|
#Insert will insert it into the given location in the database.
|
|
cursor.execute("INSERT INTO `Node` (MAC, Type) VALUES (%s, %s)", id)
|
|
#A simple print to show that the process has been executed succesfully.
|
|
print("new node assigned")
|
|
mydb.commit()
|
|
|
|
asyncio.run(main())
|
|
```
|