2024-04-02 13:32:39 +02:00
12 changed files with 301 additions and 21 deletions

View File

@@ -237,7 +237,7 @@ async def getNodeID(macAdress):
This function is alot like the original one, with the only 2 changes being that it now also commits the nodeID and that the code to make a new node is now in a different function. This function is alot like the original one, with the only 2 changes being that it now also commits the nodeID and that the code to make a new node is now in a different function.
[Link to code](server\data.py) [link to code](../../server/web-data-connection/data.py)
## The function to commit the data from the enqueteNodes ## The function to commit the data from the enqueteNodes

View File

@@ -0,0 +1,128 @@
## The websocket -> database connection classes.
I have made several classes to make the database connection more clear and easyer to overlook.
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 variables need to be global to serve for several locations in the code.
Here the code makes connection with the websocket.
```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()
```
Here we have a case of python's scoping, it couldn't read the variables correctly and by making them global the variables were now available for all functions.
```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 = []
id = (type,)
mydb = dbLogin()
cursor = mydb.cursor()
cursor.execute("""SELECT MAC FROM Node WHERE Type = %s""", id)
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
```
Here the database gets hinted to gain info of the existing nodes and find their macadress.
```py
async def getNodeID(macAdress):
id = (macAdress,)
#the db login is on a different page.
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
```
See if the node is existing, if not push it to the database.
```py
async def newNode(mac, type):
id = (mac, type)
#Same thing as before.
mydb = dbLogin()
cursor = mydb.cursor()
cursor.execute("INSERT INTO `Node` (MAC, Type) VALUES (%s, %s)", id)
print("new node assigned")
mydb.commit()
asyncio.run(main())
```

View File

@@ -9,12 +9,11 @@
<script src="https://cdn.plot.ly/plotly-latest.min.js" charset="utf-8"></script> <script src="https://cdn.plot.ly/plotly-latest.min.js" charset="utf-8"></script>
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet"> <link
href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap"
rel="stylesheet">
</head> </head>
<body>
<nav class="navbar"> <nav class="navbar">
<ul class="navbar-nav"> <ul class="navbar-nav">
<li class="nav-item"> <li class="nav-item">
@@ -26,16 +25,17 @@
<li class="nav-item"> <li class="nav-item">
<a href="settings.html" class="nav-link">Settings</a> <a href="settings.html" class="nav-link">Settings</a>
</li> </li>
<li class="nav-item">
<a href="questions-dashboard.html" class="nav-link">Questions</a>
</ul> </ul>
</nav> </nav>
<script src="https://cdn.plot.ly/plotly-latest.min.js" charset="utf-8"></script>
<body>
<script src="GaugGroup.js"></script> <script src="GaugGroup.js"></script>
<script src="graph-classes.js"></script> <script src="graph-classes.js"></script>
<script src="main.js"></script> <script src="main.js"></script>
<script src="text.js"></script>
<script src="liveGraph.js"></script> <script src="liveGraph.js"></script>
</body> </body>
</html> </html>

View File

@@ -5,6 +5,42 @@
} }
/*
.editNodeInformation{
margin-bottom: 60%;
display: flex;
justify-content: left;
} */
#editNode{
display: flex;
justify-content: center;
/* align-items: center; */
/* flex-direction: column; */
/* border-radius: 5%; */
/* border: 20px solid orange; */
}
/* #editNode {
width: 98vw;
height: 20vh;
display: flex;
justify-content: center;
/* flex-direction: column; Keep as column
/* justify-content: ;
align-items: center;
background-color: #333;
color: #fff;
padding: 10px;
border-radius: 50px;
border: 2px solid #333;
clear: both;
margin-bottom: 10px;
position: relative;
float: top;
} */
body { body {
display: flex; display: flex;
justify-content: center; justify-content: center;

27
web/newWebsite/text.html Normal file
View File

@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="settings" onclick="settings()">Settings</button>
<div id="editNode">
<p id="text">Status updating</p>
<select id="mySelect"></select>
<textarea id="inputName"></textarea>
<textarea id="inputLocation"></textarea>
<button id="button" onclick="changeText()">Change Information</button>
</div>
</body>
<header>
<script src="text.js"></script>
</header>
</html>

91
web/newWebsite/text.js Normal file
View File

@@ -0,0 +1,91 @@
apiGetAllNode = "http://145.92.8.114/getNodeInfo?macAdress=*"
nodeDataArray = {};
var updateNode = document.getElementById('editNode');
var locationInput = document.getElementById("inputLocation");
var nameInput = document.getElementById("inputName");
var select = document.getElementById('mySelect');
document.getElementById("inputName").placeholder = "Type new name here..";
document.getElementById("inputLocation").placeholder = "Type new location here..";
updateNode.style.display = "none";
function settings() {
if (updateNode.style.display === "none") {
updateNode.style.display = "block";
locationInput.value = "";
nameInput.value = "";
fetch(apiGetAllNode)
.then(response => {
if (!response.ok) {
document.getElementById('text').innerHTML = "Error: Network response was not ok";
throw new Error('Network response was not ok');
}
document.getElementById('text').innerHTML = "Fetching data";
return response.json();
})
.then(data => {
document.getElementById('text').innerHTML = "Data fetched";
handleData(data);
})
} else {
updateNode.style.display = "none";
}
}
function handleData(JSONdata) {
var i, L = select.options.length - 1;
for (i = L; i >= 0; i--) {
select.remove(i);
}
for (var i = 0; i < JSONdata.length; i++) {
var node = JSONdata[i].NodeID;
var name = JSONdata[i].Name;
var location = JSONdata[i].Location;
nodeDataArray[node] = { name: name, location: location };
// Create new option element
var option = document.createElement('option');
// Set the value of the option
option.value = node;
// Set the text of the option
option.text = name;
// Add the option to the select
select.add(option);
}
}
function changeText() {
var nodeName = encodeURIComponent(document.getElementById('inputName').value);
var nodeLocation = encodeURIComponent(document.getElementById('inputLocation').value);
updateNodeInfo(select.value, nodeName, nodeLocation);
var text = document.getElementById('text');
text.innerHTML = "Changes made"
}
function updateNodeInfo(node, newNodeName, newNodeLocation) {
apiUrl = "http://145.92.8.114/updateData?node=" + node + "&name=" + newNodeName + "&location=" + newNodeLocation;
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error('Error:', error);
});
}

View File

@@ -72,8 +72,6 @@ p1 {
} }
.nodeData { .nodeData {
display: flex; display: flex;
justify-content: left; justify-content: left;