Advertisement
cymplecy

Cheerlights Clock for TTGO-T-DISPLAY

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