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