From 7e2211dc50f438faa56881b3d1aa40e4829a1888 Mon Sep 17 00:00:00 2001 From: nmascrie Date: Wed, 5 Mar 2025 15:21:57 +0100 Subject: [PATCH] Rewrote server to work with Serial rather than Wifi (missing Wifi component on the Arduino) --- .gitignore | 1 + ArduinoCube/ArduinoCube.ino | 46 +++++++++++---------- ArduinoCube/arduino_secrets.h | 8 ++-- secret | 0 server.py | 77 ++++++++++++----------------------- 5 files changed, 56 insertions(+), 76 deletions(-) create mode 100644 secret diff --git a/.gitignore b/.gitignore index e69de29..ac180d6 100644 --- a/.gitignore +++ b/.gitignore @@ -0,0 +1 @@ +ArduinoCube/arduino_secrets.h diff --git a/ArduinoCube/ArduinoCube.ino b/ArduinoCube/ArduinoCube.ino index 54ebada..5b77dbb 100644 --- a/ArduinoCube/ArduinoCube.ino +++ b/ArduinoCube/ArduinoCube.ino @@ -12,8 +12,8 @@ */ #include -//#include #include "arduino_secrets.h" +#include #define TRIGG_BOTTOM D12 #define TRIGG_TOP D10 @@ -41,21 +41,6 @@ int status = STATUS_SAFE; int ledState = LOW; -//please enter your sensitive data in the Secret tab -//char ssid[] = SECRET_SSID; // your network SSID (name) -//char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) - -unsigned long previousMillis = 0; - -const long intervalLong = 750; -const long intervalMedLo = 250; -const long intervalMed = 150; -const long intervalMedSho = 80; -const long intervalShort = 20; - -const int trigger = 12; -const int echo = 11; - //std::string sides[6]; std::string sides[6] = {"Bottom", "Top", "Right", "Front", "Left", "Back"}; @@ -71,10 +56,14 @@ void setup() { Serial.begin(9600); Serial.println("Starting up"); + while (!Serial); + Serial.println("Serial connected."); if (!APDS.begin()) { Serial.println("Error initializing APDS-9960 sensor!"); while (1); } + + pinMode(LED_BUILTIN, OUTPUT); //Init the sensors @@ -114,26 +103,41 @@ int fire_sensor(int trigger, int echo) return (dist); } +/** + * Sends the data to the server. +*/ +void send_JSON() +{ + std::string json = "{"; + json += "\"" + sides[0] + "\":" + std::to_string(distances[0]) + ","; + json += "\"" + sides[1] + "\":" + std::to_string(distances[1]) + ","; + json += "\"" + sides[2] + "\":" + std::to_string(distances[2]) + ","; + json += "\"" + sides[3] + "\":" + std::to_string(distances[3]) + ","; + json += "\"" + sides[4] + "\":" + std::to_string(distances[4]) + ","; + json += "\"" + sides[5] + "\":" + std::to_string(distances[5]) + ""; + json += "}"; + + Serial.println(json.c_str()); +} + void loop() { unsigned long currentMillis = millis(); - Serial.print("Measure number "); - Serial.println(count); distances[0] = fire_sensor(TRIGG_BOTTOM, ECHO_BOTTOM); distances[1] = fire_sensor(TRIGG_TOP, ECHO_TOP); distances[2] = fire_sensor(TRIGG_1, ECHO_1); distances[3] = fire_sensor(TRIGG_2, ECHO_2); distances[4] = fire_sensor(TRIGG_3, ECHO_3); distances[5] = fire_sensor(TRIGG_4, ECHO_4); - - for (int i = 0; i < 6; i++) + send_JSON(); + /*for (int i = 0; i < 6; i++) { Serial.print("Sensor {"); Serial.print(sides[i].c_str()); Serial.print("} : "); Serial.print(distances[i]); Serial.println("cm"); - } + }*/ //update_status(distance); // wait a bit before reading again diff --git a/ArduinoCube/arduino_secrets.h b/ArduinoCube/arduino_secrets.h index 3768ab5..ccaa6a7 100644 --- a/ArduinoCube/arduino_secrets.h +++ b/ArduinoCube/arduino_secrets.h @@ -1,5 +1,5 @@ -#define SSID "Non" -#define PASS "Non" -#define SERV_ADDR "Non" -#define SERV_PORT "Non" +#define SSID "42LeHavre_guest" +#define PASS "" +#define SERV_ADDR "10.11.3.3" +#define SERV_PORT 8080 #define AI_KEY "Non" \ No newline at end of file diff --git a/secret b/secret new file mode 100644 index 0000000..e69de29 diff --git a/server.py b/server.py index 75cfc8b..812a74e 100644 --- a/server.py +++ b/server.py @@ -1,57 +1,32 @@ -#!/usr/bin/env python3 -""" -License: MIT License -Copyright (c) 2023 Miel Donkers - -Very simple HTTP server in python for logging requests -Usage:: - ./server.py [] -""" -from http.server import BaseHTTPRequestHandler, HTTPServer -import logging +import serial +import requests import json -class S(BaseHTTPRequestHandler): - def _set_response(self): - self.send_response(200) - self.send_header('Content-type', 'text/html') - self.end_headers() +# Adjust this to match your serial port +SERIAL_PORT = "/dev/ttyACM0" # Linux/macOS (Check with `ls /dev/tty*`) +# SERIAL_PORT = "COM3" # Windows (Check with Device Manager) +BAUD_RATE = 115200 +SERVER_URL = "http://127.0.0.1:8080" # Change to your server's IP if needed - def do_GET(self): - logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers)) - self._set_response() - self.wfile.write("GET request for {}".format(self.path).encode('utf-8')) +# Open Serial Connection +ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) +print(f"Listening on {SERIAL_PORT}...") - def do_POST(self): - content_length = int(self.headers['Content-Length']) - post_data = self.rfile.read(content_length) - - # Parse JSON - try: - data = json.loads(post_data.decode('utf-8')) - logging.info("Received data: %s", data) - except json.JSONDecodeError: - logging.error("Failed to decode JSON") - - self._set_response() - self.wfile.write("Received JSON data".encode('utf-8')) - -def run(server_class=HTTPServer, handler_class=S, port=8080): - logging.basicConfig(level=logging.INFO) - server_address = ('', port) - httpd = server_class(server_address, handler_class) - logging.info('Starting httpd...\n') +while True: try: - httpd.serve_forever() + if ser.in_waiting > 0: + data = ser.readline().decode("utf-8").strip() + print("Received:", data) + + # Validate JSON + try: + json_data = json.loads(data) + # Send data to HTTP server + print("Server response:", json_data) + except json.JSONDecodeError: + print("Invalid JSON received:", data) + except KeyboardInterrupt: - pass - httpd.server_close() - logging.info('Stopping httpd...\n') - -if __name__ == '__main__': - from sys import argv - - if len(argv) == 2: - run(port=int(argv[1])) - else: - run() \ No newline at end of file + print("\nClosing Serial Connection...") + ser.close() + break \ No newline at end of file