Merge branch 'main' of gitlab.fdmci.hva.nl:propedeuse-hbo-ict/onderwijs/2023-2024/out-a-se-ti/blok-3/qaajeeqiinii59

This commit is contained in:
Bram Barbieri
2024-03-07 13:59:03 +01:00
12 changed files with 585 additions and 361 deletions

View File

@@ -2,6 +2,7 @@
#include "Adafruit_GFX.h" #include "Adafruit_GFX.h"
#include "Adafruit_ST7796S_kbv.h" #include "Adafruit_ST7796S_kbv.h"
#include "headerFile.h" #include "headerFile.h"
#include "displayText.h"
int i = 0; int i = 0;
char* Question[] = { char* Question[] = {
@@ -22,7 +23,7 @@ char* Answer[] = {
//simplify the name of the library //simplify the name of the library
Adafruit_ST7796S_kbv tft = Adafruit_ST7796S_kbv(TFT_CS, TFT_DC, MOSI, SCK, TFT_RST, MISO); Adafruit_ST7796S_kbv tft = Adafruit_ST7796S_kbv(TFT_CS, TFT_DC, MOSI, SCK, TFT_RST, MISO);
DisplayText displayText(tft);
void setup() { void setup() {
@@ -40,32 +41,29 @@ void loop() {
tft.fillScreen(ST7796S_BLACK); // Fill the screen with black color tft.fillScreen(ST7796S_BLACK); // Fill the screen with black color
// writeText(Question[0], 2, 50, 0, 0); // writeText(Question[0], 2, 50, 0, 0);
// writeText(Answer[0], 2, 50, 300, 4000); // writeText(Answer[0], 2, 50, 300, 4000);
writeText(Question[i], 3, 0, 0, 0, true); displayText.writeText(Question[i], 3, 0, 0, 0, true, false);
writeText(Answer[i], 3, 0, 200, 0, true); displayText.writeText(Answer[i], 3, 0, 200, 0, true, true);
delay(10000); delay(10000);
} }
void writeText(char* text, int size, int posX, int posY, int screenTime, bool center){ // void writeText(char* text, int size, int posX, int posY, int screenTime, bool center){
//if true overwrites x // //if true overwrites x
if (center){ // if (center){
posX = centerText(text); // posX = centerText(text);
} // }
tft.setCursor(posX, posY); // Set the cursor to the top left corner // tft.setCursor(posX, posY); // Set the cursor to the top left corner
tft.setTextSize(size); // Set textsize // tft.setTextSize(size); // Set textsize
tft.println(text); // tft.println(text);
delay(screenTime); // delay(screenTime);
} // }
int centerText(char* text) { // int centerText(char* text) {
int16_t x1, y1; // int16_t x1, y1;
uint16_t w, h; // uint16_t w, h;
tft.getTextBounds(text, 0, 0, &x1, &y1, &w, &h); // Calculate the width of the text // tft.getTextBounds(text, 0, 0, &x1, &y1, &w, &h); // Calculate the width of the text
int x = (tft.width() - w) / 2; // Calculate the x-coordinate for the centered text // int x = (tft.width() - w) / 2; // Calculate the x-coordinate for the centered text
return x; // return x;
} // }

View File

@@ -0,0 +1,36 @@
#include "displayText.h"
#include "Arduino.h"
//constructor
DisplayText::DisplayText(Adafruit_ST7796S_kbv& tftDisplay) : tft(tftDisplay) {
tft.setCursor(0,0);
}
void DisplayText::writeText(char* text, int size, int posX, int posY, int screenTime, bool center, bool bottom) {
if (center) {
posX = centerText(text);
}
if (bottom) {
posY = bottomText(text);
}
tft.setCursor(posX, posY);
tft.setTextSize(size);
tft.println(text);
delay(screenTime);
}
int DisplayText::centerText(char* text) {
int16_t x1, y1;
uint16_t w, h;
tft.getTextBounds(text, 0, 0, &x1, &y1, &w, &h);
int x = (tft.width() - w) / 2;
return x;
}
int DisplayText::bottomText(char* text) {
int16_t x1, y1;
uint16_t w, h;
tft.getTextBounds(text, 0, 0, &x1, &y1, &w, &h);
int y = (tft.height() - h);
return y;
}

View File

@@ -0,0 +1,18 @@
#ifndef DISPLAYTEXT_H
#define DISPLAYTEXT_H
#include "Adafruit_GFX.h"
#include "Adafruit_ST7796S_kbv.h"
class DisplayText {
private:
Adafruit_ST7796S_kbv& tft;
int centerText(char* text);
int bottomText(char* text);
public:
DisplayText(Adafruit_ST7796S_kbv& tftDisplay);
void writeText(char* text, int size, int posX, int posY, int screenTime, bool center, bool bottom);
};
#endif

View File

@@ -1,224 +0,0 @@
// Sietse Jonker & Dano Bosch
// 27/02/2024
// include these libraries
#include <Wire.h>
#include <Adafruit_SH110X.h>
#include <Adafruit_SGP30.h>
#include <DHT.h>
#include <WiFiMulti.h>
#include <WiFi.h>
#include <WebSocketsClient.h>
// define pins on esp32
#define MICPIN 6
#define DHTPIN 7
#define SCL 9
#define SDA 8
#define DHTTYPE DHT11
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define i2c_adress 0x3c
#define USE_SERIAL Serial
// make new objects
Adafruit_SH1106G display = Adafruit_SH1106G(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire);
DHT dht(DHTPIN, DHTTYPE);
WiFiMulti WiFiMulti;
Adafruit_SGP30 sgp;
WebSocketsClient webSocket;
// define variables
uint16_t TVOC_base, eCO2_base;
uint16_t counter = 0;
uint16_t eCO2 = 0;
uint16_t TVOC = 0;
uint16_t interval = 5000;
float temperature = 0;
float humidity = 0;
unsigned long currentMillis;
unsigned long lastMillis;
bool errorSGP30 = false;
bool errorDHT11 = false;
bool noise = false;
// hexdump function for websockets binary handler
void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {
const uint8_t* src = (const uint8_t*) mem;
USE_SERIAL.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
for(uint32_t i = 0; i < len; i++) {
if(i % cols == 0) {
USE_SERIAL.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
}
USE_SERIAL.printf("%02X ", *src);
src++;
}
USE_SERIAL.printf("\n");
}
// handler for websocket events
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[WSc] Disconnected!\n");
break;
case WStype_CONNECTED:
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
// send message to server when Connected
webSocket.sendTXT("Connected");
break;
case WStype_TEXT:
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
// send message to server
// webSocket.sendTXT("message here");
break;
case WStype_BIN:
USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
hexdump(payload, length);
// send data to server
// webSocket.sendBIN(payload, length);
break;
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
break;
}
}
// special function to setup websocket
void websocketSetup(){
WiFiMulti.addAP("iotroam", "vbK9gbDBIB");
WiFiMulti.addAP("LansanKPN-boven", "19sander71vlieland14");
while(WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
// server address, port and URL
webSocket.begin("145.92.8.114", 80, "/ws");
// event handler
webSocket.onEvent(webSocketEvent);
// try ever 500 again if connection has failed
webSocket.setReconnectInterval(500);
}
// fucntion to reset the values if needed
void resetValues() {
TVOC_base;
eCO2_base;
counter = 0;
temperature = 0;
humidity = 0;
eCO2 = 0;
TVOC = 0;
noise = false;
lastMillis = 0;
currentMillis = 0;
}
// function to check for errors in sensors
bool checkForError(){
if (!sgp.IAQmeasure()) {
Serial.println("SGP30: BAD");
errorSGP30 = true;
} else {
Serial.println("SGP30: OK");
errorSGP30 = false;
}
if (isnan(temperature) || isnan(humidity)){
Serial.println("DHT11: BAD");
errorDHT11 = true;
} else {
Serial.println("DHT11: OK");
errorDHT11 = false;
}
return false;
}
// function to update when interval is met (see intervalCounter variable)
void update(){
// display sensordata on oled screen
displayData();
// send data to websocket server
webSocket.sendTXT("Temp: " + String(temperature));
webSocket.sendTXT("Humi: " + String(humidity));
webSocket.sendTXT("eCO2: " + String(sgp.eCO2));
webSocket.sendTXT("TVOC: " + String(sgp.TVOC));
sgp.getIAQBaseline(&eCO2_base, &TVOC_base);
// read dht11 sensor
temperature = float(dht.readTemperature());
humidity = float(dht.readHumidity());
// check if any errors occured when reading sensors
checkForError();
}
// function to display data on oled screen
void displayData() {
// clear display for new info
display.clearDisplay();
// set custom text properties
display.setTextSize(2);
display.setTextColor(SH110X_WHITE);
display.setCursor(0, 0);
// display info on oled screen
display.println((String) "Temp: " + int(temperature) + "C" + '\n'
+ "Humi: " + int(humidity) + "%" + '\n'
+ "eCO2: " + int(sgp.eCO2) + '\n'
+ "TVOC: " + int(sgp.TVOC));
// display the screen
display.display();
}
// setup function
void setup() {
// make serial connection at 115200 baud
Serial.begin(115200);
// tell display what settings to use
display.begin(i2c_adress, true);
display.clearDisplay();
// tell sensors to start reading
dht.begin();
sgp.begin();
pinMode(MICPIN, INPUT);
pinMode(DHTPIN, INPUT);
// setup websocket connection
websocketSetup();
// reset values
resetValues();
}
// loop function
void loop() {
// loop the websocket connection so it stays alive
webSocket.loop();
// update when interval is met
if (currentMillis - lastMillis >= interval){
lastMillis = millis();
update();
}
// update the counter
currentMillis = millis();
}

View File

@@ -161,6 +161,7 @@ void update(){
temperature = float(dht.readTemperature()); temperature = float(dht.readTemperature());
humidity = float(dht.readHumidity()); humidity = float(dht.readHumidity());
// check if any errors occured when reading sensors
checkForError(); checkForError();
} }
@@ -180,11 +181,13 @@ void displayData() {
+ "eCO2: " + int(sgp.eCO2) + '\n' + "eCO2: " + int(sgp.eCO2) + '\n'
+ "TVOC: " + int(sgp.TVOC)); + "TVOC: " + int(sgp.TVOC));
// display the screen
display.display(); display.display();
} }
// setup function // setup function
void setup() { void setup() {
// make serial connection at 115200 baud
Serial.begin(115200); Serial.begin(115200);
// tell display what settings to use // tell display what settings to use

View File

@@ -23,4 +23,6 @@ nav:
- Infrastructure: brainstorm/UML-infrastructure - Infrastructure: brainstorm/UML-infrastructure
- Taskflow: brainstorm/Taskflow - Taskflow: brainstorm/Taskflow
- Design: Sp1SchetsProject/FirstDesign - Design: Sp1SchetsProject/FirstDesign
- 🖨️ Software:
- Dev page: brainstrom/SotwareDocumentatie/Dev_page

View File

@@ -0,0 +1,151 @@
### parsing JSON
```js
const jsonData = JSON.parse(event.data);
// Use the parsed JSON data as needed
handleIncomingData(jsonData);
```
### Pro
function handleIncomingData(data) {
nodeNumber = data.node;
temperature = data.Temp;
humidity = data.Humi;
CO2 = data.eCO2;
TVOC = data.TVOC;
processNodeData(nodeNumber, temperature, humidity, CO2, TVOC);
}
function processNodeData(nodeNumber, temperature, humidity, CO2, TVOC) {
// Initialize the array for this node if it doesn't exist yet
if (!sensorData[nodeNumber]) {
sensorData[nodeNumber] = [];
}
// Push the new data onto the array for this node
sensorData[nodeNumber].push({
'node': nodeNumber,
'temp': temperature,
'humi': humidity,
'CO2': CO2,
'TVOC': TVOC,
});
// updateNodeData(node, temperature, humidity, lightIntensity)
updateNodeData(nodeNumber, temperature, humidity, CO2, TVOC);
// Log the array for this node
console.log(sensorData[nodeNumber]);
// If the array for this node has more than 10 elements, remove the oldest one
if (sensorData[nodeNumber].length >= 10) {
sensorData[nodeNumber].shift();
}
}
function createNodeData(node) {
// Create main div
var nodeData = document.createElement("div");
nodeData.className = "nodeData";
// Create flex-NodeData div
var flexNodeData = document.createElement("div");
flexNodeData.clsName = "flex-NodeData";
// Create p element
var pNode = document.createElement("p");
pNode.textContent = "Node " + node;
// Append p to flex-NodeData
flexNodeData.appendChild(pNode);
// Create flex-LiveData div
var flexLiveData = document.createElement("div");
flexLiveData.className = "flex-LiveData";
// Create data divs (Temperature, Humidity, Light Intensity)
var dataTypes = ["Temperatuur", "Luchtvochtigheid", "CO2", "TVOC"];
var ids = ["temperature", "humidity", "CO2", "TVOC"];
var statusIds = ["tempStatus", "humidStatus", "CO2Status", "TVOCStatus"];
for (var i = 0; i < dataTypes.length; i++) {
var dataDiv = document.createElement("div");
var dataTypeDiv = document.createElement("div");
dataTypeDiv.textContent = dataTypes[i] + ": ";
var pElement = document.createElement("p");
pElement.id = ids[i] + node;
pElement.textContent = "Not connected";
dataTypeDiv.appendChild(pElement);
dataDiv.appendChild(dataTypeDiv);
var statusElement = document.createElement("div");
statusElement.className = "statusElement";
var statusText = document.createElement("p");
statusText.className = "statusText";
statusText.id = statusIds[i];
statusText.textContent = "Not connected";
statusElement.appendChild(statusText);
dataDiv.appendChild(statusElement);
flexLiveData.appendChild(dataDiv);
}
// Append flex-LiveData to flex-NodeData
flexNodeData.appendChild(flexLiveData);
// Create flex-graph div
var flexGraph = document.createElement("div");
flexGraph.className = "flex-graph";
var graphDiv = document.createElement("div");
var graphP = document.createElement("p");
graphP.textContent = "Live graph:";
var liveGraph = document.createElement("div");
liveGraph.id = "liveGraph";
graphDiv.appendChild(graphP);
graphDiv.appendChild(liveGraph);
flexGraph.appendChild(graphDiv);
// Append flex-graph to flex-NodeData
flexNodeData.appendChild(flexGraph);
// Append flex-NodeData to main div
nodeData.appendChild(flexNodeData);
// Check if nodeDataLocation element exists
var nodeDataLocation = document.getElementById("nodeDataLocation");
if (nodeDataLocation) {
// Append main div to nodeDataLocation
nodeDataLocation.appendChild(nodeData);
} else {
console.error("Element with ID 'nodeDataLocation' does not exist.");
}
}
function updateNodeData(node, temperature, humidity, eCO2, TVOC) {
// Update the temperature, humidity and light intensity values
document.getElementById("temperature" + node).textContent = temperature;
document.getElementById("humidity" + node).textContent = humidity;
document.getElementById("CO2" + node).textContent = eCO2;
document.getElementById("TVOC" + node).textContent = TVOC;
// Update the status text
document.getElementById("tempStatus").textContent = "Connected";
document.getElementById("humidStatus").textContent = "Connected";
document.getElementById("CO2Status").textContent = "Connected";
document.getElementById("TVOCStatus").textContent = "Connected";
}

View File

@@ -67,16 +67,20 @@ We aren't using the cs2 and the pen pin because we arent utilizing the touch fun
```mermaid ```mermaid
classDiagram classDiagram
writeText <|-- Adafruit_ST7796S_kbv displayTex <|-- Adafruit_ST7796S_kbv
loop <-- writeText loop <-- displayTex
class writeText{ class displayTex{
+text +text
+color +color
+size +size
+posx +posx
+posy +posy
+writeText() +void writeText()
-int centerText(char* text)
} }
class Adafruit_ST7796S_kbv{ class Adafruit_ST7796S_kbv{

82
web/classes.js Normal file
View File

@@ -0,0 +1,82 @@
class liveGraph {
// Constructor to initialize the graph
constructor(id) {
this.timeArray = [];
this.tempArray = [];
this.humiArray = [];
this.eco2Array = [];
this.tvocArray = [];
this.cnt = 0;
this.nodeId = "liveGraph" + id;
}
// Fuction to create a graph
makeGraph() {
Plotly.plot(this.nodeId, [
{
x: this.timeArray, // Use timeArray as x values
y: this.tempArray,
mode: "lines",
line: { color: "#FF0000" },
name: "Temperature",
},
]);
Plotly.plot(this.nodeId, [
{
x: this.timeArray, // Use timeArray as x values
y: this.humiArray,
mode: "lines",
line: { color: "#80CAF6" },
name: "Humidity",
},
]);
Plotly.plot(this.nodeId, [
{
x: this.timeArray, // Use timeArray as x values
y: this.eco2Array,
mode: "lines",
line: { color: "#FFA500" },
name: "eCO2 / 10",
},
]);
Plotly.plot(this.nodeId, [
{
x: this.timeArray, // Use timeArray as x values
y: this.tvocArray,
mode: "lines",
line: { color: "#000000" },
name: "TVOC / 10",
},
]);
}
// Function to update the graph with new values
updateGraph() {
let time = new Date();
this.timeArray.push(new Date());
let update = {
x: [[this.timeArray]],
y: [[this.tempArray], [this.humiArray], [this.eco2Array], [this.tvocArray]]
};
let olderTime = time.setMinutes(time.getMinutes() - 1);
let futureTime = time.setMinutes(time.getMinutes() + 1);
let minuteView = {
xaxis: {
type: "date",
range: [olderTime, futureTime],
},
};
Plotly.relayout(this.nodeId, minuteView);
if (this.cnt === 10) clearInterval(interval);
}
updateData(temperature, humidity, eCO2, TVOC) {
// Update the graph
this.tempArray.push(temperature);
this.humiArray.push(humidity);
this.eco2Array.push(eCO2 / 10);
this.tvocArray.push(TVOC / 10);
}
}

View File

@@ -1,12 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<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>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="styles.css">
<title>Node dev page</title> <title>Node dev page</title>
<link rel="icon" type="image/x-icon" href="favicon.ico"> <!-- <link rel="icon" type="image/x-icon" href="favicon.ico"> -->
</head> </head>
@@ -16,54 +17,21 @@
<nav class="navbar"> <nav class="navbar">
<ul> <ul>
<li><a href="climate-monitor.html">Dashboard <li><a href="climate-monitor.html">Dashboard
</a></li> </a></li>
<li><a href="Map.html">Graph</a></li> <li><a href="Map.html">Graph</a></li>
</li> </li>
</ul> </ul>
</nav> </nav>
</header> </header>
<!-- Make a new flex container for the live data -->
<div class="nodeData">
<div class="flex-NodeData"> <div id="nodeDataLocation"></div>
<p>Node 1</p>
<div class="flex-LiveData">
<div>
<div>Temperatuur: <p id="temperature">Not connected</p>
</div>
<div class="statusElement">
<p class="statusText" id="tempStatus">Not connected</p>
</div>
</div>
<div>
<div>Luchtvochtigheid: <p id="humidity">Not connected</p>
</div>
<div class="statusElement">
<p class="statusText" id="humidStatus">Not connected</p>
</div>
</div>
<div>
<div>Lichtintensiteit: <p id="lightIntensity">Not connected</p>
</div>
<div class="statusElement">
<p class="statusText" id="lightIntensityStatus">Not connected</p>
</div>
</div>
</div>
<!-- Make a new flexcontainer for the graphs and API request time -->
<div class="flex-graph">
<div>
<p>Live graph:</p>
<div id="liveGraph"></div>
</div>
</div>
</div>
</div> <!-- class="nodeData" -->
<!-- Include the js file --> <!-- Include the js file -->
<script src="classes.js"></script>
<script src="main.js"></script> <script src="main.js"></script>
</body> </body>
<html> <html>

View File

@@ -1,73 +1,220 @@
let data; const sensorData = {};
let measurements; let intervalDelay = 1000;
let date; // Create WebSocket connection.
let value; const socket = new WebSocket("ws://145.92.8.114/ws");
let newArrayTemp = [];
let newArrayHumid = [];
let newArrayLight = [];
let timeArray = []; // Array to store time values
let dateArray = [1, 2, 3];
let valueArray = [1, 2, 3, 4, 5];
let valueArray2 = [1, 2, 3, 4, 5];
let valueArray3 = [1, 2, 3, 4, 5];
let valueArray4 = [1, 2, 3, 4, 5];
let newValueArray = [4, 5, 6];
let myValue = 1;
let intervalDelay = 50;
function openConnection() {
// Open connection
socket.addEventListener("open", (event) => {
console.log("Connected to the WebSocket server");
socket.send("Hello Server!");
});
class liveGraph { // Error handling
socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
// Attempt to reconnect
setTimeout(openConnection, 1000); // Retry after 1 second
});
constructor() { // Message handling
this.timeArray = []; socket.addEventListener("message", (event) => {
this.dateArray = []; try {
this.valueArray = []; const jsonData = JSON.parse(event.data);
// Use the parsed JSON data as needed
handleIncomingData(jsonData);
} catch (error) {
console.error("Error parsing JSON:", error);
} }
pushArray(array) { });
for (let i = 0; i < 10; i++) {
array.push(Math.random() * 10); // Close handling
} socket.addEventListener('close', (event) => {
} console.log('Connection closed');
makeGraph() { // Attempt to reconnect
Plotly.plot("liveGraph", [ setTimeout(openConnection, 1000); // Retry after 1 second
{ });
x: this.timeArray, // Use timeArray as x values console.log("Connected to the WebSocket server!!!!!!!!");
y: this.valueArray, }
mode: "lines",
line: { color: "#80CAF6" }, // Open the connection
name: "Temperature", openConnection();
},
]);
function handleIncomingData(data) {
nodeNumber = data.node;
temperature = data.Temp;
humidity = data.Humi;
CO2 = data.eCO2;
TVOC = data.TVOC;
processNodeData(nodeNumber, temperature, humidity, CO2, TVOC);
}
function processNodeData(nodeNumber, temperature, humidity, CO2, TVOC) {
// Initialize the array for this node if it doesn't exist yet
if (!sensorData[nodeNumber]) {
sensorData[nodeNumber] = [];
} }
updateGraph() { // Push the new data onto the array for this node
let cnt = 0; sensorData[nodeNumber].push({
let interval = setInterval(function () { 'node': nodeNumber,
var time = new Date(); 'temp': temperature,
this.timeArray.push(new Date()); 'humi': humidity,
this.pushArray(this.valueArray); 'CO2': CO2,
var update = { 'TVOC': TVOC,
x: [[this.timeArray]], });
y: [[this.newValueArray]],
}; // updateNodeData(node, temperature, humidity, lightIntensity)
var olderTime = time.setMinutes(time.getMinutes() - 1); updateNodeData(nodeNumber, temperature, humidity, CO2, TVOC);
var futureTime = time.setMinutes(time.getMinutes() + 1);
var minuteView = { // Log the array for this node
xaxis: { console.log(sensorData[nodeNumber]);
type: "date",
range: [olderTime, futureTime], // If the array for this node has more than 10 elements, remove the oldest one
}, if (sensorData[nodeNumber].length >= 10) {
}; sensorData[nodeNumber].shift();
Plotly.relayout("liveGraph", minuteView);
if (cnt === 10) clearInterval(interval);
}, intervalDelay);
} }
} }
let graph = new liveGraph();
graph.makeGraph();
graph.updateGraph();
graph.pushArray();
console.log("test");
function pushArray(array) {
for (let i = 0; i < 10; i++) {
array.push(Math.random() * 10);
}
}
//function for making the html elements for the following html code
function nodeData(data, node) {
let nodeData = document.createElement("div");
nodeData.innerHTML = data;
// nodeData.setAttribute("id", "node" + node);
document.body.appendChild(nodeData);
// console.log("Hello World");
}
function createNodeData(node) {
// Create main div
var nodeData = document.createElement("div");
nodeData.className = "nodeData";
// Create flex-NodeData div
var flexNodeData = document.createElement("div");
flexNodeData.className = "flex-NodeData";
// Create p element
var pNode = document.createElement("p");
pNode.textContent = "Node " + node;
// Append p to flex-NodeData
flexNodeData.appendChild(pNode);
// Create flex-LiveData div
var flexLiveData = document.createElement("div");
flexLiveData.className = "flex-LiveData";
// Create data divs (Temperature, Humidity, Light Intensity)
var dataTypes = ["Temperatuur", "Luchtvochtigheid", "CO2", "TVOC"];
var ids = ["temperature", "humidity", "CO2", "TVOC"];
var statusIds = ["tempStatus", "humidStatus", "CO2Status", "TVOCStatus"];
for (var i = 0; i < dataTypes.length; i++) {
var dataDiv = document.createElement("div");
var dataTypeDiv = document.createElement("div");
dataTypeDiv.textContent = dataTypes[i] + ": ";
var pElement = document.createElement("p");
pElement.id = ids[i] + node;
pElement.textContent = "Not connected";
dataTypeDiv.appendChild(pElement);
dataDiv.appendChild(dataTypeDiv);
var statusElement = document.createElement("div");
statusElement.className = "statusElement";
var statusText = document.createElement("p");
statusText.className = "statusText";
statusText.id = statusIds[i];
statusText.textContent = "Not connected";
statusElement.appendChild(statusText);
dataDiv.appendChild(statusElement);
flexLiveData.appendChild(dataDiv);
}
// Append flex-LiveData to flex-NodeData
flexNodeData.appendChild(flexLiveData);
// Create flex-graph div
var flexGraph = document.createElement("div");
flexGraph.className = "flex-graph";
var graphDiv = document.createElement("div");
var graphP = document.createElement("p");
graphP.textContent = "Live graph:";
var liveGraph = document.createElement("div");
liveGraph.id = "liveGraph" + node;
graphDiv.appendChild(graphP);
graphDiv.appendChild(liveGraph);
flexGraph.appendChild(graphDiv);
// Append flex-graph to flex-NodeData
flexNodeData.appendChild(flexGraph);
// Append flex-NodeData to main div
nodeData.appendChild(flexNodeData);
// Check if nodeDataLocation element exists
var nodeDataLocation = document.getElementById("nodeDataLocation");
if (nodeDataLocation) {
// Append main div to nodeDataLocation
nodeDataLocation.appendChild(nodeData);
} else {
console.error("Element with ID 'nodeDataLocation' does not exist.");
}
}
function updateNodeData(node, temperature, humidity, eCO2, TVOC) {
// Update the temperature, humidity and light intensity values
document.getElementById("temperature" + node).textContent = temperature;
document.getElementById("humidity" + node).textContent = humidity;
document.getElementById("CO2" + node).textContent = eCO2;
document.getElementById("TVOC" + node).textContent = TVOC;
// Update the status text
document.getElementById("tempStatus").textContent = "Connected";
document.getElementById("humidStatus").textContent = "Connected";
document.getElementById("CO2Status").textContent = "Connected";
document.getElementById("TVOCStatus").textContent = "Connected";
// Update the graph`
graphNode1.updateData(temperature, humidity, eCO2, TVOC);
graphNode1.updateGraph();
}
// Call the function to create the HTML structure
createNodeData(1);
createNodeData(2);
createNodeData(3);
createNodeData(4);
// Create a new liveGraph object
let graphNode1 = new liveGraph(1);
graphNode1.makeGraph();
let graphNode2 = new liveGraph(2);
graphNode2.makeGraph();
// openConnection();

View File

@@ -43,21 +43,56 @@ p1 {
border: solid #1f82d3 2px; border: solid #1f82d3 2px;
border-radius: 10px; border-radius: 10px;
width: 90%; width: 90%;
} }
.statusText{ .statusText{
font-size: 20px; font-size: 20px;
} }
/* body{
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-content: center;
} */
#randomShit{
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-content: center;
border: 2px solid purple;
}
#nodeDataLocation{
display: flex;
flex-direction: column;
align-items: center;
/* justify-content: center; */
/* align-content: center; */
border: 4px solid blue;
/* padding-bottom: 50%; */
}
.flex-NodeData { .flex-NodeData {
display: flex; display: flex;
margin-left: 1%; margin-left: 1%;
margin-right: 1%; margin-right: 1%;
width: 100%; justify-content: space-evenly;
height: 40%; /* height: 40%; */
flex-direction: column; flex-direction: column;
border: 3px solid #1f82d3; border: 3px solid #1f82d3;
border-radius: 20px; /* border-radius: 20px; */
/* border: 2px solid red; */
/* margin-right: 90%; */
/* width: 150vh; */
/* padding-right: 40%; */
/* padding-left: 40%; */
} }
.nodeData { .nodeData {
@@ -78,6 +113,8 @@ justify-content: left;
justify-content: space-evenly; justify-content: space-evenly;
gap: 5px; gap: 5px;
padding: 10px; padding: 10px;
} }
@@ -89,6 +126,8 @@ justify-content: left;
border-radius: 10px; border-radius: 10px;
height: fit-content; height: fit-content;
width: 30%; width: 30%;
} }
.flex-graph { .flex-graph {