5 files changed, 360 insertions(+), 0 deletions(-)

A => include/README
A => lib/README
A => platformio.ini
A => src/main.cpp
A => test/README
A => include/README +39 -0
@@ 0,0 1,39 @@ 
+
+This directory is intended for project header files.
+
+A header file is a file containing C declarations and macro definitions
+to be shared between several project source files. You request the use of a
+header file in your project source file (C, C++, etc) located in `src` folder
+by including it, with the C preprocessing directive `#include'.
+
+```src/main.c
+
+#include "header.h"
+
+int main (void)
+{
+ ...
+}
+```
+
+Including a header file produces the same results as copying the header file
+into each source file that needs it. Such copying would be time-consuming
+and error-prone. With a header file, the related declarations appear
+in only one place. If they need to be changed, they can be changed in one
+place, and programs that include the header file will automatically use the
+new version when next recompiled. The header file eliminates the labor of
+finding and changing all the copies as well as the risk that a failure to
+find one copy will result in inconsistencies within a program.
+
+In C, the usual convention is to give header files names that end with `.h'.
+It is most portable to use only letters, digits, dashes, and underscores in
+header file names, and at most one dot.
+
+Read more about using header files in official GCC documentation:
+
+* Include Syntax
+* Include Operation
+* Once-Only Headers
+* Computed Includes
+
+https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

          
A => lib/README +46 -0
@@ 0,0 1,46 @@ 
+
+This directory is intended for project specific (private) libraries.
+PlatformIO will compile them to static libraries and link into executable file.
+
+The source code of each library should be placed in a an own separate directory
+("lib/your_library_name/[here are source files]").
+
+For example, see a structure of the following two libraries `Foo` and `Bar`:
+
+|--lib
+|  |
+|  |--Bar
+|  |  |--docs
+|  |  |--examples
+|  |  |--src
+|  |     |- Bar.c
+|  |     |- Bar.h
+|  |  |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
+|  |
+|  |--Foo
+|  |  |- Foo.c
+|  |  |- Foo.h
+|  |
+|  |- README --> THIS FILE
+|
+|- platformio.ini
+|--src
+   |- main.c
+
+and a contents of `src/main.c`:
+```
+#include <Foo.h>
+#include <Bar.h>
+
+int main (void)
+{
+  ...
+}
+
+```
+
+PlatformIO Library Dependency Finder will find automatically dependent
+libraries scanning project source files.
+
+More information about PlatformIO Library Dependency Finder
+- https://docs.platformio.org/page/librarymanager/ldf.html

          
A => platformio.ini +26 -0
@@ 0,0 1,26 @@ 
+; PlatformIO Project Configuration File
+;
+;   Build options: build flags, source filter
+;   Upload options: custom upload port, speed and extra flags
+;   Library options: dependencies, extra library storages
+;   Advanced options: extra scripting
+;
+; Please visit documentation for the other options and examples
+; https://docs.platformio.org/page/projectconf.html
+
+[env:nodemcuv2]
+#upload_protocol = espota
+#upload_port = 192.168.5.73
+#upload_flags = --auth=0123
+platform = espressif8266
+platform_packages = 
+	platformio/framework-arduinoespressif8266 @ https://github.com/esp8266/Arduino.git
+board = nodemcuv2
+framework = arduino
+lib_deps = 
+	tzapu/WiFiManager
+	https://github.com/esp8266/ESPWebServer.git
+	bblanchon/ArduinoJson@^6.18.4
+	arduino-libraries/NTPClient@^3.1.0
+	mathertel/OneButton@^2.0.2
+	jwrw/ESP_EEPROM@^2.1.1

          
A => src/main.cpp +238 -0
@@ 0,0 1,238 @@ 
+#include <FS.h>                   //this needs to be first, or it all crashes and burns...
+
+#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
+#include <ESP8266mDNS.h>
+#include <WiFiUdp.h>
+#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
+#include <NTPClient.h>
+#include <ArduinoOTA.h>
+#include <Arduino.h>
+#include <ArduinoJson.h>
+#include <SHT1x.h>
+#include <ESP_EEPROM.h>
+#include <OneButton.h>
+
+/*
+ * This is a simple ESP8266/Arduino based firmware.
+ *
+ * The wifi configuration and serial numbers are configured via 
+ * a custom wireless network/captive portal. Connect to its 
+ * ssid to provide the configuration information. Holding the 
+ * flash button down for 1 second will cause the configuration
+ * to be reset and the device to enter access point mode.
+ */
+
+#define DEBUG(X...) do{if(Serial)Serial.println(X);}while(0)
+#define DEBUGCHAR(X...) do{if(Serial)Serial.print(X);}while(0)
+
+#define FIRMWARE_REVISION 1024
+#define EEPROM_BYTES_NEEDED 50
+	
+#define SLOW 250
+#define MEDIUM 100
+#define FAST 50
+
+#define sleep(X) delay(X)
+#define ON 1
+#define OFF 0
+
+WiFiClient wifiClient;
+
+WiFiUDP ntpUdp;
+
+NTPClient timeClient(ntpUdp);
+
+// 'flash' button is pin 0
+#define BUTTON_PIN 0
+
+OneButton btn = OneButton(
+        BUTTON_PIN,  // Input pin for the button
+        true,        // Button is active LOW
+        true         // Enable internal pull-up resistor
+);
+
+long ts;
+
+void blink(int speed, int count) {
+    pinMode(16, OUTPUT);
+    for(; count > 0; count--) {
+        digitalWrite(16, ON);
+        sleep(speed);
+        digitalWrite(16, OFF);
+        sleep(speed);
+    }
+    digitalWrite(16, ON);
+}
+
+//! clear the wifi configuration and restart the device in AP mode.
+void resetEverything() {
+    WiFi.enableSTA(true);
+    WiFi.persistent(true);
+    WiFi.disconnect(true);
+    WiFi.persistent(false);
+
+    delay(250);
+    ESP.reset();
+    delay(5000);
+}
+
+/* the following definitions are used to indicate that values
+ * should be saved to eprom or read from eeprom.
+ */
+bool shouldSaveConfig = false;
+bool enteredConfigMode = false;
+void configModeCallback (WiFiManager *myWiFiManager) {
+    Serial.println("config mode");
+    enteredConfigMode = true;
+}
+void saveConfigCallback () {
+    Serial.println("Should save config now");
+    if(enteredConfigMode)
+        shouldSaveConfig = true;
+}
+
+void writeStringToEEPROM(int addrOffset, const String &strToWrite)
+{
+    uint8_t len = strToWrite.length();
+    EEPROM.write(addrOffset, len);
+    for (int i = 0; i < len; i++)
+    {
+        EEPROM.write(addrOffset + 1 + i, strToWrite[i]);
+    }
+}
+
+String readStringFromEEPROM(int addrOffset)
+{
+    uint8_t newStrLen;
+    Serial.println("reading a string from eeprom");
+    EEPROM.get(addrOffset, newStrLen);
+
+    char data[newStrLen + 1];
+    for (int i = 0; i < newStrLen; i++)
+    {
+        data[i] = EEPROM.read(addrOffset + 1 + i);
+    }
+    data[newStrLen] = '\0'; 
+    return String(data);
+}
+//***********************************************
+
+void wifi_register_custom_params(WifiManager wifiManager) {
+    WiFiManagerParameter hub_serial_number("hubsn", "HubSerialNumber", "10010", 7);
+    wifiManager.addParameter(&hub_serial_number);
+
+    WiFiManagerParameter air_serial_number("airsn", "AirSerialNumber", "10012", 7);
+    wifiManager.addParameter(&air_serial_number);
+}
+
+void wifi_write_custom_params() {
+    String hs ="HB-";
+    hs = hs + (hub_serial_number.getValue());
+    hubsn = hs;
+    String as = "AR-";
+    as = as + (air_serial_number.getValue());
+    airsn = as;
+    writeStringToEEPROM(0, hubsn); // 7 bytes max
+    writeStringToEEPROM(15, airsn); // 7 bytes max
+    if(!EEPROM.commit()) resetEverything();
+    delay(100);
+}
+
+void wifi_read_custom_params() {
+    hubsn = readStringFromEEPROM(0);
+    airsn = readStringFromEEPROM(15);
+}
+
+void setup() {
+    blink(MEDIUM, 10);
+    // put your setup code here, to run once:
+    if(Serial)
+        Serial.begin(115200);
+
+    DEBUG("Welcome\n");
+
+    delay(100);
+   // resetEverything();
+    //WiFiManager
+    //Local intialization. Once its business is done, there is no need to keep it around
+    WiFiManager wifiManager;
+
+    wifi_register_custom_params(wifiManager); 
+
+    //exit after config instead of connecting
+   wifiManager.setBreakAfterConfig(true);
+
+    wifiManager.setAPCallback(configModeCallback);
+    wifiManager.setSaveConfigCallback(saveConfigCallback);
+    //reset settings - for testing - seems broken, see resetEverything()
+    //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()) {
+        DEBUG("WifiManager: failed to connect, we should reset as see if it connects");
+        delay(3000);
+        ESP.reset();
+        delay(5000);
+    }
+
+    blink(MEDIUM, 2);
+
+  ArduinoOTA.onStart([]() {
+        DEBUG("OTA Start");
+    });
+    ArduinoOTA.onEnd([]() {
+        DEBUG("\nOTA End");
+    });
+    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
+        if(Serial) Serial.printf("OTA: Progress: %u%%\r", (progress / (total / 100)));
+    });
+    ArduinoOTA.onError([](ota_error_t error) {
+        if(Serial) Serial.printf("OTA Error[%u]: ", error);
+        if (error == OTA_AUTH_ERROR) DEBUG("OTA: Auth Failed");
+        else if (error == OTA_BEGIN_ERROR) DEBUG("OTA: Begin Failed");
+        else if (error == OTA_CONNECT_ERROR) DEBUG("OTA: Connect Failed");
+        else if (error == OTA_RECEIVE_ERROR) DEBUG("OTA: Receive Failed");
+        else if (error == OTA_END_ERROR) DEBUG("OTA: End Failed");
+    });
+
+    ArduinoOTA.setPassword((const char *)"0681");
+
+    //if you get here you have connected to the WiFi
+    DEBUG("connected...yay :)");
+
+    ArduinoOTA.begin();
+
+    DEBUG("local ip: ");
+    DEBUG(WiFi.localIP());
+
+    EEPROM.begin(EEPROM_BYTES_NEEDED);
+
+    if (shouldSaveConfig) {
+		wifi_write_custom_params();
+    } else if(1){
+		wifi_read_custom_params();
+      
+    }
+	
+    timeClient.begin();
+
+    delay(1000);
+    Serial.println("ready to read");
+
+    btn.attachLongPressStart(resetEverything);
+}
+
+void loop() {
+    timeClient.update();
+    ArduinoOTA.handle();
+    btn.tick();
+
+    // don't update this every loop else you'll waste cpu
+    ts = timeClient.getEpochTime();
+
+    delay(100);
+}

          
A => test/README +11 -0
@@ 0,0 1,11 @@ 
+
+This directory is intended for PlatformIO Unit Testing and project tests.
+
+Unit Testing is a software testing method by which individual units of
+source code, sets of one or more MCU program modules together with associated
+control data, usage procedures, and operating procedures, are tested to
+determine whether they are fit for use. Unit testing finds problems early
+in the development cycle.
+
+More information about PlatformIO Unit Testing:
+- https://docs.platformio.org/page/plus/unit-testing.html