kd8bxp

cheerlight clock v6.3 updated all board weather brief

Jul 27th, 2019
492
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 10.29 KB | None | 0 0
  1. /*
  2.   Cheerlights Clock v6.3
  3.   based on @martinbateman clock code
  4.  https://t.co/1gRc56wNOE
  5.  https://pastebin.com/4Ec6d4xY
  6.  and updated v6 test code
  7.  https://pastebin.com/N2bH9m50
  8.  
  9. added cheerlight code back in from v6 above. - LeRoy Miller July 27
  10. added TTGO_T2 and M5SickC code to main code base using defines
  11.  
  12. ported to TTGO T2 Board by LeRoy Miller July 25, 2019
  13.  
  14. added Geolocate Timezone code July 25, 2019
  15. ported to M5StickC LeRoy Miller July 26, 2019
  16.  
  17. July 27 - updated M5StickC display to display weather description and temp.
  18.  reformated screen for better display of time, and color and to make room for weather info.
  19.  reformated TTGO_T2 screen to fit brief weather and temps.
  20.  
  21.   TO DO: add M5StackC Real Time Clock support
  22.  
  23.   * Idea add SPIFFs support, OTA support and Wifi Manager to update OTA
  24.   * Update API Key with no reprogramming
  25.   * Make for 24 hour (current) or 12 hour time
  26.   * Make temperatures either C or F
  27.  
  28.   Update Weather data maybe every 15 minutes or so
  29.  
  30. */
  31.  
  32. #include <HTTPClient.h>
  33. #include <ArduinoJson.h>
  34.  
  35. #include <WiFi.h>
  36. #include <NTPClient.h>
  37. #include <WiFiUdp.h>
  38. #include <TimeLib.h>
  39. #include <PubSubClient.h>
  40. #include <SPI.h>
  41.  
  42. //Define your board type default to TTGO_display
  43. #define TTGO_T2
  44. //#define M5Stick_C 1
  45.  
  46. #ifdef TTGO_T2
  47.   #include <Adafruit_GFX.h>
  48.   #include <Adafruit_SSD1331.h>
  49.   #define sclk 14
  50.   #define mosi 13
  51.   #define cs   15
  52.   #define rst  4
  53.   #define dc   16
  54.   #define TFT_BL          -1  // Display backlight control pin
  55.   // Color definitions
  56.   #define TFT_BLACK           0x0000
  57.   #define TFT_BLUE            0x001F
  58.   #define TFT_RED             0xF800
  59.   #define TFT_GREEN           0x07E0
  60.   #define TFT_CYAN            0x07FF
  61.   #define TFT_MAGENTA         0xF81F
  62.   #define TFT_YELLOW          0xFFE0
  63.   #define TFT_WHITE           0xFFFF
  64.   Adafruit_SSD1331 tft = Adafruit_SSD1331(cs, dc, mosi, sclk, rst);
  65. #elif M5Stick_C  
  66.   #include <M5StickC.h>
  67.   #define TFT_BL          -1  // Display backlight control pin
  68.   // Color definitions
  69.   #define TFT_BLACK           0x0000
  70.   #define TFT_BLUE            0x001F
  71.   #define TFT_RED             0xF800
  72.   #define TFT_GREEN           0x07E0
  73.   #define TFT_CYAN            0x07FF
  74.   #define TFT_MAGENTA         0xF81F
  75.   #define TFT_YELLOW          0xFFE0
  76.   #define TFT_WHITE           0xFFFF
  77. #else
  78.   #include <TFT_eSPI.h>
  79.   #define TFT_BL          4  // Display backlight control pin
  80.   TFT_eSPI tft = TFT_eSPI();
  81. #endif
  82.  
  83. // Replace with your network credentials
  84. const char* ssid     = "";
  85. const char* password = "";
  86. const char* mqtt_server = "simplesi.cloud";
  87. // openweathermap.org key
  88. String WEATHERKEY="";
  89.  
  90. // temp in celcius
  91. double temperature = 0.0;
  92.  
  93. //Weather Statement
  94. String weatherStatement;
  95.  
  96. // offset in seconds
  97. int gmtOffset_sec = 0;
  98. //Original Code
  99. int cheer_red = 0;
  100. int cheer_green = 0;
  101. int cheer_blue = 0;
  102. unsigned int rgb565Decimal = 0x8410;
  103. unsigned int newrgb565Decimal;
  104. String colourString = "";
  105. String newColourString;
  106.  
  107. String strData;
  108. String topicStr;
  109.  
  110. WiFiUDP ntpUDP;
  111. NTPClient timeClient(ntpUDP);
  112. WiFiClient espClient;
  113. PubSubClient client(espClient);
  114.  
  115. String payload, TZone;//, lastUpdate;
  116. String coordinateTZ; //lat=xx.xxx&lon=xxx.xxx
  117.  
  118. SemaphoreHandle_t serialMutex = NULL;
  119. void updateNTP (void *pvParams);
  120. void updateScreen (void *pvParams);
  121.  
  122. void callback(char* topic, byte* payload, unsigned int length) {
  123.  
  124.   Serial.print("Message arrived in topic: ");
  125.   Serial.println(topic);
  126.   topicStr = topic;
  127.  
  128.   Serial.print("Message:");
  129.  
  130.   strData = "";
  131.   for (int i = 0; i < length; i++) {
  132.     Serial.print((char)payload[i]);
  133.     strData += (char)payload[i];
  134.   }
  135.  
  136.   Serial.println();
  137.   Serial.println("-----------------------");
  138.  
  139.   if (topicStr.endsWith("cheerlights/rgb565Decimal")) {
  140.    
  141.     colourString = newColourString;
  142.     rgb565Decimal = strData.toInt();
  143.     Serial.println("*******");
  144.  
  145.     Serial.println(rgb565Decimal);
  146.   }  
  147.   if (topicStr.endsWith("cheerlights")) {
  148.    
  149.     newColourString = "\n" + strData + "                "; //newColourString = "Cheerlights:\n" + strData;
  150.     //sixteenBitHex = newSixteenBitHex;
  151.     Serial.println(strData);
  152.   }  
  153. } // end callback
  154.  
  155. void reconnect() {
  156.   // Loop until we're reconnected
  157.   while (!client.connected()) {
  158.     Serial.print("Attempting MQTT connection...");
  159.     // Create a random client ID
  160.     String clientId = "ESP32Client-";
  161.     clientId += String(random(0xffff), HEX);
  162.     // Attempt to connect
  163.     if (client.connect(clientId.c_str())) {
  164.       Serial.println("connected");
  165.       client.subscribe("cheerlights",1);
  166.       client.subscribe("cheerlights/rgb565Decimal",1);
  167.     } else {
  168.       Serial.print("failed, rc=");
  169.       Serial.print(client.state());
  170.       Serial.println(" try again in 5 seconds");
  171.       // Wait 5 seconds before retrying
  172.       delay(5000);
  173.     }
  174.   }
  175. }
  176.  
  177. void setup() {
  178.   // put your setup code here, to run once:
  179.   Serial.begin (115200);
  180.  
  181.   serialMutex = xSemaphoreCreateMutex ();
  182.  
  183.   if (TFT_BL > 0) {
  184.     pinMode(TFT_BL, OUTPUT);
  185.     digitalWrite(TFT_BL, HIGH);
  186.   }
  187.  
  188. #ifdef TTGO_T2
  189.   tft.begin();
  190.   tft.fillScreen(TFT_BLACK);
  191.   tft.setTextColor(TFT_YELLOW, TFT_BLACK); // Note: the new fonts do not draw the background colour
  192. #elif M5Stick_C
  193.   M5.begin();
  194.   M5.Lcd.setRotation(3);
  195.   M5.Lcd.fillScreen(TFT_BLACK);
  196.   M5.Lcd.setTextColor(TFT_YELLOW, TFT_BLACK); // Note: the new fonts do not draw the background colour
  197. #else
  198.   tft.init();
  199.   tft.setRotation(1);
  200.   tft.fillScreen(TFT_BLACK);
  201.   tft.setTextColor(TFT_YELLOW, TFT_BLACK); // Note: the new fonts do not draw the background colour
  202. #endif
  203.  
  204.   WiFi.begin(ssid, password);
  205.   while (WiFi.status() != WL_CONNECTED) {
  206.     delay(500);
  207.     Serial.print (".");
  208.   }
  209.   Serial.println(WiFi.localIP());
  210.  
  211.  
  212.   timeClient.begin();
  213.   geolocation (); // guess where I am
  214.   timeClient.setTimeOffset(gmtOffset_sec);
  215.   client.setServer(mqtt_server, 1883);
  216.   client.setCallback(callback);
  217.  
  218.   xTaskCreate (updateNTP, "NTP Client", 4096, NULL, 2, NULL);
  219.   xTaskCreate (updateScreen, "Screen", 4096, NULL, 1, NULL);
  220. }
  221.  
  222. void loop() {
  223.    if (!client.connected()) {
  224.     reconnect();
  225.   }
  226.   client.loop();
  227. }
  228.  
  229. void getJson(String url) {  
  230.    if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
  231.      HTTPClient http;  //Declare an object of class HTTPClient
  232.      http.begin(url);  //Specify request destination
  233.     int httpCode = http.GET();                                                                  //Send the request
  234.      if (httpCode > 0) { //Check the returning code
  235.        payload = http.getString();   //Get the request response payload
  236.      
  237.     }
  238.  
  239.     http.end();   //Close connection
  240.  
  241.   }
  242. }
  243.  
  244. /*
  245.  * This function will use the external IP to get a Latitude and Longitude
  246.  * which will be used for many different things for ISS tracker.
  247.  * The website http://ip-api.com is used for this.
  248.  * https://github.com/kd8bxp/M5Stack-ISS-Tracker-Updated/tree/master/M5Stack_ISS_Tracker_Updated
  249.  */
  250.  
  251. int geolocation(){
  252.   String url;
  253.   url = "http://ip-api.com/json";
  254.   getJson(url);
  255.  
  256.   const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
  257.   DynamicJsonDocument jsonBuffer(1024);
  258.   DeserializationError error = deserializeJson (jsonBuffer, payload);
  259.   if (error){
  260.       Serial.println ("deserializeJson () failed");
  261.   }
  262.   double lat = jsonBuffer["lat"];
  263.   double lon = jsonBuffer["lon"];
  264.   url = "http://api.openweathermap.org/data/2.5/weather?lat=" + String(lat) + "&lon=" + String(lon) + "&appid=" + WEATHERKEY;
  265.   Serial.println(url);
  266.   getJson(url);
  267.  
  268.   error = deserializeJson (jsonBuffer, payload);
  269.   if (error){
  270.       Serial.println ("deserializeJson () failed");
  271.   }
  272.   gmtOffset_sec = jsonBuffer["timezone"];
  273.   temperature = jsonBuffer["main"]["temp"];
  274.   temperature = temperature - 273.0;
  275.   //JsonObject obj = jsonBuffer.as<JsonObject>();
  276.  
  277.   weatherStatement = jsonBuffer["weather"][0]["description"].as<String>();
  278.   Serial.println(temperature);
  279.   Serial.println(weatherStatement);
  280. }
  281.  
  282. void updateNTP (void *pvParameters) {
  283.   (void) pvParameters;
  284.  
  285.   for (;;) {
  286.     while(!timeClient.update()) {
  287.       timeClient.forceUpdate();
  288.     }
  289.     if (xSemaphoreTake (serialMutex, (TickType_t)10) == pdTRUE) {
  290.       setTime (timeClient.getEpochTime ());
  291.       xSemaphoreGive (serialMutex);
  292.     }
  293.     vTaskDelay ((1000/portTICK_PERIOD_MS) * 60 * 15);  // update every 15 minutes.
  294.     geolocation (); // update based on location
  295.   }
  296. }
  297.  
  298. void updateScreen (void *pvParameters) {
  299.   (void) pvParameters;
  300.  
  301.   for (;;) {
  302.     if (xSemaphoreTake (serialMutex, (TickType_t)10) == pdTRUE) {
  303.       char timeString[25];
  304.       char colourString2[25];
  305.       colourString.toCharArray(colourString2,25);
  306.       time_t t = now ();
  307.       sprintf (timeString, "%02i:%02i:%02i", hour (t), minute (t), second (t));
  308.       xSemaphoreGive (serialMutex);
  309. char out[25];
  310.       sprintf (out, "%2.0f`C", temperature);
  311. #ifdef TTGO_T2
  312. //some screen flashing when updating (?)
  313.       tft.setTextSize(2);
  314.       tft.setTextColor(0x39C4, TFT_BLACK);
  315.       tft.setTextColor(rgb565Decimal, TFT_BLACK);
  316.       tft.setCursor(0,0);
  317.       tft.print(timeString);
  318.       tft.setCursor(0,4);        
  319.       tft.setTextSize(2);
  320.       tft.print(colourString2);
  321.       tft.setTextColor(TFT_WHITE, TFT_BLACK);
  322.       tft.setTextSize(1);
  323.       tft.setCursor(0,42);
  324.       tft.print(weatherStatement);
  325.       tft.setCursor(40,52);
  326.       tft.print(out);
  327. #elif M5Stick_C
  328.       M5.Lcd.setTextColor(0x39C4, TFT_BLACK);
  329.       M5.Lcd.setCursor(25,0,4);
  330.       M5.Lcd.setTextColor(rgb565Decimal, TFT_BLACK);
  331.       M5.Lcd.print(timeString); //tft.drawString (timeString, 10, 10, 7);
  332.       M5.Lcd.setCursor(0,1,4);
  333.       M5.Lcd.print(colourString2);
  334.       M5.Lcd.setCursor(0,60,2);
  335.       M5.Lcd.setTextColor(TFT_WHITE);
  336.       M5.Lcd.print(weatherStatement);
  337.       M5.Lcd.setCursor(118,60,2);
  338.       //M5.Lcd.setTextColor(TFT_WHITE);
  339.       M5.Lcd.print(out);
  340. #else      
  341.       tft.setTextColor(0x39C4, TFT_BLACK);
  342.       tft.drawString("88:88:88",10,10,7);
  343.       tft.setTextColor(rgb565Decimal, TFT_BLACK);
  344.       tft.drawString (timeString, 10, 10, 7);
  345.       tft.setTextColor(TFT_WHITE);
  346.       tft.setCursor(0,60,2);
  347.       tft.print(weatherStatement);
  348.       tft.setCursor(190, 60 ,2);
  349.       tft.println(out);
  350. #endif
  351.      
  352.     }
  353.     vTaskDelay (1000/portTICK_PERIOD_MS);
  354.   }
  355. }
Advertisement
Add Comment
Please, Sign In to add comment