From ed54bda6c3926cfcc52321f34d34f0100a965a45 Mon Sep 17 00:00:00 2001 From: Anirudh Madhusudhan Date: Sun, 21 Apr 2024 09:50:41 +0200 Subject: [PATCH] Added functionality to get and send JSON --- Hardware/Sensors/Sensors.ino | 23 +++++------- Hardware/Server/index.html | 1 + Hardware/Server/server.py | 62 ++++++++++++++++----------------- Hardware/getpostSampleClient.py | 20 ++++++++++- 4 files changed, 60 insertions(+), 46 deletions(-) diff --git a/Hardware/Sensors/Sensors.ino b/Hardware/Sensors/Sensors.ino index 30d9d5b..22fd8a1 100644 --- a/Hardware/Sensors/Sensors.ino +++ b/Hardware/Sensors/Sensors.ino @@ -1,31 +1,26 @@ -//https://gist.github.com/xxlukas42/7e7e18604f61529b8398f7fcc5785251 #ifdef __cplusplus extern "C" { #endif -uint8_t temprature_sens_read(); +uint8_t temperature_sens_read(); #ifdef __cplusplus } #endif -uint8_t temprature_sens_read(); void setup() { - // put your setup code here, to run once: - Serial.begin(115200); + Serial.begin(115200); // Initialize serial communication at 115200 bits per second } void loop() { - // put your main code here, to run repeatedly: - int measurement = 0; - measurement = hallRead(); + // Read the value from the Hall sensor + int measurement = hallRead(); Serial.print("Hall sensor measurement: "); - Serial.println(measurement); - + Serial.println(measurement); + // Read and display the temperature from the onboard sensor Serial.print("Temperature: "); - - // Convert raw temperature in F to Celsius degrees - Serial.print((temprature_sens_read() - 32) / 1.8); + float temperature = (temperature_sens_read() - 32) / 1.8; // Assuming the reading is in Fahrenheit + Serial.print(temperature); Serial.println(" C"); - delay(500); + delay(500); // Wait for half a second before the next read } diff --git a/Hardware/Server/index.html b/Hardware/Server/index.html index 55a6337..d5fc8cf 100644 --- a/Hardware/Server/index.html +++ b/Hardware/Server/index.html @@ -6,5 +6,6 @@

MangoPi

TWe are HSRWMangoPi. We chose challenge#1 and decided to explore the topic of Urban Innovation with Open Data. For this we plan on training an ML model to model the risk for drivers based on static and dynamic conditions. We ultimately aim to use the data to create policies for better traffic conditions and practices.

Post page + \ No newline at end of file diff --git a/Hardware/Server/server.py b/Hardware/Server/server.py index de40445..1affa6d 100644 --- a/Hardware/Server/server.py +++ b/Hardware/Server/server.py @@ -1,50 +1,50 @@ from http.server import BaseHTTPRequestHandler, HTTPServer import json +import logging class RequestHandler(BaseHTTPRequestHandler): - def _set_headers(self): - self.send_response(200) + + def _set_headers(self, status=200): + self.send_response(status) self.send_header('Content-type', 'application/json') self.end_headers() - # def do_POST(self): - # content_length = int(self.headers['Content-Length']) - # post_data = self.rfile.read(content_length) - # sensor_data = json.loads(post_data.decode('utf-8')) - - # # Process sensor data - # print("Received sensor data:", sensor_data) - - # self._set_headers() - # response = json.dumps({'message': 'Data received successfully'}) - # self.wfile.write(response.encode('utf-8')) - def do_POST(self): - content_length = int(self.headers['Content-Length']) - post_data = self.rfile.read(content_length) - sensor_data = json.loads(post_data.decode('utf-8')) - - # Process sensor data - print("Received sensor data:", sensor_data) - - self._set_headers() - - # Include the sent data in the response - response_message = {'message': 'Data received successfully', 'sent_data': sensor_data} - response = json.dumps(response_message) - - self.wfile.write(response.encode('utf-8')) + try: + content_length = int(self.headers['Content-Length']) # Get the size of data + post_data = self.rfile.read(content_length) # Read the data + sensor_data = json.loads(post_data.decode('utf-8')) # Decode and convert from JSON + + logging.info("Received sensor data: %s", sensor_data,) # Log the received data + + self._set_headers() + # Include the sent data in the response + response_message = {'message': 'Data received successfully', 'sent_data': sensor_data} + response = json.dumps(response_message) + self.wfile.write(response.encode('utf-8')) + + except json.JSONDecodeError: + self._set_headers(400) + response = json.dumps({'message': 'Invalid JSON received'}) + self.wfile.write(response.encode('utf-8')) + logging.error("Invalid JSON received.") + except Exception as e: + self._set_headers(500) + response = json.dumps({'message': 'Server error'}) + self.wfile.write(response.encode('utf-8')) + logging.error("Error processing request: %s", str(e)) def do_GET(self): self._set_headers() - response = json.dumps({'message': 'GET request received successfully'}) + response = json.dumps({'Sensor_data': 'Woa! There should be some data here.'}) self.wfile.write(response.encode('utf-8')) def run(server_class=HTTPServer, handler_class=RequestHandler, port=8080): + logging.basicConfig(style='{', format='{asctime} {levelname} {message}', level=logging.INFO) server_address = ('', port) httpd = server_class(server_address, handler_class) - print(f"Server running on port {port}") + logging.info("Server running on port %d", port) # Log the server start httpd.serve_forever() if __name__ == "__main__": - run() \ No newline at end of file + run() diff --git a/Hardware/getpostSampleClient.py b/Hardware/getpostSampleClient.py index 68515cc..6686ef2 100644 --- a/Hardware/getpostSampleClient.py +++ b/Hardware/getpostSampleClient.py @@ -21,14 +21,32 @@ url = "http://127.0.0.1:8080/" # Change this to your server's address # Send multiple POST requests with sensor data readings +print("Sending sensor data to server: ", sensor_data_list) +post_response = requests.post(url, json=sensor_data_list) +if post_response.status_code == 200: + print("POST request successful") + print("Server response:", post_response.json()) +else: + print("Error:", post_response.status_code) + + + for sensor_data in sensor_data_list: - post_response = requests.post(url, json=sensor_data) + + send_data = json.dumps({ + sensor_data: sensor_data_list[sensor_data], + }) + + print("Sending sensor data to server: ", send_data) + post_response = requests.post(url, json=send_data) + if post_response.status_code == 200: print("POST request successful") print("Server response:", post_response.json()) else: print("Error:", post_response.status_code) + # Send a GET request to retrieve all stored sensor data get_response = requests.get(url)