Advertisement
greenmikey

Untitled

Sep 29th, 2022
1,527
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 10.83 KB | Source Code | 0 0
  1. #include <FS.h>                   //this needs to be first, or it all crashes and burns...
  2. #include <Arduino.h>
  3. #include <ArduinoOTA.h>  
  4.  
  5. //sets up wifi accesspoint/connection
  6. #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
  7. #include <ESP8266mDNS.h>
  8.  
  9. //IR libs
  10. #include <IRremoteESP8266.h>
  11. #include <IRsend.h>
  12.  
  13. //Time + Weather Stuff
  14. #include <WifiUDP.h> //also for OTA
  15. #include <NTPClient.h>
  16. #include <Time.h>
  17. #include <TimeLib.h>
  18. #include <Timezone.h>
  19. #include <JsonListener.h>
  20. #include "OpenWeatherMapCurrent.h"
  21.  
  22. //Webpage
  23. #include <ESP8266WebServer.h>
  24. #include "index.h" //Our HTML webpage contents with javascripts
  25.  
  26. //LEDs
  27. #define LED 2  //On board LED
  28. #define IR_LED 4  // ESP8266 GPIO pin to use. Recommended: 4 (D2).
  29.  
  30. // Define NTP properties
  31. #define NTP_OFFSET   60 * 60      // In seconds
  32. #define NTP_INTERVAL 60 * 1000    // In miliseconds
  33. #define NTP_ADDRESS  "0.pool.ntp.org"  // change this to whatever pool is closest (see ntp.org)
  34. #define TIME_BETWEEN_MESSAGES 20000
  35.  
  36. IRsend irsend(IR_LED);  //create instance of IRsend
  37. unsigned int frequency = 37600; // 38kHz carrier frequency for infoglobe
  38.  
  39. ESP8266WebServer server(80); //Server on port 80
  40. bool messageLast = true;
  41. char* host = "Infoglobe";
  42. String readText;
  43.  
  44. //Weather setup
  45. OpenWeatherMapCurrent client;
  46. String OPEN_WEATHER_MAP_APP_ID = "XXX";
  47. String OPEN_WEATHER_MAP_LOCATION = "XXX";
  48. String OPEN_WEATHER_MAP_LANGUAGE = "en";
  49. String currentWeather;
  50. boolean IS_METRIC = false;
  51. uint32_t lastWeatherUpdate = 0;
  52.  
  53. WiFiUDP ntpUDP;
  54. uint32_t timeStart;
  55. NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);
  56.  
  57. //===============================================================
  58. //                    FUNCTIONS
  59. //===============================================================
  60.  
  61. void sendToGlobe(String outputMessage, String movementString = "0x04", String transitionString = "0x00"){
  62.   //convert message string to unsigned char array
  63.   unsigned char outputHex[35];
  64.   for (int i = 0; i < outputMessage.length(); ++i) {  //convert message string to char array
  65.     outputHex[i] = outputMessage[i];
  66.   }
  67.  
  68.   //convert header and transition to unsigned char
  69.   unsigned long movementHexLong = strtoul(movementString.c_str(), NULL, 0); //convert movement string to unsigned long value
  70.   unsigned char movementHex = movementHexLong; //convert unsigned long to char
  71.  
  72.   unsigned long transitionHexLong = strtoul(transitionString.c_str(), NULL, 0); //convert transition string to unsigned long value
  73.   unsigned char transitionHex = transitionHexLong; //convert unsigned long to char
  74.  
  75.   //send everything to IR LED
  76.  
  77.   if (movementString == "0x00"){sendHexRaw(&movementHex, 1);} //"transition" type movement requires 2 sends
  78.   sendHexRaw(&movementHex, 1); //header
  79.   sendHexRaw(outputHex, outputMessage.length());  // Send a raw data capture
  80.   if (movementString == "0x00"){sendHexRaw(&transitionHex, 1);}
  81.   digitalWrite(IR_LED, LOW);
  82. }
  83.  
  84. void sendHexRaw(unsigned char *sigArray, unsigned int sizeArray) {
  85.   /*  HEADER - the byte determines the transition effect
  86.       When debugging note that first four bits of header should always be '0'
  87.       00 - loads message to buffer for transition effect
  88.       01 - Static message - blanks without message
  89.       02 - Flashing static message
  90.       03 - matches static/scroll of previous message
  91.       04 - scrolling (blanks without message)
  92.       05 - Overwrite portion of existing message
  93.       06 - Toggles scrolling when sent without a message
  94.  
  95.       MESSAGE - 35 characters max - if sending a message each byte is an ASCII character.
  96.       characters not supported: % & + ; @ [ \ ] ^ _ ` { | } ~
  97.  
  98.       see http://hanixdiy.blogspot.com/2010/10/hacking-infoglobe-part-3.html for more details
  99.   */
  100.   irsend.enableIROut(frequency, 33);
  101.   uint32_t delayTime;
  102.   uint32_t sigTime = micros();
  103.   for (unsigned int i = 0; i < sizeArray; i++) { //iterate thru each byte in sigArray
  104.     register uint8_t bitMask =  0x80; //starting value of bitmask fo each Hex byte
  105.     while (bitMask) { //do 8 times for each bit of the 8 bit byte
  106.       sigTime += 1000;  //Time 1ms after our last operation (or start)
  107.       delayTime = sigTime - micros(); //The difference between current time and 1ms after our last bit
  108.       if (bitMask & sigArray[i]) { //its a One bit
  109.         irsend.space(delayTime); // LED off for 1000 usec = 1msec
  110.         //Serial.print('1');  //for debug - ruins timing but ensures you use the correct bits
  111.       }
  112.       else { // its a Zero bit
  113.         irsend.mark(delayTime);
  114.         //Serial.print('0'); //for debug - ruins timing but ensures you use the correct bits
  115.       }
  116.       bitMask = (unsigned char) bitMask >> 1; // shift mask bit along until it reaches zero > exit the loop
  117.     }
  118.   }
  119. }
  120.  
  121. void handleRoot() {
  122.   String s = MAIN_page; //Read HTML contents
  123.   server.send(200, "text/html", s); //Send web page
  124. }
  125.  
  126. void handleMessage() {   //Get current message from webpage
  127.   readText = server.arg("readMessage"); //Refer to ("GET", "setMessage?readMessage="+ text +"&trans=" + transitionType, true);
  128.   String movement = server.arg("movement");
  129.   String transType = server.arg("transType");
  130.   server.send(200, "text/plane", readText); //Send webpage current message
  131.  
  132.   //Used to see what is coming from the webpage as a test
  133.   Serial.print("Current Message: ");
  134.   Serial.println(readText);
  135.   Serial.print("Movement Type: ");
  136.   Serial.println(movement);
  137.   Serial.print("Transition Type: ");
  138.   Serial.println(transType);
  139.  
  140.   if (movement == "0x00"){
  141.     sendToGlobe(readText, movement, transType);
  142.   }
  143.   else{
  144.     sendToGlobe(readText, movement);
  145.   }
  146.   timeStart = millis();
  147.   messageLast = true;
  148. }  //end handleReadMessage
  149.  
  150. String getTimeString(){
  151.   String date;
  152.   const char * days[] = {"Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"};
  153.   const char * months[] = {"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"};
  154.   const char * ampm[] = {"AM", "PM"};
  155.    
  156.   // update the NTP client and get the UNIX UTC timestamp
  157.   timeClient.update();
  158.   unsigned long epochTime =  timeClient.getEpochTime();
  159.  
  160.   // convert received time stamp to time_t object
  161.   time_t local, utc;
  162.   utc = epochTime;
  163.  
  164.   // Then convert the UTC UNIX timestamp to local time
  165.   TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -300};  //UTC - 4 hours - change this as needed
  166.   TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -360};   //UTC - 5 hours - change this as needed
  167.   Timezone usEastern(usEDT, usEST);
  168.   local = usEastern.toLocal(utc);
  169.  
  170.   // now format the Time variables into strings with proper names for month, day etc
  171.   date += days[weekday(local)-1];
  172.   date += ", ";
  173.   date += months[month(local)-1];
  174.   date += " ";
  175.   date += day(local);
  176.   date += " ";
  177.   date += hourFormat12(local);
  178.   date += ":";
  179.   if(minute(local) < 10)  // add a zero if minute is under 10
  180.     date += "0";
  181.   date += minute(local);
  182.   date += " ";
  183.   date += ampm[isPM(local)];
  184.   timeStart = millis();
  185.   return date;
  186. }
  187.  
  188. String updateWeather(String weatherString){
  189.  
  190.   OpenWeatherMapCurrentData data;
  191.   client.setLanguage(OPEN_WEATHER_MAP_LANGUAGE);
  192.   client.setMetric(IS_METRIC);
  193.   if ((millis() - lastWeatherUpdate > 900000) || (lastWeatherUpdate == 0)){
  194.      client.updateCurrent(&data, OPEN_WEATHER_MAP_APP_ID, OPEN_WEATHER_MAP_LOCATION);
  195.      weatherString = "Temp Low: ";
  196.      weatherString += data.tempMin;
  197.      weatherString += "  High: ";
  198.      weatherString += data.tempMax;
  199.      lastWeatherUpdate = millis();
  200.      Serial.println("Updated weather");
  201.   }
  202.   return weatherString;
  203. }
  204.  
  205.  
  206. //==============================================================
  207. //                  SETUP
  208. //==============================================================
  209. void setup(void){
  210.   Serial.begin(115200);
  211.   wifi_station_set_hostname(host);
  212.   WiFiManager wifiManager;
  213.   timeClient.begin();   // Start the NTP UDP client
  214.   irsend.begin();
  215.  
  216.   //exit after config instead of connecting
  217.   wifiManager.setBreakAfterConfig(true);
  218.  
  219.   //reset settings - for testing
  220.   //wifiManager.resetSettings();
  221.  
  222.   //tries to connect to last known settings
  223.   //if it does not connect it starts an access point with the specified name
  224.   //here  "AutoConnectAP" with password "password"
  225.   //and goes into a blocking loop awaiting configuration
  226.   if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
  227.     Serial.println("failed to connect, we should reset to see if it connects");
  228.     delay(3000);
  229.     ESP.reset();
  230.     delay(5000);
  231.   }  //if you get here you have connected to the WiFi
  232.  
  233.   //Really Gross looking Arduino OTA code
  234.   ArduinoOTA.onStart([]() { Serial.println("Start OTA");});
  235.   ArduinoOTA.onEnd([]() { Serial.println("\nEnd OTA"); });
  236.   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  237.     Serial.printf("Progress: %u%%\r", (progress / (total / 100))); });
  238.   ArduinoOTA.onError([](ota_error_t error) {
  239.     Serial.printf("Error[%u]: ", error);
  240.     if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  241.     else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  242.     else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  243.     else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  244.     else if (error == OTA_END_ERROR) Serial.println("End Failed");
  245.     });
  246.   ArduinoOTA.begin();
  247.   Serial.println("Connected to wifi...yeey :)");
  248.   Serial.println("Local IP");
  249.   Serial.println(WiFi.localIP());
  250.  
  251.   //sending IP to infoglobe
  252.   readText = WiFi.localIP().toString();  //use readText to allow repeat before web access.
  253.   Serial.println(readText);
  254.   sendToGlobe(readText);
  255.  
  256.   //webserver commands
  257.   server.on("/", handleRoot);      //Which routine to handle at root location. This is display page
  258.   server.on("/setMessage", handleMessage);
  259.  
  260.   server.begin();                  //Start server
  261.   Serial.println("HTTP server started");
  262.  
  263.   //set timer for showing current date/time for set duration
  264.   timeStart = millis();
  265. }  //end setup
  266.  
  267. //==============================================================
  268. //                     LOOP
  269. //==============================================================
  270. void loop(void){
  271.   ArduinoOTA.handle();
  272.   server.handleClient();      //Handle client requests
  273.   if ((millis() - timeStart > TIME_BETWEEN_MESSAGES) && (messageLast == true)){
  274.     currentWeather = updateWeather(currentWeather);
  275.     Serial.println(currentWeather);
  276.     sendToGlobe(currentWeather);
  277.     timeStart = millis();
  278.     messageLast = false;
  279.   }
  280.  
  281.   // if ((millis()-timeStart > TIME_BETWEEN_MESSAGES) && (messageLast == true)){
  282.   //   String timeString = getTimeString();
  283.   //   sendToGlobe(timeString);
  284.   //   timeStart = millis();
  285.   //   messageLast = false;
  286.   // }
  287.   else if ((millis() - timeStart > TIME_BETWEEN_MESSAGES) && (messageLast == false)){
  288.     handleMessage(); //messageLast + timeStart set in handleMessage()
  289.   }
  290. }
  291.  
Tags: infoglobe
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement