Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <FS.h> //this needs to be first, or it all crashes and burns...
- #include <Arduino.h>
- #include <ArduinoOTA.h>
- //sets up wifi accesspoint/connection
- #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
- #include <ESP8266mDNS.h>
- //IR libs
- #include <IRremoteESP8266.h>
- #include <IRsend.h>
- //Time + Weather Stuff
- #include <WifiUDP.h> //also for OTA
- #include <NTPClient.h>
- #include <Time.h>
- #include <TimeLib.h>
- #include <Timezone.h>
- #include <JsonListener.h>
- #include "OpenWeatherMapCurrent.h"
- //Webpage
- #include <ESP8266WebServer.h>
- #include "index.h" //Our HTML webpage contents with javascripts
- //LEDs
- #define LED 2 //On board LED
- #define IR_LED 4 // ESP8266 GPIO pin to use. Recommended: 4 (D2).
- // Define NTP properties
- #define NTP_OFFSET 60 * 60 // In seconds
- #define NTP_INTERVAL 60 * 1000 // In miliseconds
- #define NTP_ADDRESS "0.pool.ntp.org" // change this to whatever pool is closest (see ntp.org)
- #define TIME_BETWEEN_MESSAGES 20000
- IRsend irsend(IR_LED); //create instance of IRsend
- unsigned int frequency = 37600; // 38kHz carrier frequency for infoglobe
- ESP8266WebServer server(80); //Server on port 80
- bool messageLast = true;
- char* host = "Infoglobe";
- String readText;
- //Weather setup
- OpenWeatherMapCurrent client;
- String OPEN_WEATHER_MAP_APP_ID = "XXX";
- String OPEN_WEATHER_MAP_LOCATION = "XXX";
- String OPEN_WEATHER_MAP_LANGUAGE = "en";
- String currentWeather;
- boolean IS_METRIC = false;
- uint32_t lastWeatherUpdate = 0;
- WiFiUDP ntpUDP;
- uint32_t timeStart;
- NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);
- //===============================================================
- // FUNCTIONS
- //===============================================================
- void sendToGlobe(String outputMessage, String movementString = "0x04", String transitionString = "0x00"){
- //convert message string to unsigned char array
- unsigned char outputHex[35];
- for (int i = 0; i < outputMessage.length(); ++i) { //convert message string to char array
- outputHex[i] = outputMessage[i];
- }
- //convert header and transition to unsigned char
- unsigned long movementHexLong = strtoul(movementString.c_str(), NULL, 0); //convert movement string to unsigned long value
- unsigned char movementHex = movementHexLong; //convert unsigned long to char
- unsigned long transitionHexLong = strtoul(transitionString.c_str(), NULL, 0); //convert transition string to unsigned long value
- unsigned char transitionHex = transitionHexLong; //convert unsigned long to char
- //send everything to IR LED
- if (movementString == "0x00"){sendHexRaw(&movementHex, 1);} //"transition" type movement requires 2 sends
- sendHexRaw(&movementHex, 1); //header
- sendHexRaw(outputHex, outputMessage.length()); // Send a raw data capture
- if (movementString == "0x00"){sendHexRaw(&transitionHex, 1);}
- digitalWrite(IR_LED, LOW);
- }
- void sendHexRaw(unsigned char *sigArray, unsigned int sizeArray) {
- /* HEADER - the byte determines the transition effect
- When debugging note that first four bits of header should always be '0'
- 00 - loads message to buffer for transition effect
- 01 - Static message - blanks without message
- 02 - Flashing static message
- 03 - matches static/scroll of previous message
- 04 - scrolling (blanks without message)
- 05 - Overwrite portion of existing message
- 06 - Toggles scrolling when sent without a message
- MESSAGE - 35 characters max - if sending a message each byte is an ASCII character.
- characters not supported: % & + ; @ [ \ ] ^ _ ` { | } ~
- see http://hanixdiy.blogspot.com/2010/10/hacking-infoglobe-part-3.html for more details
- */
- irsend.enableIROut(frequency, 33);
- uint32_t delayTime;
- uint32_t sigTime = micros();
- for (unsigned int i = 0; i < sizeArray; i++) { //iterate thru each byte in sigArray
- register uint8_t bitMask = 0x80; //starting value of bitmask fo each Hex byte
- while (bitMask) { //do 8 times for each bit of the 8 bit byte
- sigTime += 1000; //Time 1ms after our last operation (or start)
- delayTime = sigTime - micros(); //The difference between current time and 1ms after our last bit
- if (bitMask & sigArray[i]) { //its a One bit
- irsend.space(delayTime); // LED off for 1000 usec = 1msec
- //Serial.print('1'); //for debug - ruins timing but ensures you use the correct bits
- }
- else { // its a Zero bit
- irsend.mark(delayTime);
- //Serial.print('0'); //for debug - ruins timing but ensures you use the correct bits
- }
- bitMask = (unsigned char) bitMask >> 1; // shift mask bit along until it reaches zero > exit the loop
- }
- }
- }
- void handleRoot() {
- String s = MAIN_page; //Read HTML contents
- server.send(200, "text/html", s); //Send web page
- }
- void handleMessage() { //Get current message from webpage
- readText = server.arg("readMessage"); //Refer to ("GET", "setMessage?readMessage="+ text +"&trans=" + transitionType, true);
- String movement = server.arg("movement");
- String transType = server.arg("transType");
- server.send(200, "text/plane", readText); //Send webpage current message
- //Used to see what is coming from the webpage as a test
- Serial.print("Current Message: ");
- Serial.println(readText);
- Serial.print("Movement Type: ");
- Serial.println(movement);
- Serial.print("Transition Type: ");
- Serial.println(transType);
- if (movement == "0x00"){
- sendToGlobe(readText, movement, transType);
- }
- else{
- sendToGlobe(readText, movement);
- }
- timeStart = millis();
- messageLast = true;
- } //end handleReadMessage
- String getTimeString(){
- String date;
- const char * days[] = {"Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"};
- const char * months[] = {"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"};
- const char * ampm[] = {"AM", "PM"};
- // update the NTP client and get the UNIX UTC timestamp
- timeClient.update();
- unsigned long epochTime = timeClient.getEpochTime();
- // convert received time stamp to time_t object
- time_t local, utc;
- utc = epochTime;
- // Then convert the UTC UNIX timestamp to local time
- TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -300}; //UTC - 4 hours - change this as needed
- TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -360}; //UTC - 5 hours - change this as needed
- Timezone usEastern(usEDT, usEST);
- local = usEastern.toLocal(utc);
- // now format the Time variables into strings with proper names for month, day etc
- date += days[weekday(local)-1];
- date += ", ";
- date += months[month(local)-1];
- date += " ";
- date += day(local);
- date += " ";
- date += hourFormat12(local);
- date += ":";
- if(minute(local) < 10) // add a zero if minute is under 10
- date += "0";
- date += minute(local);
- date += " ";
- date += ampm[isPM(local)];
- timeStart = millis();
- return date;
- }
- String updateWeather(String weatherString){
- OpenWeatherMapCurrentData data;
- client.setLanguage(OPEN_WEATHER_MAP_LANGUAGE);
- client.setMetric(IS_METRIC);
- if ((millis() - lastWeatherUpdate > 900000) || (lastWeatherUpdate == 0)){
- client.updateCurrent(&data, OPEN_WEATHER_MAP_APP_ID, OPEN_WEATHER_MAP_LOCATION);
- weatherString = "Temp Low: ";
- weatherString += data.tempMin;
- weatherString += " High: ";
- weatherString += data.tempMax;
- lastWeatherUpdate = millis();
- Serial.println("Updated weather");
- }
- return weatherString;
- }
- //==============================================================
- // SETUP
- //==============================================================
- void setup(void){
- Serial.begin(115200);
- wifi_station_set_hostname(host);
- WiFiManager wifiManager;
- timeClient.begin(); // Start the NTP UDP client
- irsend.begin();
- //exit after config instead of connecting
- wifiManager.setBreakAfterConfig(true);
- //reset settings - for testing
- //wifiManager.resetSettings();
- //tries to connect to last known settings
- //if it does not connect it starts an access point with the specified name
- //here "AutoConnectAP" with password "password"
- //and goes into a blocking loop awaiting configuration
- if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
- Serial.println("failed to connect, we should reset to see if it connects");
- delay(3000);
- ESP.reset();
- delay(5000);
- } //if you get here you have connected to the WiFi
- //Really Gross looking Arduino OTA code
- ArduinoOTA.onStart([]() { Serial.println("Start OTA");});
- ArduinoOTA.onEnd([]() { Serial.println("\nEnd OTA"); });
- ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
- Serial.printf("Progress: %u%%\r", (progress / (total / 100))); });
- ArduinoOTA.onError([](ota_error_t error) {
- Serial.printf("Error[%u]: ", error);
- if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
- else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
- else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
- else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
- else if (error == OTA_END_ERROR) Serial.println("End Failed");
- });
- ArduinoOTA.begin();
- Serial.println("Connected to wifi...yeey :)");
- Serial.println("Local IP");
- Serial.println(WiFi.localIP());
- //sending IP to infoglobe
- readText = WiFi.localIP().toString(); //use readText to allow repeat before web access.
- Serial.println(readText);
- sendToGlobe(readText);
- //webserver commands
- server.on("/", handleRoot); //Which routine to handle at root location. This is display page
- server.on("/setMessage", handleMessage);
- server.begin(); //Start server
- Serial.println("HTTP server started");
- //set timer for showing current date/time for set duration
- timeStart = millis();
- } //end setup
- //==============================================================
- // LOOP
- //==============================================================
- void loop(void){
- ArduinoOTA.handle();
- server.handleClient(); //Handle client requests
- if ((millis() - timeStart > TIME_BETWEEN_MESSAGES) && (messageLast == true)){
- currentWeather = updateWeather(currentWeather);
- Serial.println(currentWeather);
- sendToGlobe(currentWeather);
- timeStart = millis();
- messageLast = false;
- }
- // if ((millis()-timeStart > TIME_BETWEEN_MESSAGES) && (messageLast == true)){
- // String timeString = getTimeString();
- // sendToGlobe(timeString);
- // timeStart = millis();
- // messageLast = false;
- // }
- else if ((millis() - timeStart > TIME_BETWEEN_MESSAGES) && (messageLast == false)){
- handleMessage(); //messageLast + timeStart set in handleMessage()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement