inkplate-6-arduino-library/examples/3. Projects/1-Weather_station_example/Network.cpp

275 lines
7.7 KiB
C++
Raw Normal View History

2020-07-31 10:43:38 +02:00
//Network.cpp contains various functions and classes that enable Weather station
//They have been declared in seperate file to increase readability
2020-07-29 08:51:24 +02:00
#include "Network.h"
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
2020-07-31 10:43:38 +02:00
//WiFiMulti object declaration
2020-07-29 08:51:24 +02:00
WiFiMulti WiFiMulti;
2020-07-31 10:43:38 +02:00
//Static Json from ArduinoJson library
2020-07-29 08:51:24 +02:00
StaticJsonDocument<6000> doc;
2020-07-31 10:43:38 +02:00
//Declared week days
2020-07-29 08:51:24 +02:00
char weekDays[8][8] = {
"Mon",
"Tue",
"Wed",
"Thr",
"Fri",
"Sat",
"Sun",
};
void Network::begin(char *city)
{
2020-07-31 10:43:38 +02:00
//Initiating wifi, like in BasicHttpClient example
2020-07-29 08:51:24 +02:00
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, pass);
Serial.print(F("Waiting for WiFi to connect..."));
while ((WiFiMulti.run() != WL_CONNECTED))
{
2020-07-31 10:43:38 +02:00
//Printing a dot to Serial monitor every second while waiting to connect
2020-07-29 08:51:24 +02:00
Serial.print(F("."));
delay(1000);
}
Serial.println(F(" connected"));
2020-07-31 10:43:38 +02:00
//Find internet time
2020-07-29 08:51:24 +02:00
setTime();
2020-07-31 10:43:38 +02:00
//Search for given cities woeid
2020-07-29 08:51:24 +02:00
findCity(city);
2020-07-29 09:37:28 +02:00
2020-07-31 10:43:38 +02:00
//reduce power by making WiFi module sleep
2020-07-29 09:37:28 +02:00
WiFi.setSleep(1);
2020-07-29 08:51:24 +02:00
}
2020-07-31 10:43:38 +02:00
//Gets time from ntp server
2020-07-29 08:51:24 +02:00
void Network::getTime(char *timeStr)
{
2020-07-31 10:43:38 +02:00
//Get seconds since 1.1.1970.
2020-07-29 08:51:24 +02:00
time_t nowSecs = time(nullptr);
2020-07-31 10:43:38 +02:00
//Struct used to store time
2020-07-29 08:51:24 +02:00
struct tm timeinfo;
gmtime_r(&nowSecs, &timeinfo);
2020-07-29 09:37:28 +02:00
//Copies time string into timeStr
2020-07-29 08:51:24 +02:00
strncpy(timeStr, asctime(&timeinfo) + 11, 5);
2020-07-31 10:43:38 +02:00
//Setting time string timezone
2020-07-29 08:51:24 +02:00
int hr = 10 * timeStr[0] + timeStr[1] + timeZone;
2020-07-31 10:43:38 +02:00
//Better defined modulo, in case timezone makes hours to go below 0
2020-07-29 08:51:24 +02:00
hr = (hr % 24 + 24) % 24;
2020-07-31 10:43:38 +02:00
//Adding time to '0' char makes it into whatever time char, for both digits
2020-07-29 08:51:24 +02:00
timeStr[0] = hr / 10 + '0';
timeStr[1] = hr % 10 + '0';
}
2020-07-31 10:43:38 +02:00
//Helper function to convert float to char*
2020-07-29 08:51:24 +02:00
void formatTemp(char *str, float temp)
{
2020-07-31 10:43:38 +02:00
//Built in function for float to char* conversion
2020-07-29 08:51:24 +02:00
dtostrf(temp, 2, 0, str);
}
2020-07-31 10:43:38 +02:00
//Helper function to convert float to char*
2020-07-29 08:51:24 +02:00
void formatWind(char *str, float wind)
{
2020-07-31 10:43:38 +02:00
//Built in function for float to char* conversion
2020-07-29 09:37:28 +02:00
dtostrf(wind, 2, 0, str);
2020-07-29 08:51:24 +02:00
}
2020-07-31 10:43:38 +02:00
//Function that connects to API and gets the weather data
2020-07-29 08:51:24 +02:00
void Network::getData(char *city, char *temp1, char *temp2, char *temp3, char *temp4, char *currentTemp, char *currentWind, char *currentTime, char *currentWeather, char *currentWeatherAbbr)
{
2020-07-31 10:43:38 +02:00
//Return if wifi isn't connected
2020-07-29 08:51:24 +02:00
if (WiFi.status() != WL_CONNECTED)
return;
2020-07-31 10:43:38 +02:00
//Wake up WiFi if sleeping and save inital state
2020-07-29 08:51:24 +02:00
bool sleep = WiFi.getSleep();
WiFi.setSleep(false);
2020-07-31 10:43:38 +02:00
//HTTP object used to make get request
2020-07-29 08:51:24 +02:00
HTTPClient http;
http.getStream().setNoDelay(true);
http.getStream().setTimeout(1);
2020-07-31 10:43:38 +02:00
//Add woeid to api call. woeid is API specific variable name used to set location
2020-07-29 08:51:24 +02:00
char url[256];
sprintf(url, "https://www.metaweather.com/api/location/%d/", location);
2020-07-31 10:43:38 +02:00
//Initiate http
2020-07-29 08:51:24 +02:00
http.begin(url);
2020-07-31 10:43:38 +02:00
//Actually make HTTPS GET request
2020-07-29 08:51:24 +02:00
int httpCode = http.GET();
if (httpCode == 200)
{
int32_t len = http.getSize();
if (len > 0)
{
2020-07-31 10:43:38 +02:00
//Try parsing JSON object
2020-07-29 08:51:24 +02:00
DeserializationError error = deserializeJson(doc, http.getStream());
2020-07-31 10:43:38 +02:00
//If an error happens print it to Serial monitor
2020-07-29 08:51:24 +02:00
if (error)
{
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
}
else
{
2020-07-31 10:43:38 +02:00
//Set all data got from internet using formatTemp and formatWind defined above
//This part relies heavily on ArduinoJson library
2020-07-29 08:51:24 +02:00
formatTemp(currentTemp, doc["consolidated_weather"][0][F("the_temp")].as<float>());
formatWind(currentWind, doc["consolidated_weather"][0][F("wind_speed")].as<float>());
strcpy(city, doc["title"].as<char *>());
strcpy(currentWeather, doc["consolidated_weather"][0]["weather_state_name"].as<char *>());
strcpy(currentWeatherAbbr, doc["consolidated_weather"][0]["weather_state_abbr"].as<char *>());
formatTemp(temp1, doc["consolidated_weather"][0][F("the_temp")].as<float>());
formatTemp(temp2, doc["consolidated_weather"][1][F("the_temp")].as<float>());
formatTemp(temp3, doc["consolidated_weather"][2][F("the_temp")].as<float>());
formatTemp(temp4, doc["consolidated_weather"][3][F("the_temp")].as<float>());
}
}
}
2020-07-31 10:43:38 +02:00
//Clear document and end http
2020-07-29 08:51:24 +02:00
doc.clear();
http.end();
2020-07-31 10:43:38 +02:00
//Return to initial state
2020-07-29 08:51:24 +02:00
WiFi.setSleep(sleep);
}
2020-07-31 10:43:38 +02:00
//Used to set correct time received from NTP server
2020-07-29 08:51:24 +02:00
void Network::setTime()
{
2020-07-31 10:43:38 +02:00
//Used for setting correct time
2020-07-29 08:51:24 +02:00
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
Serial.print(F("Waiting for NTP time sync: "));
time_t nowSecs = time(nullptr);
while (nowSecs < 8 * 3600 * 2)
{
2020-07-29 09:37:28 +02:00
// Print a dot every half a second while time is not set
2020-07-29 08:51:24 +02:00
delay(500);
Serial.print(F("."));
yield();
nowSecs = time(nullptr);
}
Serial.println();
2020-07-31 10:43:38 +02:00
//Used to store time info
2020-07-29 08:51:24 +02:00
struct tm timeinfo;
gmtime_r(&nowSecs, &timeinfo);
Serial.print(F("Current time: "));
Serial.print(asctime(&timeinfo));
}
2020-07-31 10:43:38 +02:00
//From epoch received from NTP server, get day of the week
2020-07-29 08:51:24 +02:00
void Network::getDays(char *day, char *day1, char *day2, char *day3)
{
2020-07-29 09:37:28 +02:00
// Seconds since 1.1.1970.
2020-07-29 08:51:24 +02:00
time_t nowSecs = time(nullptr);
2020-07-31 10:43:38 +02:00
//Find weekday
2020-07-29 08:51:24 +02:00
2020-07-31 10:43:38 +02:00
//We get seconds since 1970, add 3600 (1 hour) times the time zone and add 3 to
//make monday the first day of the week, as 1.1.1970. was a thursday
//finally do mod 7 to insure our day is within [0, 6]
2020-07-29 08:51:24 +02:00
int dayWeek = ((long)((nowSecs + 3600L * timeZone) / 86400L) + 3) % 7;
2020-07-29 09:37:28 +02:00
// Copy day data to globals in main file
2020-07-29 08:51:24 +02:00
strncpy(day, weekDays[dayWeek], 3);
strncpy(day1, weekDays[(dayWeek + 1) % 7], 3);
strncpy(day2, weekDays[(dayWeek + 2) % 7], 3);
strncpy(day3, weekDays[(dayWeek + 3) % 7], 3);
}
2020-07-31 10:43:38 +02:00
//Make API query to receive city woeid - city identification specific to API
2020-07-29 08:51:24 +02:00
void Network::findCity(char *city)
{
2020-07-31 10:43:38 +02:00
//If not connected to WiFi, return
2020-07-29 08:51:24 +02:00
if (WiFi.status() != WL_CONNECTED)
return;
2020-07-31 10:43:38 +02:00
//Wake WiFi module and save initial state
2020-07-29 08:51:24 +02:00
bool sleep = WiFi.getSleep();
WiFi.setSleep(false);
2020-07-31 10:43:38 +02:00
//HTTP object
2020-07-29 08:51:24 +02:00
HTTPClient http;
http.getStream().setNoDelay(true);
http.getStream().setTimeout(1);
2020-07-31 10:43:38 +02:00
//Add query parameter to URL
2020-07-29 08:51:24 +02:00
char url[256];
strcpy(url, "https://www.metaweather.com/api/location/search/?query=");
strcat(url, city);
2020-07-31 10:43:38 +02:00
//Initiate HTTP
2020-07-29 08:51:24 +02:00
http.begin(url);
2020-07-31 10:43:38 +02:00
//Make GET HTTP request
2020-07-29 08:51:24 +02:00
int httpCode = http.GET();
if (httpCode == 200) // 200: http success
{
int32_t len = http.getSize();
if (len > 0)
{
2020-07-31 10:43:38 +02:00
//Try to parse JSON object
2020-07-29 08:51:24 +02:00
DeserializationError error = deserializeJson(doc, http.getStream());
2020-07-31 10:43:38 +02:00
//Print error to Serial monitor if one exists
2020-07-29 08:51:24 +02:00
if (error)
{
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
}
else
{
2020-07-31 10:43:38 +02:00
//Empty list means no matches for the city
2020-07-29 08:51:24 +02:00
if (doc.size() == 0)
{
Serial.println(F("City not found"));
}
else
{
2020-07-31 10:43:38 +02:00
//woeid id used for fetching data later on
2020-07-29 08:51:24 +02:00
location = doc[0]["woeid"].as<int>();
Serial.println(F("Found city, woied:"));
Serial.println(location);
}
}
}
}
2020-07-31 10:43:38 +02:00
//Clear document and end http
2020-07-29 08:51:24 +02:00
doc.clear();
http.end();
2020-07-31 10:43:38 +02:00
//Return module to initial state
2020-07-29 08:51:24 +02:00
WiFi.setSleep(sleep);
2020-07-31 10:43:38 +02:00
};