temp. sensing at philipps desk, send to python and to influxdb

This commit is contained in:
Eilon Zohar 2025-07-01 10:46:47 +02:00
parent 7275a716bc
commit 513d4a0188
4 changed files with 161 additions and 9 deletions

View File

@ -19,6 +19,7 @@ void resetSensor() {
// Configure MAC address and IP:
byte mac[] = {0x61, 0x2C, 0xF2, 0x09, 0x73, 0xBE};
char T[20];
// the real one IPAddress ip(10, 11, 1, 22); // Static IP
@ -27,7 +28,7 @@ byte mac[] = {0x61, 0x2C, 0xF2, 0x09, 0x73, 0xBE};
#define W5500_CS_PIN 10 // 8 in E LEGO
#define W5500_RST_PIN 9 //10 in E LEGO
IPAddress serverIP(10, 44, 1, 238); // Computer
IPAddress W5500_ip(10, 11, 1, 22); // Change the last digit
IPAddress W5500_ip(10, 44, 1, 22); // Change the last digit
// Don't change
const int port = 5005;
@ -76,24 +77,37 @@ void setup() {
Serial.println(Ethernet.localIP());
// Send a message through socket
Serial.print("Sending test message");
Serial.println("Sending test message");
delay (1000);
if (client.connect (serverIP, port)) {
client.write("test");
client.stop();
Serial.print("Test Message sent");
Serial.println("Test Message sent");
} else {
Serial.print("Connection failed");}
Serial.println("Connection failed");}
}
void loop() {
// put your main code here, to run repeatedly:
// Measure temp. and humidity every 5 seconds
delay (30000);
float t = sht31.readTemperature();
float h = sht31.readHumidity();
// Send to Eilon's computer
if (!isnan(h)) {
Serial.print("Humidity = "); Serial.println(h); }
if (client.connect (serverIP, port)) {
if (!isnan(t)) {
dtostrf(t, 6, 2, T);
client.write(T);
client.stop(); }
} else {
Serial.println("Connection failed");}
}

View File

@ -0,0 +1,28 @@
import socket
import time
from datetime import datetime
import pandas as pd
import os
ip = "0.0.0.0" # Listen to all channels
port = 5005 # Should match .ino
time.sleep (5)
Data_to_influx = pd.DataFrame ({"Date": [], "Time": [], "Temperature": []})
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((ip, port))
s.listen()
print(f"Listening")
while True:
conn, addr = s.accept()
with conn:
data = conn.recv(1024)
if data:
print(f"Received from {addr} at {datetime.now()}: {data.decode().strip()}")
row = pd.DataFrame ({"Date": [str (datetime.now()) [:10]], "Time": [str (datetime.now()) [11:19]], "Temperature": [data.decode().strip()]})
Data_to_influx = pd.concat ([Data_to_influx, row], ignore_index= 1)
csv_file_name = "C:/Users/Iluz1/Desktop/Data/a.csv"
Data_to_influx.to_csv (csv_file_name)

View File

@ -0,0 +1,109 @@
#region import libraries
import socket
import time
from datetime import datetime
import pandas as pd
import os
import logging
import influxdb_client
from influxdb_client.client.influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS, WriteApi
from pyModbusTCP.client import ModbusClient
#endregion
# Update interval in seconds
update_interval = 30
# Tell the computer from where to read data
ip = "0.0.0.0"
port = 5005
# InfluxDB settings
BUCKET = "Data_FerDy"
ORG = "QF"
TOKEN = "hm_S3eCnpU72215MwHyDYljHpvw7bxtxtRhEJmUkeBTa1wEJsGv02kZF1jwaMJ2Jeo-gY-57kOQEDTP8bOc0Fg=="
URL = "http://smartlab.physi.uni-heidelberg.de:8086/"
#region define functions
def init_influxdb(url: str, token: str, org: str):
"""initiate influxDB client"""
client = influxdb_client.InfluxDBClient(
url=url,
token=token,
org=org)
write_api = client.write_api(write_options=SYNCHRONOUS)
print('InfluxDB client and influx write_API started.')
return client, write_api
def write_data_to_influxDB(influx_client: InfluxDBClient, write_api: WriteApi, record):
"""check if influxDB is alive and write data to influxDB, else start influxDB client"""
try:
# check if influxDB is ready
influx_client.ping()
# write data points
write_api.write(bucket=BUCKET, org=ORG, record=record)
print('Data written to influxDB.')
except:
print('InfluxDB ping not successful. InfluxDB cannot be reached.')
try:
# try to open the influx DB client and write API
influx_client, write_api = init_influxdb(URL, TOKEN, ORG)
except Exception as e:
print('Error with InfluxDB: {}'.format(e))
print('Data not written.')
time.sleep(10)
return influx_client, write_api
def setup_logger(logName):
# creat logger
log_dir = "logs"
os.makedirs(log_dir, exist_ok=True)
# setup logging
log_file = os.path.join(log_dir, f"%s - {datetime.now():%Y-%m-%d}.log" %logName)
logging.basicConfig(
filename=log_file,
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
encoding="utf-8"
)
# sync output to termianl
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logging.getLogger().addHandler(console)
# example
logging.info("Logger set up complete")
#endregion
def read_temp (ip, port, influx_client, write_api):
with socket.socket (socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind ((ip, port))
s.listen()
# print ("Listening")
conn, addr = s.accept()
with conn:
data = conn.recv (1024)
return data.decode().strip()
if __name__ == "__main__":
influx_client, write_api = init_influxdb(URL, TOKEN, ORG)
setup_logger ("PhillipsDeskTemp.")
logging.info ("Reading the temperature on Phillip's desk")
while 1:
T = read_temp (ip, port, influx_client, write_api)
if (T is not None and T != "test"):
T = float (T)
p1 = influxdb_client.Point ("Office").tag("Table", "Phillip's").field ("temp_on_desk", T)
influx_client, write_api = write_data_to_influxDB (influx_client, write_api, p1)
time.sleep (update_interval)

View File

@ -1,5 +1,6 @@
import socket
import time
from datetime import datetime
ip = "0.0.0.0" # Listen to all channels
port = 5005 # Should match .ino
@ -17,5 +18,5 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
with conn:
data = conn.recv(1024)
if data:
print(f"Received from {addr}: {data.decode().strip()}")
print(f"Received from {addr} at {datetime.now()}: {data.decode().strip()}")