Advertisement
kd8bxp

Cheerlight Clock ported to TTGO T2 Board v2

Jul 25th, 2019
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.   Cheerlights Clock for TTGO T2 board v2
  3.  based on @martinbateman clock code
  4.  https://t.co/1gRc56wNOE
  5.  https://pastebin.com/4Ec6d4xY
  6.  
  7. ported to TTGO T2 Board by LeRoy Miller July 25, 2019
  8.  
  9. added Geolocate Timezone code July 25, 2019
  10.  
  11. */
  12.  
  13.  
  14. #include <WiFi.h>
  15. #include <NTPClient.h>
  16. #include <WiFiUdp.h>
  17. #include <PubSubClient.h>
  18. #include <SPI.h>
  19. #include <TimeLib.h>
  20. #include <Adafruit_GFX.h>
  21. #include <Adafruit_SSD1331.h>
  22. #include <ArduinoJson.h>  //use version 5.13.5
  23. #include <HTTPClient.h>
  24. #include <DNSServer.h>
  25.  
  26. #define sclk 14
  27. #define mosi 13
  28. #define cs   15
  29. #define rst  4
  30. #define dc   16
  31.  
  32. #define TFT_BL          -1  // Display backlight control pin
  33. // Color definitions
  34. #define TFT_BLACK           0x0000
  35. #define TFT_BLUE            0x001F
  36. #define TFT_RED             0xF800
  37. #define TFT_GREEN           0x07E0
  38. #define TFT_CYAN            0x07FF
  39. #define TFT_MAGENTA         0xF81F
  40. #define TFT_YELLOW          0xFFE0
  41. #define TFT_WHITE           0xFFFF
  42.  
  43.  
  44. // Replace with your network credentials
  45. const char* ssid     = "xxxxx";
  46. const char* password = "xxxxx";
  47. const char* mqtt_server = "simplesi.cloud";
  48.  
  49. //TimeZone variables
  50. String TZAPIKEY="xxxxxxxx";  //http://timezonedb.com used to get gmtOffset
  51. String payload, TZone, lastUpdate;
  52. String coordinate; // = lat,lon
  53. String coordinateTZ; //lat=xx.xxx&lng=xxx.xxx
  54. long  gmtOffset_sec;
  55. const int   daylightOffset_sec = 0;
  56.  
  57. //Original Code
  58. int cheer_red = 0;
  59. int cheer_green = 0;
  60. int cheer_blue = 0;
  61. unsigned int rgb565Decimal = 0x8410;
  62. unsigned int newrgb565Decimal;
  63. String colourString = "";
  64. String newColourString;
  65.  
  66. String strData;
  67. String topicStr;
  68.  
  69.  
  70. Adafruit_SSD1331 tft = Adafruit_SSD1331(cs, dc, mosi, sclk, rst);
  71. WiFiUDP ntpUDP;
  72. NTPClient timeClient(ntpUDP);
  73. WiFiClient espClient;
  74. PubSubClient client(espClient);
  75.  
  76. SemaphoreHandle_t serialMutex = NULL;
  77. void Task1 (void *pvParams);
  78. void Task2 (void *pvParams);
  79.  
  80. void callback(char* topic, byte* payload, unsigned int length) {
  81.  
  82.   Serial.print("Message arrived in topic: ");
  83.   Serial.println(topic);
  84.   topicStr = topic;
  85.  
  86.   Serial.print("Message:");
  87.  
  88.   strData = "";
  89.   for (int i = 0; i < length; i++) {
  90.     Serial.print((char)payload[i]);
  91.     strData += (char)payload[i];
  92.   }
  93.  
  94.   Serial.println();
  95.   Serial.println("-----------------------");
  96.  
  97.   if (topicStr.endsWith("cheerlights/rgb565Decimal")) {
  98.    
  99.     colourString = newColourString;
  100.     rgb565Decimal = strData.toInt();
  101.     Serial.println("*******");
  102.  
  103.     Serial.println(rgb565Decimal);
  104.   }  
  105.   if (topicStr.endsWith("cheerlights")) {
  106.    
  107.     newColourString = "\n" + strData + "                "; //newColourString = "Cheerlights:\n" + strData;
  108.     //sixteenBitHex = newSixteenBitHex;
  109.     Serial.println(strData);
  110.   }  
  111. } // end callback
  112.  
  113. void reconnect() {
  114.   // Loop until we're reconnected
  115.   while (!client.connected()) {
  116.     Serial.print("Attempting MQTT connection...");
  117.     // Create a random client ID
  118.     String clientId = "ESP32Client-";
  119.     clientId += String(random(0xffff), HEX);
  120.     // Attempt to connect
  121.     if (client.connect(clientId.c_str())) {
  122.       Serial.println("connected");
  123.       client.subscribe("cheerlights",1);
  124.       client.subscribe("cheerlights/rgb565Decimal",1);
  125.     } else {
  126.       Serial.print("failed, rc=");
  127.       Serial.print(client.state());
  128.       Serial.println(" try again in 5 seconds");
  129.       // Wait 5 seconds before retrying
  130.       delay(5000);
  131.     }
  132.   }
  133. }
  134.  
  135. void setup() {
  136.   // put your setup code here, to run once:
  137.   Serial.begin (9600);
  138.   serialMutex = xSemaphoreCreateMutex ();
  139.  
  140.   if (TFT_BL > 0) {
  141.     pinMode(TFT_BL, OUTPUT);
  142.     digitalWrite(TFT_BL, HIGH);
  143.   }
  144.  
  145.   tft.begin(); //tft.SSD1331_Init();
  146.   //tft.setRotation(1);
  147.  
  148.   tft.fillScreen(TFT_BLACK);
  149.  
  150.   tft.setTextColor(TFT_YELLOW, TFT_BLACK); // Note: the new fonts do not draw the background colour
  151.  
  152.   WiFi.begin(ssid, password);
  153.   while (WiFi.status() != WL_CONNECTED) {
  154.     delay(500);
  155.     Serial.println (".");
  156.   }
  157.   Serial.println(WiFi.localIP());
  158.  
  159. geolocation(); //get latitude/longitude from external IP address (used to find Time zone)
  160. timeZone(); //used to get time zone
  161.  
  162.   timeClient.begin();
  163.   timeClient.setTimeOffset(gmtOffset_sec); //timeClient.setTimeOffset(3600);
  164.   client.setServer(mqtt_server, 1883);
  165.   client.setCallback(callback);
  166.  
  167.  
  168.   xTaskCreate (updateNTP, "NTP Client", 4096, NULL, 2, NULL);
  169.   xTaskCreate (updateScreen, "Screen", 4096, NULL, 1, NULL);
  170. }
  171.  
  172. void loop() {
  173.   if (!client.connected()) {
  174.     reconnect();
  175.   }
  176.   client.loop();
  177. }
  178.  
  179. void getJson(String url) {
  180.  
  181.    if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
  182.      HTTPClient http;  //Declare an object of class HTTPClient
  183.      http.begin(url);  //Specify request destination
  184.     int httpCode = http.GET();                                                                  //Send the request
  185.      if (httpCode > 0) { //Check the returning code
  186.        payload = http.getString();   //Get the request response payload
  187.      
  188.     }
  189.  
  190.     http.end();   //Close connection
  191.  
  192.   }
  193. }
  194.  
  195.  
  196. void geolocation(){
  197.  
  198.     String url;
  199.     url = "http://ip-api.com/json";
  200.     getJson(url);
  201.  
  202.   const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
  203.   DynamicJsonBuffer jsonBuffer(capacity);
  204.   JsonObject& root = jsonBuffer.parseObject(payload);
  205.   root.printTo(Serial);
  206.   if (!root.success()) {
  207.     Serial.println("parseObject() failed");
  208.     return;
  209.   }
  210.  
  211.   // Extract values
  212.   Serial.println(("Response:"));
  213.   Serial.println(root["lat"].as<char*>());
  214.   Serial.println(root["lon"].as<char*>());
  215.   coordinate = String(root["lat"].as<char*>()) + "," + String(root["lon"].as<char*>());
  216.   //coordinatePrev = "lat=" + String(root["lat"].as<char*>()) + "&lon=" + String(root["lon"].as<char*>()); //do we use this anywhere (?)
  217.   coordinateTZ = "lat=" + String(root["lat"].as<char*>()) + "&lng=" + String(root["lon"].as<char*>());
  218.   //mylat = root["lat"];
  219.   //mylon = root["lon"];
  220.  // M5.Lcd.println("My Lat/Lon: "+coordinate);
  221.  Serial.println("My Lat/Lon: "+coordinate);
  222. }
  223.  
  224. /*
  225.  * Used to get the GMT offset for your timezone
  226.  */
  227.  
  228.  void timeZone() {
  229.  String url;
  230.  url = "http://api.timezonedb.com/v2/get-time-zone?key=" + TZAPIKEY + "&format=json&fields=gmtOffset,abbreviation&by=position&"+coordinateTZ;
  231.  getJson(url);
  232.   StaticJsonBuffer<512> jsonBuffer;
  233.   JsonObject& root = jsonBuffer.parseObject(payload);
  234.   if (!root.success()) {
  235.     Serial.println("parseObject() failed");
  236.     return;
  237.   }
  238.   gmtOffset_sec = root["gmtOffset"];
  239.   const char* temp1 = root["abbreviation"];
  240.   TZone = (String)temp1;
  241.   Serial.print("GMT Offset = ");
  242.   Serial.print(gmtOffset_sec);
  243.   Serial.println(" " + TZone);
  244.   //M5.Lcd.println("GMT Offset = "+(String)gmtOffset_sec);
  245. }
  246.  
  247.  
  248.  
  249.  
  250. void updateNTP (void *pvParameters) {
  251.   (void) pvParameters;
  252.  
  253.   for (;;) {
  254.     if (xSemaphoreTake (serialMutex, (TickType_t)10) == pdTRUE) {
  255.       while(!timeClient.update()) {
  256.         timeClient.forceUpdate();
  257.       }
  258.       setTime (timeClient.getEpochTime ());
  259.       xSemaphoreGive (serialMutex);
  260.     }
  261.     vTaskDelay ((1000/portTICK_PERIOD_MS) * 60 * 60);  // update every hour
  262.   }
  263. }
  264.  
  265. void updateScreen (void *pvParameters) {
  266.   (void) pvParameters;
  267.  
  268.   for (;;) {
  269.     if (xSemaphoreTake (serialMutex, (TickType_t)10) == pdTRUE) {
  270.       char timeString[25];
  271.       char colourString2[25];
  272.       colourString.toCharArray(colourString2,25);
  273.  
  274.       time_t t = now ();
  275.       sprintf (timeString, "%02i:%02i:%02i", hour (t), minute (t), second (t));
  276.       xSemaphoreGive (serialMutex);
  277.       tft.setTextSize(2);
  278.       tft.setTextColor(0x39C4, TFT_BLACK);
  279.       //tft.setCursor(0,0);
  280.       //tft.print("88:88:88"); //tft.drawString("88:88:88",10,10,7);
  281.       tft.setTextColor(rgb565Decimal, TFT_BLACK);
  282.       tft.setCursor(0,0);
  283.       tft.print(timeString); //tft.drawString (timeString, 10, 10, 7);
  284.       tft.setTextSize(1);
  285.       tft.setCursor(0,18);
  286.       //tft.print(colourString2); //tft.drawString (colourString2, 0, 80, 4);
  287.       tft.println("Cheerlights:");
  288.       tft.setTextSize(2);
  289.       tft.print(colourString2);
  290.     }
  291.     vTaskDelay (1000/portTICK_PERIOD_MS);
  292.   }
  293. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement