kd8bxp

v6.2 display weather brief on M5StickC

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