kd8bxp

T-Display TTGO T2 M5StickC Cheerlights Clock v6.1

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