hanze/muizenval

renamed to remote, extend remote-client (22fbacd6518658e8762f0f222e59b4260983ded1)
Repositories

commit 22fbacd6518658e8762f0f222e59b4260983ded1
parent d58c1a861f91a9ba3090305198baada78c2bd26a
Author: Friedel Schön <[email protected]>
Date:   Fri, 17 Jun 2022 09:19:02 +0200

renamed to remote, extend remote-client

Diffstat:
M5g-client/5g-client.ino62+++++++++++++++++++++++++++++++++++---------------------------
D5g-client/include/passthrough.h18------------------
A5g-client/include/remote.h18++++++++++++++++++
D5g-client/passthrough.ino69---------------------------------------------------------------------
A5g-client/remote.ino69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dpassthough.py50--------------------------------------------------
Aremote.py54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtest-server.py35++++++++++++++++++++++++++++-------
8 files changed, 204 insertions(+), 171 deletions(-)

diff --git a/5g-client/5g-client.ino b/5g-client/5g-client.ino @@ -1,6 +1,6 @@ #include "include/config.h" #include "include/modem.h" -#include "include/passthrough.h" +#include "include/remote.h" #include <Sodaq_LSM303AGR.h> #include <Sodaq_UBlox_GPS.h> @@ -10,11 +10,13 @@ #define BATVOLT_R2 10.0f #define BATVOLT_PIN BAT_VOLT +#define statusDelay 5 // seconds + #define batteryFactor 0.978 / ADC_AREF*(BATVOLT_R1 / BATVOLT_R2 + 1) // sara_modem modem; Sodaq_LSM303AGR accel; -passthrough pass; +remote pass; void setup() { // -*- hardware initiation -*- @@ -38,7 +40,7 @@ void setup() { // Enable the Accelerometer accel.enableAccelerometer(); - pass.connect("muizenval.tk", 80); + pass.connect("127.0.0.1", 5000); // modem.send("ATE0"); // disable command-echo @@ -99,12 +101,12 @@ void setup() { modem.send("AT+UHTTPC=0,5,\"/api/search_connect\",\"\",\"TEST!\",1");*/ - // usbSerial.println(prefixInfo "initiation completed, starting passthrough:"); + // usbSerial.println(prefixInfo "initiation completed, starting remote:"); } void loop() { - /* // -*- passthrough for custom commands -*- + /* // -*- remote for custom commands -*- while (usbSerial.available()) modemSerial.write(usbSerial.read()); @@ -119,31 +121,37 @@ void loop() { // usbSerial.println(buffer); }*/ - static double lat = 0, lon = 0, accuracy = 0; + static int last = 0; + int now = millis(); - if (sodaq_gps.scan(true, 10000)) { - lat = sodaq_gps.getLat(); - lon = sodaq_gps.getLon(); - accuracy = 1.0 / sodaq_gps.getHDOP() * 100; - // -> 100% the best, 0% the worst - // usbSerial.print(sodaq_gps.getLat(), 13); - // usbSerial.print(" - "); - // usbSerial.print(sodaq_gps.getLon(), 13); - // usbSerial.print(" ~ accuracy "); - // usbSerial.print(1.0 / sodaq_gps.getHDOP() * 100, 1); - // usbSerial.println("%"); - } + static double lat = 0, lon = 0, accuracy = 0; - passthrough::http_packet req, res; - req.method = "POST"; - req.endpoint = "/api/update"; - req.body["latitude"] = lat; - req.body["longitude"] = lon; - req.body["accuracy"] = accuracy; - req.body["battery"] = batteryVoltage(); - req.body["temperature"] = temperature(); + if (now - last > statusDelay * 1000) { + if (sodaq_gps.scan(true, 10000)) { + lat = sodaq_gps.getLat(); + lon = sodaq_gps.getLon(); + accuracy = 1.0 / sodaq_gps.getHDOP() * 100; + // -> 100% the best, 0% the worst + // usbSerial.print(sodaq_gps.getLat(), 13); + // usbSerial.print(" - "); + // usbSerial.print(sodaq_gps.getLon(), 13); + // usbSerial.print(" ~ accuracy "); + // usbSerial.print(1.0 / sodaq_gps.getHDOP() * 100, 1); + // usbSerial.println("%"); + } - pass.send(req); + remote::http_packet req, res; + req.method = "POST"; + req.endpoint = "/api/update"; + req.body["latitude"] = lat; + req.body["longitude"] = lon; + req.body["accuracy"] = accuracy; + req.body["battery"] = batteryVoltage(); + req.body["temperature"] = temperature(); + + pass.send(req); + last = now; + } // usbSerial.print(batteryVoltage()); // usbSerial.println("V battery"); diff --git a/5g-client/include/passthrough.h b/5g-client/include/passthrough.h @@ -1,17 +0,0 @@ -#pragma once - -#include <Arduino_JSON.h> - -struct passthrough { - struct http_packet { - const char* method; - const char* endpoint; - JSONVar headers; - JSONVar body; - }; - - void init(); - void connect(const char* host, int port); - const char* send(http_packet request, http_packet& response); - const char* send(http_packet request); -}; -\ No newline at end of file diff --git a/5g-client/include/remote.h b/5g-client/include/remote.h @@ -0,0 +1,17 @@ +#pragma once + +#include <Arduino_JSON.h> + +struct remote { + struct http_packet { + const char* method; + const char* endpoint; + JSONVar headers; + JSONVar body; + }; + + void init(); + void connect(const char* host, int port); + const char* send(http_packet request, http_packet& response); + const char* send(http_packet request); +}; +\ No newline at end of file diff --git a/5g-client/passthrough.ino b/5g-client/passthrough.ino @@ -1,69 +0,0 @@ -#include "include/config.h" -#include "include/passthrough.h" - -JSONVar readJSON() { - char line[lineBuffer]; - char buf; - int i = 0; - for (;;) { - while (!usbSerial.available()) - ; - buf = usbSerial.read(); - if (buf == '\r') - continue; - if (buf == '\n') - break; - line[i++] = buf; - } - line[i++] = '\0'; - - return JSON.parse(line); -} - -void passthrough::init() { - usbSerial.println("{\"command\":\"hello\"}"); - JSONVar res_json = readJSON(); - if (res_json["error"] != nullptr) { - // :( - } -} - -void passthrough::connect(const char* host, int port) { - JSONVar body; - body["command"] = "connect"; - body["host"] = host; - body["port"] = port; - - usbSerial.println(body); -} - -const char* passthrough::send(http_packet request, http_packet& response) { - JSONVar body; - body["command"] = "send"; - body["method"] = request.method; - body["endpoint"] = request.endpoint; - body["headers"] = request.headers; - body["body"] = request.body; - usbSerial.println(body); - - JSONVar res_json = readJSON(); - response.body = res_json["body"]; - response.headers = res_json["headers"]; - - return res_json["error"]; -} - - -const char* passthrough::send(http_packet request) { - JSONVar body; - body["command"] = "send"; - body["method"] = request.method; - body["endpoint"] = request.endpoint; - body["headers"] = request.headers; - body["body"] = request.body; - usbSerial.println(body); - - JSONVar res_json = readJSON(); - - return res_json["error"]; -} diff --git a/5g-client/remote.ino b/5g-client/remote.ino @@ -0,0 +1,69 @@ +#include "include/config.h" +#include "include/remote.h" + +JSONVar readJSON() { + char line[lineBuffer]; + char buf; + int i = 0; + for (;;) { + while (!usbSerial.available()) + ; + buf = usbSerial.read(); + if (buf == '\r') + continue; + if (buf == '\n') + break; + line[i++] = buf; + } + line[i++] = '\0'; + + return JSON.parse(line); +} + +void remote::init() { + usbSerial.println("{\"command\":\"hello\"}"); + JSONVar res_json = readJSON(); + if (res_json["error"] != nullptr) { + // :( + } +} + +void remote::connect(const char* host, int port) { + JSONVar body; + body["command"] = "connect"; + body["host"] = host; + body["port"] = port; + + usbSerial.println(body); +} + +const char* remote::send(http_packet request, http_packet& response) { + JSONVar body; + body["command"] = "send"; + body["method"] = request.method; + body["endpoint"] = request.endpoint; + body["headers"] = request.headers; + body["body"] = request.body; + usbSerial.println(body); + + JSONVar res_json = readJSON(); + response.body = res_json["body"]; + response.headers = res_json["headers"]; + + return res_json["error"]; +} + + +const char* remote::send(http_packet request) { + JSONVar body; + body["command"] = "send"; + body["method"] = request.method; + body["endpoint"] = request.endpoint; + body["headers"] = request.headers; + body["body"] = request.body; + usbSerial.println(body); + + JSONVar res_json = readJSON(); + + return res_json["error"]; +} diff --git a/passthough.py b/passthough.py @@ -1,50 +0,0 @@ -from http.client import HTTPConnection -from typing import Optional - -import serial -import sys -import json - -if len(sys.argv) < 2: - print(f'{sys.argv[0]} <port>') - -serial_port = serial.Serial(port=sys.argv[1], baudrate=115200) - -client: Optional[HTTPConnection] = None - -def handle(req): - global client - - if 'command' not in req: - return 'command ommitted' - elif req['command'] == 'hello': - return None - elif req['command'] == 'connect': - client = HTTPConnection(req['host'], req['port']) - elif req['command'] == 'send': - if client is None: - return 'not connected' - client.request(req['method'], req['endpoint'], json.dumps(req['body']), req['headers'] or {}) - res = client.getresponse() - return { 'code': res.status, 'headers': dict(res.headers), 'body': json.load(res) } - else: - return 'unknown command' - -while serial_port.is_open: - req = json.loads(serial_port.readline()) - - print('-> ' + repr(req)) - res = handle(req) - - if type(res) == str: - res = { "error": res } - elif res is None: - res = { "error": None } - elif type(res) == dict: - if 'error' not in res: - res['error'] = None - else: - res = { "error": None, "value": res } - print('<- ' + repr(res)) - - serial_port.write((json.dumps(res) + '\n').encode()) diff --git a/remote.py b/remote.py @@ -0,0 +1,54 @@ +from http.client import HTTPConnection +from typing import Optional + +import serial +import sys +import json + +if len(sys.argv) < 2: + print(f'{sys.argv[0]} <port>') + +serial_port = serial.Serial(port=sys.argv[1], baudrate=115200) + +client: Optional[HTTPConnection] = None + +def handle(req): + global client + + if 'command' not in req: + return 'command ommitted' + elif req['command'] == 'hello': + return None + elif req['command'] == 'connect': + client = HTTPConnection(req['host'], req['port']) + elif req['command'] == 'send': + headers = req['headers'] or {} + headers['Content-Type'] = 'application/json' + if client is None: + return 'not connected' + client.request(req['method'], req['endpoint'], json.dumps(req['body']), headers) + res = client.getresponse() + return { 'code': res.status, 'headers': dict(res.headers), 'body': json.load(res) } + else: + return 'unknown command' + +while serial_port.is_open: + try: + req = json.loads(serial_port.readline()) + print('-> ' + repr(req)) + res = handle(req) + except Exception as e: + res = { 'error': 'internal', 'description': str(e) } + + if type(res) == str: + res = { "error": res } + elif res is None: + res = { "error": None } + elif type(res) == dict: + if 'error' not in res: + res['error'] = None + else: + res = { "error": None, "value": res } + print('<- ' + repr(res)) + + serial_port.write((json.dumps(res) + '\n').encode()) diff --git a/test-server.py b/test-server.py @@ -10,7 +10,7 @@ battery = 0 temperature = 0 [email protected]("/api/update", methods=['POST']) [email protected]("/api/update") def update(): global latitude, longitude, accuracy, battery, temperature @@ -25,12 +25,33 @@ def update(): return {"error": "request must be json"}, 415 [email protected]("/") [email protected]("/") def index(): return f''' - <p>latitude: {latitude}</p> - <p>longitude: {longitude}</p> - <p>accuracy: {accuracy}</p> - <p>battery: {battery}</p> - <p>temperature: {temperature}</p> + <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" + integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ==" + crossorigin=""/> + <script src="https://unpkg.com/[email protected]/dist/leaflet.js" + integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ==" + crossorigin=""></script> + + <h1>Status update</h1> + <p>latitude: <code>{latitude:.10f}</code></p> + <p>longitude: <code>{longitude:.10f}</code></p> + <p>accuracy: <code>{accuracy:.2f}%</code></p> + <p>battery: <code>{battery}V</code></p> + <p>temperature: <code>{temperature}&deg;c</code></p> + + <div id="map" style='height: 50%;'></div> + + <script type="text/javascript"> + var map = L.map('map').setView([52.283333, 5.666667], 7); + L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png', {{ + maxZoom: 19, + attribution: '© OpenStreetMap' + }}).addTo(map); + var marker = L.marker([{latitude}, {longitude}]).addTo(map); + </script> ''' + +app.run('0.0.0.0', 5000)