Add first Code

This commit is contained in:
Mueller Wayan
2025-09-13 18:31:40 +02:00
commit b0a9af64ad
11 changed files with 1264 additions and 0 deletions
+148
View File
@@ -0,0 +1,148 @@
/*
Web client
This sketch connects to a website (http://www.google.com)
using an Arduino WIZnet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe, based on work by Adrian McEwen
*/
#include <SPI.h>
#include <Wire.h>
#include "rgb_lcd.h"
#include <Ethernet.h>
#include <EthernetUdp.h>
#include "SBB_Request.h"
rgb_lcd lcd;
const int colorR = 0;
const int colorG = 0;
const int colorB = 170;
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
// name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);
IPAddress myDns(192, 168, 0, 1);
EthernetUDP udp;
NTPClient timeClient(udp, "pool.ntp.org", 0);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
// Variables to measure the speed
unsigned long beginMicros, endMicros;
unsigned long byteCount = 0;
bool printWebData = true; // set to false for better speed measurement
Sbb_Connection sbbConnection;
void setup() {
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH Shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// try to configure using IP address instead of DHCP:
Ethernet.begin(mac, ip, myDns);
} else {
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
// give the Ethernet shield a second to initialize:
delay(1000);
sbbConnection.initialize(&client, &timeClient);
sbbConnection.setDepStation("St.Gallen Hochwacht");
sbbConnection.setDestStation("St. Gallen, Bahnhof");
sbbConnection.setRequestedDepartures(2);
sbbConnection.setRefreshCycle(30000);
sbbConnection.onRefresh = refresh;
lcd.begin(16, 2);
lcd.setRGB(colorR, colorG, colorB);
}
void refresh(Departure departures[], int numberOfDepartures){
Serial.println("Auswertung:");
lcd.clear();
lcd.setCursor(0, 0);
//Serial.println((int)departures);
for(int i = 0; i < numberOfDepartures; i++){
//Serial.println(departures[i].departureTime.year);
if(departures[i].departureTime.year != 0){
lcd.print(departures[i].Name);
lcd.setCursor(7, 0);
String lcdString = "";
if(departures[i].departureTime.houre < 10) lcdString.concat("0");
lcdString.concat(departures[i].departureTime.houre);
lcdString.concat(":");
if(departures[i].departureTime.minute < 10) lcdString.concat("0");
lcdString.concat(departures[i].departureTime.minute);
lcd.print(lcdString);
lcd.setCursor(13, 0);
lcdString = "";
if(departures[i].minutesUntilDeparture < 10 && departures[i].minutesUntilDeparture > 0) lcdString.concat("0");
lcdString.concat(departures[i].minutesUntilDeparture);
lcdString.concat("'");
lcd.print(lcdString);
Serial.print("Bus: ");
Serial.print(departures[i].Name);
Serial.print(" Time: ");
Serial.print(departures[i].departureTime.houre);
Serial.print(":");
Serial.print(departures[i].departureTime.minute);
Serial.print(" in ");
Serial.println(departures[i].minutesUntilDeparture);
}
}
Serial.println("Auswertung Ende");
}
void loop() {
sbbConnection.work();
}
+269
View File
@@ -0,0 +1,269 @@
#include "WString.h"
#include "SBB_Request.h"
bool bFirst;
void Sbb_Connection::initialize(EthernetClient * ethClient, NTPClient * ntpClient)
{
client = ethClient;
this->ntpClient = ntpClient;
filter["stationboard"][0]["stop"]["departure"] = true;
filter["stationboard"][0]["category"] = true;
filter["stationboard"][0]["number"] = true;
filter["stationboard"][0]["passList"][0]["station"]["name"] = true;
ntpClient->begin();
bFirst = true;
}
Date_Time parseDateTime(String toParse){
Date_Time retval;
int splitidx = toParse.indexOf('-');
retval.year = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf('-');
retval.month = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf('T');
retval.day = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf(':');
retval.houre = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf(':');
retval.minute = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf('+');
retval.seconds = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
retval.offset = toParse.toInt() / 100;
return retval;
}
VehicleType parseVehicleType(String toParse){
return VehicleType::bus;
}
String urlEncode(const char* str) {
String encoded = "";
char c;
while ((c = *str++)) {
// Zulässige Zeichen direkt übernehmen
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encoded += c;
}
// Alle anderen Zeichen URL-encoden
else {
char buf[4];
sprintf(buf, "%%%02X", (unsigned char)c);
encoded += buf;
}
}
return encoded;
}
int calcTimeDelta(int depTime, int acttime){
if(depTime >= acttime){
return depTime -acttime;
}else{
return (60-acttime) + depTime;
}
}
void Sbb_Connection::work(){
switch(state){
case requestState::waitUntilDelayIsOver:
if (bFirst){
lastRequest = millis();
state = requestState::connectandRequest;
bFirst = false;
}
if (millis() - lastRequest >= timeDelay) {
lastRequest = millis();
state = requestState::connectandRequest; // Übergang zu einem anderen Zustand, z. B. Anfrage senden
}
break;
case requestState::connectandRequest:
#ifdef debug
Serial.print("connecting to ");
Serial.print(sbbServer);
Serial.println("...");
#endif
// if you get a connection, report back via serial:
if (client->connect(sbbServer, 80)) {
#ifdef debug
Serial.print("connected to ");
Serial.println(client->remoteIP());
#endif
// Make a HTTP request:
String encodedStation = urlEncode(stationName.c_str());
client->print("GET /v1/stationboard?station=");
client->print(encodedStation);
client->print("&limit=");
client->print(requestedDepartures);
client->println(" HTTP/1.1");
client->println("Host: transport.opendata.ch");
client->println("Connection: close");
client->println(); // Ende der Header
Serial.print("GET /v1/stationboard?station=");
Serial.print(encodedStation);
Serial.println("&limit=5 HTTP/1.1");
Serial.println("Host: transport.opendata.ch");
Serial.println("Connection: close");
Serial.println();
state = requestState::waitForHeader;
} else {
#ifdef debug
// if you didn't get a connection to the server:
Serial.println("connection failed");
#endif
state = requestState::waitUntilDelayIsOver;
}
break;
case requestState::waitForHeader:
while (client->available()) {
buffer[buffercounter++] = client->read();
if (buffercounter >= 4 &&
buffer[buffercounter - 4] == '\r' &&
buffer[buffercounter - 3] == '\n' &&
buffer[buffercounter - 2] == '\r' &&
buffer[buffercounter - 1] == '\n')
{
#ifdef debug
buffer[buffercounter] = '\0';
Serial.print(buffer);
#endif
buffercounter = 0;
state = requestState::waitforAnswer;
break;
}
if (buffercounter >= sizeof(buffer) - 1) {
buffercounter = 0;
state = requestState::waitforAnswer;
break;
}
}
break;
case requestState::waitforAnswer:
if (client->available() > 0) {
DeserializationError error = deserializeJson(doc, *client, DeserializationOption::Filter(filter));
if (error) {
#ifdef debug
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
#endif
state = requestState::waitUntilDelayIsOver;
return;
}
}
if (!client->connected()) {
#ifdef debug
Serial.println();
Serial.println("Verbindung geschlossen");
#endif
while (client->available()) {
buffer[buffercounter++] = client->read();
if (buffercounter >= sizeof(buffer) - 1)
break;
}
buffercounter = 0;
state = requestState::processAnswer;
}
break;
case requestState::processAnswer:
#ifdef debug
serializeJson(doc, Serial);
Serial.println(); // Zeilenumbruch danach, damit alles sauber aussieht
#endif
for (int i = 0; i < requestedDepartures; i++){
depArray[i] = parseDeparture(i);
}
state = requestState::getTime;
break;
case requestState::getTime:
ntpClient->update();
for(int i = 0; i < requestedDepartures; i++){
#ifdef debug
Serial.print("Lesbare Zeit: ");
Serial.print(ntpClient->getHours() + depArray[i].departureTime.offset);
Serial.print(":");
Serial.print(ntpClient->getMinutes());
Serial.print(":");
Serial.println(ntpClient->getSeconds());
#endif
depArray[i].minutesUntilDeparture = calcTimeDelta(depArray[i].departureTime.minute, ntpClient->getMinutes());
}
state = requestState::sendActualisation;
break;
case requestState::sendActualisation:
onRefresh(depArray, requestedDepartures);
state = requestState::waitUntilDelayIsOver;
break;
default:
state = requestState::waitUntilDelayIsOver;
break;
}
}
bool checkDestination(String str1, String str2){
str1.replace(",","");
str1.replace(" ","");
str2.replace(",","");
str2.replace(" ","");
str1.toLowerCase();
str2.toLowerCase();
return str1.equals(str2);
}
Departure Sbb_Connection::parseDeparture(int depIndex){
Departure retval;
bool reachesDestination = false;
JsonObject departure = doc["stationboard"].as<JsonArray>()[depIndex];
for(JsonObject stationentry : departure["passList"].as<JsonArray>()){
if(checkDestination(stationentry["station"]["name"].as<String>(), destinationName)){
reachesDestination = true;
}
}
if (reachesDestination){
retval.departureTime = parseDateTime(departure["stop"]["departure"].as<String>());
#ifdef debug
Serial.print(retval.departureTime.houre);
Serial.print(":");
Serial.print(retval.departureTime.minute);
Serial.print(":");
Serial.print(retval.departureTime.seconds);
Serial.print(":");
Serial.print(retval.departureTime.year);
Serial.print("Ofst:");
Serial.println(retval.departureTime.offset);
#endif
retval.Name = departure["number"].as<String>();
retval.vehicleType = parseVehicleType(departure["category"].as<String>());
}
else{
retval.departureTime = parseDateTime("0000-00-00T00:00:00+0000");
}
return retval;
}
+82
View File
@@ -0,0 +1,82 @@
#ifndef SBB_REQUEST_H
#define SBB_REQUEST_H
#define debug
#include <SPI.h>
#include <Ethernet.h>
#include <ArduinoJson.h>
#include <Arduino.h>
#include <NTPClient.h>
typedef enum{
train,
tram,
ship,
bus,
cableway
} VehicleType;
typedef struct{
int year;
int month;
int day;
int houre;
int minute;
int seconds;
int offset;
} Date_Time;
typedef struct{
VehicleType vehicleType;
String Name;
Date_Time departureTime;
int minutesUntilDeparture;
} Departure;
VehicleType parseVehicleType(String toParse);
Date_Time parseDateTime(String toParse);
class Sbb_Connection{
public:
void initialize(EthernetClient * ethClient, NTPClient * ntpClient);
void work();
void setRefreshCycle(unsigned long milliseconds){timeDelay = milliseconds;};
void setRequestedDepartures(int num){requestedDepartures = num; depArray = new Departure[num];};
void setDepStation(String name){stationName = name;};
void setDestStation(String name){destinationName = name;};
void setVehicleFilter(VehicleType* typeFilter){vehicleTypeFilter = typeFilter;};
void (*onRefresh)(Departure departures[], int numberOfDepartures);
private:
typedef enum {
waitUntilDelayIsOver,
connectandRequest,
waitForHeader,
waitforAnswer,
processAnswer,
getTime,
sendActualisation
} requestState;
char sbbServer[30] = "transport.opendata.ch";
char buffer[512];
StaticJsonDocument<3000> doc;
StaticJsonDocument<256> filter;
unsigned int buffercounter;
requestState state;
unsigned long lastRequest;
EthernetClient* client;
NTPClient * ntpClient;
VehicleType* vehicleTypeFilter;
String destinationName;
int requestedDepartures;
unsigned long timeDelay;
String stationName;
Departure * depArray;
Departure parseDeparture(int depIndex);
};
#endif
View File
+8
View File
@@ -0,0 +1,8 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
"version": "0.2.0",
"configurations": [
]
}
+126
View File
@@ -0,0 +1,126 @@
/*
This sketch shows the Ethernet event usage
*/
#include <ETH.h>
#include "SBB_Request.h"
#include "Sbb_LCD_Screen.h"
#include <Udp.h> // UDP Support
#include <WiFiUdp.h>
#include <NTPClient.h> // NTP Client
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 3600, 60000);
NetworkClient client;
Sbb_Connection sbbConnection;
SBB_LCD sbbLcd;
#ifndef ETH_PHY_CS
#define ETH_PHY_TYPE ETH_PHY_W5500
#define ETH_PHY_ADDR 1
#define ETH_PHY_CS 14
#define ETH_PHY_IRQ 10
#define ETH_PHY_RST 9
#define ETH_PHY_SPI_HOST SPI2_HOST
#define ETH_PHY_SPI_SCK 13
#define ETH_PHY_SPI_MISO 12
#define ETH_PHY_SPI_MOSI 11
#endif
#define MaxNumberOfDepartures 20
static bool eth_connected = false;
void onEvent(arduino_event_id_t event, arduino_event_info_t info) {
switch (event) {
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH Started");
//set eth hostname here
ETH.setHostname("esp32-eth0");
sbbLcd.SetDebugMessages("ETH Started", "");
break;
case ARDUINO_EVENT_ETH_CONNECTED: Serial.println("ETH Connected"); sbbLcd.SetDebugMessages("Connected", ""); break;
case ARDUINO_EVENT_ETH_GOT_IP: Serial.printf("ETH Got IP: '%s'\n", esp_netif_get_desc(info.got_ip.esp_netif)); Serial.println(ETH);
sbbLcd.ResetDebug();
eth_connected = true;
break;
case ARDUINO_EVENT_ETH_LOST_IP:
Serial.println("ETH Lost IP");
sbbLcd.SetDebugMessages("Lost IP", "");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH Disconnected");
sbbLcd.SetDebugMessages("Disconnected", "");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH Stopped");
eth_connected = false;
break;
default: break;
}
}
void task1(void* param){
while(true){
sbbLcd.Work();
}
}
void setup() {
Serial.begin(115200);
sbbLcd.Initalize(MaxNumberOfDepartures);
Network.onEvent(onEvent);
ETH.begin(ETH_PHY_TYPE, ETH_PHY_ADDR, ETH_PHY_CS, ETH_PHY_IRQ, ETH_PHY_RST, ETH_PHY_SPI_HOST, ETH_PHY_SPI_SCK, ETH_PHY_SPI_MISO, ETH_PHY_SPI_MOSI);
delay(1000);
Serial.println("Started");
sbbConnection.initialize(&client, &timeClient);
sbbConnection.setDepStation("St.Gallen Hochwacht");
sbbConnection.setDestStation("St. Gallen, Bahnhof");
sbbConnection.setRequestedDepartures(MaxNumberOfDepartures);
sbbConnection.setRefreshCycle(30000);
sbbConnection.onRefresh = refresh;
xTaskCreate(task1, "LCD_task", 8192, NULL, 2, NULL);
Serial.println("InitEnd");
}
void refresh(Departure departures[], int numberOfDepartures){
Serial.println("Auswertung:");
if(xSemaphoreTake(sbbLcd.lcdMutex, portMAX_DELAY)){
sbbLcd.depEntries = 0;
for(int i = 0; i < numberOfDepartures; i++){
if(departures[i].departureTime.year != 0){
sbbLcd.departures[sbbLcd.depEntries++] = departures[i];
Serial.print("Bus: ");
Serial.print(departures[i].Name);
Serial.print(" Time: ");
Serial.print(departures[i].departureTime.houre);
Serial.print(":");
Serial.print(departures[i].departureTime.minute);
Serial.print(" in ");
Serial.println(departures[i].minutesUntilDeparture);
}
}
sbbLcd.setActualized();
xSemaphoreGive(sbbLcd.lcdMutex);
}
Serial.println("Auswertung Ende");
}
void loop() {
sbbConnection.work(eth_connected);
}
+352
View File
@@ -0,0 +1,352 @@
#include "WString.h"
#include "SBB_Request.h"
bool bFirst;
#define MAX_BODY_SIZE 500 * 1024 // Max 120 KB, abhängig vom PSRAM
char* readChunkedBodyToPsram(Client& client, size_t& outLength) {
char* buffer = (char*)heap_caps_malloc(MAX_BODY_SIZE, MALLOC_CAP_SPIRAM);
if (!buffer) {
Serial.println("Fehler: PSRAM nicht verfügbar oder zu klein.");
return nullptr;
}
size_t totalLength = 0;
String line;
while (client.connected()) {
// Schritt 1: Chunk-Größe lesen
line = client.readStringUntil('\n');
line.trim(); // Entfernt \r und Leerzeichen
if (line.length() == 0) continue;
int chunkSize = (int) strtol(line.c_str(), nullptr, 16);
if (chunkSize == 0) break; // Letzter Chunk
// Sicherheit: nicht mehr als MAX_BODY_SIZE lesen
if (totalLength + chunkSize >= MAX_BODY_SIZE) {
Serial.println("Fehler: JSON zu groß für Puffer!");
heap_caps_free(buffer);
return nullptr;
}
// Schritt 2: Chunk-Inhalt lesen
int bytesRead = 0;
while (bytesRead < chunkSize) {
if (!client.available()) delay(1);
int c = client.read();
if (c < 0) continue;
buffer[totalLength++] = (char)c;
bytesRead++;
}
// Schritt 3: \r\n am Chunk-Ende überspringen
client.read(); // \r
client.read(); // \n
}
// Null-Terminierung (nur für String-Ausgaben oder ArduinoJson)
buffer[totalLength] = '\0';
outLength = totalLength;
return buffer;
}
void Sbb_Connection::initialize(NetworkClient * ethClient, NTPClient * ntpClient)
{
client = ethClient;
this->ntpClient = ntpClient;
filter["stationboard"][0]["stop"]["departure"] = true;
filter["stationboard"][0]["category"] = true;
filter["stationboard"][0]["number"] = true;
filter["stationboard"][0]["passList"][0]["station"]["name"] = true;
ntpClient->begin();
bFirst = true;
}
Date_Time parseDateTime(String toParse){
Date_Time retval;
int splitidx = toParse.indexOf('-');
retval.year = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf('-');
retval.month = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf('T');
retval.day = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf(':');
retval.houre = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf(':');
retval.minute = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
splitidx = toParse.indexOf('+');
retval.seconds = toParse.substring(0,splitidx).toInt();
toParse = toParse.substring(splitidx + 1);
retval.offset = toParse.toInt() / 100;
return retval;
}
VehicleType parseVehicleType(String toParse){
return VehicleType::bus;
}
String urlEncode(const char* str) {
String encoded = "";
char c;
while ((c = *str++)) {
// Zulässige Zeichen direkt übernehmen
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encoded += c;
}
// Alle anderen Zeichen URL-encoden
else {
char buf[4];
sprintf(buf, "%%%02X", (unsigned char)c);
encoded += buf;
}
}
return encoded;
}
int calcTimeDelta(int depTime, int actTime, int depHour, int actHour) {
if (depHour < actHour) depHour += 24;
int deltaMinutes = (depHour * 60 + depTime) - (actHour * 60 + actTime);
return max(deltaMinutes, 0);
}
void Sbb_Connection::work(bool connected){
switch(state){
case requestState::waitUntilDelayIsOver:
if (bFirst && connected){
lastRequest = millis();
state = requestState::connectandRequest;
bFirst = false;
}
if (millis() - lastRequest >= timeDelay && connected) {
lastRequest = millis();
state = requestState::connectandRequest; // Übergang zu einem anderen Zustand, z. B. Anfrage senden
}
break;
case requestState::connectandRequest:
#ifdef debug
Serial.print("connecting to ");
Serial.print(sbbServer);
Serial.println("...");
#endif
// if you get a connection, report back via serial:
if (client->connect(sbbServer, 80)) {
#ifdef debug
Serial.print("connected to ");
Serial.println(client->remoteIP());
#endif
// Make a HTTP request:
String encodedStation = urlEncode(stationName.c_str());
client->print("GET /v1/stationboard?station=");
client->print(encodedStation);
client->print("&limit=");
client->print(requestedDepartures);
client->println(" HTTP/1.1");
client->println("Host: transport.opendata.ch");
client->println("Connection: close");
client->println(); // Ende der Header
Serial.print("GET /v1/stationboard?station=");
Serial.print(encodedStation);
Serial.println("&limit=5 HTTP/1.1");
Serial.println("Host: transport.opendata.ch");
Serial.println("Connection: close");
Serial.println();
state = requestState::waitForHeader;
buffercounter = 0;
} else {
#ifdef debug
// if you didn't get a connection to the server:
Serial.println("connection failed");
#endif
state = requestState::waitUntilDelayIsOver;
}
break;
case requestState::waitForHeader:
while (client->available()) {
char c = client->read();
buffer[buffercounter++] = c;
// Optional zur Debug-Ausgabe zwischenspeichern
if (buffercounter < sizeof(buffer) - 1)
buffer[buffercounter] = '\0';
// Wenn komplettes Header-Ende erkannt wurde: \r\n\r\n
if (buffercounter >= 4 &&
buffer[buffercounter - 4] == '\r' &&
buffer[buffercounter - 3] == '\n' &&
buffer[buffercounter - 2] == '\r' &&
buffer[buffercounter - 1] == '\n') {
#ifdef debug
Serial.println(F("HTTP Header empfangen:"));
Serial.println(buffer);
#endif
// Nach "Transfer-Encoding: chunked" im Header suchen
if(strstr(buffer, "Transfer-Encoding: chunked") != nullptr){
state = requestState::processChunked;
break;
}
buffercounter = 0;
state = requestState::waitforAnswer;
break;
}
// Falls Header zu groß wird (Sicherheitsgrenze)
if (buffercounter >= sizeof(buffer) - 1) {
#ifdef debug
Serial.println(F("Warnung: HTTP-Header zu lang!"));
#endif
buffercounter = 0;
state = requestState::waitforAnswer;
break;
}
}
break;
case requestState::processChunked:{
size_t jsonLength;
char * jsonBody = readChunkedBodyToPsram(*client, jsonLength);
Serial.println(jsonBody);
if (jsonBody) {
DeserializationError err = deserializeJson(doc, jsonBody, jsonLength);
if (err) {
#ifdef debug
Serial.print(F("deserializeJson() failed: "));
Serial.println(err.f_str());
#endif
state = requestState::waitUntilDelayIsOver;
} else {
state = requestState::processAnswer;
}
heap_caps_free(jsonBody); // WICHTIG!
}
}
break;
case requestState::waitforAnswer:
if (client->available() > 0) {
DeserializationError error = deserializeJson(doc, *client, DeserializationOption::Filter(filter));
if (error) {
#ifdef debug
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
#endif
state = requestState::waitUntilDelayIsOver;
return;
}
}
if (!client->connected()) {
#ifdef debug
Serial.println();
Serial.println("Verbindung geschlossen");
#endif
while (client->available()) {
buffer[buffercounter++] = client->read();
if (buffercounter >= sizeof(buffer) - 1)
break;
}
buffercounter = 0;
state = requestState::processAnswer;
}
break;
case requestState::processAnswer:
#ifdef debug
serializeJson(doc, Serial);
Serial.println(); // Zeilenumbruch danach, damit alles sauber aussieht
#endif
for (int i = 0; i < requestedDepartures; i++){
depArray[i] = parseDeparture(i);
}
state = requestState::getTime;
break;
case requestState::getTime:
ntpClient->update();
for(int i = 0; i < requestedDepartures; i++){
#ifdef debug
Serial.print("Lesbare Zeit: ");
Serial.print(ntpClient->getHours() + depArray[i].departureTime.offset);
Serial.print(":");
Serial.print(ntpClient->getMinutes());
Serial.print(":");
Serial.println(ntpClient->getSeconds());
#endif
depArray[i].minutesUntilDeparture = calcTimeDelta(depArray[i].departureTime.minute, ntpClient->getMinutes(),depArray[i].departureTime.houre, ntpClient->getHours() + depArray[i].departureTime.offset - 1);
}
state = requestState::sendActualisation;
break;
case requestState::sendActualisation:
onRefresh(depArray, requestedDepartures);
state = requestState::waitUntilDelayIsOver;
break;
default:
state = requestState::waitUntilDelayIsOver;
break;
}
}
bool checkDestination(String str1, String str2){
str1.replace(",","");
str1.replace(" ","");
str2.replace(",","");
str2.replace(" ","");
str1.toLowerCase();
str2.toLowerCase();
return str1.equals(str2);
}
Departure Sbb_Connection::parseDeparture(int depIndex){
Departure retval;
bool reachesDestination = false;
JsonObject departure = doc["stationboard"].as<JsonArray>()[depIndex];
for(JsonObject stationentry : departure["passList"].as<JsonArray>()){
if(checkDestination(stationentry["station"]["name"].as<String>(), destinationName)){
reachesDestination = true;
}
}
if (reachesDestination){
retval.departureTime = parseDateTime(departure["stop"]["departure"].as<String>());
#ifdef debug
Serial.print(retval.departureTime.houre);
Serial.print(":");
Serial.print(retval.departureTime.minute);
Serial.print(":");
Serial.print(retval.departureTime.seconds);
Serial.print(":");
Serial.print(retval.departureTime.year);
Serial.print("Ofst:");
Serial.println(retval.departureTime.offset);
#endif
retval.Name = departure["number"].as<String>();
retval.vehicleType = parseVehicleType(departure["category"].as<String>());
}
else{
retval.departureTime = parseDateTime("0000-00-00T00:00:00+0000");
}
return retval;
}
+103
View File
@@ -0,0 +1,103 @@
#ifndef SBB_REQUEST_H
#define SBB_REQUEST_H
#define debug
#include <SPI.h>
#include <ETH.h>
#include <ArduinoJson.h>
#include <Arduino.h>
#include <NTPClient.h>
#include <esp_heap_caps.h>
typedef enum{
train,
tram,
ship,
bus,
cableway
} VehicleType;
typedef struct{
int year;
int month;
int day;
int houre;
int minute;
int seconds;
int offset;
} Date_Time;
typedef struct{
VehicleType vehicleType;
String Name;
Date_Time departureTime;
int minutesUntilDeparture;
} Departure;
VehicleType parseVehicleType(String toParse);
Date_Time parseDateTime(String toParse);
class PsramAllocator : public ArduinoJson::Allocator{
public:
void* allocate(size_t size) override {
return heap_caps_malloc(size, MALLOC_CAP_SPIRAM);
}
void deallocate(void* ptr) override{
heap_caps_free(ptr);
}
void* reallocate(void* ptr, size_t new_size) override {
return heap_caps_realloc(ptr, new_size, MALLOC_CAP_SPIRAM);
}
};
class Sbb_Connection{
public:
Sbb_Connection() : doc(&allocator){};
void initialize(NetworkClient * ethClient, NTPClient * ntpClient);
void work(bool connected);
void setRefreshCycle(unsigned long milliseconds){timeDelay = milliseconds;};
void setRequestedDepartures(int num){requestedDepartures = num; depArray = new Departure[num];};
void setDepStation(String name){stationName = name;};
void setDestStation(String name){destinationName = name;};
void setVehicleFilter(VehicleType* typeFilter){vehicleTypeFilter = typeFilter;};
void (*onRefresh)(Departure departures[], int numberOfDepartures);
private:
typedef enum {
waitUntilDelayIsOver,
connectandRequest,
waitForHeader,
processChunked,
waitforAnswer,
processAnswer,
getTime,
sendActualisation
} requestState;
char sbbServer[30] = "transport.opendata.ch";
char buffer[512];
JsonDocument doc;
PsramAllocator allocator;
StaticJsonDocument<256> filter;
unsigned int buffercounter;
requestState state;
unsigned long lastRequest;
NetworkClient* client;
NTPClient * ntpClient;
VehicleType* vehicleTypeFilter;
String destinationName;
int requestedDepartures;
unsigned long timeDelay;
String stationName;
Departure * depArray;
Departure parseDeparture(int depIndex);
};
#endif
+137
View File
@@ -0,0 +1,137 @@
#include "Sbb_LCD_Screen.h"
#define UpPin 47
#define DownPin 48
#define movingSensorInput 18
#define displayLines 2
#define offlineTime 40000
#define lcdOffTime 120000
String padRight(String str, int length) {
while (str.length() < length) str += " ";
return str;
}
void SBB_LCD::Initalize(int maxEntries){
departures = new Departure[maxEntries];
this->maxEntries = maxEntries;
Wire.begin(SDA, SCL);
lcd.begin(16, displayLines);
lcd.setRGB(colorR, colorG, colorB);
pinMode(UpPin, INPUT_PULLUP);
pinMode(DownPin, INPUT_PULLUP);
pinMode(movingSensorInput, INPUT);
lcdMutex = xSemaphoreCreateMutex();
}
bool upPressed = false;
bool downPressed = false;
bool backlightchanged = false;
void SBB_LCD::Work(){
if (millis() - lastButtonTime >= offlineTime){
displayindex = 0;
}
if(!digitalRead(UpPin) && !upPressed){
if(--displayindex < 0) displayindex = 0;
lastButtonTime = millis();
upPressed = true;
actualized = true;
}
if(digitalRead(UpPin)){
upPressed = false;
}
if(!digitalRead(DownPin) && !downPressed){
if(++displayindex > depEntries - 2) displayindex = depEntries - 2;
lastButtonTime = millis();
downPressed = true;
actualized = true;
}
if(digitalRead(DownPin)){
downPressed = false;
}
if(digitalRead(movingSensorInput)){
lastMovement = millis();
}
bool lcdBacklight = false;
if (millis() - lastMovement >= lcdOffTime){
lcdBacklight = false;
}else{
lcdBacklight = true;
}
if(xSemaphoreTake(lcdMutex, portMAX_DELAY)){
if(lcdBacklight != backlightchanged){
backlightchanged = lcdBacklight;
if(lcdBacklight){
lcd.setRGB(colorR, colorG, colorB);
}
else{
lcd.setRGB(0, 0, 0);
}
}
//lcd.clear();
if (debugLine1.isEmpty()){
if (depEntries >=2 && actualized){
for(int i = 0; i < displayLines; i++){
Departure departure = departures[displayindex + i];
lcd.setCursor(0, i);
lcd.print(padRight(departure.Name,6));
lcd.setCursor(6, i);
String lcdString = "";
if(departure .departureTime.houre < 10) lcdString.concat("0");
lcdString.concat(departure.departureTime.houre);
lcdString.concat(":");
if(departure.departureTime.minute < 10) lcdString.concat("0");
lcdString.concat(departure.departureTime.minute);
lcd.print(lcdString);
lcd.setCursor(12, i);
lcdString = "";
if(departure.minutesUntilDeparture < 100 && departure.minutesUntilDeparture >= 0) lcdString.concat("0");
else if(departure.minutesUntilDeparture < 0) lcdString.concat(" ");
if(departure.minutesUntilDeparture < 10 && departure.minutesUntilDeparture >= 0) lcdString.concat("0");
lcdString.concat(departure.minutesUntilDeparture);
lcdString.concat("'");
lcd.print(lcdString);
}
actualized = false;
}
}else{
lcd.setCursor(0, 0);
lcd.print(debugLine1);
lcd.setCursor(0, 1);
lcd.print(debugLine2);
}
xSemaphoreGive(lcdMutex);
}
vTaskDelay(30 / portTICK_PERIOD_MS);
}
void SBB_LCD::SetDebugMessages(String line1, String line2){
if(xSemaphoreTake(lcdMutex, portMAX_DELAY)){
lcd.clear();
debugLine1 = line1;
debugLine2 = line2;
xSemaphoreGive(lcdMutex);
}
}
void SBB_LCD::ResetDebug(){
if(xSemaphoreTake(lcdMutex, portMAX_DELAY)){
lcd.clear();
debugLine1 = "";
debugLine2 = "";
lcd.clear();
xSemaphoreGive(lcdMutex);
}
}
+39
View File
@@ -0,0 +1,39 @@
#ifndef SBB_LCD_SCREEN_H
#define SBB_LCD_SCREEN_H
#include <Arduino.h>
#include <Wire.h>
#include "rgb_lcd.h"
#include "SBB_Request.h"
#define SDA 17
#define SCL 16
class SBB_LCD{
public:
void Initalize(int maxEntries);
void Work();
void SetDebugMessages(String line1, String line2);
void ResetDebug();
void setActualized(){actualized = true;};
Departure * departures;
int depEntries = 0;
SemaphoreHandle_t lcdMutex;
private:
bool actualized = false;
rgb_lcd lcd;
String debugLine1 = "";
String debugLine2 = "";
int8_t displayindex = 0;
unsigned long lastButtonTime;
unsigned long lastMovement;
int maxEntries;
int colorR = 0;
int colorG = 0;
int colorB = 170;
};
#endif