Advertisement
Snelvuur

Untitled

May 25th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Required Libarys:
  2. // async-mqtt-client:  https://codeload.github.com/marvinroger/async-mqtt-client/zip/master
  3. // ESPAsyncTCP:        https://codeload.github.com/me-no-dev/ESPAsyncTCP/zip/master
  4. // HX711:              https://codeload.github.com/bogde/HX711/zip/master
  5.  
  6. #include <ESP8266WiFi.h>
  7. #include <EEPROM.h>
  8. #include <Ticker.h>
  9. #include <AsyncMqttClient.h>
  10. #include <HX711.h>
  11. #include <ArduinoOTA.h>
  12. #include "config.h"
  13.  
  14. HX711 scale;
  15.  
  16. AsyncMqttClient mqttClient;
  17. Ticker mqttReconnectTimer;
  18.  
  19. WiFiEventHandler wifiConnectHandler;
  20. WiFiEventHandler wifiDisconnectHandler;
  21. Ticker wifiReconnectTimer;
  22.  
  23. bool firstRun = true;
  24. unsigned char samples;
  25. int sum, average, offset;
  26. char oldResult[10];
  27.  
  28. void eeWriteInt(int pos, int val) {
  29.   byte* p = (byte*) &val;
  30.   EEPROM.write(pos, *p);
  31.   EEPROM.write(pos + 1, *(p + 1));
  32.   EEPROM.write(pos + 2, *(p + 2));
  33.   EEPROM.write(pos + 3, *(p + 3));
  34.   EEPROM.commit();
  35. }
  36.  
  37. int eeGetInt(int pos) {
  38.   int val;
  39.   byte* p = (byte*) &val;
  40.   *p        = EEPROM.read(pos);
  41.   *(p + 1)  = EEPROM.read(pos + 1);
  42.   *(p + 2)  = EEPROM.read(pos + 2);
  43.   *(p + 3)  = EEPROM.read(pos + 3);
  44.   return val;
  45. }
  46.  
  47.  
  48. void connectToWifi() {
  49.   Serial.printf("[WiFi] Connecting to %s...\n", WIFI_SSID);
  50.  
  51.   WiFi.hostname(WIFI_CLIENT_ID);
  52.   WiFi.mode(WIFI_STA);
  53.   if (WIFI_STATIC_IP != 0) {
  54.     WiFi.config(WIFI_CLIENT_IP, WIFI_GATEWAY_IP, WIFI_SUBNET_IP, WIFI_DNS_IP);
  55.   }
  56.  
  57.   delay(500);
  58.  
  59.   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  60. }
  61.  
  62. void onWifiConnect(const WiFiEventStationModeGotIP& event) {
  63.   Serial.print("[WiFi] Connected, IP address: ");
  64.   Serial.println(WiFi.localIP());
  65.   wifiReconnectTimer.detach();
  66.   connectToMqtt();
  67. }
  68.  
  69. void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  70.   Serial.println("[WiFi] Disconnected from Wi-Fi!");
  71.   mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  72.   wifiReconnectTimer.once(WIFI_RECONNECT_TIME, connectToWifi);
  73. }
  74.  
  75. void connectToMqtt() {
  76.   Serial.println("[MQTT] Connecting to MQTT...");
  77.   mqttClient.connect();
  78. }
  79.  
  80. void onMqttConnect(bool sessionPresent) {
  81.   Serial.println("[MQTT] Connected to MQTT!");
  82.  
  83.   mqttReconnectTimer.detach();
  84.  
  85.   Serial.print("Session present: ");
  86.   Serial.println(sessionPresent);
  87.   uint16_t packetIdSub = mqttClient.subscribe(MQTT_TOPIC_TARE, MQTT_TOPIC_TARE_QoS);
  88.   Serial.print("Subscribing to ");
  89.   Serial.println(MQTT_TOPIC_TARE);
  90. }
  91.  
  92. void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  93.   Serial.println("[MQTT] Disconnected from MQTT!");
  94.  
  95.   if (WiFi.isConnected()) {
  96.     Serial.println("[MQTT] Trying to reconnect...");
  97.     mqttReconnectTimer.once(MQTT_RECONNECT_TIME, connectToMqtt);
  98.   }
  99. }
  100.  
  101. void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  102.   if (!strcmp(topic, MQTT_TOPIC_TARE)) {
  103.     Serial.print("Zeroing: ");
  104.     Serial.println(average / (float) 100);
  105.     offset = average;
  106.     if (SAVE_TARE != 0) {
  107.       Serial.print("Saving to EEPROM...");
  108.       eeWriteInt(EEPROM_ADDRESS, offset);
  109.     }
  110.   }
  111. }
  112.  
  113. void setup() {
  114.   scale.begin(PIN_DOUT,PIN_CLK);
  115.   Serial.begin(115200);
  116.   EEPROM.begin(512);
  117.   Serial.println("Startup!");
  118.  
  119.   wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
  120.   wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);
  121.  
  122.   mqttClient.onConnect(onMqttConnect);
  123.   mqttClient.onDisconnect(onMqttDisconnect);
  124.   mqttClient.onMessage(onMqttMessage);
  125.   mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  126.  
  127.   if (MQTT_USER != "") {
  128.     mqttClient.setCredentials(MQTT_USER, MQTT_PASS);
  129.   }
  130.  
  131.   if (SAVE_TARE == 1) {
  132.     offset = eeGetInt(EEPROM_ADDRESS);
  133.  
  134.     Serial.print("Loading offset from EEPROM: ");
  135.     Serial.println(offset / (float) 100);
  136.   } else {
  137.     scale.tare();
  138.   }
  139.  
  140.   scale.set_scale(CALIBRATION);
  141.  
  142.   if (OTA_PATCH == 1) {
  143.     ArduinoOTA.onStart([]() {
  144.       String type;
  145.       if (ArduinoOTA.getCommand() == U_FLASH) {
  146.         type = "sketch";
  147.       } else { // U_SPIFFS
  148.         type = "filesystem";
  149.       }
  150.  
  151.       // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
  152.       Serial.println("Start updating " + type);
  153.     });
  154.     ArduinoOTA.onEnd([]() {
  155.       Serial.println("\nEnd");
  156.     });
  157.     ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  158.       Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  159.     });
  160.     ArduinoOTA.onError([](ota_error_t error) {
  161.       Serial.printf("Error[%u]: ", error);
  162.       if (error == OTA_AUTH_ERROR) {
  163.         Serial.println("Auth Failed");
  164.       } else if (error == OTA_BEGIN_ERROR) {
  165.         Serial.println("Begin Failed");
  166.       } else if (error == OTA_CONNECT_ERROR) {
  167.         Serial.println("Connect Failed");
  168.       } else if (error == OTA_RECEIVE_ERROR) {
  169.         Serial.println("Receive Failed");
  170.       } else if (error == OTA_END_ERROR) {
  171.         Serial.println("End Failed");
  172.       }
  173.     });
  174.  
  175.     ArduinoOTA.setHostname(WIFI_CLIENT_ID);
  176.     ArduinoOTA.setPassword(OTA_PASS);
  177.  
  178.  
  179.     ArduinoOTA.begin();
  180.   }
  181.  
  182.   connectToWifi();
  183. }
  184.  
  185. void loop() {
  186.   if (WiFi.isConnected() && (OTA_PATCH != 0)) {
  187.     ArduinoOTA.handle();
  188.   }
  189.   sum += scale.get_units() * 100;
  190.   samples++;
  191.  
  192.   if (samples >= NUM_SAMPLES) {
  193.     if (firstRun) {
  194.       firstRun = false;
  195.       if (SAVE_TARE == 0) {
  196.         average = offset;
  197.         return;
  198.       }
  199.     }
  200.  
  201.  
  202.     char result[10];
  203.     average = sum / samples;
  204.     dtostrf(((average - offset) / (float) 100), 5, RESOLUTION, result);
  205.    
  206.     if (mqttClient.connected() && strcmp(result, oldResult)) {
  207.       mqttClient.publish(MQTT_TOPIC_LOAD, MQTT_TOPIC_LOAD_QoS, true, result);
  208.       Serial.print("Pushing new result:");
  209.       Serial.println(result);
  210.     }
  211.  
  212.     strncpy(oldResult, result, 10);
  213.     samples = 0;
  214.     sum = 0;
  215.   }
  216. //  Serial.print("Free heap:");
  217. //  Serial.println(ESP.getFreeHeap(),DEC);
  218.   delay(SAMPLE_PERIOD);
  219. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement