Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Cheerlights Clock v6.3
- based on @martinbateman clock code
- https://t.co/1gRc56wNOE
- https://pastebin.com/4Ec6d4xY
- and updated v6 test code
- https://pastebin.com/N2bH9m50
- added cheerlight code back in from v6 above. - LeRoy Miller July 27
- added TTGO_T2 and M5SickC code to main code base using defines
- ported to TTGO T2 Board by LeRoy Miller July 25, 2019
- added Geolocate Timezone code July 25, 2019
- ported to M5StickC LeRoy Miller July 26, 2019
- July 27 - updated M5StickC display to display weather description and temp.
- reformated screen for better display of time, and color and to make room for weather info.
- reformated TTGO_T2 screen to fit brief weather and temps.
- TO DO: add M5StackC Real Time Clock support
- * Idea add SPIFFs support, OTA support and Wifi Manager to update OTA
- * Update API Key with no reprogramming
- * Make for 24 hour (current) or 12 hour time
- * Make temperatures either C or F
- Update Weather data maybe every 15 minutes or so
- */
- #include <HTTPClient.h>
- #include <ArduinoJson.h>
- #include <WiFi.h>
- #include <NTPClient.h>
- #include <WiFiUdp.h>
- #include <TimeLib.h>
- #include <PubSubClient.h>
- #include <SPI.h>
- //Define your board type default to TTGO_display
- #define TTGO_T2
- //#define M5Stick_C 1
- #ifdef TTGO_T2
- #include <Adafruit_GFX.h>
- #include <Adafruit_SSD1331.h>
- #define sclk 14
- #define mosi 13
- #define cs 15
- #define rst 4
- #define dc 16
- #define TFT_BL -1 // Display backlight control pin
- // Color definitions
- #define TFT_BLACK 0x0000
- #define TFT_BLUE 0x001F
- #define TFT_RED 0xF800
- #define TFT_GREEN 0x07E0
- #define TFT_CYAN 0x07FF
- #define TFT_MAGENTA 0xF81F
- #define TFT_YELLOW 0xFFE0
- #define TFT_WHITE 0xFFFF
- Adafruit_SSD1331 tft = Adafruit_SSD1331(cs, dc, mosi, sclk, rst);
- #elif M5Stick_C
- #include <M5StickC.h>
- #define TFT_BL -1 // Display backlight control pin
- // Color definitions
- #define TFT_BLACK 0x0000
- #define TFT_BLUE 0x001F
- #define TFT_RED 0xF800
- #define TFT_GREEN 0x07E0
- #define TFT_CYAN 0x07FF
- #define TFT_MAGENTA 0xF81F
- #define TFT_YELLOW 0xFFE0
- #define TFT_WHITE 0xFFFF
- #else
- #include <TFT_eSPI.h>
- #define TFT_BL 4 // Display backlight control pin
- TFT_eSPI tft = TFT_eSPI();
- #endif
- // Replace with your network credentials
- const char* ssid = "";
- const char* password = "";
- const char* mqtt_server = "simplesi.cloud";
- // openweathermap.org key
- String WEATHERKEY="";
- // temp in celcius
- double temperature = 0.0;
- //Weather Statement
- String weatherStatement;
- // offset in seconds
- int gmtOffset_sec = 0;
- //Original Code
- int cheer_red = 0;
- int cheer_green = 0;
- int cheer_blue = 0;
- unsigned int rgb565Decimal = 0x8410;
- unsigned int newrgb565Decimal;
- String colourString = "";
- String newColourString;
- String strData;
- String topicStr;
- WiFiUDP ntpUDP;
- NTPClient timeClient(ntpUDP);
- WiFiClient espClient;
- PubSubClient client(espClient);
- String payload, TZone;//, lastUpdate;
- String coordinateTZ; //lat=xx.xxx&lon=xxx.xxx
- SemaphoreHandle_t serialMutex = NULL;
- void updateNTP (void *pvParams);
- void updateScreen (void *pvParams);
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived in topic: ");
- Serial.println(topic);
- topicStr = topic;
- Serial.print("Message:");
- strData = "";
- for (int i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- strData += (char)payload[i];
- }
- Serial.println();
- Serial.println("-----------------------");
- if (topicStr.endsWith("cheerlights/rgb565Decimal")) {
- colourString = newColourString;
- rgb565Decimal = strData.toInt();
- Serial.println("*******");
- Serial.println(rgb565Decimal);
- }
- if (topicStr.endsWith("cheerlights")) {
- newColourString = "\n" + strData + " "; //newColourString = "Cheerlights:\n" + strData;
- //sixteenBitHex = newSixteenBitHex;
- Serial.println(strData);
- }
- } // end callback
- void reconnect() {
- // Loop until we're reconnected
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Create a random client ID
- String clientId = "ESP32Client-";
- clientId += String(random(0xffff), HEX);
- // Attempt to connect
- if (client.connect(clientId.c_str())) {
- Serial.println("connected");
- client.subscribe("cheerlights",1);
- client.subscribe("cheerlights/rgb565Decimal",1);
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- // Wait 5 seconds before retrying
- delay(5000);
- }
- }
- }
- void setup() {
- // put your setup code here, to run once:
- Serial.begin (115200);
- serialMutex = xSemaphoreCreateMutex ();
- if (TFT_BL > 0) {
- pinMode(TFT_BL, OUTPUT);
- digitalWrite(TFT_BL, HIGH);
- }
- #ifdef TTGO_T2
- tft.begin();
- tft.fillScreen(TFT_BLACK);
- tft.setTextColor(TFT_YELLOW, TFT_BLACK); // Note: the new fonts do not draw the background colour
- #elif M5Stick_C
- M5.begin();
- M5.Lcd.setRotation(3);
- M5.Lcd.fillScreen(TFT_BLACK);
- M5.Lcd.setTextColor(TFT_YELLOW, TFT_BLACK); // Note: the new fonts do not draw the background colour
- #else
- tft.init();
- tft.setRotation(1);
- tft.fillScreen(TFT_BLACK);
- tft.setTextColor(TFT_YELLOW, TFT_BLACK); // Note: the new fonts do not draw the background colour
- #endif
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print (".");
- }
- Serial.println(WiFi.localIP());
- timeClient.begin();
- geolocation (); // guess where I am
- timeClient.setTimeOffset(gmtOffset_sec);
- client.setServer(mqtt_server, 1883);
- client.setCallback(callback);
- xTaskCreate (updateNTP, "NTP Client", 4096, NULL, 2, NULL);
- xTaskCreate (updateScreen, "Screen", 4096, NULL, 1, NULL);
- }
- void loop() {
- if (!client.connected()) {
- reconnect();
- }
- client.loop();
- }
- void getJson(String url) {
- if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
- HTTPClient http; //Declare an object of class HTTPClient
- http.begin(url); //Specify request destination
- int httpCode = http.GET(); //Send the request
- if (httpCode > 0) { //Check the returning code
- payload = http.getString(); //Get the request response payload
- }
- http.end(); //Close connection
- }
- }
- /*
- * This function will use the external IP to get a Latitude and Longitude
- * which will be used for many different things for ISS tracker.
- * The website http://ip-api.com is used for this.
- * https://github.com/kd8bxp/M5Stack-ISS-Tracker-Updated/tree/master/M5Stack_ISS_Tracker_Updated
- */
- int geolocation(){
- String url;
- url = "http://ip-api.com/json";
- getJson(url);
- const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
- DynamicJsonDocument jsonBuffer(1024);
- DeserializationError error = deserializeJson (jsonBuffer, payload);
- if (error){
- Serial.println ("deserializeJson () failed");
- }
- double lat = jsonBuffer["lat"];
- double lon = jsonBuffer["lon"];
- url = "http://api.openweathermap.org/data/2.5/weather?lat=" + String(lat) + "&lon=" + String(lon) + "&appid=" + WEATHERKEY;
- Serial.println(url);
- getJson(url);
- error = deserializeJson (jsonBuffer, payload);
- if (error){
- Serial.println ("deserializeJson () failed");
- }
- gmtOffset_sec = jsonBuffer["timezone"];
- temperature = jsonBuffer["main"]["temp"];
- temperature = temperature - 273.0;
- //JsonObject obj = jsonBuffer.as<JsonObject>();
- weatherStatement = jsonBuffer["weather"][0]["description"].as<String>();
- Serial.println(temperature);
- Serial.println(weatherStatement);
- }
- void updateNTP (void *pvParameters) {
- (void) pvParameters;
- for (;;) {
- while(!timeClient.update()) {
- timeClient.forceUpdate();
- }
- if (xSemaphoreTake (serialMutex, (TickType_t)10) == pdTRUE) {
- setTime (timeClient.getEpochTime ());
- xSemaphoreGive (serialMutex);
- }
- vTaskDelay ((1000/portTICK_PERIOD_MS) * 60 * 15); // update every 15 minutes.
- geolocation (); // update based on location
- }
- }
- void updateScreen (void *pvParameters) {
- (void) pvParameters;
- for (;;) {
- if (xSemaphoreTake (serialMutex, (TickType_t)10) == pdTRUE) {
- char timeString[25];
- char colourString2[25];
- colourString.toCharArray(colourString2,25);
- time_t t = now ();
- sprintf (timeString, "%02i:%02i:%02i", hour (t), minute (t), second (t));
- xSemaphoreGive (serialMutex);
- char out[25];
- sprintf (out, "%2.0f`C", temperature);
- #ifdef TTGO_T2
- //some screen flashing when updating (?)
- tft.setTextSize(2);
- tft.setTextColor(0x39C4, TFT_BLACK);
- tft.setTextColor(rgb565Decimal, TFT_BLACK);
- tft.setCursor(0,0);
- tft.print(timeString);
- tft.setCursor(0,4);
- tft.setTextSize(2);
- tft.print(colourString2);
- tft.setTextColor(TFT_WHITE, TFT_BLACK);
- tft.setTextSize(1);
- tft.setCursor(0,42);
- tft.print(weatherStatement);
- tft.setCursor(40,52);
- tft.print(out);
- #elif M5Stick_C
- M5.Lcd.setTextColor(0x39C4, TFT_BLACK);
- M5.Lcd.setCursor(25,0,4);
- M5.Lcd.setTextColor(rgb565Decimal, TFT_BLACK);
- M5.Lcd.print(timeString); //tft.drawString (timeString, 10, 10, 7);
- M5.Lcd.setCursor(0,1,4);
- M5.Lcd.print(colourString2);
- M5.Lcd.setCursor(0,60,2);
- M5.Lcd.setTextColor(TFT_WHITE);
- M5.Lcd.print(weatherStatement);
- M5.Lcd.setCursor(118,60,2);
- //M5.Lcd.setTextColor(TFT_WHITE);
- M5.Lcd.print(out);
- #else
- tft.setTextColor(0x39C4, TFT_BLACK);
- tft.drawString("88:88:88",10,10,7);
- tft.setTextColor(rgb565Decimal, TFT_BLACK);
- tft.drawString (timeString, 10, 10, 7);
- tft.setTextColor(TFT_WHITE);
- tft.setCursor(0,60,2);
- tft.print(weatherStatement);
- tft.setCursor(190, 60 ,2);
- tft.println(out);
- #endif
- }
- vTaskDelay (1000/portTICK_PERIOD_MS);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment