From c96bba349af171e12e01732f919f42afde8035a8 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 13 Oct 2020 19:55:36 -0500 Subject: [PATCH 001/186] add async indicator updates --- neoindicator.h | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/neoindicator.h b/neoindicator.h index 0a47f22..3198fbc 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -4,7 +4,7 @@ #include #ifdef DEBUG -bool DEBUG_neoind = false; +bool DEBUG_neoind = true; #else bool DEBUG_neoind = false; #endif @@ -28,6 +28,8 @@ int INDNUMPIXELS = 1; bool INDPINRESET = false; uint8_t neoIndTaskID; // timer task +uint32_t indColor; + void init_indicator(uint16_t pin){ // Adafruit_NeoPixel // strip = ind; @@ -39,10 +41,13 @@ void init_indicator(uint16_t pin){ ind.show(); ind.show(); // on purpose, ensure its blanked for glitched resets delay(1); - if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset // init_strip(); } +void indSetNextColor(uint32_t c){ + indColor = c; +} + void debugColor(uint32_t c){ Serial.println("Debug color"); Serial.println("[RGB] Red: " + (String)red(c)); @@ -54,8 +59,11 @@ void indSetColor(uint32_t c){ if(DEBUG_neoind)Serial.println("[IND] set ind color:" + (String)c); // debugColor(c); ind.setPixelColor( 0, c ); - ind.show(); if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset + portDISABLE_INTERRUPTS(); // the other workaround + strip.show(); + portENABLE_INTERRUPTS(); + indSetNextColor(ind.getPixelColor(0)); } // alias @@ -75,6 +83,7 @@ void indSetColor(uint8_t r,uint8_t g,uint8_t b){ ind.show(); // delay(1); if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset + // indSetNextColor(ind.getPixelColor(0)); } void setIndColor(uint8_t r,uint8_t g,uint8_t b){ @@ -90,6 +99,13 @@ void stop_indicator(){ // @todo unset object } +void updateIndColor(){ + if(indColor != ind.getPixelColor(0)){ + ind.setPixelColor(0,indColor); + ind.show(); + } +} + // Rainbow cycle along whole strip. Pass delay time (in ms) between frames. void rainbowInd(int wait) { // Hue of first pixel runs 3 complete loops through the color wheel. @@ -188,6 +204,13 @@ void indTest(){ Serial.println("[IND] indtest complete"); } +void indTest2(){ + ind.setBrightness(255); // full bright + + indSetColor(255,0,0); + delay(500); +} + void accentSetColor(uint32_t c){ if(DEBUG_neoind)Serial.println("[IND] set accent color"); for(size_t i=1; i Date: Tue, 13 Oct 2020 19:56:03 -0500 Subject: [PATCH 002/186] make these temp callbacks generic --- httpd.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/httpd.h b/httpd.h index ccb222f..f02bb4d 100644 --- a/httpd.h +++ b/httpd.h @@ -12,7 +12,7 @@ void handleRoot() { Serial.println("has arg ledindex"); String pixel = server.arg(F("ledindex")); // ledIndex = pixel; - setPixel(pixel.toInt()); + // setHTTPValue(pixel.toInt()); // strip.setPixelColor(pixel.toInt(),strip.Color(255,0,0)); Serial.println("Setting pixel:" + (String)pixel); // strip.show(); @@ -31,7 +31,7 @@ void handleRoot() { // delay(2000); // server.send(200, "text/plain", "hello from esp8266! PWM set:" + (String)getPWM()); // analogWrite(16,pwmvalue.toInt()); - setPWM(pwmvalue); + // setHTTPValue(pwmvalue); } // digitalWrite(LED_BUILTIN, 1); From 4c41457e705b0eda04fc5b410978b054fc010f27 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 13 Oct 2020 19:56:32 -0500 Subject: [PATCH 003/186] uint --- ota.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ota.h b/ota.h index 728fa9f..09232e7 100644 --- a/ota.h +++ b/ota.h @@ -16,14 +16,17 @@ const char* otahost = "esp8266OTA"; // esp8266-[ChipID] bool otastarted = false; -int lastprogress = 0; // micros timestamp -int progressthrottle = 0;// progress serial throttle, should make ota faster +uint lastprogress = 0; // micros timestamp +uint progressthrottle = 0;// progress serial throttle, should make ota faster void handleOTA(){ // MDNS.update(); // handled by ota, not required ArduinoOTA.handle(); } +void processOTA(){ + handleOTA(); +} // Port defaults to 8266 // ArduinoOTA.setPort(8266); From 6460c20f22c4a5405af0a1107e07d1769f788d98 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 13 Oct 2020 19:57:00 -0500 Subject: [PATCH 004/186] fix some compile issues and esp32 --- wifi_funcs.h | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index a312c37..04bbf7a 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -3,8 +3,16 @@ #include -// const char* hostname = "esp8266REFLOW"; +#ifdef ESP8266 + #include + #include +#elif defined(ESP32) + #include + #include +#endif + +// const char* hostname = "esp8266REFLOW"; // enable wifi sta // disable sleep @@ -44,7 +52,11 @@ void init_WiFi(int timeout = 10000){ Serial.print("[WIFI] IP: "); Serial.println(WiFi.localIP()); Serial.print("[WIFI] HOST: "); - Serial.println(WiFi.getHostname()); + #ifdef ESP32 + Serial.println(WiFi.getHostname()); // getHostName + #else + Serial.println(WiFi.hostname()); // getHostName + #endif } else{ Serial.println("[ERROR] WIFI CONNECT FAILED"); @@ -53,6 +65,10 @@ void init_WiFi(int timeout = 10000){ delay(500); } +void init_wifi(){ + init_WiFi(); +} + int getRSSIasQuality() { int RSSI = WiFi.RSSI(); int quality = 0; @@ -89,6 +105,10 @@ void enableWiFi(){ void disableWiFi(){ WiFi.mode(WIFI_OFF); + #ifdef ESP32 + WiFi.mode( WIFI_MODE_NULL ); + btStop(); + #endif } // uint32_t ResetReason(void) From 154d7473721c03e1f38744aa4a9e7a4b58676ad9 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 22 Oct 2020 21:32:15 -0500 Subject: [PATCH 005/186] move grapher class out, it tried to autocompile --- classes/grapher/about.h | 55 ----- classes/grapher/grapher.cpp | 390 ------------------------------------ classes/grapher/grapher.h | 62 ------ 3 files changed, 507 deletions(-) delete mode 100644 classes/grapher/about.h delete mode 100644 classes/grapher/grapher.cpp delete mode 100644 classes/grapher/grapher.h diff --git a/classes/grapher/about.h b/classes/grapher/about.h deleted file mode 100644 index bdf9e59..0000000 --- a/classes/grapher/about.h +++ /dev/null @@ -1,55 +0,0 @@ -about.h - - -create graph - -init - -id -width -height -x coord -y coord - -axis x -axis y -labels - -precision - -styles - - border - background - - -gridlines -colors - gridlines minor/major/base - grid x, interval, range - grid y - grid logarithmic, extended - grid close ( adds closing gridline , looks better if no border) - - -labels - on/off, - padding - size (graphics lib dependant) - -sublclass traces - -id -y upper limit -y lower limit -y scaler* - -color -segment colors* - -style - dashed - dots - -fills, area under/over - diff --git a/classes/grapher/grapher.cpp b/classes/grapher/grapher.cpp deleted file mode 100644 index a42e0c1..0000000 --- a/classes/grapher/grapher.cpp +++ /dev/null @@ -1,390 +0,0 @@ -#include "grapher.h" - - -grapher::~grapher(int width = 0, int height = 0, int xPos = 0, int yPos = 0){ - _x = xPos; - _y = yPos; - _w = width; - _h = height; - - init_graph(); -} - -// candidate for class -grapher::init_graph(){ - - // class vars - xPos = _x; - yPos = _y; - width = _w; - height = _h; - - double x, y; - - // use full size - // setup basic inputs, x,y and W,h, add padding automatically if showing axis, and auto compensate for graph function y offset bottom left! - - // int height; - // int width; - bool invertWH = false; - - if(width == 0 && height == 0){ - width = TFT_WIDTH; //240; - height = TFT_HEIGHT; // 320; - invertWH = true; - } - - // invert width height (tft_eSPI uses shortend wide for some reason) - if(invertWH){ - int _height = height; - height = width; - width = _height; - } - - // init defaults - Serial.println("[GRAPH] init w:" + (String)width + " h: " + (String)height); - // int xPos = 0; - // int yPos = 0; - - // @todo add better clamping for display size - // if xpos + width > tft.width - // if ypos + height > tft.height - width -= xPos+1; // reduce width kludge - // height -= yPos+1; - - Serial.println("[GRAPH] init x:" + (String)width + " y: " + (String)height); - - // axis padding - bool xaxis = false; // show xaxis padding - bool yaxis = false; // show yaxis padding - int xaxispad = 20; // set padding for graph when xaxis shown - int yaxispad = 16; - - int16_t graph_w = width; // temp vars, edit in place - int16_t graph_h = height; - - int graphOff_x = xPos; - int graphOff_y = yPos+height; // translate y position from TL to BL relative - - if(xaxis){ - graph_w += -xaxispad; - graphOff_x += xaxispad; - } - if(yaxis){ - graph_h += -yaxispad; - graphOff_y += -yaxispad; - } - - // data set - double _x = 0; // x = x data point - double _y = 0; // y = y datapont - byte dp = 0; // dp = decimal place precision - double gx = graphOff_x; // gx = x graph location (top left) - double gy = graphOff_y; // gy = y graph location (bottom left) - double w = graph_w; // w = width of graph - double h = graph_h; // h = height of graph - - // @todo make grid value based not pixel, stupid - double xlo = 0; // xlo = lower bound of x axis - x scale min - double xhi = 100; // xhi = upper bound of x axis - x scale max - double xinc = 5; // xinc = division of x axis (pixels not count) - - int xgridpx = (h/(xhi-xlo))*xinc; - - double ylo = 0; // ylo = lower bound of y axis - y scale min - double yhi = 100; // yhi = upper bound of y axis - y scale max - double yinc = 5; // yinc = division of y axis (pixels not count) - - int ygridpx = (w/(yhi-ylo))*yinc; - - char *title = ""; // title = title of graph - char *xlabel = "x"; // xlabel = x asis label - char *ylabel = "y"; // ylabel = y asis label - boolean &redraw = display1; // &redraw = flag to redraw graph on first call only - - unsigned int color = PURPLE; // color = plotted trace colour - unsigned int bgcolor = bcolor; - - Serial.println("[GRAPH] grid x px: " + (String)xgridpx); - Serial.println("[GRAPH] grid y px: " + (String)ygridpx); - - // draw background to overwrite previous traces - int padding = 3; // we add bg padding so you can see traces at 0 and max - tft.fillRect((int16_t)xPos,(int16_t)yPos-padding,(int16_t)w,(int16_t)h+(padding*2),bgcolor); - // drawBorder(RED); - Graph(tft, _x, _y, dp, gx, gy, w, h, xlo, xhi, xinc, ylo, yhi, yinc, title, xlabel, ylabel,redraw, color); - // Graph(tft, x, y, 2, 30, 135-8, 240-30, 135-8, 0, 6.5, 1, -1, 1, .25, "x", "y", "", display1, YELLOW); -} - - -void Graph(RM_tft &tft, double x, double y, byte dp, - double gx, double gy, double w, double h, - double xlo, double xhi, double xinc, - double ylo, double yhi, double yinc, - char *title, char *xlabel, char *ylabel, - boolean &redraw, unsigned int pcolor) { - - double ydiv, xdiv; - double i; - double temp; - int rot, newrot; - - _h = h; - _w = w; - _gx = gx; - _gy = gy; - - syncGraphInstance(graphID); - - bool drawXbaseline = false; - bool drawYbaseline = false; - - if (redraw == true) { - - bool showaxis_x = true; // @NI - bool showaxis_y = true; // @NI - - // redraw = false; - // initialize old x and old y in order to draw the first point of the graph - // but save the transformed value - // note my transform funcition is the same as the map function, except the map uses long and we need doubles - //ox = (x - xlo) * ( w) / (xhi - xlo) + gx; - //oy = (y - ylo) * (gy - h - gy) / (yhi - ylo) + gy; - - // tft.setTextDatum(MR_DATUM); - - // draw y scale - for ( i = ylo; i <= yhi; i += yinc){ - // compute the transform - temp = (i - ylo) * (gy - h - gy) / (yhi - ylo) + gy; //posy - - if (i == 0 && drawYbaseline) { - tft.drawLine(gx, temp, gx + w, temp, acolor); // Y a line - tft.setTextColor(lcolor, bcolor); - // tft.drawString(xlabel, (int)(gx + w -q 8) , (int)temp, 2); // x axis label - } - else { - tft.drawLine(gx, temp, gx + w, temp, gcolor); - } - - // draw the y axis values - int yvalpad = 4; // will not go negative ( might depend on driver and buffer though ) - int yvalsize = 1; - // tft.setTextColor(tcolor, bcolor); - tft.setTextColor(tcolor); - // precision is default Arduino--this could really use some format control - // if(dp>0) tft.drawFloat(i, dp, gx - yvalpad, temp, yvalsize); // y axis value labels w padding - // else tft.drawString((String)(int)round(i),(int)(gx - yvalpad), (int)temp, yvalsize); - } - - // draw x scale - for (i = xlo; i <= xhi; i += xinc) { - - // compute the transform - temp = (i - xlo) * ( w) / (xhi - xlo) + gx; // posx - if (i == 0 && drawXbaseline ) { - tft.drawLine(temp, gy, temp, gy - h, acolor); // Y a-line @todo draws on top of y values - tft.setTextColor(lcolor, bcolor); - // tft.setTextDatum(BC_DATUM); - // tft.drawString(ylabel, (int)temp, (int)(gy - h - 8) , 2); // y axis label BT-height w padding, @todo rotate - } - else { - tft.drawLine(temp, gy, temp, gy - h, gcolor); - } - - // Serial.println(i); - // Serial.println(xhi); - // Serial.println(xinc); - // Serial.println((String)abs(xhi/xinc)); - // Close graph grid, @todo add actual border options - // if(i == abs(xhi/xinc)){ - if(i!= xhi && i == abs(xhi/xinc)){ - tft.drawLine(gx + w, gy, gx + w, gy - h, gcolor); // Y end line (w-1?) - } - - // draw the x axis values - int xvalpad = 7; - int xvalsize = 1; - // tft.setTextColor(tcolor, bcolor); - tft.setTextColor(tcolor); - // tft.setTextDatum(TC_DATUM); - // precision is default Arduino--this could really use some format control - // drawFloat(float floatNumber, uint8_t dp, int32_t poX, int32_t poY, [puint8_t font]) - // if(dp>0)tft.drawFloat(i, dp, temp, gy + xvalpad, xvalsize); // x axis value labels w padding - // else tft.drawString((String)(int)round(i),(int)temp,(int)(gy + xvalpad), xvalsize); // v pad +7, fontsize 1 - } - - //draw graph title - tft.setTextColor(tcolor, bcolor); - // tft.drawString(title, (int)(gx + w / 2) , (int)(gy - h - 30), 4); // x axis label - } - - -/** - * [addPoint description] - * @param tft tft instance - * @param id trace id (hardcoded 0-6 ATM) - * @param x x coord - * @param y y coord - * @param xlo x lo - * @param xhi x high - * @param ylo y lo - * @param yhi y high - * @param pcolor point color - */ -void addPoint(RM_tft &tft, int id, double x, double y, - double xlo, double xhi, - double ylo, double yhi, - unsigned int pcolor, int size = 0) -{ - - if(_DEBUG_POINT){ - Serial.print("\n[GRAPH] ADDPOINT id: "+(String)id+ " x - y: "); - Serial.print(x); - Serial.print(" - "); - Serial.println(y); - } - - setGraphInstance(graphID); - - double w = _w; - double h = _h; - double gx = _gx; - double gy = _gy; - bool doubleLine = false; - - // the coordinates are now drawn, plot the data - // the entire plotting code are these few lines... - // recall that ox and oy are initialized above - x = (x - xlo) * ( w) / (xhi - xlo) + gx; - y = (y - ylo) * (gy - h - gy) / (yhi - ylo) + gy; - - if ((x < gx) || (x > gx+w)) {return;} - if ((y < gy-h) || (y > gy)) {return;} - - double ox = getGraphLine(id,0); - double oy = getGraphLine(id,1); - - if(_DEBUG_POINT){ - Serial.print("\n[GRAPH] x - y: "); - Serial.print(x); - Serial.print(" - "); - Serial.println(y); - Serial.print("\n[GRAPH] ox - oy: "); - Serial.print(ox); - Serial.print(" - "); - Serial.println(oy); - - Serial.print("\n[GRAPH] gx - gy: "); - Serial.print(gx); - Serial.print(" - "); - Serial.println(gy); - Serial.println("------"); - Serial.println("DrawLine"); - Serial.flush(); - } - - tft.drawLine(ox, oy, x, y, pcolor); // STILL DOUBLE! - - // drawing 2 more lines to give the graph some thickness - if(size>1){ - tft.drawLine(ox, oy + 1, x, y + 1, pcolor); - tft.drawLine(ox, oy - 1, x, y - 1, pcolor); - } - - // store last point - setGraphLine(id,x,y); - // ox = x; - // oy = y; -} - - -/** - * [addPointSet description] - * @param {[type]} int id [description] - * @param {[type]} int sample [description] - * @param {[type]} double value [description] - * @param {[type]} int numSamples [description] - * @param {Number} int vsize [description] - * @param {Number} int size [description] - */ -void addPointSet(int id, int sample, double value, int numSamples,int vsize = 100,int size = 1,int yindexstart = 0){ - // if(id != filteredId && filteredId >= 0) return; - if(_DEBUG_POINT){ - Serial.println("addPointSet"); - Serial.println(id); - Serial.println(sample); - Serial.println(value); - } - int i = sample; - // int vsize = 100; - // if(sample=0) addPoint(tft,id, 0, 0 , 0, numSamples, 0, vsize, getLineColor(0,0)); // @FIXME does not show up , must add 0 point - // int yindexstart = 65; // start Y at non 0 value - unsigned int c = WHITE; - if(size==0){ - size = 2; - c = GRAY; - } - else c = getLineColor(id,0); - addPoint(tft,id, i, value , 0, numSamples, yindexstart, vsize, c,size); - - // addPoint(tft,id, i, ((abs(vsize/numSamples))*(i)) , 0, numSamples, 0, vsize, getLineColor(i-1,0)); -} - - -void test_trace_sin(){ - double x, y; - for (x = 0; x <= 6.3; x += .1) { - y = sin(x); - // Trace(tft, x, y, 1, 60, 290, 390, 260, 0, 6.5, 1, -1, 1, .25, "Sin(x)", "x", "fn(x)", update1, YELLOW); - addPoint(tft, 0,x, y, 0, 6.5, -1, 1, YELLOW); - // Graph(tft, x, y, dp, gx, gy, w, h, xlo, xhi, xinc, ylo, yhi, yinc, title, xlabel, ylabel,redraw, color); - delay(100); - } -} - -void test_trace(uint32_t c){ - double x, y; - for (x = 0; x <= 100; x += 10) { - // addPoint(RM_tft &tft, int id, double x, double y,double xlo, double xhi,double ylo, double yhi,unsigned int pcolor) - // addPoint(RM_tft &tft, id, x, y, xlo, xhi ylo, yhi, color) - addPoint(tft, 0,x, x, 0, 100, 0, 100, c); - delay(100); - } -} - -// add a bunch of traces for testing -void testTraces(int sample){ - return; - int ssize = 240; - int vsize = 100; - int numTraces = 4; - for(int i=0;i Date: Thu, 22 Oct 2020 21:32:48 -0500 Subject: [PATCH 006/186] add i2c pinswap --- io_utils.h | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/io_utils.h b/io_utils.h index 134d0b7..9d59023 100644 --- a/io_utils.h +++ b/io_utils.h @@ -1,6 +1,8 @@ #ifndef io_utils_h #define io_utils_h +bool swap = false; + int getPinMode(uint8_t pin) { if (pin >= NUM_DIGITAL_PINS) return (-1); @@ -21,13 +23,16 @@ void debugPin(uint8_t pin){ Serial.println(" pinstate: " + (String)digitalRead(pin)); } -void scani2c(){ + +void scani2c(bool pinswap = false){ + swap = pinswap; byte error, address; int nDevices; - Wire.begin(); + if(!swap)Wire.begin(); + else Wire.begin(SCL,SDA); // begin(sda, scl) SWAP! Serial.print("[I2C] SDA:"+(String) SDA); Serial.print(" SCL:"+(String) SCL); - Serial.println(""); + Serial.println(swap ? " \nSWAPPED" : ""); Serial.println("[I2C] Scanning ... "); nDevices = 0; From 5124afa0d7f876469ab73a38813af531e22cc6b6 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 22 Oct 2020 21:33:26 -0500 Subject: [PATCH 007/186] esp32 cleanups --- httpd.h | 3 +-- temp_logger.h | 4 ++++ wifi_funcs.h | 10 ++++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/httpd.h b/httpd.h index f02bb4d..849d26a 100644 --- a/httpd.h +++ b/httpd.h @@ -1,7 +1,6 @@ -#include +#include "wifi_funcs.h" #include #include -#include ESP8266WebServer server(80); diff --git a/temp_logger.h b/temp_logger.h index defc236..5f8f7ed 100644 --- a/temp_logger.h +++ b/temp_logger.h @@ -32,7 +32,11 @@ BarGraph bar0; #define USENEOIND // use neopixel indicator #ifdef USENEOIND + #ifdef ESP32 + #define NEOINDPIN 19 + #else #define NEOINDPIN 2 + #endif #include #include #endif diff --git a/wifi_funcs.h b/wifi_funcs.h index 04bbf7a..911bb8f 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -14,6 +14,14 @@ // const char* hostname = "esp8266REFLOW"; +void setWiFiHostname(const char* hostname){ + #ifdef ESP32 + WiFi.setHostname(hostname); + #else + WiFi.hostname(hostname); + #endif +} + // enable wifi sta // disable sleep // timeout connect @@ -231,6 +239,8 @@ String getResetReason(){ // { // } } + #else + return ""; #endif } From 16ab14e0ef2d365f10d825d731bbdc69b7d91cbf Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 22 Oct 2020 21:55:40 -0500 Subject: [PATCH 008/186] add double show and no interrupts for esp32 issues --- neoindicator.h | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/neoindicator.h b/neoindicator.h index 3198fbc..c5e0856 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -9,6 +9,26 @@ bool DEBUG_neoind = true; bool DEBUG_neoind = false; #endif +#ifdef ESP32 +bool showTwice = true; +bool noInterrupts = true; +#else +bool showTwice = false; +bool noInterrupts = false; +#endif + +// // these are const, so they don't eat RAM +// const uint32_t np_white = ind.Color(255,255,255); +// const uint32_t np_black = ind.Color(0 ,0,0); +// const uint32_t np_red = ind.Color(255,0,0); +// const uint32_t np_orange = ind.Color(255,128,0); +// const uint32_t np_yellow = ind.Color(255,100,0); // 255,100,0 +// const uint32_t np_green = ind.Color(0 ,255,0); +// const uint32_t np_cyan = ind.Color(0 ,255,128); +// const uint32_t np_blue = ind.Color(0 ,0,255); +// const uint32_t np_purple = ind.Color(128,0,255); +// const uint32_t np_turquoise = ind.Color(0,80,80); + #include Adafruit_NeoPixel ind = Adafruit_NeoPixel(); // Adafruit_NeoPixel strip = Adafruit_NeoPixel(1, PIN, NEO_GRB + NEO_KHZ800); @@ -21,7 +41,7 @@ Adafruit_NeoPixel ind = Adafruit_NeoPixel(); // palevioletred #DB7093 rgb(219,112,147) // mediumvioletred #C71585 rgb(199,21,133) -uint16_t INDBRIGHTNESS = 30; +uint16_t INDBRIGHTNESS = 60; int INDNUMPIXELS = 1; #define INDPIXELSTYPE NEO_GRB + NEO_KHZ800 @@ -59,10 +79,12 @@ void indSetColor(uint32_t c){ if(DEBUG_neoind)Serial.println("[IND] set ind color:" + (String)c); // debugColor(c); ind.setPixelColor( 0, c ); - if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset - portDISABLE_INTERRUPTS(); // the other workaround - strip.show(); - portENABLE_INTERRUPTS(); + if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset + if(noInterrupts) portDISABLE_INTERRUPTS(); + ind.show(); + if(showTwice) ind.show(); + if(noInterrupts) portENABLE_INTERRUPTS(); + // #endif indSetNextColor(ind.getPixelColor(0)); } @@ -79,11 +101,7 @@ void setIndColor(uint32_t c){ void indSetColor(uint8_t r,uint8_t g,uint8_t b){ if(DEBUG_neoind)Serial.println("[IND] set ind color RGB:"+(String) ind.Color(r,g,b)); // debugColor(ind.Color(r,g,b)); - ind.setPixelColor(0,ind.Color(r,g,b)); - ind.show(); - // delay(1); - if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset - // indSetNextColor(ind.getPixelColor(0)); + indSetColor(ind.Color(r,g,b)); } void setIndColor(uint8_t r,uint8_t g,uint8_t b){ From b28e7b19e18671babbd6644576b344d6e9d32f5e Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 22 Oct 2020 22:22:02 -0500 Subject: [PATCH 009/186] add sense_env --- sense_env.h | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 sense_env.h diff --git a/sense_env.h b/sense_env.h new file mode 100644 index 0000000..3494176 --- /dev/null +++ b/sense_env.h @@ -0,0 +1,83 @@ +#ifndef sensors_h +#define sensors_h + +#include + +#ifdef USELM75 +#include +#include +// Create I2C LM75A instance +LM75A lm75(true, //A0 LM75A pin state + true, //A1 LM75A pin state + true); //A2 LM75A pin state +#endif + +#ifdef USESHT21 +#include +HTU21D myHTU21D(HTU21D_RES_RH12_TEMP14); +#endif + + +void init_sht(){ + #ifdef USESHT21 + bool init = myHTU21D.begin(); + if(init){ + Serial.println(F("HTU21D, SHT21 sensor is active")); + } + else + { + Serial.println(F("HTU21D, SHT21 sensor is faild or not connected")); //(F()) saves string to flash & keeps dynamic memory free + } + // while (myHTU21D.begin(SCL,SDA) != true) + // { + // Serial.println(F("HTU21D, SHT21 sensor is failed or not connected")); //(F()) saves string to flash & keeps dynamic memory free + // delay(5000); + // } + // Serial.println(F("HTU21D, SHT21 sensor is active")); + #endif +} + +void get_sht(){ + #ifdef USESHT21 + /* DEMO - 1 */ + Serial.println(F("DEMO 1: 12-Bit Resolution")); + Serial.print(F("Humidity............: ")); Serial.print(myHTU21D.readHumidity()); Serial.println(F(" +-2%")); + Serial.print(F("Compensated Humidity: ")); Serial.print(myHTU21D.readCompensatedHumidity()); Serial.println(F(" +-2%")); + + Serial.println(F("DEMO 1: 14-Bit Resolution")); + Serial.print(F("Temperature.........: ")); Serial.print(myHTU21D.readTemperature()); Serial.println(F(" +-0.3C")); + + + /* DEMO - 2 */ + Serial.println(F("DEMO 2: 11-Bit Resolution")); + myHTU21D.setResolution(HTU21D_RES_RH11_TEMP11); + Serial.print(F("Humidity............: ")); Serial.print(myHTU21D.readHumidity()); Serial.println(F(" +-2%")); + Serial.print(F("Compensated Humidity: ")); Serial.print(myHTU21D.readCompensatedHumidity()); Serial.println(F(" +-2%")); + + Serial.println(F("DEMO 2: 11-Bit Resolution")); + Serial.print(F("Temperature.........: ")); Serial.print(myHTU21D.readTemperature()); Serial.println(F(" +-0.3C")); + + + /* DEMO - 3 */ + Serial.println(F("DEMO 3: Battery Status")); + if (myHTU21D.batteryStatus() == true) Serial.println(F("Battery.............: OK. Level > 2.25v")); + else Serial.println(F("Battery.............: LOW. Level < 2.25v")); + + + /* DEMO - 4 */ + Serial.println(F("DEMO 4:")); + Serial.print(F("Firmware version....: ")); Serial.println(myHTU21D.readFirmwareVersion()); + + + /* DEMO - 5 */ + Serial.println(F("DEMO 5:")); + Serial.print(F("Sensor's ID.........: ")); Serial.println(myHTU21D.readDeviceID()); + + + /* back to lib. default resolution */ + myHTU21D.softReset(); + myHTU21D.setResolution(HTU21D_RES_RH12_TEMP14); + #endif +} + +#endif \ No newline at end of file From c40d8584b23bfcb9c0ea8ee29891a88288e70c6e Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 4 Nov 2020 11:16:23 -0600 Subject: [PATCH 010/186] add mqtt --- wifi_funcs.h | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index 911bb8f..3b4a0a6 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -244,4 +244,77 @@ String getResetReason(){ #endif } -#endif \ No newline at end of file + +#include +WiFiClient espClient; +PubSubClient client(espClient); + +void MQTTreconnect() { + // Loop until we're reconnected + while (!client.connected()) { + Serial.print("Attempting MQTT connection..."); + // Create a random client ID + String clientId = "ESP8266Client-"; + clientId += String(random(0xffff), HEX); + // Attempt to connect + if (client.connect(clientId.c_str())) { + Serial.println("connected"); + // Once connected, publish an announcement... + client.publish("TESTOUT", "hello world"); + // ... and resubscribe + client.subscribe("TESTIN"); + } else { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" try again in 5 seconds"); + // Wait 5 seconds before retrying + delay(5000); + } + delay(100); + } +} + +void MQTTcallback(char* topic, byte* payload, unsigned int length) { + Serial.print("Message arrived ["); + Serial.print(topic); + Serial.print("] "); + for (int i = 0; i < length; i++) { + Serial.print((char)payload[i]); + } + Serial.println(); + + // Switch on the LED if an 1 was received as first character + if ((char)payload[0] == '1') { + // digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level + // but actually the LED is on; this is because + // it is active low on the ESP-01) + } + // else { + // // digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH + // } + +} + +void process_MQTT(){ +if (!client.connected()) { + MQTTreconnect(); + } + client.loop(); +} + +void init_MQTT(){ + client.setServer(mqtt_server_ip, 1883); + client.setCallback(MQTTcallback); + process_MQTT(); +} + +void MQTT_pub(String topic, String msg){ + Serial.print("Publish message: "); + Serial.print("topic: "); + Serial.print(topic); + Serial.print(" mesg: "); + Serial.println(msg); + client.publish(topic.c_str(), msg.c_str()); +} + +#endif \ No newline at end of file From d5cd936a25e3b1359f2b0921352bfe3beb8b381b Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 5 Nov 2020 23:12:28 -0600 Subject: [PATCH 011/186] added better test, fix fatal error --- ssr.h | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/ssr.h b/ssr.h index 83cba7a..7d63991 100644 --- a/ssr.h +++ b/ssr.h @@ -11,14 +11,24 @@ bool DEBUG_ssr = false; #endif float currentDuty = 0; // ssrpower -bool invertDuty = true; // invert logic vcc range +bool invertDuty = false; // invert logic vcc range +bool invertLOW = false; int _ssrRelayPin = -1; +void ssr_off(){ + digitalWrite(_ssrRelayPin,invertLOW ? HIGH : LOW); +} + +void ssr_on(){ + digitalWrite(_ssrRelayPin,invertLOW ? LOW : HIGH); +} + void ssr_init(int pin){ _ssrRelayPin = pin; pinMode( _ssrRelayPin, OUTPUT ); - digitalWrite(_ssrRelayPin,HIGH); + delay(600); + ssr_off(); #ifdef ESP8266 analogWriteRange(255); // esp8266 @@ -41,7 +51,7 @@ void SetSSRFrequency( int duty,int power =1) // Write the clamped duty cycle to the RELAYPIN GPIO int out = invertDuty ? 255-duty : duty; - #ifdef ESP8266P + #ifdef ESP8266 analogWrite( _ssrRelayPin, out); #endif // if(duty == 0)digitalWrite(RELAYPIN,invertDuty ? LOW:HIGH); @@ -71,6 +81,16 @@ float getSSRPower(){ } void ssrTest(){ + + ssr_on(); + delay(1000); + ssr_off(); + delay(1000); + ssr_on(); + delay(1000); + ssr_off(); + delay(1000); + // Turn off the SSR - duty cycle of 0 SetSSRFrequency( 255 ); // test pulse delay(1000); @@ -79,6 +99,7 @@ void ssrTest(){ SetSSRFrequency( 255 ); // test pulse delay(1000); SetSSRFrequency( 0 ); + ssr_off(); } #endif \ No newline at end of file From 9ebefc66f2e4d08c27ccf8c1462f7c647a456675 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 5 Nov 2020 23:12:43 -0600 Subject: [PATCH 012/186] fix esp8266 interrupts --- neoindicator.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/neoindicator.h b/neoindicator.h index c5e0856..3d4047d 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -80,10 +80,14 @@ void indSetColor(uint32_t c){ // debugColor(c); ind.setPixelColor( 0, c ); if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset + #ifdef ESP32 if(noInterrupts) portDISABLE_INTERRUPTS(); + #endif ind.show(); if(showTwice) ind.show(); + #ifdef ESP32 if(noInterrupts) portENABLE_INTERRUPTS(); + #endif // #endif indSetNextColor(ind.getPixelColor(0)); } From ddda1f26d23c1ea0ef46b227ccc86447b7ce6364 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 5 Nov 2020 23:12:53 -0600 Subject: [PATCH 013/186] added more sensors --- sense_env.h | 133 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 128 insertions(+), 5 deletions(-) diff --git a/sense_env.h b/sense_env.h index 3494176..c581c82 100644 --- a/sense_env.h +++ b/sense_env.h @@ -3,9 +3,12 @@ #include +#define USESHT31 +// #define USESHT21 +#define USEBMP280 + #ifdef USELM75 #include -#include // Create I2C LM75A instance LM75A lm75(true, //A0 LM75A pin state true, //A1 LM75A pin state @@ -17,9 +20,115 @@ LM75A lm75(true, //A0 LM75A pin state HTU21D myHTU21D(HTU21D_RES_RH12_TEMP14); #endif +#ifdef USESHT31 +#include +Adafruit_SHT31 sht31 = Adafruit_SHT31(); +#endif -void init_sht(){ - #ifdef USESHT21 +#ifdef USEBMP280 +#include +Adafruit_BMP280 bmp; // I2C +#endif + +#ifdef USEBMP280 +void init_bmp280(){ + if (!bmp.begin(BMP280_ADDRESS_ALT)) { + Serial.println(F("Could not find a valid BMP280 sensor, check wiring!")); + } + + /* Default settings from datasheet. */ + bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */ + Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */ + Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */ + Adafruit_BMP280::FILTER_X16, /* Filtering. */ + Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */ +} + +void print_bmp280(){ + Serial.print(F("Temperature = ")); + Serial.print(bmp.readTemperature()); + Serial.println(" *C"); + + Serial.print(F("Pressure = ")); + Serial.print(bmp.readPressure()); + Serial.println(" Pa"); + + Serial.print(F("Approx altitude = ")); + Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */ + Serial.println(" m"); + + Serial.println(); +} +#endif + + +#ifdef USESHT31 +bool enableHeater = false; +uint8_t loopCnt = 0; + +void init_sht31(){ + bool init = sht31.begin(0x44); + if(init){ + Serial.println(F("SHT31 sensor is active")); + } + else + { + Serial.println(F("SHT31 sensor is faild or not connected")); //(F()) saves string to flash & keeps dynamic memory free + } + + Serial.print("Heater Enabled State: "); + if (sht31.isHeaterEnabled()) Serial.println("ENABLED"); + else Serial.println("DISABLED"); +} + +String getSHT31Temperature(){ + float t = sht31.readTemperature(); + if(isnan(t)) return ""; + return (String) t; +} + +String getSHT31Humidity(){ + float h = sht31.readHumidity(); + if(isnan(h)) return ""; + return (String) h; +} + +void print_sht31(){ + float t = sht31.readTemperature(); + float h = sht31.readHumidity(); + + if (! isnan(t)) { // check if 'is not a number' + Serial.print("Temp *C = "); Serial.print(t); Serial.print("\t\t"); + } else { + Serial.println("Failed to read temperature"); + } + + if (! isnan(h)) { // check if 'is not a number' + Serial.print("Hum. % = "); Serial.println(h); + } else { + Serial.println("Failed to read humidity"); + } +} + +void sht31_process(){ + // Toggle heater enabled state every 30 seconds + // An ~3.0 degC temperature increase can be noted when heater is enabled + if (++loopCnt == 30) { + enableHeater = !enableHeater; + sht31.heater(enableHeater); + Serial.print("Heater Enabled State: "); + if (sht31.isHeaterEnabled()) + Serial.println("ENABLED"); + else + Serial.println("DISABLED"); + + loopCnt = 0; + } +} +#endif + +#ifdef USESHT21 +void init_sht21(){ bool init = myHTU21D.begin(); if(init){ Serial.println(F("HTU21D, SHT21 sensor is active")); @@ -34,10 +143,13 @@ void init_sht(){ // delay(5000); // } // Serial.println(F("HTU21D, SHT21 sensor is active")); - #endif } -void get_sht(){ +String getSHT21(){ + return (String)myHTU21D.readCompensatedHumidity() +} + +void print_sht21(){ #ifdef USESHT21 /* DEMO - 1 */ Serial.println(F("DEMO 1: 12-Bit Resolution")); @@ -79,5 +191,16 @@ void get_sht(){ myHTU21D.setResolution(HTU21D_RES_RH12_TEMP14); #endif } +#endif + +#ifdef USELM75 +void init_LM75(){ +} + +void print_LM75(){ + Serial.println((String)lm75.getTemperatureInFahrenheit() + " F"); +} +#endif + #endif \ No newline at end of file From d54e8fb4c7d0f806debea1fd612d5697a3159a3c Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 6 Nov 2020 20:38:27 -0600 Subject: [PATCH 014/186] esp32 support --- httpd.h | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/httpd.h b/httpd.h index 849d26a..2d7733a 100644 --- a/httpd.h +++ b/httpd.h @@ -1,8 +1,14 @@ #include "wifi_funcs.h" #include -#include +#ifdef ESP8266 +#include ESP8266WebServer server(80); +#elif defined ESP32 +#include +WebServer server(80); +#endif + void handleRoot() { @@ -30,7 +36,7 @@ void handleRoot() { // delay(2000); // server.send(200, "text/plain", "hello from esp8266! PWM set:" + (String)getPWM()); // analogWrite(16,pwmvalue.toInt()); - // setHTTPValue(pwmvalue); + setHTTPValue(pwmvalue); } // digitalWrite(LED_BUILTIN, 1); @@ -90,5 +96,7 @@ void httpd_init(){ void httpd_process(void) { server.handleClient(); + #ifdef ESP8266 MDNS.update(); + #endif } From fa4c511409eefa7f5a93411574d61bd74503192d Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 6 Nov 2020 20:38:41 -0600 Subject: [PATCH 015/186] esp32 dac support --- ssr.h | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/ssr.h b/ssr.h index 7d63991..9951827 100644 --- a/ssr.h +++ b/ssr.h @@ -32,7 +32,7 @@ void ssr_init(int pin){ #ifdef ESP8266 analogWriteRange(255); // esp8266 - // analogWriteFreq(240); // min 100hz + // analogWriteFreq(120); // min 100hz #elif defined(ESP32) #endif } @@ -53,6 +53,8 @@ void SetSSRFrequency( int duty,int power =1) int out = invertDuty ? 255-duty : duty; #ifdef ESP8266 analogWrite( _ssrRelayPin, out); + #elif defined(ESP32) + dacWrite(_ssrRelayPin,out); #endif // if(duty == 0)digitalWrite(RELAYPIN,invertDuty ? LOW:HIGH); // if(duty == 255)digitalWrite(RELAYPIN,!invertDuty ? LOW:HIGH); @@ -89,7 +91,7 @@ void ssrTest(){ ssr_on(); delay(1000); ssr_off(); - delay(1000); + delay(2000); // Turn off the SSR - duty cycle of 0 SetSSRFrequency( 255 ); // test pulse @@ -99,6 +101,17 @@ void ssrTest(){ SetSSRFrequency( 255 ); // test pulse delay(1000); SetSSRFrequency( 0 ); + + for(int i=0;i<255;i++){ + SetSSRFrequency( i ); + delay(100); + } + + for(int i=0;i<255;i++){ + SetSSRFrequency( 255-i ); + delay(100); + } + ssr_off(); } From d6b308a51ba71acc1f8eeb2472941006f07e3db5 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 6 Nov 2020 20:38:50 -0600 Subject: [PATCH 016/186] esp32 fixe --- wifi_funcs.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index 3b4a0a6..ba65f28 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -8,10 +8,10 @@ #include #elif defined(ESP32) #include - #include + #include + #include #endif - // const char* hostname = "esp8266REFLOW"; void setWiFiHostname(const char* hostname){ From aa2bf5b71afc61dcc2a1025c8ee88730c0d774ae Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 18 Dec 2020 13:36:33 -0600 Subject: [PATCH 017/186] more reset verbose --- wifi_funcs.h | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/wifi_funcs.h b/wifi_funcs.h index 911bb8f..25dc828 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -174,6 +174,50 @@ void disableWiFi(){ // } // } +// switch ( reason) +// { +// case 1 : Serial.println ("POWERON_RESET");break; /**<1, Vbat power on reset*/ +// case 3 : Serial.println ("SW_RESET");break; /**<3, Software reset digital core*/ +// case 4 : Serial.println ("OWDT_RESET");break; /**<4, Legacy watch dog reset digital core*/ +// case 5 : Serial.println ("DEEPSLEEP_RESET");break; /**<5, Deep Sleep reset digital core*/ +// case 6 : Serial.println ("SDIO_RESET");break; /**<6, Reset by SLC module, reset digital core*/ +// case 7 : Serial.println ("TG0WDT_SYS_RESET");break; /**<7, Timer Group0 Watch dog reset digital core*/ +// case 8 : Serial.println ("TG1WDT_SYS_RESET");break; /**<8, Timer Group1 Watch dog reset digital core*/ +// case 9 : Serial.println ("RTCWDT_SYS_RESET");break; /**<9, RTC Watch dog Reset digital core*/ +// case 10 : Serial.println ("INTRUSION_RESET");break; /**<10, Instrusion tested to reset CPU*/ +// case 11 : Serial.println ("TGWDT_CPU_RESET");break; /**<11, Time Group reset CPU*/ +// case 12 : Serial.println ("SW_CPU_RESET");break; /**<12, Software reset CPU*/ +// case 13 : Serial.println ("RTCWDT_CPU_RESET");break; /**<13, RTC Watch dog Reset CPU*/ +// case 14 : Serial.println ("EXT_CPU_RESET");break; /**<14, for APP CPU, reseted by PRO CPU*/ +// case 15 : Serial.println ("RTCWDT_BROWN_OUT_RESET");break;*<15, Reset when the vdd voltage is not stable +// case 16 : Serial.println ("RTCWDT_RTC_RESET");break; /**<16, RTC Watch dog reset digital core and rtc module*/ +// default : Serial.println ("NO_MEAN"); +// } +// } + +// void verbose_print_reset_reason(RESET_REASON reason) +// { +// switch ( reason) +// { +// case 1 : Serial.println ("Vbat power on reset");break; +// case 3 : Serial.println ("Software reset digital core");break; +// case 4 : Serial.println ("Legacy watch dog reset digital core");break; +// case 5 : Serial.println ("Deep Sleep reset digital core");break; +// case 6 : Serial.println ("Reset by SLC module, reset digital core");break; +// case 7 : Serial.println ("Timer Group0 Watch dog reset digital core");break; +// case 8 : Serial.println ("Timer Group1 Watch dog reset digital core");break; +// case 9 : Serial.println ("RTC Watch dog Reset digital core");break; +// case 10 : Serial.println ("Instrusion tested to reset CPU");break; +// case 11 : Serial.println ("Time Group reset CPU");break; +// case 12 : Serial.println ("Software reset CPU");break; +// case 13 : Serial.println ("RTC Watch dog Reset CPU");break; +// case 14 : Serial.println ("for APP CPU, reseted by PRO CPU");break; +// case 15 : Serial.println ("Reset when the vdd voltage is not stable");break; +// case 16 : Serial.println ("RTC Watch dog reset digital core and rtc module");break; +// default : Serial.println ("NO_MEAN"); +// } +// } + // String ESP_getResetReason(void) { // return ESP32GetResetReason(0); // CPU 0 // } From 7f45b66da96f12be9f2003f4f71a7332b210df65 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 10:40:12 -0600 Subject: [PATCH 018/186] buzzer esp8266 only --- buzzer.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/buzzer.h b/buzzer.h index 86fa48d..115e084 100644 --- a/buzzer.h +++ b/buzzer.h @@ -1,6 +1,7 @@ #ifndef buzzer_h #define buzzer_h +#ifdef ESP8266 #include #include ESP8266_Tones BUZZER_TONE(BUZ_PIN); @@ -125,3 +126,4 @@ void playBlurpA(){ } #endif +#endif From 4c2f30cf0df650b0aac523976d0a93e268dc9f44 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 10:40:21 -0600 Subject: [PATCH 019/186] http freq --- httpd.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/httpd.h b/httpd.h index 2d7733a..5656417 100644 --- a/httpd.h +++ b/httpd.h @@ -39,6 +39,20 @@ void handleRoot() { setHTTPValue(pwmvalue); } + if(server.hasArg(F("freq"))){ + Serial.println("has arg FREQ"); + String pwmvalue = server.arg(F("freq")); + // ledIndex = pixel; + // setPWM(pwmvalue.toInt()); + // strip.setPixelColor(pixel.toInt(),strip.Color(255,0,0)); + Serial.println("Setting FREQ:" + (String)pwmvalue); + // strip.show(); + // delay(2000); + // server.send(200, "text/plain", "hello from esp8266! PWM set:" + (String)getPWM()); + // analogWrite(16,pwmvalue.toInt()); + setHTTPValueB(pwmvalue); + } + // digitalWrite(LED_BUILTIN, 1); server.send(200, "text/plain", "hello from esp8266!"); // digitalWrite(LED_BUILTIN, 0); From 9a4a4d3755b5d8277f47f203a70d2b554ce4683c Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 10:40:43 -0600 Subject: [PATCH 020/186] add nominal --- ntc_multi.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ntc_multi.h b/ntc_multi.h index a61bb2f..5754ee5 100644 --- a/ntc_multi.h +++ b/ntc_multi.h @@ -35,12 +35,13 @@ int rt = 330000/V - 320000; // 10000); // Value of the series resistor uint16_t resist = 100000; +uint16_t ntcnominal = 100000; uint16_t betaco = 3950; bool lowside = true; -THERMISTOR ntc(NTC_PIN,resist,betaco,resist,lowside); -THERMISTOR ntcB(NTC_BPIN,resist,betaco,resist,!lowside); -THERMISTOR ntcC(NTC_CPIN,resist,betaco,resist,lowside); +THERMISTOR ntc(NTC_PIN,ntcnominal,betaco,resist,lowside); +THERMISTOR ntcB(NTC_BPIN,ntcnominal,betaco,resist,!lowside); +THERMISTOR ntcC(NTC_CPIN,ntcnominal,betaco,resist,lowside); // Global temperature reading float ntc_temp; From 003497a0e942a9b9bebf1b7c6fdde20f97a1de05 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 10:41:52 -0600 Subject: [PATCH 021/186] esp32 analog shim --- ssr.h | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/ssr.h b/ssr.h index 9951827..bc9f62e 100644 --- a/ssr.h +++ b/ssr.h @@ -1,9 +1,13 @@ #ifndef ssr_h #define ssr_h -#define RELAYPIN 16 // relay control SSR PWM +#define RELAYPIN 3 // relay control SSR PWM #include +#ifdef ESP32 +#include +#endif + #ifdef DEBUG bool DEBUG_ssr = true; #else @@ -12,19 +16,19 @@ bool DEBUG_ssr = false; float currentDuty = 0; // ssrpower bool invertDuty = false; // invert logic vcc range -bool invertLOW = false; +bool invertLOW = false; int _ssrRelayPin = -1; void ssr_off(){ - digitalWrite(_ssrRelayPin,invertLOW ? HIGH : LOW); + if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,invertLOW ? HIGH : LOW); } void ssr_on(){ - digitalWrite(_ssrRelayPin,invertLOW ? LOW : HIGH); + if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,invertLOW ? LOW : HIGH); } -void ssr_init(int pin){ +void ssr_init(uint16_t pin){ _ssrRelayPin = pin; pinMode( _ssrRelayPin, OUTPUT ); delay(600); @@ -54,7 +58,8 @@ void SetSSRFrequency( int duty,int power =1) #ifdef ESP8266 analogWrite( _ssrRelayPin, out); #elif defined(ESP32) - dacWrite(_ssrRelayPin,out); + analogWrite( _ssrRelayPin, out); + // dacWrite(_ssrRelayPin,out); #endif // if(duty == 0)digitalWrite(RELAYPIN,invertDuty ? LOW:HIGH); // if(duty == 255)digitalWrite(RELAYPIN,!invertDuty ? LOW:HIGH); @@ -74,6 +79,12 @@ void setSSR(int duty){ SetSSRFrequency(duty); } +void setSSRFreq(int duty){ + #ifdef ESP8266 + analogWriteFreq(duty); // min 100hz + #endif +} + float getSSRDuty(){ return currentDuty; } @@ -82,7 +93,7 @@ float getSSRPower(){ return ( currentDuty / 255.0 ) * 100; } -void ssrTest(){ +void ssrTest(int speed){ ssr_on(); delay(1000); From 46f65523483cdd00635fe9a81d185e10e7660a63 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 10:42:11 -0600 Subject: [PATCH 022/186] temp logger multi ntc --- temp_logger.h | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/temp_logger.h b/temp_logger.h index 5f8f7ed..d3bd134 100644 --- a/temp_logger.h +++ b/temp_logger.h @@ -2,6 +2,9 @@ #define temp_logger_h // #include +#ifdef ESP32 +#include +#endif #include #include @@ -11,9 +14,9 @@ // #include #include #include -#include +// #include #include -#include +// #include // #include #include @@ -41,7 +44,7 @@ BarGraph bar0; #include #endif -// #define USENTC // use thermistor +#define USENTC // use thermistor #ifdef USENTC #include #endif @@ -68,7 +71,7 @@ BarGraph bar0; #define GFXX18pt &FreeSans18pt7b // #define GFXX18pt &FreeMono18pt7b -bool USEWIFI = true; // enabled wifi +bool USEWIFI = true; // enabled wifi, NOT connect wifi Average fps(10); // init stats for avg (samples) @@ -133,7 +136,7 @@ int SCREENHEIGHT = 240; // TFT_WIDTH int GRAPHHEIGHT = SCREENHEIGHT-(FOOTERH); //padding 200px int GRAPHWIDTH = SCREENWIDTH; -int graphInterval = 1000; // graph update rate ms +int graphInterval = 60000; // graph update rate ms TFT_eSprite spr = TFT_eSprite(&tft); @@ -499,17 +502,21 @@ uint8_t TITLETOPPAD = 4; // main title top padding // add getter for colors? + // 7 magenta + // 8 cyan + // 4 greenyellow + // void updateTempA(){ String str = TEMPA; // Serial.println("footer val1: " + str); if(DEBUG_BOX) tft.setTextColor(WHITE,DEBUG_HC1); - else tft.setTextColor(WHITE,HC1); + else tft.setTextColor(getLineColor(7,0),HC1); tft.setTextDatum(TL_DATUM); int lpad = 2; tft.setTextPadding(115); // drawDatumMarker(2,2); // tft.setFreeFont(AA_FONT_MED); // Must load the font first - lpad += tft.drawString(str,lpad,TITLETOPPAD,4); + lpad += tft.drawString(str+"`",lpad,TITLETOPPAD,4); // Serial.println(lpad); tft.setTextPadding(0); } @@ -518,13 +525,13 @@ void updateTempB(){ String str = TEMPB; // Serial.println("footer val1: " + str); if(DEBUG_BOX) tft.setTextColor(WHITE,DEBUG_HC1); - else tft.setTextColor(WHITE,HC1); + else tft.setTextColor(getLineColor(8,0),HC1); tft.setTextDatum(TL_DATUM); int lpad = 120; tft.setTextPadding(115); // drawDatumMarker(2,2); // tft.setFreeFont(AA_FONT_MED); // Must load the font first - lpad += tft.drawString(str,lpad,TITLETOPPAD,4); + lpad += tft.drawString(str+"`",lpad,TITLETOPPAD,4); // Serial.println(lpad); tft.setTextPadding(0); } @@ -533,13 +540,13 @@ void updateTempC(){ String str = TEMPC; // Serial.println("footer val1: " + str); if(DEBUG_BOX) tft.setTextColor(WHITE,DEBUG_HC1); - else tft.setTextColor(WHITE,HC1); - tft.setTextDatum(TL_DATUM); + else tft.setTextColor(getLineColor(4,0),HC1); + tft.setTextDatum(TR_DATUM); int rpad = 5; tft.setTextPadding(115); // drawDatumMarker(2,2); // tft.setFreeFont(AA_FONT_MED); // Must load the font first - rpad += tft.drawString(str,SCREENWIDTH-rpad,TITLETOPPAD,4); + rpad += tft.drawString(str+"`",SCREENWIDTH-rpad,TITLETOPPAD,4); // Serial.println(lpad); tft.setTextPadding(0); } @@ -547,7 +554,7 @@ void updateTitle(){ String str = TITLE; // Serial.println("footer val1: " + str); if(DEBUG_BOX) tft.setTextColor(WHITE,DEBUG_HC1); - else tft.setTextColor(WHITE,HC1); + else tft.setTextColor(getLineColor(4,0),HC1); tft.setTextDatum(TL_DATUM); int lpad = 2; tft.setTextPadding(115); From 73f71e28995f8aae50e86c8a1e54c257ca7f365f Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 10:42:20 -0600 Subject: [PATCH 023/186] Update wifi_funcs.h --- wifi_funcs.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index ba65f28..38bea0f 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -268,7 +268,7 @@ void MQTTreconnect() { Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying - delay(5000); + // delay(5000); } delay(100); } @@ -296,7 +296,7 @@ void MQTTcallback(char* topic, byte* payload, unsigned int length) { } void process_MQTT(){ -if (!client.connected()) { + if (!client.connected()) { MQTTreconnect(); } client.loop(); From 6114d7642165b0cbe2d617a011ca21b58db616a6 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 10:42:33 -0600 Subject: [PATCH 024/186] Update oled_i2c_sh1106.h --- oled_i2c_sh1106.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index 49b349c..ef06350 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -67,18 +67,19 @@ void whiteText(){ void print_oled(String str,uint8_t size,bool flush){ lcd.clearBuffer(); // clear the internal memory lcd.setFont(u8g2_font_ncenB08_tr); - lcd.drawStr(0,10,String(micros()).c_str()); // write something to the internal memory + // lcd.drawStr(0,10,String(micros()).c_str()); // write something to the internal memory lcd.setFont(u8g2_font_inb30_mn); lcd.drawStr(0,60,str.c_str()); // lcd.drawStr(0,10,micros().c_str(); // write something to the internal memory if(flush)lcd.sendBuffer(); // transfer internal memory to the display } +// @todo add pinswap void init_oled(bool preamble){ Serial.println("\nInitializing SSD1106 OLED"); Serial.println("SDA: "+(String)SDA); Serial.println("SCL: "+(String)SCL); - Wire.begin(5,4); // begin(sda, scl) SWAP! + // Wire.begin(5,4); // begin(sda, scl) SWAP! // Wire.begin(); // begin(sda, scl) SWAP! Wire.setClock(400000L); // lcd.setDisplayRotation(U8G2_R2); From b640e3206b075b499a098a35c2ab0d911de20b36 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 18:38:00 -0600 Subject: [PATCH 025/186] fixed inversion --- button_abs.h | 33 +++++++++++++++++++++++++++++---- ssr.h | 36 ++++++++++++++++++++++++------------ 2 files changed, 53 insertions(+), 16 deletions(-) diff --git a/button_abs.h b/button_abs.h index 0876a78..9f95dd0 100644 --- a/button_abs.h +++ b/button_abs.h @@ -12,14 +12,26 @@ const int interruptPin = 3; // if motor.h stalldetect, Real interrupt for io exp const int encoderSWPin = 0; const int encoderAPin = 1; const int encoderBPin = 2; + int _maximumEncoderValue = 0; // 128; 0 for non counting mode -int encoderStale = 0; -int encoderLast = -1; -bool encoderHasChange = false; -bool useInt = false; + +int encoderStale = 0; // prev stale value +int encoderLast = -1; // prev value + +bool encoderHasChange = false; // flag enc change +bool useInt = false; // use interrupts, via interruptPin + +bool encoderHasPress = false; +bool encoderHasHold = false; volatile bool PCFInterruptFlag = false; +void encoderClear(){ + encoderHasPress = false; + encoderHasHold = false; + encoderHasChange = false; +} + void ICACHE_RAM_ATTR onEncoderChange(int newValue) { if(_maximumEncoderValue > 0){ Serial.print("[ENCODER] change to "); @@ -55,7 +67,11 @@ void ICACHE_RAM_ATTR onEncoderChange(int newValue) { void ICACHE_RAM_ATTR onEncoderSWPressed(uint8_t pin, bool heldDown) { Serial.print("[ENCODER] Button "); Serial.println(heldDown ? "Held" : "Pressed"); + encoderHasPress = true; + encoderHasHold = heldDown; } + + // adjust the encoder acceleraton // HWACCEL_FAST // HWACCEL_SLOWER @@ -103,6 +119,15 @@ void setEncoderMax(int maximumEncoderValue){ _maximumEncoderValue = maximumEncoderValue; } +void checkAnalogSW(uint8_t pin, uint16_t value){ + // adc range / value 1024/500 = 2 states+ etc + if(analogRead(pin) < value){ + encoderHasPress = true; + delay(50); + if(analogRead(pin) < value) encoderHasHold = true; + } +} + // IoAbstractionRef iodev = switches.getIoAbstraction(); // iodev->pinDirection(7,OUTPUT); // bool res = iodev->runLoop(); diff --git a/ssr.h b/ssr.h index bc9f62e..ef839d7 100644 --- a/ssr.h +++ b/ssr.h @@ -14,18 +14,19 @@ bool DEBUG_ssr = true; bool DEBUG_ssr = false; #endif +bool ssrDisabled = false; float currentDuty = 0; // ssrpower -bool invertDuty = false; // invert logic vcc range -bool invertLOW = false; +bool invertDuty = true; // invert logic vcc range +bool invertLOW = false; // Drive SSR with VCC int _ssrRelayPin = -1; void ssr_off(){ - if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,invertLOW ? HIGH : LOW); + if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,invertLOW ? LOW : HIGH); } void ssr_on(){ - if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,invertLOW ? LOW : HIGH); + if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,invertLOW ? HIGH : LOW); } void ssr_init(uint16_t pin){ @@ -45,6 +46,14 @@ void ssr_init(){ ssr_init(RELAYPIN); } +void disableSSR(bool disabled = true){ + ssrDisabled = disabled; +} + +void toggleSSR(bool disabled = true){ + ssrDisabled != ssrDisabled; +} + // This is where the SSR is controlled via PWM void SetSSRFrequency( int duty,int power =1) { @@ -55,14 +64,17 @@ void SetSSRFrequency( int duty,int power =1) // Write the clamped duty cycle to the RELAYPIN GPIO int out = invertDuty ? 255-duty : duty; - #ifdef ESP8266 - analogWrite( _ssrRelayPin, out); - #elif defined(ESP32) - analogWrite( _ssrRelayPin, out); - // dacWrite(_ssrRelayPin,out); - #endif - // if(duty == 0)digitalWrite(RELAYPIN,invertDuty ? LOW:HIGH); - // if(duty == 255)digitalWrite(RELAYPIN,!invertDuty ? LOW:HIGH); + + if(!ssrDisabled){ + #ifdef ESP8266 + analogWrite( _ssrRelayPin, out); + #elif defined(ESP32) + analogWrite( _ssrRelayPin, out); + // dacWrite(_ssrRelayPin,out); + #endif + // if(duty == 0)digitalWrite(RELAYPIN,invertDuty ? LOW:HIGH); + // if(duty == 255)digitalWrite(RELAYPIN,!invertDuty ? LOW:HIGH); + } if(duty!=currentDuty){ // if(DEBUG_ssr) Serial.println("[SSR] " + (String)duty); From a96039d096a8a4a5fd97c05e998064f013f2e981 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 18:38:02 -0600 Subject: [PATCH 026/186] Update oled_i2c_sh1106.h --- oled_i2c_sh1106.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index ef06350..9cef5ce 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -142,7 +142,7 @@ int printInverted(const char* str,uint16_t posx,uint16_t posy){ int padx = (lcd.getStrWidth("OFF")-lcd.getStrWidth("ON"))/2; // w padding // int pady = 2; // h padding int pady = 1; // h padding - Serial.println(padx); + // Serial.println(padx); lcd.setDrawColor(1); uint16_t strw = lcd.drawStr(posx+padx, posy, str); // x,y(NEGATIVE GOING!) From 9da8f54250b24c60e4f6cc3995dfef71fcd430a0 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 20:53:42 -0600 Subject: [PATCH 027/186] Update button_abs.h --- button_abs.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/button_abs.h b/button_abs.h index 9f95dd0..8bd2cec 100644 --- a/button_abs.h +++ b/button_abs.h @@ -119,11 +119,11 @@ void setEncoderMax(int maximumEncoderValue){ _maximumEncoderValue = maximumEncoderValue; } -void checkAnalogSW(uint8_t pin, uint16_t value){ +void checkAnalogSW(uint8_t pin, uint16_t value,uint32_t hold){ // adc range / value 1024/500 = 2 states+ etc if(analogRead(pin) < value){ encoderHasPress = true; - delay(50); + delay(hold); if(analogRead(pin) < value) encoderHasHold = true; } } From 8eefc896a3cc0ec5b4f56ed41b429577a7ea0ab0 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 20:54:00 -0600 Subject: [PATCH 028/186] reflowplate --- max31855.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/max31855.h b/max31855.h index 87b3bf2..21c4b4c 100644 --- a/max31855.h +++ b/max31855.h @@ -20,7 +20,8 @@ #define MAXCS 16 // 2 #define MAXCLK 14 // HWSLK #define MAXMISO 4 -Adafruit_MAX31855 tc(MAXCLK,MAXCS,MAXMISO); +// Adafruit_MAX31855 tc(MAXCLK,MAXCS,MAXMISO); +Adafruit_MAX31855 tc(14,15,12); #ifdef TC2 Adafruit_MAX31855 tcB(1); From c500f4857609481e17f6d3db12bb70a08779bea3 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 20 Dec 2020 20:54:13 -0600 Subject: [PATCH 029/186] was confusing --- ssr.h | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/ssr.h b/ssr.h index ef839d7..ffb87a0 100644 --- a/ssr.h +++ b/ssr.h @@ -21,12 +21,13 @@ bool invertLOW = false; // Drive SSR with VCC int _ssrRelayPin = -1; + void ssr_off(){ - if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,invertLOW ? LOW : HIGH); + if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,!invertLOW ? HIGH : LOW); } void ssr_on(){ - if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,invertLOW ? HIGH : LOW); + if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,!invertLOW ? LOW : HIGH); } void ssr_init(uint16_t pin){ @@ -46,14 +47,6 @@ void ssr_init(){ ssr_init(RELAYPIN); } -void disableSSR(bool disabled = true){ - ssrDisabled = disabled; -} - -void toggleSSR(bool disabled = true){ - ssrDisabled != ssrDisabled; -} - // This is where the SSR is controlled via PWM void SetSSRFrequency( int duty,int power =1) { @@ -72,8 +65,8 @@ void SetSSRFrequency( int duty,int power =1) analogWrite( _ssrRelayPin, out); // dacWrite(_ssrRelayPin,out); #endif - // if(duty == 0)digitalWrite(RELAYPIN,invertDuty ? LOW:HIGH); - // if(duty == 255)digitalWrite(RELAYPIN,!invertDuty ? LOW:HIGH); + // if(duty == 0)ssr_off(); + // if(duty == 255)ssr_on(); } if(duty!=currentDuty){ @@ -105,6 +98,20 @@ float getSSRPower(){ return ( currentDuty / 255.0 ) * 100; } +void ssr_resume(){ + if(_ssrRelayPin > 0) setSSR(currentDuty); +} + +void disableSSR(bool disabled = true){ + ssrDisabled = disabled; +} + +void toggleSSR(){ + ssrDisabled = !ssrDisabled; + if(!ssrDisabled) ssr_resume(); + else ssr_off(); +} + void ssrTest(int speed){ ssr_on(); From 71c853c8b482802358b87e021bee76d3f6e1eeae Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 21 Dec 2020 15:02:25 -0600 Subject: [PATCH 030/186] split out mqtt --- mqtt.h | 146 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 mqtt.h diff --git a/mqtt.h b/mqtt.h new file mode 100644 index 0000000..2b60d98 --- /dev/null +++ b/mqtt.h @@ -0,0 +1,146 @@ +#ifndef mqtt_h +#define mqtt_h + +#include + +WiFiClient espClient; + +PubSubClient client(espClient); + + +void MQTTreconnect() { + + // Loop until we're reconnected + + while (!client.connected()) { + + Serial.print("Attempting MQTT connection..."); + + // Create a random client ID + + String clientId = "ESP8266Client-"; + + clientId += String(random(0xffff), HEX); + + // Attempt to connect + + if (client.connect(clientId.c_str())) { + + Serial.println("connected"); + + // Once connected, publish an announcement... + + client.publish("TESTOUT", "hello world"); + + // ... and resubscribe + + client.subscribe("TESTIN"); + + } else { + + Serial.print("failed, rc="); + + Serial.print(client.state()); + + Serial.println(" try again in 5 seconds"); + + // Wait 5 seconds before retrying + + // delay(5000); + + } + + delay(100); + + } + +} + + + +void MQTTcallback(char* topic, byte* payload, unsigned int length) { + + Serial.print("Message arrived ["); + + Serial.print(topic); + + Serial.print("] "); + + for (int i = 0; i < length; i++) { + + Serial.print((char)payload[i]); + + } + + Serial.println(); + + + + // Switch on the LED if an 1 was received as first character + + if ((char)payload[0] == '1') { + + // digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level + + // but actually the LED is on; this is because + + // it is active low on the ESP-01) + + } + + // else { + + // // digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH + + // } + + + +} + + + +void process_MQTT(){ + + if (!client.connected()) { + + MQTTreconnect(); + + } + + client.loop(); + +} + + + +void init_MQTT(){ + + client.setServer(mqtt_server_ip, 1883); + + client.setCallback(MQTTcallback); + + process_MQTT(); + +} + + + +void MQTT_pub(String topic, String msg){ + + Serial.print("Publish message: "); + + Serial.print("topic: "); + + Serial.print(topic); + + Serial.print(" mesg: "); + + Serial.println(msg); + + client.publish(topic.c_str(), msg.c_str()); + +} + + +#endif \ No newline at end of file From ae94e786a07950810ef9c2954fb7ea30bd09a677 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 21 Dec 2020 15:02:33 -0600 Subject: [PATCH 031/186] collect dependancies --- dependancies.txt | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 dependancies.txt diff --git a/dependancies.txt b/dependancies.txt new file mode 100644 index 0000000..fde9921 --- /dev/null +++ b/dependancies.txt @@ -0,0 +1,7 @@ +dependancies + +panstamp/thermistor +MajenkoLibraries/Average +ug82 +jackw01/PIDAutotuner +luisllamasbinaburo/Arduino-Interpolation \ No newline at end of file From 7d89bf3bc383b72b1c8b2db45059f7ce4f5560ee Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 21 Dec 2020 15:02:52 -0600 Subject: [PATCH 032/186] update for non modified thermistor lib --- ntc_multi.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ntc_multi.h b/ntc_multi.h index 5754ee5..6b37666 100644 --- a/ntc_multi.h +++ b/ntc_multi.h @@ -39,9 +39,15 @@ uint16_t ntcnominal = 100000; uint16_t betaco = 3950; bool lowside = true; +#ifdef local_thermistor_h THERMISTOR ntc(NTC_PIN,ntcnominal,betaco,resist,lowside); THERMISTOR ntcB(NTC_BPIN,ntcnominal,betaco,resist,!lowside); THERMISTOR ntcC(NTC_CPIN,ntcnominal,betaco,resist,lowside); +#else +THERMISTOR ntc(NTC_PIN,ntcnominal,betaco,resist); +THERMISTOR ntcB(NTC_BPIN,ntcnominal,betaco,resist); +THERMISTOR ntcC(NTC_CPIN,ntcnominal,betaco,resist); +#endif // Global temperature reading float ntc_temp; From 1d241fbb8ab9d92bb8245bc8a96e2a0526e0fbcd Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 21 Dec 2020 15:03:00 -0600 Subject: [PATCH 033/186] fixup --- oled_i2c_sh1106.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index 9cef5ce..db60569 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -75,16 +75,16 @@ void print_oled(String str,uint8_t size,bool flush){ } // @todo add pinswap -void init_oled(bool preamble){ +void init_oled(bool preamble,bool pinswap = false){ Serial.println("\nInitializing SSD1106 OLED"); Serial.println("SDA: "+(String)SDA); Serial.println("SCL: "+(String)SCL); - // Wire.begin(5,4); // begin(sda, scl) SWAP! + if(pinswap) Wire.begin(5,4); // begin(sda, scl) SWAP! // Wire.begin(); // begin(sda, scl) SWAP! - Wire.setClock(400000L); + // Wire.setClock(400000L); // lcd.setDisplayRotation(U8G2_R2); lcd.begin(); - // lcd.setI2CAddress(0x07a); + lcd.setI2CAddress(0x7A); // if(!lcd.begin()) { // Address 0x3C for 128x32 // Serial.println(F("SSD1106 begin failed")); // } From 535401691cb0104e789854206491b3237b83a4fe Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 21 Dec 2020 15:03:11 -0600 Subject: [PATCH 034/186] updates for lib --- pidtune.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pidtune.h b/pidtune.h index d7fb983..d1d42fc 100644 --- a/pidtune.h +++ b/pidtune.h @@ -49,7 +49,7 @@ void init_pidtune(){ // tuner.setZNMode(PIDAutotuner::ZNModeNoOvershoot); // This must be called immediately before the tuning loop - tuner.startTuningLoop(); + tuner.startTuningLoop(micros()); // Run a loop until tuner.isFinished() returns true long microseconds; @@ -63,7 +63,7 @@ void init_pidtune(){ float input = doSomethingToGetInput(); // Call tunePID() with the input value - float output = tuner.tunePID(input); + float output = tuner.tunePID(input,micros()); // Set the output - tunePid() will return values within the range configured // by setOutputRange(). Don't change the value or the tuning results will be From 7a8cf06c3ba3fe6706a1d0df45354beb049e3575 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 21 Dec 2020 15:03:18 -0600 Subject: [PATCH 035/186] remove mqtt --- wifi_funcs.h | 73 ---------------------------------------------------- 1 file changed, 73 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index 495d232..3c91937 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -288,77 +288,4 @@ String getResetReason(){ #endif } - -#include -WiFiClient espClient; -PubSubClient client(espClient); - -void MQTTreconnect() { - // Loop until we're reconnected - while (!client.connected()) { - Serial.print("Attempting MQTT connection..."); - // Create a random client ID - String clientId = "ESP8266Client-"; - clientId += String(random(0xffff), HEX); - // Attempt to connect - if (client.connect(clientId.c_str())) { - Serial.println("connected"); - // Once connected, publish an announcement... - client.publish("TESTOUT", "hello world"); - // ... and resubscribe - client.subscribe("TESTIN"); - } else { - Serial.print("failed, rc="); - Serial.print(client.state()); - Serial.println(" try again in 5 seconds"); - // Wait 5 seconds before retrying - // delay(5000); - } - delay(100); - } -} - -void MQTTcallback(char* topic, byte* payload, unsigned int length) { - Serial.print("Message arrived ["); - Serial.print(topic); - Serial.print("] "); - for (int i = 0; i < length; i++) { - Serial.print((char)payload[i]); - } - Serial.println(); - - // Switch on the LED if an 1 was received as first character - if ((char)payload[0] == '1') { - // digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level - // but actually the LED is on; this is because - // it is active low on the ESP-01) - } - // else { - // // digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH - // } - -} - -void process_MQTT(){ - if (!client.connected()) { - MQTTreconnect(); - } - client.loop(); -} - -void init_MQTT(){ - client.setServer(mqtt_server_ip, 1883); - client.setCallback(MQTTcallback); - process_MQTT(); -} - -void MQTT_pub(String topic, String msg){ - Serial.print("Publish message: "); - Serial.print("topic: "); - Serial.print(topic); - Serial.print(" mesg: "); - Serial.println(msg); - client.publish(topic.c_str(), msg.c_str()); -} - #endif \ No newline at end of file From 2a08779510a4ab5814733f2914041792e83513f4 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 21 Dec 2020 23:21:39 -0600 Subject: [PATCH 036/186] add syslog --- syslog.h | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 syslog.h diff --git a/syslog.h b/syslog.h new file mode 100644 index 0000000..3f25c9b --- /dev/null +++ b/syslog.h @@ -0,0 +1,63 @@ +#ifndef syslog_h +#define syslog_h + +#include +#include // https://github.com/arcao/Syslog + +#include + +// Syslog server connection info +#define SYSLOG_SERVER "syslog-server" +#define SYSLOG_PORT 514 + +// This device info +#define DEVICE_HOSTNAME "my-device" +#define APP_NAME "my-app" + +// A UDP instance to let us send and receive packets over UDP +WiFiUDP udpClient; + +// Create a new syslog instance with LOG_KERN facility +Syslog syslog(udpClient, SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME, LOG_KERN); +int iteration = 1; + +void init_syslog(){ + Serial.println("[SYSLOG] init"); + // Syslog new syslog(udpClient); + + syslog.server(SYSLOG_SERVER, SYSLOG_PORT); + syslog.deviceHostname(DEVICE_HOSTNAME); + syslog.appName(APP_NAME); + syslog.defaultPriority(LOG_KERN); +} + +void sendLogTest(){ + syslog.log(LOG_INFO, "Begin Send"); + + // Log message can be formated like with printf function. + syslog.logf(LOG_ERR, "This is error message no. %d", iteration); + syslog.logf(LOG_INFO, "This is info message no. %d", iteration); + + // You can force set facility in pri parameter for this log message. More + // facilities in syslog.h or in Linux syslog documentation. + syslog.logf(LOG_DAEMON | LOG_INFO, "This is daemon info message no. %d", + iteration); + + // You can set default facility and severity level and use it for all log + // messages (beware defaultPriority is stored permanently!) + syslog.defaultPriority(LOG_FTP | LOG_INFO); + syslog.logf("This is ftp info message no. %d", iteration); + + // Send log messages up to LOG_WARNING severity + syslog.logMask(LOG_UPTO(LOG_WARNING)); + syslog.log(LOG_ERR, "This is logged."); + syslog.log(LOG_WARNING, "This is logged."); + syslog.log(LOG_NOTICE, "This is not logged."); + syslog.log(LOG_INFO, "This is not logged."); + + // F() macro is supported too + syslog.log(LOG_INFO, F("End loop")); + iteration++; +} + +#endif \ No newline at end of file From a03e581c2a3f279b5344383b3a6c374d3b33133a Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 21 Dec 2020 23:40:49 -0600 Subject: [PATCH 037/186] reflowplate oled is 78 --- oled_i2c_sh1106.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index db60569..ed2a01a 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -84,7 +84,7 @@ void init_oled(bool preamble,bool pinswap = false){ // Wire.setClock(400000L); // lcd.setDisplayRotation(U8G2_R2); lcd.begin(); - lcd.setI2CAddress(0x7A); + // lcd.setI2CAddress(0x7A); // if(!lcd.begin()) { // Address 0x3C for 128x32 // Serial.println(F("SSD1106 begin failed")); // } From b8cc5f2822865e1c4fad4036d4dfb8f07189f4ec Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 3 Jan 2021 19:39:35 -0600 Subject: [PATCH 038/186] hostname --- httpd.h | 3 ++- wifi_funcs.h | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/httpd.h b/httpd.h index 5656417..c760b97 100644 --- a/httpd.h +++ b/httpd.h @@ -54,7 +54,8 @@ void handleRoot() { } // digitalWrite(LED_BUILTIN, 1); - server.send(200, "text/plain", "hello from esp8266!"); + // server.send(200, "text/plain", "hello from esp8266!"); + server.send(200, "text/plain", "hello from " + getHostname()); // digitalWrite(LED_BUILTIN, 0); } diff --git a/wifi_funcs.h b/wifi_funcs.h index 3c91937..790e1b6 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -22,6 +22,14 @@ void setWiFiHostname(const char* hostname){ #endif } +String getHostname(){ + #ifdef ESP32 + return WiFi.getHostname(); // getHostName + #else + return WiFi.hostname(); // getHostName + #endif +} + // enable wifi sta // disable sleep // timeout connect From b433393c1cfb27401e0f96b64a91e93a3d4f4233 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 3 Jan 2021 19:40:09 -0600 Subject: [PATCH 039/186] disable temp delay --- max31855.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/max31855.h b/max31855.h index 21c4b4c..2b29c59 100644 --- a/max31855.h +++ b/max31855.h @@ -67,7 +67,7 @@ float internalTemp = 0; // cold junction float currentTempCorr = 0; // linearized k type float lastTemp = -1; // used in pid.h -int TCinterval = 200; // temp reading interval +int TCinterval = 0; // temp reading interval // TC WARN // options From 6568bb7cdcd25a54634b5fdecef6a28d18a5f686 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 3 Jan 2021 19:40:18 -0600 Subject: [PATCH 040/186] disable debug pritn --- neoindicator.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/neoindicator.h b/neoindicator.h index 3d4047d..4e17919 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -157,8 +157,8 @@ void rainbowInd(int wait) { // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t indWheel(byte WheelPos) { - Serial.print("indWheel: "); - Serial.print(WheelPos,BIN); + // Serial.print("indWheel: "); + // Serial.print(WheelPos,BIN); WheelPos = 255 - WheelPos; if(WheelPos < 85) { return ind.Color(255 - WheelPos * 3, 0, WheelPos * 3); From 7085f82bf14e587cbd91bd985f71707e726e3291 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 3 Jan 2021 19:40:44 -0600 Subject: [PATCH 041/186] clean up --- oled_i2c_sh1106.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index ed2a01a..7e00f3a 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -80,9 +80,8 @@ void init_oled(bool preamble,bool pinswap = false){ Serial.println("SDA: "+(String)SDA); Serial.println("SCL: "+(String)SCL); if(pinswap) Wire.begin(5,4); // begin(sda, scl) SWAP! - // Wire.begin(); // begin(sda, scl) SWAP! // Wire.setClock(400000L); - // lcd.setDisplayRotation(U8G2_R2); + lcd.setDisplayRotation(U8G2_R2); lcd.begin(); // lcd.setI2CAddress(0x7A); // if(!lcd.begin()) { // Address 0x3C for 128x32 From c625a69fc4b10d9b37124dcd0acdfa430b53a83a Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 19 Jan 2021 10:41:31 -0600 Subject: [PATCH 042/186] reconect? --- mqtt.h | 71 +++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 50 insertions(+), 21 deletions(-) diff --git a/mqtt.h b/mqtt.h index 2b60d98..3b87bf0 100644 --- a/mqtt.h +++ b/mqtt.h @@ -7,11 +7,12 @@ WiFiClient espClient; PubSubClient client(espClient); +String clientID = ""; void MQTTreconnect() { // Loop until we're reconnected - + // this is blocking while (!client.connected()) { Serial.print("Attempting MQTT connection..."); @@ -98,49 +99,77 @@ void MQTTcallback(char* topic, byte* payload, unsigned int length) { } +long lastReconnectAttempt = 0; +uint16_t mqttretry = 5000; +boolean mqttReconnect() { + WiFi.reconnect(); + return WiFi.status() == 'WL_CONNECTED'; +} -void process_MQTT(){ - +void mqtt_checkconn(){ if (!client.connected()) { + long now = millis(); + if (now - lastReconnectAttempt > mqttretry) { + lastReconnectAttempt = now; + // Attempt to reconnect + if (mqttReconnect()) { + lastReconnectAttempt = 0; + client.connect(clientID.c_str()); + } + } + } else { + // Client connected + client.loop(); + } +} - MQTTreconnect(); - +void process_MQTT_nb(){ + if (!client.connected()) { + mqtt_checkconn(); } - - client.loop(); - + client.loop(); // will wait loop reconnect to mqtt } +void process_MQTT(){ + MQTTreconnect(); + client.loop(); // will wait loop reconnect to mqtt +} +void init_MQTT(String clientid){ + clientID = clientid; + client.setServer(mqtt_server_ip, 1883); + client.setCallback(MQTTcallback); + process_MQTT(); +} void init_MQTT(){ - client.setServer(mqtt_server_ip, 1883); - client.setCallback(MQTTcallback); - process_MQTT(); - } - void MQTT_pub(String topic, String msg){ - - Serial.print("Publish message: "); - + Serial.print("[MQTT] Publish message: "); Serial.print("topic: "); - Serial.print(topic); - Serial.print(" mesg: "); - Serial.println(msg); - client.publish(topic.c_str(), msg.c_str()); - } +void MQTT_pub(String topic, String sensor, String value){ + Serial.print("[MQTT] Publish message: "); + Serial.print("topic: "); + Serial.print(topic+"/"+clientID+"/"+sensor); + Serial.print("\t\tvalue: "); + Serial.println(value); + if(value == "") { + Serial.println("[ERROR] MQTT value is empty"); + return; + } + client.publish((topic+"/"+clientID+"/"+sensor).c_str(), value.c_str()); +} #endif \ No newline at end of file From d1bb977926d2d7153822a70add649aa0e570824c Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 19 Jan 2021 10:42:12 -0600 Subject: [PATCH 043/186] add new stuff --- sense_env.h | 366 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 360 insertions(+), 6 deletions(-) diff --git a/sense_env.h b/sense_env.h index c581c82..3f10b7d 100644 --- a/sense_env.h +++ b/sense_env.h @@ -1,11 +1,278 @@ #ifndef sensors_h #define sensors_h +// BUGS +// sensors do not reinit is they drop out +// co2 voc, resubmits the same value over and over if device is lost +// use real temp and humidity to compensate other sensors + #include -#define USESHT31 -// #define USESHT21 -#define USEBMP280 +// I2C +// #define USESHT31 // SHT31 Temp/Humidity +// #define USESHT21 // SHT21 / HTU21D Temp/Humidity +#define USEBMP180 // BMP180 Temp/Pressure/Altitude (replaces BMP085) https://www.adafruit.com/product/1603 +/* +Vin: 3 to 5VDC +Logic: 3 to 5V compliant +Pressure sensing range: 300-1100 hPa (9000m to -500m above sea level) +Up to 0.03hPa / 0.25m resolution +-40 to +85°C operational range, +-2°C temperature accuracy +This board/chip uses I2C 7-bit address 0x77. +*/ + +#define USEBMP280 // BMP280 Temp/Pressure/Altitude (upgrade to BMP085/BMP180/BMP183) +#define USECS811 // CCS811 Temp/CO2/VOC +#define USEGP2Y // Sharp Particle/Dust sensor GP2Y1010AU0F, GP2Y1014AU0F +#define APDS9960 // Proximity, Light, RGB, and Gesture Sensor + +#define BH1750 // Light Sensor + +#define TSL2561 // Luminosity/Lux/Light Address = 0x39 //Slave addr also 0x29 or 0x49 +/* +TSL2561 +Approximates Human eye Response +Precisely Measures Illuminance in Diverse Lighting Conditions +Temperature range: -30 to 80 *C +Dynamic range (Lux): 0.1 to 40,000 Lux +Voltage range: 2.7-3.6V +Interface: I2C + +TSL2591 ++ +Approximates Human eye Response +Extremely wide dynamic range 1 to 600,000,000 Counts +Lux Range: 188 uLux sensitivity, up to 88,000 Lux input measurements. +Temperature range: -30 to 80 *C +Voltage range: 3.3-5V into onboard regulator +Interface: I2C +*/ + +// [I2C] Device found - ADDR: 0x23 // BH1750 +// [I2C] Device found - ADDR: 0x39 // APDS9960 / TSL2561 +// [I2C] Device found - ADDR: 0x5A // +// [I2C] Device found - ADDR: 0x76 // + +/* +#ifdef ENV_TEMPLATE +#include + +void init_env(){ +} + +void print_env(){ +} + +float get_env(uint8_t channel = 0){ + // print_env(); + if(channel == 0) return ; + if(channel == 1) return ; + if(channel == 2) return ; + +#endif +*/ + +/* +#ifdef ENV_TEMPLATE +#include + +bool init_env(){ +} + +void print_env(){ +} + +float get_env(uint8_t channel = 0){ + // print_env(); + if(channel == 0) return ; + if(channel == 1) return ; + if(channel == 2) return ; + +#endif +*/ + +#ifdef BH1750 +#include //inlude the library +hp_BH1750 env_BH1750; + +// BH1750Address addr = BH1750_TO_VCC; +// BH1750Address BH1750addr = BH1750_TO_GROUND; +// 0x23/0x5A , or 0X5C +// BH1750_TO_GROUND = 0x23, +// BH1750_TO_VCC = 0x5C + +bool init_bh1750(){ + Serial.println("[ENV] hp_BH175 init"); + bool status = env_BH1750.begin(BH1750_TO_GROUND); // will be false no sensor found + // use BH1750_TO_GROUND or BH1750_TO_VCC depending how you wired the address pin of the sensor. + + // BH1750.calibrateTiming(); //uncomment this line if you want to speed up your sensor + env_BH1750.start(); + // BH1750.start(BH1750_QUALITY_HIGH2, mtreg); + // BH1750.setQuality(mode); + + if(!status) Serial.println("[ERROR] failed to initialize device! Please check your wiring."); + else Serial.println("[ENV] Device initialized!"); + return status; +} + +void print_bh1750(){ + if (env_BH1750.hasValue() == true) { // non blocking reading + float lux = env_BH1750.getLux(); + Serial.println(lux); + env_BH1750.start(); + } +} + +float get_bh1750(uint8_t channel = 0){ + float lux; + if(channel == 0){ + if (env_BH1750.hasValue() == true) { // non blocking reading + lux = env_BH1750.getLux(); + env_BH1750.start(); + Serial.println(lux); + } + } + else{ + env_BH1750.start(); //starts a measurement + lux=env_BH1750.getLux(); + Serial.println(lux); + } + return lux; +} +#endif + + +#ifdef APDS9960 + +#include "Adafruit_APDS9960.h" +Adafruit_APDS9960 apds; +uint8_t apds_int_pin = -1; + +bool init_apds(){ + bool ret = false; + ret = apds.begin(); + if(!ret){ + Serial.println("[ERROR] APDS9960 init failed"); + } + else Serial.println("[ENV] APDS9960 initialized!"); + if(apds_int_pin > 0) pinMode(apds_int_pin, INPUT_PULLUP); + return ret; +} + +void init_apds_color(){ + //enable color sensign mode + apds.enableColor(true); +} + +void init_apds_proximity(){ + if(apds_int_pin > 0) pinMode(apds_int_pin, INPUT_PULLUP); + //enable proximity mode + apds.enableProximity(true); + //set the interrupt threshold to fire when proximity reading goes above 175 + apds.setProximityInterruptThreshold(0, 175); + //enable the proximity interrupt + apds.enableProximityInterrupt(); +} + +void init_apds_gesture(){ + apds.enableProximity(true); + apds.enableGesture(true); +} + +// NOT interrupt +String get_apds_proximity(){ + if(!digitalRead(apds_int_pin)){ + Serial.println(apds.readProximity()); + + //clear the interrupt + apds.clearInterrupt(); + } +} + +String get_apds_gesture(){ + uint8_t gesture = apds.readGesture(); + if(gesture == APDS9960_DOWN) Serial.println("v"); + if(gesture == APDS9960_UP) Serial.println("^"); + if(gesture == APDS9960_LEFT) Serial.println("<"); + if(gesture == APDS9960_RIGHT) Serial.println(">"); + return ""; +} + +void print_apds_color(){ + uint16_t r, g, b, c; + + //wait for color data to be ready + while(!apds.colorDataReady()){ + delay(5); + } + + //get the data and print the different channels + apds.getColorData(&r, &g, &b, &c); + Serial.print("red: "); + Serial.print(r); + + Serial.print(" green: "); + Serial.print(g); + + Serial.print(" blue: "); + Serial.print(b); + + Serial.print(" clear: "); + Serial.println(c); + Serial.println(); +} + +float get_apds_color(uint8_t channel = 0){ + // print_apds_color(); + uint16_t r, g, b, c; + if(!apds.colorDataReady()) return 0; + apds.getColorData(&r, &g, &b, &c); + if(channel == 0) return r; + if(channel == 1) return g; + if(channel == 2) return b; + if(channel == 3) return c; + return 0; +} + +#endif + + +#ifdef USEGP2Y +#include +const uint8_t SHARP_LED_PIN = 27; // Sharp Dust/particle sensor Led Pin +const uint8_t SHARP_VO_PIN = 33; // Sharp Dust/particle analog out pin used for reading +GP2YDustSensor dustSensor(GP2YDustSensorType::GP2Y1014AU0F, SHARP_LED_PIN, SHARP_VO_PIN,5); +#endif + +#ifdef USEGP2Y +void init_gp2y(){ + dustSensor.setBaseline(0.1); // set no dust voltage according to your own experiments + //dustSensor.setCalibrationFactor(1.1); // calibrate against precision instrument + dustSensor.begin(); + // dustSensor.setSensitivity(); + // getBaselineCandidate(); + // setBaseline(); +} + +float get_gp2y(uint8_t channel = 0){ + // print_bmp280(); + if(channel == 0) return dustSensor.getDustDensity(10); + if(channel == 1) return dustSensor.getRunningAverage(); + if(channel == 2) return analogRead(SHARP_VO_PIN); +} + +String print_gp2y(){ + // Serial.print("Dust density: "); + Serial.print(dustSensor.getDustDensity(10)); + // Serial.print(" ug/m3; Running average: "); + Serial.print("\t"); + Serial.print(dustSensor.getRunningAverage()); + // Serial.println(" ug/m3"); + Serial.print("\t"); + Serial.print(analogRead(SHARP_VO_PIN)); + Serial.println(""); +} +#endif #ifdef USELM75 #include @@ -15,16 +282,19 @@ LM75A lm75(true, //A0 LM75A pin state true); //A2 LM75A pin state #endif +// SHT21 / HTU21D Temp/Humidity #ifdef USESHT21 #include HTU21D myHTU21D(HTU21D_RES_RH12_TEMP14); #endif +// SHT31 Temp/Humidity #ifdef USESHT31 #include Adafruit_SHT31 sht31 = Adafruit_SHT31(); #endif +// BMP280 Temp/Pressure/Altitude #ifdef USEBMP280 #include Adafruit_BMP280 bmp; // I2C @@ -33,8 +303,9 @@ Adafruit_BMP280 bmp; // I2C #ifdef USEBMP280 void init_bmp280(){ if (!bmp.begin(BMP280_ADDRESS_ALT)) { - Serial.println(F("Could not find a valid BMP280 sensor, check wiring!")); + Serial.println(F("[ERROR] Could not find a valid BMP280 sensor, check wiring!")); } + else Serial.println(F("[ENV] BMP280 sensor is active")); /* Default settings from datasheet. */ bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */ @@ -45,6 +316,8 @@ void init_bmp280(){ } void print_bmp280(){ + Serial.print(F("Status")); + Serial.println((String)bmp.getStatus()); Serial.print(F("Temperature = ")); Serial.print(bmp.readTemperature()); Serial.println(" *C"); @@ -59,7 +332,16 @@ void print_bmp280(){ Serial.println(); } -#endif + +// BUGGY returns bad values not null, or noint +float get_bmp280(uint8_t channel = 0){ + // print_bmp280(); + if(channel == 0) return bmp.readTemperature(); + if(channel == 1) return bmp.readPressure(); + if(channel == 2) return bmp.readAltitude(1013.25); +} + +#endif #ifdef USESHT31 @@ -69,7 +351,7 @@ uint8_t loopCnt = 0; void init_sht31(){ bool init = sht31.begin(0x44); if(init){ - Serial.println(F("SHT31 sensor is active")); + Serial.println(F("[ENV] SHT31 sensor is active")); } else { @@ -202,5 +484,77 @@ void print_LM75(){ } #endif +// ************************************************************* +// CCS811 Temp/CO2/VOC +#ifdef USECS811 +#include "Adafruit_CCS811.h" +Adafruit_CCS811 ccs; + +void init_cs811(){ + Serial.println("[ENV] cs811 init"); + if(!ccs.begin()){ + Serial.println("[ERROR] CS811 Begin Failed"); + } + else { + //calibrate temperature sensor + while(!ccs.available() && millis() < 30000); + float temp = ccs.calculateTemperature(); + Serial.println("[ENV] CS811 set offset " + String(temp-25.0)); + ccs.setTempOffset(temp - 25.0); + } + // ccs.setDriveMode(uint8_t mode); + ccs.readData(); +} + +void print_cs811(){ + if(ccs.available()){ + float temp = ccs.calculateTemperature(); + if(!ccs.readData()){ + Serial.print("CO2: "); + Serial.print(ccs.geteCO2()); + Serial.print("ppm, TVOC: "); + Serial.print(ccs.getTVOC()); + Serial.print("ppb Temp:"); + Serial.println(temp); + } + } + else{ + Serial.println("[ERROR] cs811 not available"); + } +} + +// first call usually fails? +float get_cs811(uint8_t channel = 0){ + // print_cs811(); + // if(!ccs.available()) return 0; + // if(ccs.readData()) return 0; + // @todo detect failures, or else func return old values + if(!ccs.available()) Serial.println("[ERROR] cs811 not available"); // always false? + if(ccs.checkError()) Serial.println("[ERROR] Assert cs811 check error"); // always false? + uint8_t err = ccs.readData(); + float ret; + if(err != 0) Serial.println("[ERROR] cs811 readData " + (String)err); + if(channel == 0) ret = ccs.calculateTemperature(); + if(channel == 1) ret = ccs.geteCO2(); + if(channel == 2) ret = ccs.getTVOC(); + if(channel == 3) ret = ccs.getCurrentSelected(); + return ret; +} +#endif + + +/** + * [filterSensor description] + * @param {[type]} float n [description] + * @param {[type]} a low limit + * @param {[type]} b high limit + * @param {String} c replace + * @return {[type]} [description] + */ +String filterSensor( float n, float a,float b,String c = ""){ + if(n <= a ) return c; + if(n >= b ) return c; + return (String)n; +} #endif \ No newline at end of file From ad33926856dfbcbe1fc65cffd6f0120c97d402d1 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 19 Jan 2021 10:42:27 -0600 Subject: [PATCH 044/186] deviceid --- wifi_funcs.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/wifi_funcs.h b/wifi_funcs.h index 790e1b6..bcfdb6f 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -6,14 +6,26 @@ #ifdef ESP8266 #include #include + #define WIFI_getChipId() ESP.getChipId() #elif defined(ESP32) #include #include #include + #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() #endif // const char* hostname = "esp8266REFLOW"; + +String getDeviecID(){ + String _wifissidprefix = "ESP"; + String hostString = String(WIFI_getChipId(),HEX); + hostString.toUpperCase(); + // char hostString[16] = {0}; + // sprintf(hostString, "%06X", ESP.getChipId()); + return _wifissidprefix + "_" + hostString; +} + void setWiFiHostname(const char* hostname){ #ifdef ESP32 WiFi.setHostname(hostname); @@ -107,6 +119,7 @@ void checkWifi(){ Serial.println("[WIFI] WiFi Disconnected"); WiFi.reconnect(); } else { + Serial.println("[WIFI] WiFi CONNECTED"); Serial.println("[WIFI] RSSI: "+(String)getRSSIasQuality()); #ifdef USENEOIND indSetColor(0,255,0); From d50d3c23d9ce30eb88cdb6d350b3cc06849bc6d0 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 19 Jan 2021 10:42:47 -0600 Subject: [PATCH 045/186] analogwrite compile issues --- temp_logger.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/temp_logger.h b/temp_logger.h index d3bd134..d039eb8 100644 --- a/temp_logger.h +++ b/temp_logger.h @@ -2,9 +2,9 @@ #define temp_logger_h // #include -#ifdef ESP32 -#include -#endif +// #ifdef ESP32 +// #include +// #endif #include #include @@ -136,7 +136,7 @@ int SCREENHEIGHT = 240; // TFT_WIDTH int GRAPHHEIGHT = SCREENHEIGHT-(FOOTERH); //padding 200px int GRAPHWIDTH = SCREENWIDTH; -int graphInterval = 60000; // graph update rate ms +int graphInterval = 15000; // graph update rate ms TFT_eSprite spr = TFT_eSprite(&tft); @@ -843,7 +843,7 @@ void wifiIcon(bool enabled = true,bool connected = false){ #define ICON_CHR_WIFI_OVERB "*" #define ICON_CHR_FANA "\"" #define ICON_CHR_FANB "#" -#define ICON_CHR_FANOVERA"$" +#define ICON_CHR_FANOVERA "$" #define ICON_CHR_FANOVERB "%" #define ICON_CHR_HEAT "&" From 7c96aae6046461d3b79e5ba4bbd7063546fa038e Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 2 Feb 2021 21:40:33 -0600 Subject: [PATCH 046/186] json mqtt --- mqtt.h | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/mqtt.h b/mqtt.h index 3b87bf0..2e4fe99 100644 --- a/mqtt.h +++ b/mqtt.h @@ -1,12 +1,21 @@ #ifndef mqtt_h #define mqtt_h +#define USEJSON +#ifdef USEJSON +#include +StaticJsonDocument<500> payload; +// payload["sensor"] = "gps"; +// payload["time"] = 1351824120; +#endif + #include WiFiClient espClient; PubSubClient client(espClient); +bool debug_mqtt = false; String clientID = ""; void MQTTreconnect() { @@ -149,7 +158,37 @@ void init_MQTT(){ process_MQTT(); } +#ifdef USEJSON +void MQTT_pub(String topic, String sensor, String value){ + Serial.print("[MQTT] Publish: "); + Serial.print(sensor); + Serial.print("\t"); + Serial.println(value); + if(value == "") { + Serial.println("[ERROR] MQTT value is empty"); + return; + } + // JsonArray data = payload.createNestedArray(topic); + payload["topic"] = topic; + payload["clientid"] = clientID; + payload["type"] = sensor; + payload["value"] = value.toFloat(); + // payload["unit"] = ""; + if(debug_mqtt) serializeJson(payload, Serial); + // serializeJsonPretty(payload, Serial); + + String output; + serializeJson(payload,output); + client.publish(topic.c_str(),("["+output+"\n]").c_str()); // must be object? + // close ? +} + +void MQTT_pub_send(){ + // client.publish("sensor",serializeJson(payload)); + serializeJsonPretty(payload, Serial); +} +#else void MQTT_pub(String topic, String msg){ Serial.print("[MQTT] Publish message: "); Serial.print("topic: "); @@ -171,5 +210,6 @@ void MQTT_pub(String topic, String sensor, String value){ } client.publish((topic+"/"+clientID+"/"+sensor).c_str(), value.c_str()); } +#endif #endif \ No newline at end of file From 2fa6dbfca933cf6b8c9fd019cbd16b43a8520873 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 2 Feb 2021 21:40:55 -0600 Subject: [PATCH 047/186] disable neoind debug --- neoindicator.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neoindicator.h b/neoindicator.h index 4e17919..99c3bc5 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -4,7 +4,7 @@ #include #ifdef DEBUG -bool DEBUG_neoind = true; +bool DEBUG_neoind = false; #else bool DEBUG_neoind = false; #endif From 208e6a05c05c55d02747a062d93237d2648b5daf Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 2 Feb 2021 21:41:22 -0600 Subject: [PATCH 048/186] esp 32 basic ntc --- ntc.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ntc.h b/ntc.h index 88a8a94..a498f9f 100644 --- a/ntc.h +++ b/ntc.h @@ -18,7 +18,7 @@ */ // Analog pin used to read the NTC -#define NTC_PIN A0 +#define NTC_PIN 32 // #define VERBOSE_SENSOR_ENABLED 1 // 100000 / (320000 +RT) * 3.3 @@ -27,9 +27,9 @@ int rt = 330000/V - 320000; // Thermistor object THERMISTOR thermistor(NTC_PIN, // Analog pin - 100000, // Nominal resistance at 25 ºC + 10000, // Nominal resistance at 25 ºC 3950, // thermistor's beta coefficient - 100000); // Value of the series resistor + 10000); // Value of the series resistor // Global temperature reading float ntc_temp; From 5d6f5e7e4dbdf817c854bfefd3093e31b8ecbbc7 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 2 Feb 2021 21:41:50 -0600 Subject: [PATCH 049/186] sht31 --- sense_env.h | 70 ++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 53 insertions(+), 17 deletions(-) diff --git a/sense_env.h b/sense_env.h index 3f10b7d..964873a 100644 --- a/sense_env.h +++ b/sense_env.h @@ -9,9 +9,9 @@ #include // I2C -// #define USESHT31 // SHT31 Temp/Humidity +#define USESHT31 // SHT31 Temp/Humidity // #define USESHT21 // SHT21 / HTU21D Temp/Humidity -#define USEBMP180 // BMP180 Temp/Pressure/Altitude (replaces BMP085) https://www.adafruit.com/product/1603 +// #define USEBMP180 // BMP180 Temp/Pressure/Altitude (replaces BMP085) https://www.adafruit.com/product/1603 /* Vin: 3 to 5VDC Logic: 3 to 5V compliant @@ -22,6 +22,9 @@ This board/chip uses I2C 7-bit address 0x77. */ #define USEBMP280 // BMP280 Temp/Pressure/Altitude (upgrade to BMP085/BMP180/BMP183) +// #define USEBME280 // BME280 Humidity/Pressure/Altitude +// Pressure: 300...1100 hPa + #define USECS811 // CCS811 Temp/CO2/VOC #define USEGP2Y // Sharp Particle/Dust sensor GP2Y1010AU0F, GP2Y1014AU0F #define APDS9960 // Proximity, Light, RGB, and Gesture Sensor @@ -110,8 +113,8 @@ bool init_bh1750(){ // BH1750.start(BH1750_QUALITY_HIGH2, mtreg); // BH1750.setQuality(mode); - if(!status) Serial.println("[ERROR] failed to initialize device! Please check your wiring."); - else Serial.println("[ENV] Device initialized!"); + if(!status) Serial.println("[ERROR] bh1750 failed to initialize device! Please check your wiring."); + else Serial.println("[ENV] bh1750 Device initialized!"); return status; } @@ -241,7 +244,12 @@ float get_apds_color(uint8_t channel = 0){ #include const uint8_t SHARP_LED_PIN = 27; // Sharp Dust/particle sensor Led Pin const uint8_t SHARP_VO_PIN = 33; // Sharp Dust/particle analog out pin used for reading -GP2YDustSensor dustSensor(GP2YDustSensorType::GP2Y1014AU0F, SHARP_LED_PIN, SHARP_VO_PIN,5); +uint16_t gp2y_avgnumsamples = 10; // running average samples +uint16_t gp2y_numsamples = 5; // num samples to return + +// GP2Y1010AU0F +// GP2Y1014AU0F +GP2YDustSensor dustSensor(GP2YDustSensorType::GP2Y1014AU0F, SHARP_LED_PIN, SHARP_VO_PIN, gp2y_avgnumsamples); #endif #ifdef USEGP2Y @@ -249,21 +257,27 @@ void init_gp2y(){ dustSensor.setBaseline(0.1); // set no dust voltage according to your own experiments //dustSensor.setCalibrationFactor(1.1); // calibrate against precision instrument dustSensor.begin(); + + // * Set sensitivity in volts/100ug/m3 + // * Typical sensitivity is 0.5V, set by default + // * GP2Y1010AU0F sensitivity: min/typ/max: 0.425 / 0.5 / 0.75 + // * GP2Y1014AU0F sensitivity: min/typ/max: 0.35 / 0.5 / 0.65 // dustSensor.setSensitivity(); + // getBaselineCandidate(); // setBaseline(); } float get_gp2y(uint8_t channel = 0){ // print_bmp280(); - if(channel == 0) return dustSensor.getDustDensity(10); + if(channel == 0) return dustSensor.getDustDensity(gp2y_numsamples); if(channel == 1) return dustSensor.getRunningAverage(); if(channel == 2) return analogRead(SHARP_VO_PIN); } String print_gp2y(){ // Serial.print("Dust density: "); - Serial.print(dustSensor.getDustDensity(10)); + Serial.print(dustSensor.getDustDensity(gp2y_numsamples)); // Serial.print(" ug/m3; Running average: "); Serial.print("\t"); Serial.print(dustSensor.getRunningAverage()); @@ -285,7 +299,14 @@ LM75A lm75(true, //A0 LM75A pin state // SHT21 / HTU21D Temp/Humidity #ifdef USESHT21 #include -HTU21D myHTU21D(HTU21D_RES_RH12_TEMP14); +/* +resolution: +HTU21D_RES_RH12_TEMP14 - RH: 12Bit, Temperature: 14Bit, by default +HTU21D_RES_RH8_TEMP12 - RH: 8Bit, Temperature: 12Bit +HTU21D_RES_RH10_TEMP13 - RH: 10Bit, Temperature: 13Bit +HTU21D_RES_RH11_TEMP11 - RH: 11Bit, Temperature: 11Bit +*/ +HTU21D myHTU21D(HTU21D_RES_RH12_TEMP14); // 0x40 #endif // SHT31 Temp/Humidity @@ -343,7 +364,6 @@ float get_bmp280(uint8_t channel = 0){ #endif - #ifdef USESHT31 bool enableHeater = false; uint8_t loopCnt = 0; @@ -355,12 +375,12 @@ void init_sht31(){ } else { - Serial.println(F("SHT31 sensor is faild or not connected")); //(F()) saves string to flash & keeps dynamic memory free + Serial.println(F("[ERROR] SHT31 init failed")); } Serial.print("Heater Enabled State: "); if (sht31.isHeaterEnabled()) Serial.println("ENABLED"); - else Serial.println("DISABLED"); + else Serial.println("DISABLED"); } String getSHT31Temperature(){ @@ -413,12 +433,15 @@ void sht31_process(){ void init_sht21(){ bool init = myHTU21D.begin(); if(init){ - Serial.println(F("HTU21D, SHT21 sensor is active")); + Serial.println(F("[ENV] HTU21D, SHT21 sensor initialized")); } else { - Serial.println(F("HTU21D, SHT21 sensor is faild or not connected")); //(F()) saves string to flash & keeps dynamic memory free + Serial.println(F("[ERROR] HTU21D, SHT21 sensor is failed or not connected")); //(F()) saves string to flash & keeps dynamic memory free } + + delay(1000); + init = myHTU21D.begin(); // while (myHTU21D.begin(SCL,SDA) != true) // { // Serial.println(F("HTU21D, SHT21 sensor is failed or not connected")); //(F()) saves string to flash & keeps dynamic memory free @@ -427,12 +450,11 @@ void init_sht21(){ // Serial.println(F("HTU21D, SHT21 sensor is active")); } -String getSHT21(){ - return (String)myHTU21D.readCompensatedHumidity() +String getSHT21Humidity(){ + return (String)myHTU21D.readCompensatedHumidity(); } void print_sht21(){ - #ifdef USESHT21 /* DEMO - 1 */ Serial.println(F("DEMO 1: 12-Bit Resolution")); Serial.print(F("Humidity............: ")); Serial.print(myHTU21D.readHumidity()); Serial.println(F(" +-2%")); @@ -471,7 +493,6 @@ void print_sht21(){ /* back to lib. default resolution */ myHTU21D.softReset(); myHTU21D.setResolution(HTU21D_RES_RH12_TEMP14); - #endif } #endif @@ -557,4 +578,19 @@ String filterSensor( float n, float a,float b,String c = ""){ return (String)n; } + +// #define USEINTVCC +#ifdef USEINTVCC +#ifdef ESP32 + extern "C" int rom_phy_get_vdd33(); +#endif + +float getVoltage(){ + #ifdef ESP32 + float voltage = ((float)rom_phy_get_vdd33()) / 1000; + return voltage; + #endif +} +#endif + #endif \ No newline at end of file From 0ee67d43af259488442565e98857fc211ad84c4e Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 2 Feb 2021 21:42:07 -0600 Subject: [PATCH 050/186] downtime resboot --- wifi_funcs.h | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index bcfdb6f..e45eca9 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -16,6 +16,10 @@ // const char* hostname = "esp8266REFLOW"; +bool debug_wifi = false; + +long downtimeRestart = 300000; +long downtime = 0; String getDeviecID(){ String _wifissidprefix = "ESP"; @@ -113,14 +117,18 @@ int getRSSIasQuality() { void checkWifi(){ if(WiFi.status() != WL_CONNECTED ){ + if(downtime == 0) downtime = millis(); + if(millis() > downtime + downtimeRestart) ESP.restart(); #ifdef USENEOIND indSetColor(255,0,0); #endif - Serial.println("[WIFI] WiFi Disconnected"); + Serial.println("[WIFI] WiFi is Disconnected"); WiFi.reconnect(); } else { - Serial.println("[WIFI] WiFi CONNECTED"); - Serial.println("[WIFI] RSSI: "+(String)getRSSIasQuality()); + if(debug_wifi){ + Serial.println("[WIFI] WiFi is CONNECTED"); + Serial.println("[WIFI] RSSI: "+(String)getRSSIasQuality()); + } #ifdef USENEOIND indSetColor(0,255,0); #endif From 2659f5d85777ab1f1703bd6e56338ede920ea5ce Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 7 Feb 2021 20:46:06 -0600 Subject: [PATCH 051/186] add syslogging --- log.h | 88 +++++++++++++++++++++++++++++++ log_syslog.h | 144 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 232 insertions(+) create mode 100644 log_syslog.h diff --git a/log.h b/log.h index ad29016..7de4f71 100644 --- a/log.h +++ b/log.h @@ -1,6 +1,94 @@ #ifndef log_h #define log_h +#define USESYSLOG +#ifdef USESYSLOG +#include +#endif + +// https://github.com/Chris--A/PrintEx + + +// char logData[32]; // Allocate some space for the string, cmd buffer +// char logChar= 0; // Where to store the character read +String logData = ""; + +// void emptyLogBuffer(){ +// // clear buffer +// logData = 0; +// logData[0] = (char)0; +// inputString = ""; +// } + +char newbuffer[256]; +int newbufferidx = 0; + +void sendToSyslog(String msg){ + // Serial.println("newline not found at: " + (String)((logData.trim()).indexOf("\n"))); + // if(logData.indexOf("\n") >= 0){ + // Serial.println("newline found at: " + (String)logData.indexOf("\n")); + // syslog.log(LOG_INFO,msg); + // } + Serial.print("[RAW] "); + Serial.println(String(newbuffer).substring(0,newbufferidx)); + syslog.log(LOG_INFO,String(newbuffer).substring(0,newbufferidx-2)); + // todo clean up string, remove whitespace such as CR LF \t + // logData = ""; + // newbuffer = 0; + newbuffer[0] = (char)0; + newbufferidx = 0; +} + +class MySerial : public Stream { +public: + virtual int available() { return (0); } + virtual int read() { return (0); } + virtual int peek() { return (0); } + virtual void flush() {} + void begin(unsigned long, uint8_t) {} + void end() {} + + virtual size_t write(uint8_t newchar) { + if(newbufferidx>256) newbufferidx = 0; + newbuffer[newbufferidx] = newchar; + newbufferidx++; + if(newchar == 0x0a) sendToSyslog(""); + return (1); + } + + virtual size_t write(const uint8_t *buffer, size_t size) + { + size_t n = 0; + while(size--) { + // newbuffer[newbufferidx] = char(*buffer); + // newbufferidx++; + n += write(*buffer++); + } + // Serial.print("[BUFF] "); + // Serial.println((String)newbuffer); + // logData = String(newbuffer); + // sendToSyslog(""); + return n; + } +}; + +MySerial dummySerial; +Stream &_Logger = Serial1; + +// using Print::write; +// #if ARDUINO >= 100 +// virtual size_t write(uint8_t); +// #else +// virtual void write(uint8_t); +// #endif + +#include +LoggingStream Logger(dummySerial, _Logger); +// String result = LoggingStream.str(); +// WriteLoggingStream loggingClient(client, Serial); +// loggingClient.println("GET / HTTP/1.1"); +// loggingClient.println("User-Agent: Arduino"); + #include #ifdef ESP8266 diff --git a/log_syslog.h b/log_syslog.h new file mode 100644 index 0000000..800bd6a --- /dev/null +++ b/log_syslog.h @@ -0,0 +1,144 @@ +#ifndef log_syslog_h +#define log_syslog_h + +#include +#include +#include +#include + + +// @todo add print println stream capability +// add manual flush, ammend to buffer send buffer at once instead of real time, or batch sending. + +WiFiUDP udpClient; + +Syslog syslog(udpClient, SYSLOG_PROTO_IETF); // SYSLOG_PROTO_BSD +// Syslog syslog(udpClient, SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME, LOG_KERN); + +String logTopic = "ESP"; +int iteration = 1; + +#define DEVICE_HOSTNAME "my-device" +#define APP_NAME "my-app" + +const char* syslog_hostname; +const char* syslog_appname; + +void init_syslog(){ + Serial.println("[LOG] syslog init"); + Serial.println("[LOG] syslog hostname: " + getHostname()); + Serial.println("[LOG] syslog appname: " + logTopic); + + // syslog_hostname = getHostname().c_str(); // gibberish not working + syslog_hostname = WiFi.getHostname(); + syslog_appname = logTopic.c_str(); + // prepare syslog configuration here (can be anywhere before first call of + // log/logf method) + syslog.server(syslog_server_ip, syslog_server_port); + syslog.deviceHostname(syslog_hostname); + syslog.appName(syslog_appname); + // syslog.deviceHostname(DEVICE_HOSTNAME); + // syslog.appName(APP_NAME); + syslog.defaultPriority(LOG_INFO); +} + +void sendLogTest(){ + String startmsg = "Started"; + syslog.log(LOG_INFO, startmsg); + return; + // Log message can be formated like with printf function. + syslog.logf(LOG_ERR, "This is error message no. %d", iteration); + syslog.logf(LOG_INFO, "This is info message no. %d", iteration); + + // You can force set facility in pri parameter for this log message. More + // facilities in syslog.h or in Linux syslog documentation. + syslog.logf(LOG_DAEMON | LOG_INFO, "This is daemon info message no. %d", + iteration); + + // You can set default facility and severity level and use it for all log + // messages (beware defaultPriority is stored permanently!) + // syslog.defaultPriority(LOG_FTP | LOG_INFO); + syslog.logf("This is ftp info message no. %d", iteration); + + // Send log messages up to LOG_WARNING severity + syslog.logMask(LOG_UPTO(LOG_WARNING)); + syslog.log(LOG_ERR, "This is logged."); + syslog.log(LOG_WARNING, "This is logged."); + syslog.log(LOG_NOTICE, "This is not logged."); + syslog.log(LOG_INFO, "This is not logged."); + + // F() macro is supported too + syslog.log(LOG_INFO, F("End loop")); + iteration++; +} + +void sendSyslog(){ + syslog.log(LOG_INFO, F("End loop")); +} + +// // Syslog protocol format +// #define SYSLOG_PROTO_IETF 0 // RFC 5424 +// #define SYSLOG_PROTO_BSD 1 // RFC 3164 + +// /* +// * priorities/facilities are encoded into a single 32-bit quantity, where the +// * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility +// * (0-big number). Both the priorities and the facilities map roughly +// * one-to-one to strings in the syslogd(8) source code. This mapping is +// * included in this file. +// * +// * priorities (these are ordered) +// */ +// #define LOG_EMERG 0 /* system is unusable */ +// #define LOG_ALERT 1 /* action must be taken immediately */ +// #define LOG_CRIT 2 /* critical conditions */ +// #define LOG_ERR 3 /* error conditions */ +// #define LOG_WARNING 4 /* warning conditions */ +// #define LOG_NOTICE 5 /* normal but significant condition */ +// #define LOG_INFO 6 /* informational */ +// #define LOG_DEBUG 7 /* debug-level messages */ + +// #define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */ +// /* extract priority */ +// #define LOG_PRI(p) ((p) & LOG_PRIMASK) +// #define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri)) + +// /* facility codes */ +// #define LOG_KERN (0<<3) kernel messages +// #define LOG_USER (1<<3) /* random user-level messages */ +// #define LOG_MAIL (2<<3) /* mail system */ +// #define LOG_DAEMON (3<<3) /* system daemons */ +// #define LOG_AUTH (4<<3) /* security/authorization messages */ +// #define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */ +// #define LOG_LPR (6<<3) /* line printer subsystem */ +// #define LOG_NEWS (7<<3) /* network news subsystem */ +// #define LOG_UUCP (8<<3) /* UUCP subsystem */ +// #define LOG_CRON (9<<3) /* clock daemon */ +// #define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */ +// #define LOG_FTP (11<<3) /* ftp daemon */ + +// /* other codes through 15 reserved for system use */ +// #define LOG_LOCAL0 (16<<3) /* reserved for local use */ +// #define LOG_LOCAL1 (17<<3) /* reserved for local use */ +// #define LOG_LOCAL2 (18<<3) /* reserved for local use */ +// #define LOG_LOCAL3 (19<<3) /* reserved for local use */ +// #define LOG_LOCAL4 (20<<3) /* reserved for local use */ +// #define LOG_LOCAL5 (21<<3) /* reserved for local use */ +// #define LOG_LOCAL6 (22<<3) /* reserved for local use */ +// #define LOG_LOCAL7 (23<<3) /* reserved for local use */ +// +// System errors +// Example of a system error message: + +// May 11 10:40:48 scrooge disk-health-nurse[26783]: [ID 702911 user.error] m:SY-mon-full-500 c:H : partition health measures for /var did not suffice - still using 96% of partition space + +// The message can be split in to the following columns: + +// Column 1 = "May 11 10:40:48" > Timestamp +// Column 2 = "scrooge" > Loghost +// Column 3 = "disk-health-nurse[26783]:" > Application/Process +// Column 4 = "[ID 702911 user.error]" > Syslog facility.level +// Column 5 = "m:SY-mon-full-500" > Message ID +// Column 6 = "c:H : partition health..." > Message [possibly including rid, sid, ip] + +#endif \ No newline at end of file From 6ab0c1c99256a9a98e25b2f9a808553c7740aa11 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 7 Feb 2021 20:46:21 -0600 Subject: [PATCH 052/186] using new logger --- mqtt.h | 56 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/mqtt.h b/mqtt.h index 2e4fe99..ecdd7bb 100644 --- a/mqtt.h +++ b/mqtt.h @@ -24,7 +24,7 @@ void MQTTreconnect() { // this is blocking while (!client.connected()) { - Serial.print("Attempting MQTT connection..."); + Logger.print("Attempting MQTT connection..."); // Create a random client ID @@ -36,7 +36,7 @@ void MQTTreconnect() { if (client.connect(clientId.c_str())) { - Serial.println("connected"); + Logger.println("connected"); // Once connected, publish an announcement... @@ -48,11 +48,11 @@ void MQTTreconnect() { } else { - Serial.print("failed, rc="); + Logger.print("failed, rc="); - Serial.print(client.state()); + Logger.print(client.state()); - Serial.println(" try again in 5 seconds"); + Logger.println(" try again in 5 seconds"); // Wait 5 seconds before retrying @@ -70,19 +70,19 @@ void MQTTreconnect() { void MQTTcallback(char* topic, byte* payload, unsigned int length) { - Serial.print("Message arrived ["); + Logger.print("Message arrived ["); - Serial.print(topic); + Logger.print(topic); - Serial.print("] "); + Logger.print("] "); for (int i = 0; i < length; i++) { - Serial.print((char)payload[i]); + Logger.print((char)payload[i]); } - Serial.println(); + Logger.println(); @@ -147,25 +147,25 @@ void process_MQTT(){ void init_MQTT(String clientid){ clientID = clientid; - client.setServer(mqtt_server_ip, 1883); + client.setServer(mqtt_server_ip, mqtt_server_port); client.setCallback(MQTTcallback); process_MQTT(); } void init_MQTT(){ - client.setServer(mqtt_server_ip, 1883); + client.setServer(mqtt_server_ip, mqtt_server_port); client.setCallback(MQTTcallback); process_MQTT(); } #ifdef USEJSON void MQTT_pub(String topic, String sensor, String value){ - Serial.print("[MQTT] Publish: "); - Serial.print(sensor); - Serial.print("\t"); - Serial.println(value); + Logger.print("[MQTT] Publish: "); + Logger.print(sensor); + Logger.print(" "); + Logger.println(value); if(value == "") { - Serial.println("[ERROR] MQTT value is empty"); + Logger.println("[ERROR] MQTT value is empty"); return; } // JsonArray data = payload.createNestedArray(topic); @@ -190,22 +190,22 @@ void MQTT_pub_send(){ #else void MQTT_pub(String topic, String msg){ - Serial.print("[MQTT] Publish message: "); - Serial.print("topic: "); - Serial.print(topic); - Serial.print(" mesg: "); - Serial.println(msg); + Logger.print("[MQTT] Publish message: "); + Logger.print("topic: "); + Logger.print(topic); + Logger.print(" mesg: "); + Logger.println(msg); client.publish(topic.c_str(), msg.c_str()); } void MQTT_pub(String topic, String sensor, String value){ - Serial.print("[MQTT] Publish message: "); - Serial.print("topic: "); - Serial.print(topic+"/"+clientID+"/"+sensor); - Serial.print("\t\tvalue: "); - Serial.println(value); + Logger.print("[MQTT] Publish message: "); + Logger.print("topic: "); + Logger.print(topic+"/"+clientID+"/"+sensor); + Logger.print("\t\tvalue: "); + Logger.println(value); if(value == "") { - Serial.println("[ERROR] MQTT value is empty"); + Logger.println("[ERROR] MQTT value is empty"); return; } client.publish((topic+"/"+clientID+"/"+sensor).c_str(), value.c_str()); From 15bf5297683721058adffe7cb96cbc9b35458d85 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 7 Feb 2021 20:46:45 -0600 Subject: [PATCH 053/186] cleanup --- sense_env.h | 2 +- wifi_funcs.h | 6 +----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/sense_env.h b/sense_env.h index 964873a..c4cb9b0 100644 --- a/sense_env.h +++ b/sense_env.h @@ -243,7 +243,7 @@ float get_apds_color(uint8_t channel = 0){ #ifdef USEGP2Y #include const uint8_t SHARP_LED_PIN = 27; // Sharp Dust/particle sensor Led Pin -const uint8_t SHARP_VO_PIN = 33; // Sharp Dust/particle analog out pin used for reading +const uint8_t SHARP_VO_PIN = 33; // Sharp Dust/particle analog out pin used for reading uint16_t gp2y_avgnumsamples = 10; // running average samples uint16_t gp2y_numsamples = 5; // num samples to return diff --git a/wifi_funcs.h b/wifi_funcs.h index e45eca9..fa4ac53 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -84,11 +84,7 @@ void init_WiFi(int timeout = 10000){ Serial.print("[WIFI] IP: "); Serial.println(WiFi.localIP()); Serial.print("[WIFI] HOST: "); - #ifdef ESP32 - Serial.println(WiFi.getHostname()); // getHostName - #else - Serial.println(WiFi.hostname()); // getHostName - #endif + getHostname(); } else{ Serial.println("[ERROR] WIFI CONNECT FAILED"); From 0e8626acae4cc26ae4ac7c53fd595f3a2e2af6b6 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 7 Feb 2021 22:03:58 -0600 Subject: [PATCH 054/186] logger --- sense_env.h | 185 ++++++++++++++++++++++++++-------------------------- 1 file changed, 93 insertions(+), 92 deletions(-) diff --git a/sense_env.h b/sense_env.h index c4cb9b0..2ca239d 100644 --- a/sense_env.h +++ b/sense_env.h @@ -7,6 +7,7 @@ // use real temp and humidity to compensate other sensors #include +#include // I2C #define USESHT31 // SHT31 Temp/Humidity @@ -104,7 +105,7 @@ hp_BH1750 env_BH1750; // BH1750_TO_VCC = 0x5C bool init_bh1750(){ - Serial.println("[ENV] hp_BH175 init"); + Logger.println("[ENV] hp_BH175 init"); bool status = env_BH1750.begin(BH1750_TO_GROUND); // will be false no sensor found // use BH1750_TO_GROUND or BH1750_TO_VCC depending how you wired the address pin of the sensor. @@ -113,15 +114,15 @@ bool init_bh1750(){ // BH1750.start(BH1750_QUALITY_HIGH2, mtreg); // BH1750.setQuality(mode); - if(!status) Serial.println("[ERROR] bh1750 failed to initialize device! Please check your wiring."); - else Serial.println("[ENV] bh1750 Device initialized!"); + if(!status) Logger.println("[ERROR] bh1750 failed to initialize device! Please check your wiring."); + else Logger.println("[ENV] bh1750 Device initialized!"); return status; } void print_bh1750(){ if (env_BH1750.hasValue() == true) { // non blocking reading float lux = env_BH1750.getLux(); - Serial.println(lux); + Logger.println(lux); env_BH1750.start(); } } @@ -132,13 +133,13 @@ float get_bh1750(uint8_t channel = 0){ if (env_BH1750.hasValue() == true) { // non blocking reading lux = env_BH1750.getLux(); env_BH1750.start(); - Serial.println(lux); + Logger.println(lux); } } else{ env_BH1750.start(); //starts a measurement lux=env_BH1750.getLux(); - Serial.println(lux); + Logger.println(lux); } return lux; } @@ -155,9 +156,9 @@ bool init_apds(){ bool ret = false; ret = apds.begin(); if(!ret){ - Serial.println("[ERROR] APDS9960 init failed"); + Logger.println("[ERROR] APDS9960 init failed"); } - else Serial.println("[ENV] APDS9960 initialized!"); + else Logger.println("[ENV] APDS9960 initialized!"); if(apds_int_pin > 0) pinMode(apds_int_pin, INPUT_PULLUP); return ret; } @@ -185,7 +186,7 @@ void init_apds_gesture(){ // NOT interrupt String get_apds_proximity(){ if(!digitalRead(apds_int_pin)){ - Serial.println(apds.readProximity()); + Logger.println(apds.readProximity()); //clear the interrupt apds.clearInterrupt(); @@ -194,10 +195,10 @@ String get_apds_proximity(){ String get_apds_gesture(){ uint8_t gesture = apds.readGesture(); - if(gesture == APDS9960_DOWN) Serial.println("v"); - if(gesture == APDS9960_UP) Serial.println("^"); - if(gesture == APDS9960_LEFT) Serial.println("<"); - if(gesture == APDS9960_RIGHT) Serial.println(">"); + if(gesture == APDS9960_DOWN) Logger.println("v"); + if(gesture == APDS9960_UP) Logger.println("^"); + if(gesture == APDS9960_LEFT) Logger.println("<"); + if(gesture == APDS9960_RIGHT) Logger.println(">"); return ""; } @@ -211,18 +212,18 @@ void print_apds_color(){ //get the data and print the different channels apds.getColorData(&r, &g, &b, &c); - Serial.print("red: "); - Serial.print(r); + Logger.print("red: "); + Logger.print(r); - Serial.print(" green: "); - Serial.print(g); + Logger.print(" green: "); + Logger.print(g); - Serial.print(" blue: "); - Serial.print(b); + Logger.print(" blue: "); + Logger.print(b); - Serial.print(" clear: "); - Serial.println(c); - Serial.println(); + Logger.print(" clear: "); + Logger.println(c); + Logger.println(); } float get_apds_color(uint8_t channel = 0){ @@ -276,15 +277,15 @@ float get_gp2y(uint8_t channel = 0){ } String print_gp2y(){ - // Serial.print("Dust density: "); - Serial.print(dustSensor.getDustDensity(gp2y_numsamples)); - // Serial.print(" ug/m3; Running average: "); - Serial.print("\t"); - Serial.print(dustSensor.getRunningAverage()); - // Serial.println(" ug/m3"); - Serial.print("\t"); - Serial.print(analogRead(SHARP_VO_PIN)); - Serial.println(""); + // Logger.print("Dust density: "); + Logger.print(dustSensor.getDustDensity(gp2y_numsamples)); + // Logger.print(" ug/m3; Running average: "); + Logger.print("\t"); + Logger.print(dustSensor.getRunningAverage()); + // Logger.println(" ug/m3"); + Logger.print("\t"); + Logger.print(analogRead(SHARP_VO_PIN)); + Logger.println(""); } #endif @@ -324,9 +325,9 @@ Adafruit_BMP280 bmp; // I2C #ifdef USEBMP280 void init_bmp280(){ if (!bmp.begin(BMP280_ADDRESS_ALT)) { - Serial.println(F("[ERROR] Could not find a valid BMP280 sensor, check wiring!")); + Logger.println(F("[ERROR] Could not find a valid BMP280 sensor, check wiring!")); } - else Serial.println(F("[ENV] BMP280 sensor is active")); + else Logger.println(F("[ENV] BMP280 sensor is active")); /* Default settings from datasheet. */ bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */ @@ -337,21 +338,21 @@ void init_bmp280(){ } void print_bmp280(){ - Serial.print(F("Status")); - Serial.println((String)bmp.getStatus()); - Serial.print(F("Temperature = ")); - Serial.print(bmp.readTemperature()); - Serial.println(" *C"); + Logger.print(F("Status")); + Logger.println((String)bmp.getStatus()); + Logger.print(F("Temperature = ")); + Logger.print(bmp.readTemperature()); + Logger.println(" *C"); - Serial.print(F("Pressure = ")); - Serial.print(bmp.readPressure()); - Serial.println(" Pa"); + Logger.print(F("Pressure = ")); + Logger.print(bmp.readPressure()); + Logger.println(" Pa"); - Serial.print(F("Approx altitude = ")); - Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */ - Serial.println(" m"); + Logger.print(F("Approx altitude = ")); + Logger.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */ + Logger.println(" m"); - Serial.println(); + Logger.println(); } // BUGGY returns bad values not null, or noint @@ -371,16 +372,16 @@ uint8_t loopCnt = 0; void init_sht31(){ bool init = sht31.begin(0x44); if(init){ - Serial.println(F("[ENV] SHT31 sensor is active")); + Logger.println(F("[ENV] SHT31 sensor is active")); } else { - Serial.println(F("[ERROR] SHT31 init failed")); + Logger.println(F("[ERROR] SHT31 init failed")); } - Serial.print("Heater Enabled State: "); - if (sht31.isHeaterEnabled()) Serial.println("ENABLED"); - else Serial.println("DISABLED"); + Logger.print("Heater Enabled State: "); + if (sht31.isHeaterEnabled()) Logger.println("ENABLED"); + else Logger.println("DISABLED"); } String getSHT31Temperature(){ @@ -400,15 +401,15 @@ void print_sht31(){ float h = sht31.readHumidity(); if (! isnan(t)) { // check if 'is not a number' - Serial.print("Temp *C = "); Serial.print(t); Serial.print("\t\t"); + Logger.print("Temp *C = "); Logger.print(t); Logger.print("\t\t"); } else { - Serial.println("Failed to read temperature"); + Logger.println("Failed to read temperature"); } if (! isnan(h)) { // check if 'is not a number' - Serial.print("Hum. % = "); Serial.println(h); + Logger.print("Hum. % = "); Logger.println(h); } else { - Serial.println("Failed to read humidity"); + Logger.println("Failed to read humidity"); } } @@ -418,11 +419,11 @@ void sht31_process(){ if (++loopCnt == 30) { enableHeater = !enableHeater; sht31.heater(enableHeater); - Serial.print("Heater Enabled State: "); + Logger.print("Heater Enabled State: "); if (sht31.isHeaterEnabled()) - Serial.println("ENABLED"); + Logger.println("ENABLED"); else - Serial.println("DISABLED"); + Logger.println("DISABLED"); loopCnt = 0; } @@ -433,21 +434,21 @@ void sht31_process(){ void init_sht21(){ bool init = myHTU21D.begin(); if(init){ - Serial.println(F("[ENV] HTU21D, SHT21 sensor initialized")); + Logger.println(F("[ENV] HTU21D, SHT21 sensor initialized")); } else { - Serial.println(F("[ERROR] HTU21D, SHT21 sensor is failed or not connected")); //(F()) saves string to flash & keeps dynamic memory free + Logger.println(F("[ERROR] HTU21D, SHT21 sensor is failed or not connected")); //(F()) saves string to flash & keeps dynamic memory free } delay(1000); init = myHTU21D.begin(); // while (myHTU21D.begin(SCL,SDA) != true) // { - // Serial.println(F("HTU21D, SHT21 sensor is failed or not connected")); //(F()) saves string to flash & keeps dynamic memory free + // Logger.println(F("HTU21D, SHT21 sensor is failed or not connected")); //(F()) saves string to flash & keeps dynamic memory free // delay(5000); // } - // Serial.println(F("HTU21D, SHT21 sensor is active")); + // Logger.println(F("HTU21D, SHT21 sensor is active")); } String getSHT21Humidity(){ @@ -456,38 +457,38 @@ String getSHT21Humidity(){ void print_sht21(){ /* DEMO - 1 */ - Serial.println(F("DEMO 1: 12-Bit Resolution")); - Serial.print(F("Humidity............: ")); Serial.print(myHTU21D.readHumidity()); Serial.println(F(" +-2%")); - Serial.print(F("Compensated Humidity: ")); Serial.print(myHTU21D.readCompensatedHumidity()); Serial.println(F(" +-2%")); + Logger.println(F("DEMO 1: 12-Bit Resolution")); + Logger.print(F("Humidity............: ")); Logger.print(myHTU21D.readHumidity()); Logger.println(F(" +-2%")); + Logger.print(F("Compensated Humidity: ")); Logger.print(myHTU21D.readCompensatedHumidity()); Logger.println(F(" +-2%")); - Serial.println(F("DEMO 1: 14-Bit Resolution")); - Serial.print(F("Temperature.........: ")); Serial.print(myHTU21D.readTemperature()); Serial.println(F(" +-0.3C")); + Logger.println(F("DEMO 1: 14-Bit Resolution")); + Logger.print(F("Temperature.........: ")); Logger.print(myHTU21D.readTemperature()); Logger.println(F(" +-0.3C")); /* DEMO - 2 */ - Serial.println(F("DEMO 2: 11-Bit Resolution")); + Logger.println(F("DEMO 2: 11-Bit Resolution")); myHTU21D.setResolution(HTU21D_RES_RH11_TEMP11); - Serial.print(F("Humidity............: ")); Serial.print(myHTU21D.readHumidity()); Serial.println(F(" +-2%")); - Serial.print(F("Compensated Humidity: ")); Serial.print(myHTU21D.readCompensatedHumidity()); Serial.println(F(" +-2%")); + Logger.print(F("Humidity............: ")); Logger.print(myHTU21D.readHumidity()); Logger.println(F(" +-2%")); + Logger.print(F("Compensated Humidity: ")); Logger.print(myHTU21D.readCompensatedHumidity()); Logger.println(F(" +-2%")); - Serial.println(F("DEMO 2: 11-Bit Resolution")); - Serial.print(F("Temperature.........: ")); Serial.print(myHTU21D.readTemperature()); Serial.println(F(" +-0.3C")); + Logger.println(F("DEMO 2: 11-Bit Resolution")); + Logger.print(F("Temperature.........: ")); Logger.print(myHTU21D.readTemperature()); Logger.println(F(" +-0.3C")); /* DEMO - 3 */ - Serial.println(F("DEMO 3: Battery Status")); - if (myHTU21D.batteryStatus() == true) Serial.println(F("Battery.............: OK. Level > 2.25v")); - else Serial.println(F("Battery.............: LOW. Level < 2.25v")); + Logger.println(F("DEMO 3: Battery Status")); + if (myHTU21D.batteryStatus() == true) Logger.println(F("Battery.............: OK. Level > 2.25v")); + else Logger.println(F("Battery.............: LOW. Level < 2.25v")); /* DEMO - 4 */ - Serial.println(F("DEMO 4:")); - Serial.print(F("Firmware version....: ")); Serial.println(myHTU21D.readFirmwareVersion()); + Logger.println(F("DEMO 4:")); + Logger.print(F("Firmware version....: ")); Logger.println(myHTU21D.readFirmwareVersion()); /* DEMO - 5 */ - Serial.println(F("DEMO 5:")); - Serial.print(F("Sensor's ID.........: ")); Serial.println(myHTU21D.readDeviceID()); + Logger.println(F("DEMO 5:")); + Logger.print(F("Sensor's ID.........: ")); Logger.println(myHTU21D.readDeviceID()); /* back to lib. default resolution */ @@ -501,7 +502,7 @@ void init_LM75(){ } void print_LM75(){ - Serial.println((String)lm75.getTemperatureInFahrenheit() + " F"); + Logger.println((String)lm75.getTemperatureInFahrenheit() + " F"); } #endif @@ -512,15 +513,15 @@ void print_LM75(){ Adafruit_CCS811 ccs; void init_cs811(){ - Serial.println("[ENV] cs811 init"); + Logger.println("[ENV] cs811 init"); if(!ccs.begin()){ - Serial.println("[ERROR] CS811 Begin Failed"); + Logger.println("[ERROR] CS811 Begin Failed"); } else { //calibrate temperature sensor while(!ccs.available() && millis() < 30000); float temp = ccs.calculateTemperature(); - Serial.println("[ENV] CS811 set offset " + String(temp-25.0)); + Logger.println("[ENV] CS811 set offset " + String(temp-25.0)); ccs.setTempOffset(temp - 25.0); } // ccs.setDriveMode(uint8_t mode); @@ -531,16 +532,16 @@ void print_cs811(){ if(ccs.available()){ float temp = ccs.calculateTemperature(); if(!ccs.readData()){ - Serial.print("CO2: "); - Serial.print(ccs.geteCO2()); - Serial.print("ppm, TVOC: "); - Serial.print(ccs.getTVOC()); - Serial.print("ppb Temp:"); - Serial.println(temp); + Logger.print("CO2: "); + Logger.print(ccs.geteCO2()); + Logger.print("ppm, TVOC: "); + Logger.print(ccs.getTVOC()); + Logger.print("ppb Temp:"); + Logger.println(temp); } } else{ - Serial.println("[ERROR] cs811 not available"); + Logger.println("[ERROR] cs811 not available"); } } @@ -550,11 +551,11 @@ float get_cs811(uint8_t channel = 0){ // if(!ccs.available()) return 0; // if(ccs.readData()) return 0; // @todo detect failures, or else func return old values - if(!ccs.available()) Serial.println("[ERROR] cs811 not available"); // always false? - if(ccs.checkError()) Serial.println("[ERROR] Assert cs811 check error"); // always false? + if(!ccs.available()) Logger.println("[ERROR] cs811 not available"); // always false? + if(ccs.checkError()) Logger.println("[ERROR] Assert cs811 check error"); // always false? uint8_t err = ccs.readData(); float ret; - if(err != 0) Serial.println("[ERROR] cs811 readData " + (String)err); + if(err != 0) Logger.println("[ERROR] cs811 readData " + (String)err); if(channel == 0) ret = ccs.calculateTemperature(); if(channel == 1) ret = ccs.geteCO2(); if(channel == 2) ret = ccs.getTVOC(); From 84c942b3de2c3e9354392340b624586f879c8423 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 7 Feb 2021 22:04:10 -0600 Subject: [PATCH 055/186] remove dup --- syslog.h | 63 -------------------------------------------------------- 1 file changed, 63 deletions(-) delete mode 100644 syslog.h diff --git a/syslog.h b/syslog.h deleted file mode 100644 index 3f25c9b..0000000 --- a/syslog.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef syslog_h -#define syslog_h - -#include -#include // https://github.com/arcao/Syslog - -#include - -// Syslog server connection info -#define SYSLOG_SERVER "syslog-server" -#define SYSLOG_PORT 514 - -// This device info -#define DEVICE_HOSTNAME "my-device" -#define APP_NAME "my-app" - -// A UDP instance to let us send and receive packets over UDP -WiFiUDP udpClient; - -// Create a new syslog instance with LOG_KERN facility -Syslog syslog(udpClient, SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME, LOG_KERN); -int iteration = 1; - -void init_syslog(){ - Serial.println("[SYSLOG] init"); - // Syslog new syslog(udpClient); - - syslog.server(SYSLOG_SERVER, SYSLOG_PORT); - syslog.deviceHostname(DEVICE_HOSTNAME); - syslog.appName(APP_NAME); - syslog.defaultPriority(LOG_KERN); -} - -void sendLogTest(){ - syslog.log(LOG_INFO, "Begin Send"); - - // Log message can be formated like with printf function. - syslog.logf(LOG_ERR, "This is error message no. %d", iteration); - syslog.logf(LOG_INFO, "This is info message no. %d", iteration); - - // You can force set facility in pri parameter for this log message. More - // facilities in syslog.h or in Linux syslog documentation. - syslog.logf(LOG_DAEMON | LOG_INFO, "This is daemon info message no. %d", - iteration); - - // You can set default facility and severity level and use it for all log - // messages (beware defaultPriority is stored permanently!) - syslog.defaultPriority(LOG_FTP | LOG_INFO); - syslog.logf("This is ftp info message no. %d", iteration); - - // Send log messages up to LOG_WARNING severity - syslog.logMask(LOG_UPTO(LOG_WARNING)); - syslog.log(LOG_ERR, "This is logged."); - syslog.log(LOG_WARNING, "This is logged."); - syslog.log(LOG_NOTICE, "This is not logged."); - syslog.log(LOG_INFO, "This is not logged."); - - // F() macro is supported too - syslog.log(LOG_INFO, F("End loop")); - iteration++; -} - -#endif \ No newline at end of file From 3d7ec031e3bdbc73b063a5b0f5d011f6f2f0c248 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 7 Feb 2021 22:04:20 -0600 Subject: [PATCH 056/186] logger --- io_utils.h | 51 ++++++++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/io_utils.h b/io_utils.h index 9d59023..bfbacf5 100644 --- a/io_utils.h +++ b/io_utils.h @@ -1,6 +1,8 @@ #ifndef io_utils_h #define io_utils_h +#include + bool swap = false; int getPinMode(uint8_t pin) @@ -17,23 +19,22 @@ int getPinMode(uint8_t pin) } void debugPin(uint8_t pin){ - Serial.print("[PIN] " + (String)pin); - Serial.print(" pinmode: "); - Serial.print(getPinMode(pin),HEX); - Serial.println(" pinstate: " + (String)digitalRead(pin)); + Logger.print("[PIN] " + (String)pin); + Logger.print(" pinmode: "); + Logger.print(getPinMode(pin),HEX); + Logger.println(" pinstate: " + (String)digitalRead(pin)); } - void scani2c(bool pinswap = false){ swap = pinswap; byte error, address; int nDevices; if(!swap)Wire.begin(); else Wire.begin(SCL,SDA); // begin(sda, scl) SWAP! - Serial.print("[I2C] SDA:"+(String) SDA); - Serial.print(" SCL:"+(String) SCL); - Serial.println(swap ? " \nSWAPPED" : ""); - Serial.println("[I2C] Scanning ... "); + Logger.print("[I2C] SDA:"+(String) SDA); + Logger.print(" SCL:"+(String) SCL); + Logger.println(swap ? " \nSWAPPED" : ""); + Logger.println("[I2C] Scanning ... "); nDevices = 0; for(address = 1; address < 127; address++ ) @@ -52,42 +53,42 @@ void scani2c(bool pinswap = false){ if (res == 0) { - Serial.print("[I2C] Device found - ADDR: 0x"); + Logger.print("[I2C] Device found - ADDR: 0x"); if (address<16) - Serial.print("0"); - Serial.print(address,HEX); - Serial.println(""); + Logger.print("0"); + Logger.print(address,HEX); + Logger.println(""); nDevices++; } else if(res!=2) { - Serial.println("[ERROR]:" + (String)res); - Serial.print("Unknown error ADDR: 0x"); + Logger.println("[ERROR]:" + (String)res); + Logger.print("Unknown error ADDR: 0x"); if (address<16) - Serial.print("0"); - Serial.print(address,HEX); - Serial.println(""); + Logger.print("0"); + Logger.print(address,HEX); + Logger.println(""); } } if (nDevices == 0) - Serial.println("[ERROR] No I2C devices found\n"); + Logger.println("[ERROR] No I2C devices found\n"); else - Serial.println("[I2C] scan done\n"); + Logger.println("[I2C] scan done\n"); } void scanPins(){ for(int i = 0;i<6;i++){ if(i == 1) continue; pinMode(i,INPUT_PULLUP); - Serial.print((String)digitalRead(i)); + Logger.print((String)digitalRead(i)); // debugPin(i); } for(int i = 12;i<17;i++){ pinMode(i,INPUT_PULLUP); // debugPin(i); - Serial.print((String)digitalRead(i)); + Logger.print((String)digitalRead(i)); } - Serial.println(""); + Logger.println(""); } #ifdef ESP32 @@ -115,8 +116,8 @@ void restoreADC() { WRITE_PERI_REG(SENS_SAR_READ_CTRL2_REG, reg_b); //VERY IMPORTANT: DO THIS TO NOT HAVE INVERTED VALUES! SET_PERI_REG_MASK(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_DATA_INV); -Serial.println(analogRead(4)); -Serial.println(analogRead(33)); +Logger.println(analogRead(4)); +Logger.println(analogRead(33)); } #endif From 9449ddd26579d11371f6f18154399629afe3fd16 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 7 Feb 2021 22:04:31 -0600 Subject: [PATCH 057/186] error logging --- log.h | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/log.h b/log.h index 7de4f71..2b79341 100644 --- a/log.h +++ b/log.h @@ -29,9 +29,13 @@ void sendToSyslog(String msg){ // Serial.println("newline found at: " + (String)logData.indexOf("\n")); // syslog.log(LOG_INFO,msg); // } - Serial.print("[RAW] "); - Serial.println(String(newbuffer).substring(0,newbufferidx)); - syslog.log(LOG_INFO,String(newbuffer).substring(0,newbufferidx-2)); + // Serial.print("[RAW] "); + // Serial.println(String(newbuffer).substring(0,newbufferidx)); + msg = String(newbuffer).substring(0,newbufferidx-2); + String msgb = msg; + msgb.toLowerCase(); + if(msgb.indexOf("error") != -1) syslog.log(LOG_ERR,msg); + else syslog.log(LOG_INFO,msg); // todo clean up string, remove whitespace such as CR LF \t // logData = ""; // newbuffer = 0; @@ -73,7 +77,7 @@ class MySerial : public Stream { }; MySerial dummySerial; -Stream &_Logger = Serial1; +Stream &_Logger = Serial; // using Print::write; // #if ARDUINO >= 100 From f8cdd98aca0887885c14b578a647e1bf0bc28390 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 8 Feb 2021 15:31:26 -0600 Subject: [PATCH 058/186] clean up syslog --- log.h | 67 ++++++++++++++++++++++++++--------------------------------- 1 file changed, 29 insertions(+), 38 deletions(-) diff --git a/log.h b/log.h index 2b79341..0c347d5 100644 --- a/log.h +++ b/log.h @@ -9,74 +9,65 @@ // https://github.com/Chris--A/PrintEx -// char logData[32]; // Allocate some space for the string, cmd buffer -// char logChar= 0; // Where to store the character read -String logData = ""; - -// void emptyLogBuffer(){ -// // clear buffer -// logData = 0; -// logData[0] = (char)0; -// inputString = ""; -// } - -char newbuffer[256]; -int newbufferidx = 0; +char logbuffer[256]; +int logbufferidx = 0; // end char +// might need a ring buffer here, so we can keep logging mutiple messages and send delayed void sendToSyslog(String msg){ - // Serial.println("newline not found at: " + (String)((logData.trim()).indexOf("\n"))); // if(logData.indexOf("\n") >= 0){ // Serial.println("newline found at: " + (String)logData.indexOf("\n")); // syslog.log(LOG_INFO,msg); // } // Serial.print("[RAW] "); - // Serial.println(String(newbuffer).substring(0,newbufferidx)); - msg = String(newbuffer).substring(0,newbufferidx-2); + // Serial.println(String(logbuffer).substring(0,logbufferidx)); + msg = String(logbuffer).substring(0,logbufferidx-2); String msgb = msg; - msgb.toLowerCase(); - if(msgb.indexOf("error") != -1) syslog.log(LOG_ERR,msg); - else syslog.log(LOG_INFO,msg); + msgb.toLowerCase(); // lowercase for string match levels + msgb.trim(); // remove cr lf + + uint16_t level = LOG_INFO; + if(msgb.indexOf("notice") != -1) level = LOG_NOTICE; + if(msgb.indexOf("error") != -1) level = LOG_ERR; + if(msgb.indexOf("warning") != -1) level = LOG_WARNING; + if(msgb.indexOf("fatal") != -1) level = LOG_CRIT; + + syslog.log(level,msg); // todo clean up string, remove whitespace such as CR LF \t - // logData = ""; - // newbuffer = 0; - newbuffer[0] = (char)0; - newbufferidx = 0; + // reset buffer + logbuffer[0] = (char)0; + logbufferidx = 0; } -class MySerial : public Stream { +class print2syslog : public Stream { public: - virtual int available() { return (0); } + bool begun = false; + virtual int available() { return (begun); } virtual int read() { return (0); } virtual int peek() { return (0); } virtual void flush() {} - void begin(unsigned long, uint8_t) {} - void end() {} + void begin(unsigned long, uint8_t) {begun = true;} + void end() {begun=false;} virtual size_t write(uint8_t newchar) { - if(newbufferidx>256) newbufferidx = 0; - newbuffer[newbufferidx] = newchar; + if(!begun) return; + newbuffer[logbufferidx] = newchar; newbufferidx++; - if(newchar == 0x0a) sendToSyslog(""); + if(newbufferidx>256 || newchar == 0x0a) sendToSyslog(""); // buffer full or newline, @todo if no newline at max buffer drop it, use flag for delayed write return (1); } virtual size_t write(const uint8_t *buffer, size_t size) { + if(!begun) return; size_t n = 0; while(size--) { - // newbuffer[newbufferidx] = char(*buffer); - // newbufferidx++; n += write(*buffer++); } - // Serial.print("[BUFF] "); - // Serial.println((String)newbuffer); - // logData = String(newbuffer); - // sendToSyslog(""); return n; } }; -MySerial dummySerial; +print2syslog syslogger; Stream &_Logger = Serial; // using Print::write; @@ -87,7 +78,7 @@ Stream &_Logger = Serial; // #endif #include -LoggingStream Logger(dummySerial, _Logger); +LoggingStream Logger(syslogger, _Logger); // String result = LoggingStream.str(); // WriteLoggingStream loggingClient(client, Serial); // loggingClient.println("GET / HTTP/1.1"); From 6c30c0adada3bd2a7be369deeb61306e64035314 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 8 Feb 2021 15:31:34 -0600 Subject: [PATCH 059/186] minor --- max31855.h | 2 +- sense_env.h | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/max31855.h b/max31855.h index 2b29c59..f2239f3 100644 --- a/max31855.h +++ b/max31855.h @@ -27,7 +27,7 @@ Adafruit_MAX31855 tc(14,15,12); Adafruit_MAX31855 tcB(1); #endif -bool updateLock = false; +bool updateLock = false; // lockout updating temps // Averaging // options diff --git a/sense_env.h b/sense_env.h index 2ca239d..9f66b75 100644 --- a/sense_env.h +++ b/sense_env.h @@ -1,6 +1,20 @@ #ifndef sensors_h #define sensors_h + +// supported sensors +// SHT31 +// SHT21 +// HTU21D +// +// BMP280 +// BME280 +// CS811 +// GP2Y +// TSL2561 +// BH1750 +// + // BUGS // sensors do not reinit is they drop out // co2 voc, resubmits the same value over and over if device is lost @@ -22,7 +36,7 @@ Up to 0.03hPa / 0.25m resolution This board/chip uses I2C 7-bit address 0x77. */ -#define USEBMP280 // BMP280 Temp/Pressure/Altitude (upgrade to BMP085/BMP180/BMP183) +#define USEBMP280 // BMP280 Temp/Pressure/Altitude (upgrade for BMP085/BMP180/BMP183) // #define USEBME280 // BME280 Humidity/Pressure/Altitude // Pressure: 300...1100 hPa From a2ed0ae90b95c27c78d4a9ae10dde1c142013f96 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 8 Feb 2021 17:00:28 -0600 Subject: [PATCH 060/186] credential template --- creds.h | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/creds.h b/creds.h index 35da71d..7f1f181 100644 --- a/creds.h +++ b/creds.h @@ -1,8 +1,27 @@ +#ifndef creds_h +#define creds_h -String apikeya = "SOMEPRIVATEKEY"; -const char* SSID = "MYSSID"; -const char* PASS = "MYPASS"; +String apikeya = ""; +const char* SSID_B = ""; +const char* PASS_B = ""; + +const char* SSID = ""; +const char* PASS = ""; const char* STASSID = SSID; -const char* STAPSK = PASS; +const char* STAPSK = PASS; + +const char* ssid = SSID; // your network SSID (name) +const char* password = PASS; + +// mqtt +const char* mqtt_server_host = ""; +const char* mqtt_server_ip = ""; +const int mqtt_server_port = 1883; + +// syslog +const char* syslog_server_host = mqtt_server_host; +const char* syslog_server_ip = mqtt_server_ip; +const int syslog_server_port = 514; +#endif \ No newline at end of file From fd2f6b695470284f8c0695a23ef94569a23600cf Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 8 Feb 2021 17:00:48 -0600 Subject: [PATCH 061/186] Create .gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9860452 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +creds.h From d909c1d79d5c61fc23bd2a6bc00461bcc11b3028 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 10 Feb 2021 21:43:07 -0600 Subject: [PATCH 062/186] fix rename --- log.h | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/log.h b/log.h index 0c347d5..049f19b 100644 --- a/log.h +++ b/log.h @@ -1,3 +1,4 @@ + #ifndef log_h #define log_h @@ -49,16 +50,16 @@ class print2syslog : public Stream { void end() {begun=false;} virtual size_t write(uint8_t newchar) { - if(!begun) return; - newbuffer[logbufferidx] = newchar; - newbufferidx++; - if(newbufferidx>256 || newchar == 0x0a) sendToSyslog(""); // buffer full or newline, @todo if no newline at max buffer drop it, use flag for delayed write + if(!begun) return 0; + logbuffer[logbufferidx] = newchar; + logbufferidx++; + if(logbufferidx>256 || newchar == 0x0a) sendToSyslog(""); // buffer full or newline, @todo if no newline at max buffer drop it, use flag for delayed write return (1); } virtual size_t write(const uint8_t *buffer, size_t size) { - if(!begun) return; + if(!begun) return 0; size_t n = 0; while(size--) { n += write(*buffer++); @@ -70,6 +71,8 @@ class print2syslog : public Stream { print2syslog syslogger; Stream &_Logger = Serial; +Stream &Logger = Serial; + // using Print::write; // #if ARDUINO >= 100 // virtual size_t write(uint8_t); @@ -78,7 +81,7 @@ Stream &_Logger = Serial; // #endif #include -LoggingStream Logger(syslogger, _Logger); +// LoggingStream Logger(syslogger, _Logger); // String result = LoggingStream.str(); // WriteLoggingStream loggingClient(client, Serial); // loggingClient.println("GET / HTTP/1.1"); From 3a21478f1ebaa434386b7a2f418b66d3bfe8f6d7 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Feb 2021 09:30:10 -0600 Subject: [PATCH 063/186] rename logger --- log.h | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/log.h b/log.h index 0c347d5..7541251 100644 --- a/log.h +++ b/log.h @@ -120,35 +120,35 @@ LoggingStream Logger(syslogger, _Logger); #endif template - void DEBUG_WM(Generic text); + void DEBUGGER(Generic text); template - void DEBUG_WM(debuglevel_t level,Generic text); + void DEBUGGER(debuglevel_t level,Generic text); template - void DEBUG_WM(Generic text,Genericb textb); + void DEBUGGER(Generic text,Genericb textb); template - void DEBUG_WM(debuglevel_t level, Generic text,Genericb textb); + void DEBUGGER(debuglevel_t level, Generic text,Genericb textb); // DEBUG -// @todo fix DEBUG_WM(0,0); +// @todo fix DEBUGGER(0,0); template -void DEBUG_WM(Generic text) { - DEBUG_WM(DEBUG_NOTIFY,text,""); +void DEBUGGER(Generic text) { + DEBUGGER(DEBUG_NOTIFY,text,""); } template -void DEBUG_WM(debuglevel_t level,Generic text) { - if(_debugLevel >= level) DEBUG_WM(level,text,""); +void DEBUGGER(debuglevel_t level,Generic text) { + if(_debugLevel >= level) DEBUGGER(level,text,""); } template -void DEBUG_WM(Generic text,Genericb textb) { - DEBUG_WM(DEBUG_NOTIFY,text,textb); +void DEBUGGER(Generic text,Genericb textb) { + DEBUGGER(DEBUG_NOTIFY,text,textb); } template -void DEBUG_WM(debuglevel_t level,Generic text,Genericb textb) { +void DEBUGGER(debuglevel_t level,Generic text,Genericb textb) { if(!_debug || _debugLevel < level) return; if(_debugLevel >= DEBUG_MAX){ @@ -193,14 +193,14 @@ void DEBUG_WM(debuglevel_t level,Generic text,Genericb textb) { void debugPlatformInfo(){ #ifdef ESP8266 system_print_meminfo(); - DEBUG_WM(F("getCoreVersion(): "),ESP.getCoreVersion()); - DEBUG_WM(F("system_get_sdk_version(): "),system_get_sdk_version()); - DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); - DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); + DEBUGGER(F("getCoreVersion(): "),ESP.getCoreVersion()); + DEBUGGER(F("system_get_sdk_version(): "),system_get_sdk_version()); + DEBUGGER(F("system_get_boot_version():"),system_get_boot_version()); + DEBUGGER(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); #elif defined(ESP32) size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); - DEBUG_WM("Free heap: ", freeHeap); - DEBUG_WM("ESP-IDF version: ", esp_get_idf_version()); + DEBUGGER("Free heap: ", freeHeap); + DEBUGGER("ESP-IDF version: ", esp_get_idf_version()); #endif } From 79d5a4634844f39890ccc55e3dbbc7d2411cc2a9 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Feb 2021 16:38:35 -0600 Subject: [PATCH 064/186] updates --- io_utils.h | 1 + log.h | 6 ++++-- neoindicator.h | 2 +- oled_i2c.h | 47 ++++++++++++++++++++++++++++++++++++++--------- wifi_funcs.h | 2 +- 5 files changed, 45 insertions(+), 13 deletions(-) diff --git a/io_utils.h b/io_utils.h index bfbacf5..76b8349 100644 --- a/io_utils.h +++ b/io_utils.h @@ -2,6 +2,7 @@ #define io_utils_h #include +#include bool swap = false; diff --git a/log.h b/log.h index 8bc7f1b..f38f977 100644 --- a/log.h +++ b/log.h @@ -2,19 +2,20 @@ #ifndef log_h #define log_h -#define USESYSLOG +// #define USESYSLOG #ifdef USESYSLOG #include #endif // https://github.com/Chris--A/PrintEx - +// StreamUtils char logbuffer[256]; int logbufferidx = 0; // end char // might need a ring buffer here, so we can keep logging mutiple messages and send delayed void sendToSyslog(String msg){ + #ifdef USESYSLOG // if(logData.indexOf("\n") >= 0){ // Serial.println("newline found at: " + (String)logData.indexOf("\n")); // syslog.log(LOG_INFO,msg); @@ -37,6 +38,7 @@ void sendToSyslog(String msg){ // reset buffer logbuffer[0] = (char)0; logbufferidx = 0; + #endif } class print2syslog : public Stream { diff --git a/neoindicator.h b/neoindicator.h index 99c3bc5..52e83a4 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -11,7 +11,7 @@ bool DEBUG_neoind = false; #ifdef ESP32 bool showTwice = true; -bool noInterrupts = true; +bool noInterrupts = false; // causes crashes, sometimes ? #else bool showTwice = false; bool noInterrupts = false; diff --git a/oled_i2c.h b/oled_i2c.h index 4d6c80a..ad47031 100644 --- a/oled_i2c.h +++ b/oled_i2c.h @@ -1,23 +1,21 @@ /*oled_i2c*/ #include +#include #include #include // #define SH1106_128_64 #define SCREEN_WIDTH 128 // OLED display width, in pixels -#define SCREEN_HEIGHT 64 // OLED display height, in pixels +#define SCREEN_HEIGHT 32 // OLED display height, in pixels #define OLED_RESET -1 // Adafruit_SSD1306 lcd(OLED_RESET); -Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET,800000,800000); +Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT); +// Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET,800000,800000); int fpsmicros = 0; -// #if (SSD1306_LCDHEIGHT != 64) -// #error("Height incorrect, please fix Adafruit_SSD1306.h!"); -// #endif - void invertText(){ lcd.setTextColor(BLACK, WHITE); // 'inverted' text } @@ -26,6 +24,10 @@ void whiteText(){ lcd.setTextColor(WHITE); // 'inverted' text } +void i2cpinswap(){ + Wire.begin(SCL,SDA); // begin(sda, scl) SWAP! +} + // void init_oled(){ // init_oled(false); // } @@ -50,7 +52,22 @@ void print_oled(String str,uint8_t size,bool flush){ lcd.setTextColor(WHITE); lcd.setCursor(0,0); lcd.println(str); - if(flush)lcd.display(); + if(flush) lcd.display(); +} + +/** + * print oled lines + * @param str string to print + * @param no line 0-3 + * @param size text size 1-2 + */ +void print_oled_line(String str,uint16_t no = 1,uint16_t size = 1){ + uint16_t y = 0; + if(size == 1) y = 9*no; + if(size == 2) y = 18*no; + lcd.setCursor(0,y); + lcd.setTextSize(size); + lcd.println(str); } void init_oled(bool preamble){ @@ -58,12 +75,12 @@ void init_oled(bool preamble){ Serial.println("SDA: "+(String)SDA); Serial.println("SCL: "+(String)SCL); - Wire.begin(SCL,SDA); // begin(sda, scl) SWAP! + // Wire.begin(SCL,SDA); // begin(sda, scl) SWAP! // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally if(!lcd.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 Serial.println(F("SSD1306 allocation failed")); } - + lcd.setRotation(2); // Wire.setClock(400000L); // set i2c speed 400khz // Wire.setClock(100000L); // set i2c speed 400khz @@ -84,6 +101,18 @@ void init_oled(bool preamble){ lcd.display(); } +void oled_test(){ + print_oled_line("Line One",0); + print_oled_line("Line Two",1); + print_oled_line("Line Three",2); + lcd.display(); + delay(1000); + lcd.clearDisplay(); + print_oled_line("Line One",0,2); + print_oled_line("Line Two",2); + lcd.display(); +} + void displayFPS(){ lcd.print((String)(1000000/((micros()-fpsmicros)/2))); // println(" FPS"); diff --git a/wifi_funcs.h b/wifi_funcs.h index fa4ac53..cd835e1 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -88,7 +88,7 @@ void init_WiFi(int timeout = 10000){ } else{ Serial.println("[ERROR] WIFI CONNECT FAILED"); - Serial.println("[WIFI] waited for " + (String)(millis()-start/1000) + "seconds"); + Serial.println("[WIFI] waited for " + (String)(millis()-start/1000) + " seconds"); } delay(500); } From aaa8cdfae45b353363843bd2712969b74293595f Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 23 Feb 2021 06:34:36 -0600 Subject: [PATCH 065/186] mqtt multiple json topics at once --- jsontest.cpp | 62 ++++++++++++++++++ mqtt.h | 175 ++++++++++++++++++++++++++++++--------------------- 2 files changed, 166 insertions(+), 71 deletions(-) create mode 100644 jsontest.cpp diff --git a/jsontest.cpp b/jsontest.cpp new file mode 100644 index 0000000..e77d6c9 --- /dev/null +++ b/jsontest.cpp @@ -0,0 +1,62 @@ +#include + +StaticJsonDocument<1024> payload; +StaticJsonDocument<1024> rootdoc; +DynamicJsonDocument pubjson(1024); +JsonArray jsondata = pubjson.to(); + +void setup(){ + Serial.begin(115200); +} + +void add(){ + payload["topic"] = "thetopic"; + payload["clientid"] = "theclientid"; + payload["type"] = "thetype"; + payload["value"] = "thevalue"; + jsondata.add(payload); +} + +void prepare(){ + rootdoc.add(pubjson); + + char message[1024]; + serializeJson(rootdoc, message); + Serial.println((String)message); + // client.publish(topic,message); // do stuff + + // serial output, arrlen is 3 last element is always null + // [{"topic":"thetopic","clientid":"theclientid","type":"thetype","value":"thevalue"}, + // {"topic":"thetopic","clientid":"theclientid","type":"thetype","value":"thevalue"},null] + + // clean + rootdoc.clear(); + jsondata = pubjson.to(); +} + +void test(){ + StaticJsonDocument<256> doc; + + JsonObject doc_0 = doc.createNestedObject(); + doc_0["topic"] = "device"; + doc_0["clientid"] = "ESP_ENV"; + doc_0["type"] = "uptime_s"; + doc_0["value"] = 25; + + JsonObject doc_1 = doc.createNestedObject(); + doc_1["topic"] = "device"; + doc_1["clientid"] = "ESP_ENV"; + doc_1["type"] = "rssi"; + doc_1["value"] = 92; + + serializeJson(doc, Serial); +} + + +void loop(){ + add(); + add(); + prepare(); + // test(); + delay(5000); +} \ No newline at end of file diff --git a/mqtt.h b/mqtt.h index ecdd7bb..a37d418 100644 --- a/mqtt.h +++ b/mqtt.h @@ -1,21 +1,31 @@ #ifndef mqtt_h #define mqtt_h +#undef nullptr + #define USEJSON #ifdef USEJSON #include -StaticJsonDocument<500> payload; +StaticJsonDocument<2048> payload; +StaticJsonDocument<2048> rootdoc; // payload["sensor"] = "gps"; // payload["time"] = 1351824120; + + // const size_t CAPACITY = JSON_ARRAY_SIZE(1); + // StaticJsonDocument docH; + // JsonArray arrayH = docH.to(); + DynamicJsonDocument pubjson(2048); + JsonArray jsondata = pubjson.to(); #endif #include +#define MQTT_MAX_PACKET_SIZE 2048 WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = false; +bool debug_mqtt = true; String clientID = ""; void MQTTreconnect() { @@ -23,89 +33,38 @@ void MQTTreconnect() { // Loop until we're reconnected // this is blocking while (!client.connected()) { - - Logger.print("Attempting MQTT connection..."); - - // Create a random client ID - - String clientId = "ESP8266Client-"; - - clientId += String(random(0xffff), HEX); - + Logger.println("[MQTT] Connecting..."); // Attempt to connect - - if (client.connect(clientId.c_str())) { - - Logger.println("connected"); - + if (client.connect(clientID.c_str())) { + Logger.println("[MQTT] Connected"); // Once connected, publish an announcement... - client.publish("TESTOUT", "hello world"); - // ... and resubscribe - client.subscribe("TESTIN"); - } else { - - Logger.print("failed, rc="); - + Logger.print("[ERROR] [MQTT] failed, rc="); Logger.print(client.state()); - Logger.println(" try again in 5 seconds"); - // Wait 5 seconds before retrying - // delay(5000); - } - delay(100); - } - } - void MQTTcallback(char* topic, byte* payload, unsigned int length) { - - Logger.print("Message arrived ["); - + Logger.print("[MQTT] IN Message arrived ["); Logger.print(topic); - Logger.print("] "); - + Logger.print("payload: "); for (int i = 0; i < length; i++) { - Logger.print((char)payload[i]); - } - - Logger.println(); - - - - // Switch on the LED if an 1 was received as first character - + Logger.println(""); if ((char)payload[0] == '1') { - - // digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level - - // but actually the LED is on; this is because - - // it is active low on the ESP-01) - - } - - // else { - - // // digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH - - // } - - - + Logger.println("[MQTT] payload: TRIGGERED"); + } } long lastReconnectAttempt = 0; @@ -145,20 +104,24 @@ void process_MQTT(){ client.loop(); // will wait loop reconnect to mqtt } -void init_MQTT(String clientid){ - clientID = clientid; +void init_MQTT(){ client.setServer(mqtt_server_ip, mqtt_server_port); client.setCallback(MQTTcallback); + if (client.connect(clientID.c_str())) Logger.println("[MQTT] connected"); + client.setBufferSize(2048); + client.subscribe("downstream"); process_MQTT(); + // jsondata = pubjson.to(); + // jsondata = pubjson.createNestedArray(); } -void init_MQTT(){ - client.setServer(mqtt_server_ip, mqtt_server_port); - client.setCallback(MQTTcallback); - process_MQTT(); +void init_MQTT(String clientid){ + clientID = clientid; // global + init_MQTT(); } #ifdef USEJSON + void MQTT_pub(String topic, String sensor, String value){ Logger.print("[MQTT] Publish: "); Logger.print(sensor); @@ -168,24 +131,94 @@ void MQTT_pub(String topic, String sensor, String value){ Logger.println("[ERROR] MQTT value is empty"); return; } + // JsonArray data = payload.createNestedArray(topic); payload["topic"] = topic; payload["clientid"] = clientID; payload["type"] = sensor; payload["value"] = value.toFloat(); // payload["unit"] = ""; + // if(topic == "device") + jsondata.add(payload); + + // serializeJson(jsondata, Serial); + // if(debug_mqtt) serializeJson(payload, Serial); + // serializeJsonPretty(payload, Serial); + + // String output; + // serializeJson(payload,output); + // client.publish(topic.c_str(),("["+output+"\n]").c_str()); // must be object? + // close ? +} + +void MQTT_pub(String topic, String sensor, String value, bool json){ + Logger.print("[MQTT] Publish: "); + Logger.print(sensor); + Logger.print(" "); + Logger.println(value); + if(value == "") { + Logger.println("[ERROR] MQTT value is empty"); + return; + } + JsonArray data = payload.createNestedArray(topic); + payload["topic"] = data; + payload["clientid"] = clientID; + payload["type"] = sensor; + payload["value"] = value.toFloat(); + // payload["unit"] = ""; if(debug_mqtt) serializeJson(payload, Serial); // serializeJsonPretty(payload, Serial); String output; serializeJson(payload,output); + client.publish(topic.c_str(),("["+output+"\n]").c_str()); // must be object? // close ? + // mqttClient.beginMessage(topic); + // serializeJson(doc, mqttClient); + // mqttClient.endMessage(); + // client.print + // client.endPublish(); + // client.beginPublish("greenBottles/lyrics", msgLen, false); + + // const size_t capacity = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(3); + // DynamicJsonBuffer jsonBuffer(capacity); + + // JsonObject& root = jsonBuffer.createObject(); + // root["sensor"] = "gps"; + // root["time"] = 1351824120; + + // JsonArray& data = root.createNestedArray("data"); + // data.add(48.75608); + // data.add(2.302038); + + // root.printTo(Serial); } -void MQTT_pub_send(){ - // client.publish("sensor",serializeJson(payload)); - serializeJsonPretty(payload, Serial); +void MQTT_pub_send(String topic){ + Logger.println("[MQTT] sending json"); + // serializeJson(jsondata, Logger); + // rootdoc.createNestedObject(); + // rootdoc.add(pubjson); + // String output; + // serializeJson(pubjson,output); + // Serial.println(output); + // serializeJson(rootdoc,output); + // Serial.println(output); + // Serial.flush(); + + char message[2048]; + serializeJson(pubjson, message); + Serial.println((String)message); + client.publish(topic.c_str(),message); + delay(500); + // pubjson.clear(); + rootdoc.clear(); + // jsondata.clear(); + // rootdoc.createNestedObject(jsondata); + jsondata = pubjson.to(); + // payload.clear(); + // pubjson.garbageCollect(); } #else From b66b6727c71908aadfb6a4b46dcfbd69a7b4e9ba Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 23 Feb 2021 06:35:00 -0600 Subject: [PATCH 066/186] remove dup fps --- tft_graph.h | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/tft_graph.h b/tft_graph.h index 458a29e..56d9559 100644 --- a/tft_graph.h +++ b/tft_graph.h @@ -1149,27 +1149,27 @@ void tft_footer_val1(){ tft_set_footer_val2(); } -int fpsmicros = millis(); -char buffer [32]; - -void displayFPS(){ - // tft_footer_val1(); - return; - tft.setTextSize(2); - tft.setTextColor(WHITE,HC2); - tft.setCursor(TFT_WIDTH,TFT_HEIGHT-100); - // frames / sec = 1 / (sec / frame) - // tft.println((String)(1000/((micros()-fpsmicros)))); - // tft.println((String)(1000000/((micros()-fpsmicros)))); - // tft.print(" "); - sprintf (buffer, "%03u",(int)(1000/((millis()-fpsmicros)))); - // Serial.println((String)(1000/((millis()-fpsmicros)))); - // tft.println((String)(1000/(millis()-fpsmicros))); - tft.println(buffer); - // Serial.println(buffer); - // println(" FPS"); - fpsmicros = millis(); -} +// int fpsmicros = millis(); +// char buffer [32]; + +// void displayFPS(){ +// // tft_footer_val1(); +// return; +// tft.setTextSize(2); +// tft.setTextColor(WHITE,HC2); +// tft.setCursor(TFT_WIDTH,TFT_HEIGHT-100); +// // frames / sec = 1 / (sec / frame) +// // tft.println((String)(1000/((micros()-fpsmicros)))); +// // tft.println((String)(1000000/((micros()-fpsmicros)))); +// // tft.print(" "); +// sprintf (buffer, "%03u",(int)(1000/((millis()-fpsmicros)))); +// // Serial.println((String)(1000/((millis()-fpsmicros)))); +// // tft.println((String)(1000/(millis()-fpsmicros))); +// tft.println(buffer); +// // Serial.println(buffer); +// // println(" FPS"); +// fpsmicros = millis(); +// } // what is this note? lol // float smoothing = 0.9; // larger=more smoothing From d60045151069bd1f5e1aef039fb13f337d187c51 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 23 Feb 2021 06:35:25 -0600 Subject: [PATCH 067/186] wifi debugging --- wifi_funcs.h | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index cd835e1..371b059 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -2,6 +2,7 @@ #define wifi_funcs_h #include +#include // @BUG error: 'Logger' was not declared in this scope, makes no sense #ifdef ESP8266 #include @@ -21,6 +22,10 @@ bool debug_wifi = false; long downtimeRestart = 300000; long downtime = 0; +bool wifiIsConnected(){ + return WiFi.status() == WL_CONNECTED; +} + String getDeviecID(){ String _wifissidprefix = "ESP"; String hostString = String(WIFI_getChipId(),HEX); @@ -46,11 +51,25 @@ String getHostname(){ #endif } +void WiFi_print_sta(){ + if(wifiIsConnected()){ + Serial.println("[WIFI] CONNECTED"); + Serial.print("[WIFI] IP: "); + Serial.println(WiFi.localIP()); + Serial.print("[WIFI] HOST: "); + getHostname(); + } +} + // enable wifi sta // disable sleep // timeout connect // set hostname ? void init_WiFi(int timeout = 10000){ + if(wifiIsConnected()){ + WiFi_print_sta(); + return; + } WiFi.mode(WIFI_STA); #ifdef ESP8266 WiFi.setSleepMode(WIFI_NONE_SLEEP); @@ -79,12 +98,8 @@ void init_WiFi(int timeout = 10000){ Serial.println(""); - if(WiFi.status() == WL_CONNECTED){ - Serial.println("[WIFI] CONNECTED"); - Serial.print("[WIFI] IP: "); - Serial.println(WiFi.localIP()); - Serial.print("[WIFI] HOST: "); - getHostname(); + if(wifiIsConnected()){ + WiFi_print_sta(); } else{ Serial.println("[ERROR] WIFI CONNECT FAILED"); @@ -255,9 +270,6 @@ void disableWiFi(){ // if (SW_RESET == reason) { return REASON_EXT_SYS_RST; } // } -bool wifiIsConnected(){ - return WiFi.status() == WL_CONNECTED; -} String WiFi_SSID(bool persistent) { From 4e7d83a94236e5747af9607ddd3c34999d2f8357 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 23 Feb 2021 06:35:41 -0600 Subject: [PATCH 068/186] i2cscan 8 bit --- io_utils.h | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/io_utils.h b/io_utils.h index 76b8349..ed5ee80 100644 --- a/io_utils.h +++ b/io_utils.h @@ -56,8 +56,10 @@ void scani2c(bool pinswap = false){ { Logger.print("[I2C] Device found - ADDR: 0x"); if (address<16) - Logger.print("0"); - Logger.print(address,HEX); + Logger.print("0x"); + Logger.print(address,HEX); // 7 bit + Logger.print(" 0x"); + Logger.print(2*address,HEX); // 8bit Logger.println(""); nDevices++; } @@ -74,7 +76,8 @@ void scani2c(bool pinswap = false){ if (nDevices == 0) Logger.println("[ERROR] No I2C devices found\n"); else - Logger.println("[I2C] scan done\n"); + Logger.print("[I2C] scan done found "); + Logger.println(nDevices); } void scanPins(){ @@ -92,7 +95,25 @@ void scanPins(){ Logger.println(""); } +void pinregister(){ + // maintain a store of pins we are using before passing them to functions + // better than a simple define, as we can + // register a pin for use, to avoid using a pin twice + // even if this is a preocompiler structure, it would stil be able to warn + // also can let you set the use as a flag so you know if you are using it as adc or input + // and on esp32 etc set the pins desired specs and avoid conflicts with multiple adc reads +} + #ifdef ESP32 + +#define ADC_1 36 +#define ADC_2 38 // missing from some boards? +#define ADC_3 39 +#define ADC_4 32 +#define ADC_5 33 +#define ADC_6 34 +#define ADC_7 37 + // ADC2 restoring procedure // This is a Workaround to use ADC2 Pins on ESP32 when Wifi or Bluetooth is on. // (usually only ADC1 Pins are usable for analogRead() when Wifi or Bluetooth is on.) From f93313b7893a657b04ade1e0e4734549792aee79 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 23 Feb 2021 06:35:56 -0600 Subject: [PATCH 069/186] adding avg --- sense_env.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sense_env.h b/sense_env.h index 9f66b75..c67d6b6 100644 --- a/sense_env.h +++ b/sense_env.h @@ -1,6 +1,9 @@ #ifndef sensors_h #define sensors_h +#include + +Average avg_a(10); // supported sensors // SHT31 @@ -555,7 +558,7 @@ void print_cs811(){ } } else{ - Logger.println("[ERROR] cs811 not available"); + Logger.println("[ERROR] cs811 not available"); // } } @@ -565,7 +568,7 @@ float get_cs811(uint8_t channel = 0){ // if(!ccs.available()) return 0; // if(ccs.readData()) return 0; // @todo detect failures, or else func return old values - if(!ccs.available()) Logger.println("[ERROR] cs811 not available"); // always false? + // if(!ccs.available()) Logger.println("[ERROR] cs811 not available"); // always false? if(ccs.checkError()) Logger.println("[ERROR] Assert cs811 check error"); // always false? uint8_t err = ccs.readData(); float ret; From 2deece9303f8600b8cebe7a6f3bb429798807d9b Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 23 Feb 2021 06:36:30 -0600 Subject: [PATCH 070/186] oled sh1106 --- oled_i2c_sh1106.h | 42 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index 7e00f3a..bd0dc55 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -30,7 +30,7 @@ U8G2_SH1106_128X64_NONAME_F_HW_I2C lcd(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); -int fpsmicros = 0; +int oledfpsmicros = 0; // #if (SSD1306_LCDHEIGHT != 64) // #error("Height incorrect, please fix Adafruit_SSD1306.h!"); @@ -64,6 +64,21 @@ void whiteText(){ // display.display(); // } +/** + * print oled lines + * @param str string to print + * @param no line 0-3 + * @param size text size 1-2 + */ +void print_oled_line(String str,uint16_t no = 1,uint16_t size = 1){ + uint16_t y = 0; + if(size == 1) y = 9*no; + if(size == 2) y = 18*no; + lcd.setCursor(0,y); + // lcd.setTextSize(size); + lcd.println(str); +} + void print_oled(String str,uint8_t size,bool flush){ lcd.clearBuffer(); // clear the internal memory lcd.setFont(u8g2_font_ncenB08_tr); @@ -119,9 +134,9 @@ void init_oled(bool preamble,bool pinswap = false){ } void displayFPS(){ - lcd.print((String)(1000000/((micros()-fpsmicros)/2))); + lcd.print((String)(1000000/((micros()-oledfpsmicros)/2))); // println(" FPS"); - fpsmicros = micros(); + oledfpsmicros = micros(); } // void printInverted(const char* str){ @@ -164,6 +179,27 @@ int printValuePair(const char* str,String strb,int x,int y){ return xoff; // get new cursor? } +void oled_test(uint8_t num = 0){ + // print_oled_line(msg, line, size); + for(uint8_t i=0;i Date: Tue, 23 Feb 2021 06:36:52 -0600 Subject: [PATCH 071/186] update log toggling --- log.h | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/log.h b/log.h index f38f977..206869a 100644 --- a/log.h +++ b/log.h @@ -2,7 +2,7 @@ #ifndef log_h #define log_h -// #define USESYSLOG +#define USESYSLOG #ifdef USESYSLOG #include #endif @@ -43,7 +43,7 @@ void sendToSyslog(String msg){ class print2syslog : public Stream { public: - bool begun = false; + bool begun = true; // allow muting via availability virtual int available() { return (begun); } virtual int read() { return (0); } virtual int peek() { return (0); } @@ -71,20 +71,22 @@ class print2syslog : public Stream { }; print2syslog syslogger; -Stream &_Logger = Serial; +// syslogger.begin(); + +#include -Stream &Logger = Serial; +Stream &_Logger = Serial; +LoggingStream Logger(syslogger, _Logger); +// Stream &Logger = Serial; // BYPASS lOGGER -// using Print::write; -// #if ARDUINO >= 100 -// virtual size_t write(uint8_t); +// #ifdef USESYSLOG +// LoggingStream Logger(syslogger, _Logger); // #else -// virtual void write(uint8_t); + // Stream &Logger = Serial; // BYPASS lOGGER // #endif -#include -// LoggingStream Logger(syslogger, _Logger); -// String result = LoggingStream.str(); +// logging streams options +// String result = LoggingStream.str(); // WriteLoggingStream loggingClient(client, Serial); // loggingClient.println("GET / HTTP/1.1"); // loggingClient.println("User-Agent: Arduino"); From f7cd4879959eb66acb736ffc465b34bdcdc785d8 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 23 Feb 2021 06:37:17 -0600 Subject: [PATCH 072/186] dups? --- oled_i2c.h | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/oled_i2c.h b/oled_i2c.h index ad47031..ec62c2c 100644 --- a/oled_i2c.h +++ b/oled_i2c.h @@ -1,4 +1,6 @@ /*oled_i2c*/ +#ifndef oled_i2c_h +#define oled_i2c_h #include #include @@ -14,7 +16,7 @@ Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT); // Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET,800000,800000); -int fpsmicros = 0; +int oledfpsmicros = 0; void invertText(){ lcd.setTextColor(BLACK, WHITE); // 'inverted' text @@ -101,20 +103,30 @@ void init_oled(bool preamble){ lcd.display(); } -void oled_test(){ - print_oled_line("Line One",0); - print_oled_line("Line Two",1); - print_oled_line("Line Three",2); - lcd.display(); - delay(1000); - lcd.clearDisplay(); - print_oled_line("Line One",0,2); - print_oled_line("Line Two",2); - lcd.display(); +void oled_test(uint8_t num = 0){ + // print_oled_line(msg, line, size); + for(uint8_t i=0;i Date: Tue, 23 Feb 2021 06:37:30 -0600 Subject: [PATCH 073/186] debuggin coments --- log_syslog.h | 5 ++--- temp_logger.h | 2 ++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/log_syslog.h b/log_syslog.h index 800bd6a..d002db4 100644 --- a/log_syslog.h +++ b/log_syslog.h @@ -43,7 +43,7 @@ void init_syslog(){ } void sendLogTest(){ - String startmsg = "Started"; + String startmsg = "[BOOT] Device Started"; syslog.log(LOG_INFO, startmsg); return; // Log message can be formated like with printf function. @@ -52,8 +52,7 @@ void sendLogTest(){ // You can force set facility in pri parameter for this log message. More // facilities in syslog.h or in Linux syslog documentation. - syslog.logf(LOG_DAEMON | LOG_INFO, "This is daemon info message no. %d", - iteration); + syslog.logf(LOG_DAEMON | LOG_INFO, "This is daemon info message no. %d", iteration); // You can set default facility and severity level and use it for all log // messages (beware defaultPriority is stored permanently!) diff --git a/temp_logger.h b/temp_logger.h index d039eb8..f77438e 100644 --- a/temp_logger.h +++ b/temp_logger.h @@ -71,6 +71,8 @@ BarGraph bar0; #define GFXX18pt &FreeSans18pt7b // #define GFXX18pt &FreeMono18pt7b +int fpsmicros = 0; + bool USEWIFI = true; // enabled wifi, NOT connect wifi Average fps(10); // init stats for avg (samples) From 202c12948b50a8b0da14206af21a011750f8794e Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Feb 2021 22:55:09 -0600 Subject: [PATCH 074/186] logger replacements --- button_abs.h | 39 +++++++++++++++++++++++++-------------- httpd.h | 16 ++++++++-------- oled_i2c_sh1106.h | 37 +++++++++++++++++++++++++++++-------- 3 files changed, 62 insertions(+), 30 deletions(-) diff --git a/button_abs.h b/button_abs.h index 8bd2cec..9b9f2e3 100644 --- a/button_abs.h +++ b/button_abs.h @@ -33,30 +33,38 @@ void encoderClear(){ } void ICACHE_RAM_ATTR onEncoderChange(int newValue) { + // @todo always a false trigger on start + // if(encoderLast < 0){ + // Logger.println("[ENC] init fired"); + // encoderLast = newValue; + // encoderClear(); + // return; // init + // } + if(_maximumEncoderValue > 0){ - Serial.print("[ENCODER] change to "); - Serial.print(newValue); - Serial.print(" from "); - Serial.print(encoderLast); + Logger.print("[ENCODER] change to "); + Logger.print(newValue); + Logger.print(" from "); + Logger.print(encoderLast); if(encoderLast == newValue){ - Serial.println("\n"); + Logger.println("\n"); return; } bool dir = (encoderLast > newValue); - Serial.println(" dir: " + String(dir ? "CC" : "CW")); + Logger.println(" dir: " + String(dir ? "CC" : "CW")); encoderStale = encoderLast; encoderLast = newValue; encoderHasChange = true; } else{ if(newValue == 0){ - Serial.print("[ENCODER] no change"); + Logger.print("[ENCODER] no change"); return; } - Serial.print("[ENCODER] change by "); - Serial.print(newValue); + Logger.print("[ENCODER] change by "); + Logger.print(newValue); bool dir = (newValue == 1); - Serial.println(" dir: " + String(dir ? "CW" : "CC")); // for plotting use 10,20 etc + Logger.println(" dir: " + String(dir ? "CW" : "CC")); // for plotting use 10,20 etc encoderStale = encoderLast; encoderLast = newValue; @@ -65,8 +73,8 @@ void ICACHE_RAM_ATTR onEncoderChange(int newValue) { } void ICACHE_RAM_ATTR onEncoderSWPressed(uint8_t pin, bool heldDown) { - Serial.print("[ENCODER] Button "); - Serial.println(heldDown ? "Held" : "Pressed"); + Logger.print("[ENCODER] Button "); + Logger.println(heldDown ? "Held" : "Pressed"); encoderHasPress = true; encoderHasHold = heldDown; } @@ -95,7 +103,10 @@ void init_encoder(int encoderAPin, int encoderBPin, int encoderSWPin,uint8_t add } // encoder sw + #ifndef ENC_SW_ANALOG switches.addSwitch(encoderSWPin, onEncoderSWPressed); // encoder button press + #endif + // encoder setupRotaryEncoderWithInterrupt(encoderAPin, encoderBPin, onEncoderChange); if(_maximumEncoderValue > 0) switches.changeEncoderPrecision(_maximumEncoderValue, 0); @@ -131,10 +142,10 @@ void checkAnalogSW(uint8_t pin, uint16_t value,uint32_t hold){ // IoAbstractionRef iodev = switches.getIoAbstraction(); // iodev->pinDirection(7,OUTPUT); // bool res = iodev->runLoop(); - // if(res!=1) Serial.println("devsync: " + (String)res); + // if(res!=1) Logger.println("devsync: " + (String)res); // taskManager.runLoop(); // if(!res){ - // Serial.println("error"); + // Logger.println("error"); // delay(500); // } #endif \ No newline at end of file diff --git a/httpd.h b/httpd.h index c760b97..4f094fb 100644 --- a/httpd.h +++ b/httpd.h @@ -14,24 +14,24 @@ void handleRoot() { if(server.hasArg(F("ledindex"))){ - Serial.println("has arg ledindex"); + Logger.println("has arg ledindex"); String pixel = server.arg(F("ledindex")); // ledIndex = pixel; // setHTTPValue(pixel.toInt()); // strip.setPixelColor(pixel.toInt(),strip.Color(255,0,0)); - Serial.println("Setting pixel:" + (String)pixel); + Logger.println("Setting pixel:" + (String)pixel); // strip.show(); // delay(2000); server.send(200, "text/plain", "hello from esp8266! ledindex SET"); } if(server.hasArg(F("pwm"))){ - Serial.println("has arg PWM"); + Logger.println("has arg PWM"); String pwmvalue = server.arg(F("pwm")); // ledIndex = pixel; // setPWM(pwmvalue.toInt()); // strip.setPixelColor(pixel.toInt(),strip.Color(255,0,0)); - Serial.println("Setting PWM:" + (String)pwmvalue); + Logger.println("Setting PWM:" + (String)pwmvalue); // strip.show(); // delay(2000); // server.send(200, "text/plain", "hello from esp8266! PWM set:" + (String)getPWM()); @@ -40,12 +40,12 @@ void handleRoot() { } if(server.hasArg(F("freq"))){ - Serial.println("has arg FREQ"); + Logger.println("has arg FREQ"); String pwmvalue = server.arg(F("freq")); // ledIndex = pixel; // setPWM(pwmvalue.toInt()); // strip.setPixelColor(pixel.toInt(),strip.Color(255,0,0)); - Serial.println("Setting FREQ:" + (String)pwmvalue); + Logger.println("Setting FREQ:" + (String)pwmvalue); // strip.show(); // delay(2000); // server.send(200, "text/plain", "hello from esp8266! PWM set:" + (String)getPWM()); @@ -78,7 +78,7 @@ void handleNotFound() { void httpd_init(){ if (MDNS.begin("esp8266")) { - Serial.println("MDNS responder started"); + Logger.println("[MDNS] responder started"); } server.on("/", handleRoot); @@ -106,7 +106,7 @@ void httpd_init(){ }); server.begin(); - Serial.println("HTTP server started"); + Logger.println("[HTTP] server started"); } void httpd_process(void) { diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index bd0dc55..57cf39a 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -1,6 +1,6 @@ /*oled_i2c*/ -// DOESNT WORK +#include #include // #include // #include @@ -16,6 +16,21 @@ #include #endif +// https://github.com/olikraus/u8g2/wiki/fntlistall#24-pixel-height +// U8g2 Font names +// '_' '_' +// Description +// t Transparent font, Do not use a background color. +// h All glyphs have common height. +// m All glyphs have common height and width (monospace). +// 8 All glyphs fit into a 8x8 pixel box. +// Description +// f The font includes up to 256 glyphs. +// r Only glyphs on the range of the ASCII codes 32 to 127 are included in the font. +// u Only glyphs on the range of the ASCII codes 32 to 95 (uppercase chars) are included in the font. +// n Only numbers and extra glyphs for writing date and time strings are included in the font. +// ... Other custom character list. + // #define WHITE SH110X_WHITE // #define BLACK SH110X_BLACK @@ -89,16 +104,22 @@ void print_oled(String str,uint8_t size,bool flush){ if(flush)lcd.sendBuffer(); // transfer internal memory to the display } -// @todo add pinswap void init_oled(bool preamble,bool pinswap = false){ - Serial.println("\nInitializing SSD1106 OLED"); - Serial.println("SDA: "+(String)SDA); - Serial.println("SCL: "+(String)SCL); - if(pinswap) Wire.begin(5,4); // begin(sda, scl) SWAP! + Logger.println("[OLED] Initializing SSD1106 OLED"); + Logger.println("[I2C] SDA: "+(String)SDA); + Logger.println("[I2C] SCL: "+(String)SCL); + if(pinswap){ + Wire.begin(5,4); // begin(sda, scl) SWAP! + Logger.println("[I2C] pinswapped"); + Logger.println("[I2C] SDA: "+(String)SDA); + Logger.println("[I2C] SCL: "+(String)SCL); + } // Wire.setClock(400000L); - lcd.setDisplayRotation(U8G2_R2); + #ifdef ROT + lcd.setDisplayRotation(U8G2_R2); + #endif lcd.begin(); - // lcd.setI2CAddress(0x7A); + // lcd.setI2CAddress(0x78); // if(!lcd.begin()) { // Address 0x3C for 128x32 // Serial.println(F("SSD1106 begin failed")); // } From 75e3d2ddabf11625956c6907dd099aec4fd3ca7d Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Feb 2021 22:55:16 -0600 Subject: [PATCH 075/186] esp32 buzzer --- buzzer.h | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/buzzer.h b/buzzer.h index 115e084..9b69821 100644 --- a/buzzer.h +++ b/buzzer.h @@ -2,6 +2,7 @@ #define buzzer_h #ifdef ESP8266 + #include #include ESP8266_Tones BUZZER_TONE(BUZ_PIN); @@ -125,5 +126,36 @@ void playBlurpA(){ delay(50); } +void chime(){ + playBlurpA(); +} + +void alarm(){ + blurp4(); +} + +#else + +bool init_buzzer(){ + pinMode(BUZ_PIN,OUTPUT); +} + +bool chime(){ + analogWrite(BUZ_PIN,500); + delay(100); + analogWrite(BUZ_PIN,500); + delay(100); + analogWrite(BUZ_PIN,0); +} + +bool soundalarm(){ + analogWrite(BUZ_PIN,500); + delay(100); + analogWrite(BUZ_PIN,500); + delay(100); + analogWrite(BUZ_PIN,0); +} + #endif + #endif From e471eadc14956140263c665cdc23928aebb2164d Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Feb 2021 22:55:48 -0600 Subject: [PATCH 076/186] some updates for reflowplate --- io_utils.h | 4 ++++ neoindicator.h | 6 +++--- number_format.h | 17 +++++++++++++++++ ssr.h | 27 +++++++++++++++++++++------ 4 files changed, 45 insertions(+), 9 deletions(-) diff --git a/io_utils.h b/io_utils.h index ed5ee80..1a9082f 100644 --- a/io_utils.h +++ b/io_utils.h @@ -4,6 +4,10 @@ #include #include +#ifdef ESP32 +#include +#endif + bool swap = false; int getPinMode(uint8_t pin) diff --git a/neoindicator.h b/neoindicator.h index 52e83a4..5c0ad80 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -206,11 +206,11 @@ void indTest(){ ind.setBrightness(255); // full bright indSetColor(255,0,0); - delay(500); + delay(wait*100); indSetColor(0,255,0); - delay(500); + delay(wait*100); indSetColor(0,0,255); - delay(500); + delay(wait*100); indSetColor(0,0,0); delay(200); diff --git a/number_format.h b/number_format.h index 81c8ea0..dc4fdfb 100644 --- a/number_format.h +++ b/number_format.h @@ -9,4 +9,21 @@ float round_f_2(float x){ return round(x); } +// inline double round( double val ) +// { +// if( val < 0 ) return ceil(val - 0.5); +// return floor(val + 0.5); +// } + +// template +// string sFormat(const char *f, T value) +// { +// char buffer[64]; +// snprintf(buffer, sizeof(buffer), f, value); +// return string(buffer); +// } + +// printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456); + + #endif \ No newline at end of file diff --git a/ssr.h b/ssr.h index ffb87a0..ba34309 100644 --- a/ssr.h +++ b/ssr.h @@ -3,10 +3,7 @@ #define RELAYPIN 3 // relay control SSR PWM #include - -#ifdef ESP32 -#include -#endif +#include #ifdef DEBUG bool DEBUG_ssr = true; @@ -14,14 +11,13 @@ bool DEBUG_ssr = true; bool DEBUG_ssr = false; #endif -bool ssrDisabled = false; +bool ssrDisabled = true; // safety ON float currentDuty = 0; // ssrpower bool invertDuty = true; // invert logic vcc range bool invertLOW = false; // Drive SSR with VCC int _ssrRelayPin = -1; - void ssr_off(){ if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,!invertLOW ? HIGH : LOW); } @@ -68,6 +64,7 @@ void SetSSRFrequency( int duty,int power =1) // if(duty == 0)ssr_off(); // if(duty == 255)ssr_on(); } + else ssr_off(); // ENFORCE SAFETY if(duty!=currentDuty){ // if(DEBUG_ssr) Serial.println("[SSR] " + (String)duty); @@ -145,4 +142,22 @@ void ssrTest(int speed){ ssr_off(); } +void ssrPing(int speed){ + + ssr_on(); + delay(1000); + ssr_off(); + + for(int i=0;i<255;i+20){ + SetSSRFrequency( i ); + delay(100); + } + + for(int i=0;i<255;i+20){ + SetSSRFrequency( 255-i ); + delay(100); + } + + ssr_off(); +} #endif \ No newline at end of file From c9cd24455ecec23ea6ef540d6a120d9e66b5587f Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Feb 2021 22:56:06 -0600 Subject: [PATCH 077/186] wifi helpers --- wifi_funcs.h | 129 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 82 insertions(+), 47 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index 371b059..8e67269 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -2,7 +2,6 @@ #define wifi_funcs_h #include -#include // @BUG error: 'Logger' was not declared in this scope, makes no sense #ifdef ESP8266 #include @@ -22,6 +21,76 @@ bool debug_wifi = false; long downtimeRestart = 300000; long downtime = 0; + +/** IP to String? */ +String toStringIp(IPAddress ip) { + String res = ""; + for (int i = 0; i < 3; i++) { + res += String((ip >> (8 * i)) & 0xFF) + "."; + } + res += String(((ip >> 8 * 3)) & 0xFF); + return res; +} + +String WiFi_SSID(bool persistent) { + persistent = true; + #ifdef ESP8266 + struct station_config conf; + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[33]; //ssid can be up to 32chars, => plus null term + memcpy(tmp, conf.ssid, sizeof(conf.ssid)); + tmp[32] = 0; //nullterm in case of 32 char ssid + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + if(persistent){ + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.ssid)); + } + else { + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_ap_record_t info; + if(!esp_wifi_sta_get_ap_info(&info)) { + return String(reinterpret_cast(info.ssid)); + } + return String(); + } + #endif +} + +String WiFi_psk(bool persistent) { + persistent = true; + #ifdef ESP8266 + struct station_config conf; + + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[65]; //psk is 64 bytes hex => plus null term + memcpy(tmp, conf.password, sizeof(conf.password)); + tmp[64] = 0; //null term in case of 64 byte psk + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + // only if wifi is init + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.password)); + #endif +} + +bool wifiIsAutoConnect(){ + return WiFi_SSID(true) != ""; +} + bool wifiIsConnected(){ return WiFi.status() == WL_CONNECTED; } @@ -45,7 +114,7 @@ void setWiFiHostname(const char* hostname){ String getHostname(){ #ifdef ESP32 - return WiFi.getHostname(); // getHostName + return WiFi.getHostname(); // getHostName ( @todo return string of c.str?) #else return WiFi.hostname(); // getHostName #endif @@ -65,11 +134,11 @@ void WiFi_print_sta(){ // disable sleep // timeout connect // set hostname ? -void init_WiFi(int timeout = 10000){ - if(wifiIsConnected()){ - WiFi_print_sta(); - return; - } +void init_WiFi(int timeout){ + // if(wifiIsConnected()){ + // WiFi_print_sta(); + // return; + // } WiFi.mode(WIFI_STA); #ifdef ESP8266 WiFi.setSleepMode(WIFI_NONE_SLEEP); @@ -80,7 +149,8 @@ void init_WiFi(int timeout = 10000){ // WiFi.hostname(hostname); unsigned long start = millis(); - WiFi.begin(SSID,PASS); + if(wifiIsAutoConnect) WiFi.begin(); + else WiFi.begin(SSID,PASS); if(timeout > 0){ Serial.println("[WIFI] Connecting to wifi... [" + (String)timeout + " ms]\n"); while((WiFi.status() != WL_CONNECTED) && (millis()-start < timeout)){ @@ -91,7 +161,7 @@ void init_WiFi(int timeout = 10000){ else { Serial.println("[WIFI] Connecting to wifi, waiting..... "); while(WiFi.waitForConnectResult() != WL_CONNECTED){ - Serial.print("."); + // Serial.print("."); delay(100); } } @@ -109,7 +179,7 @@ void init_WiFi(int timeout = 10000){ } void init_wifi(){ - init_WiFi(); + init_WiFi(0); } int getRSSIasQuality() { @@ -148,7 +218,7 @@ void checkWifi(){ void enableWiFi(){ WiFi.mode(WIFI_STA); - init_WiFi(); + init_WiFi(0); } void disableWiFi(){ @@ -270,42 +340,6 @@ void disableWiFi(){ // if (SW_RESET == reason) { return REASON_EXT_SYS_RST; } // } - -String WiFi_SSID(bool persistent) { - - #ifdef ESP8266 - struct station_config conf; - if(persistent) wifi_station_get_config_default(&conf); - else wifi_station_get_config(&conf); - - char tmp[33]; //ssid can be up to 32chars, => plus null term - memcpy(tmp, conf.ssid, sizeof(conf.ssid)); - tmp[32] = 0; //nullterm in case of 32 char ssid - return String(reinterpret_cast(tmp)); - - #elif defined(ESP32) - if(persistent){ - wifi_config_t conf; - esp_wifi_get_config(WIFI_IF_STA, &conf); - return String(reinterpret_cast(conf.sta.ssid)); - } - else { - if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ - return String(); - } - wifi_ap_record_t info; - if(!esp_wifi_sta_get_ap_info(&info)) { - return String(reinterpret_cast(info.ssid)); - } - return String(); - } - #endif -} - -bool wifiIsAutoConnect(){ - return WiFi_SSID(true) != ""; -} - String getResetReason(){ int reason; #ifdef ESP8266 @@ -325,4 +359,5 @@ String getResetReason(){ #endif } + #endif \ No newline at end of file From 2fc19ec17f322448dfe37dababfe34532212e990 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Feb 2021 22:57:18 -0600 Subject: [PATCH 078/186] have to pass hostname to syslog If we try to get it from esp it takes too long to use as devicename in logs, investigate better solutions --- log_syslog.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/log_syslog.h b/log_syslog.h index d002db4..c7d2a98 100644 --- a/log_syslog.h +++ b/log_syslog.h @@ -1,6 +1,7 @@ #ifndef log_syslog_h #define log_syslog_h +#include #include #include #include @@ -24,13 +25,14 @@ int iteration = 1; const char* syslog_hostname; const char* syslog_appname; -void init_syslog(){ +void init_syslog(const char* hostname){ Serial.println("[LOG] syslog init"); Serial.println("[LOG] syslog hostname: " + getHostname()); Serial.println("[LOG] syslog appname: " + logTopic); // syslog_hostname = getHostname().c_str(); // gibberish not working - syslog_hostname = WiFi.getHostname(); + syslog_hostname = hostname; + // : getHostname().c_str(); syslog_appname = logTopic.c_str(); // prepare syslog configuration here (can be anywhere before first call of // log/logf method) From 5640bc60dd97c877744901e2e4e7412eef9a24f5 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 2 Mar 2021 23:08:11 -0600 Subject: [PATCH 079/186] pid ssr logger --- buzzer.h | 9 ++++--- pid.h | 74 +++++++++++++++++++++++++++++--------------------------- ssr.h | 14 ++++++++--- 3 files changed, 55 insertions(+), 42 deletions(-) diff --git a/buzzer.h b/buzzer.h index 9b69821..c4e8f8e 100644 --- a/buzzer.h +++ b/buzzer.h @@ -127,11 +127,14 @@ void playBlurpA(){ } void chime(){ - playBlurpA(); + blurp4(); } -void alarm(){ - blurp4(); +void soundalarm(){ + for(int i=0; i<6; i++){ + blurp6(); + delay(50); + } } #else diff --git a/pid.h b/pid.h index 2c9e91f..bb920c1 100644 --- a/pid.h +++ b/pid.h @@ -11,6 +11,7 @@ #include // #include #include // https://github.com/br3ttb/Arduino-PID-Library +#include // [PIDTUNE] COMPLETE // P 97.403 @@ -25,6 +26,7 @@ uint16_t fullPowerPeriod = 10000; // full power startup pulse period bool fullPowerStartup = true; // enable full power period +bool pidEnabled = false; int long pidTimerStart = 0; bool pidRunning = false; // flag is pid running, used for init start etc. @@ -34,7 +36,7 @@ bool isCuttoff = false; bool isFanOn = false; float lastWantedTemp = -1; -bool DEBUG_pid = false; +bool DEBUG_pid = true; //Define Variables we'll be connecting to double Setpoint, Input, Output; @@ -171,20 +173,20 @@ void pid_preset_I(){ } void pid_peak(){ - Serial.println("[PID] adjust tunings"); + Logger.println("[PID] adjust tunings"); myPID.SetTunings(KpAgr, KiAgr, KdAgr); // @todo confirm tunings } void init_PID(){ // float Kp=97.403, Ki=3.142, Kd=754.9, Hz=10; - Serial.println("[PID] init"); - Serial.println("[PID] PID : " + (String)Kp + " " + (String)Ki + " " + (String)Kd); + Logger.println("[PID] init"); + Logger.println("[PID] PID : " + (String)Kp + " " + (String)Ki + " " + (String)Kd); myPID.SetMode(AUTOMATIC); myPID.SetOutputLimits(0,250); // depending on the ssr freq, low values do nothing < 5%, test this, even 1% will slowly add thermal over time // myPID.SetSampleTime(120); - // if(!res) Serial.println("[ERROR] init FAILED (outputrange)"); - // if(myPID.err()) Serial.println("[ERROR] init FAILED (construct)"); + // if(!res) Logger.println("[ERROR] init FAILED (outputrange)"); + // if(myPID.err()) Logger.println("[ERROR] init FAILED (construct)"); } void pidStart(){ @@ -193,10 +195,12 @@ void pidStart(){ myPID.SetMode(MANUAL); Output = 250; // output never returns to normal !!!! } + // pidEnabled = true; pidRunning = true; } void run_PID(){ + // if(!pidEnabled) return; if(!pidRunning) pidStart(); // updateTemps(); // this is too close to the PID freq // make sure temps are updated before calling run pid, but do not run close to the same frequency @@ -215,10 +219,10 @@ void run_PID(){ // why is PID doing effort after setpoint if(Input > Setpoint && (Output > 1)){ - Serial.println("[PID] WTF PID"); + // Logger.println("[PID] WTF PID"); } - // Serial.print("-"); - // Serial.print(Output); + // Logger.print("-"); + // Logger.print(Output); if(fullPowerStartup){ if(millis()-pidTimerStart < fullPowerPeriod){ } @@ -251,7 +255,7 @@ void MatchTemp() // set.lookAhead = 2; // set.lookAheadWarm = 2; - // Serial.print("."); + // Logger.print("."); // if(wantedTemp > 0) run_PID(); // return; float duty = 0; @@ -278,28 +282,28 @@ void MatchTemp() DEBUG_pid = currentDelta > 0; if(DEBUG_pid){ - Serial.print( "[PID]" ); + Logger.print( "[PID]" ); - // Serial.print( "T: " ); - // Serial.print( timeX ); + // Logger.print( "T: " ); + // Logger.print( timeX ); - Serial.print( " Current: " ); - Serial.print( currentTemp ); + Logger.print( " Current: " ); + Logger.print( currentTemp ); - Serial.print( " Wanted: " ); - Serial.print( wantedTemp ); + Logger.print( " Wanted: " ); + Logger.print( wantedTemp ); - Serial.print( " T Diff: " ); - Serial.print( tempDiff ); + Logger.print( " T Diff: " ); + Logger.print( tempDiff ); - Serial.print( " W Diff: " ); - Serial.print( wantedDiff ); + Logger.print( " W Diff: " ); + Logger.print( wantedDiff ); - Serial.print( " Perc: " ); - Serial.print( perc ); + Logger.print( " Perc: " ); + Logger.print( perc ); - Serial.print( " Delta: " ); - Serial.print( currentDelta ); + Logger.print( " Delta: " ); + Logger.print( currentDelta ); } float base = 128; @@ -316,27 +320,27 @@ if(DEBUG_pid){ base = constrain( base, 0, 256 ); if(DEBUG_pid){ - Serial.print(" Base: "); - Serial.print( base ); - // Serial.print( " -> " ); + Logger.print(" Base: "); + Logger.print( base ); + // Logger.print( " -> " ); } duty = base + ( 172 * perc ); // 172? if(DEBUG_pid){ - Serial.print(" Duty: "); - Serial.print( duty ); - Serial.print( " -> " ); - Serial.println(""); + Logger.print(" Duty: "); + Logger.print( duty ); + Logger.print( " -> " ); + Logger.println(""); } // if(duty<0)duty = 0; duty = constrain( duty, 0, 256 ); // override for full blast at start - // Serial.println("startFullBlast"); - // Serial.println(timeX); - // Serial.println(CurrentGraph().reflowGraphX[1]); + // Logger.println("startFullBlast"); + // Logger.println(timeX); + // Logger.println(CurrentGraph().reflowGraphX[1]); // if ( set.startFullBlast && (timeX < CurrentGraph().reflowGraphX[1]) ) duty = 256; // if ( set.startFullBlast && timeX < CurrentGraph().reflowGraphX[1] && currentTemp < wantedTemp ) duty = 256; setSSR( duty ); diff --git a/ssr.h b/ssr.h index ba34309..3592324 100644 --- a/ssr.h +++ b/ssr.h @@ -4,6 +4,9 @@ #include #include +#include + +#define DEBUG #ifdef DEBUG bool DEBUG_ssr = true; @@ -27,6 +30,7 @@ void ssr_on(){ } void ssr_init(uint16_t pin){ + Logger.println("[SSR] ready on pin " + (String)_ssrRelayPin); _ssrRelayPin = pin; pinMode( _ssrRelayPin, OUTPUT ); delay(600); @@ -54,6 +58,8 @@ void SetSSRFrequency( int duty,int power =1) // Write the clamped duty cycle to the RELAYPIN GPIO int out = invertDuty ? 255-duty : duty; + // Logger.println("[SSR] " + (String)out); + if(!ssrDisabled){ #ifdef ESP8266 analogWrite( _ssrRelayPin, out); @@ -67,11 +73,11 @@ void SetSSRFrequency( int duty,int power =1) else ssr_off(); // ENFORCE SAFETY if(duty!=currentDuty){ - // if(DEBUG_ssr) Serial.println("[SSR] " + (String)duty); - if(duty<1 && DEBUG_ssr) Serial.println("[SSR]: OFF"); + // if(DEBUG_ssr) Logger.println("[SSR] " + (String)duty); + if(duty<1 && DEBUG_ssr) Logger.println("[SSR]: OFF"); else{ - if(DEBUG_ssr) Serial.print("[SSR] ON"); - if(DEBUG_ssr) Serial.println( " - duty: " + (String)duty + " " + String( ( duty / 256.0 ) * 100) + "%" +" pow:" + String( round_f( power * 100 )) + "%" ); + if(DEBUG_ssr) Logger.print("[SSR] ON"); + if(DEBUG_ssr) Logger.println( " - duty: " + (String)duty + " " + String( ( duty / 256.0 ) * 100) + "%" +" pow:" + String( round_f( power * 100 )) + "%" ); } } currentDuty = duty; From 447dcd8a4ef7cc2147c64e2d5a9aac2a5193cf04 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 14 Mar 2021 21:34:01 -0500 Subject: [PATCH 080/186] debugging --- httpportal.h | 30 ++++++++++++++++++++++++++++++ mqtt.h | 13 +++++++++---- pid.h | 4 ++-- 3 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 httpportal.h diff --git a/httpportal.h b/httpportal.h new file mode 100644 index 0000000..939c64d --- /dev/null +++ b/httpportal.h @@ -0,0 +1,30 @@ +#ifndef httpportal_h +#define httpportal_h + +#include + +#include +WiFiManager portal(Logger); + +void init_httpportal(String title = ""){ + portal.setDebugOutput(true,"[HTTPP] "); + // invert theme, dark + portal.setDarkMode(true); + std::vector menu = {"wifi","param","info","sep","update","restart","exit"}; + portal.setMenu(menu); // custom menu, pass vector + portal.setTitle(title); +} + +void begin_httpportal(){ + portal.startWebPortal(); +} + +void stop_httpportal(){ + +} + +void process_httpportal(){ + portal.process(); +} + +#endif diff --git a/mqtt.h b/mqtt.h index a37d418..68aafe2 100644 --- a/mqtt.h +++ b/mqtt.h @@ -123,6 +123,7 @@ void init_MQTT(String clientid){ #ifdef USEJSON void MQTT_pub(String topic, String sensor, String value){ + #ifdef debug_mqtt Logger.print("[MQTT] Publish: "); Logger.print(sensor); Logger.print(" "); @@ -131,7 +132,7 @@ void MQTT_pub(String topic, String sensor, String value){ Logger.println("[ERROR] MQTT value is empty"); return; } - + #endif // JsonArray data = payload.createNestedArray(topic); payload["topic"] = topic; payload["clientid"] = clientID; @@ -152,6 +153,7 @@ void MQTT_pub(String topic, String sensor, String value){ } void MQTT_pub(String topic, String sensor, String value, bool json){ + #ifdef debug_mqtt Logger.print("[MQTT] Publish: "); Logger.print(sensor); Logger.print(" "); @@ -160,10 +162,11 @@ void MQTT_pub(String topic, String sensor, String value, bool json){ Logger.println("[ERROR] MQTT value is empty"); return; } + #endif JsonArray data = payload.createNestedArray(topic); - payload["topic"] = data; + payload["topic"] = data; // tag key = tag value payload["clientid"] = clientID; - payload["type"] = sensor; + payload["type"] = sensor; // field key = field value payload["value"] = value.toFloat(); // payload["unit"] = ""; if(debug_mqtt) serializeJson(payload, Serial); @@ -196,7 +199,9 @@ void MQTT_pub(String topic, String sensor, String value, bool json){ } void MQTT_pub_send(String topic){ - Logger.println("[MQTT] sending json"); + #ifdef debug_mqtt + Logger.println("[MQTT] sending json for topic " + topic); + #endif // serializeJson(jsondata, Logger); // rootdoc.createNestedObject(); // rootdoc.add(pubjson); diff --git a/pid.h b/pid.h index bb920c1..2f126a0 100644 --- a/pid.h +++ b/pid.h @@ -23,7 +23,7 @@ // 1468.5591 // da fuq? -uint16_t fullPowerPeriod = 10000; // full power startup pulse period +uint16_t fullPowerPeriod = 8000; // full power startup pulse period bool fullPowerStartup = true; // enable full power period bool pidEnabled = false; @@ -41,7 +41,7 @@ bool DEBUG_pid = true; //Define Variables we'll be connecting to double Setpoint, Input, Output; -float integatorReset = 0.75; // when to reset Ki +float integatorReset = 0.75; // when to reset Ki percent of delta 75% // profiling open // pulse 100% @ 23C From 245ea4efa96ecfc4f598cc7d3a253171b438ae0a Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 17 Mar 2021 23:29:20 -0500 Subject: [PATCH 081/186] add MPU6050 --- sense_env.h | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 91 insertions(+), 2 deletions(-) diff --git a/sense_env.h b/sense_env.h index c67d6b6..ab0099e 100644 --- a/sense_env.h +++ b/sense_env.h @@ -27,6 +27,9 @@ Average avg_a(10); #include // I2C + +#define MPU6050 // MPU 6050 GY521 3axis gyro/accel + #define USESHT31 // SHT31 Temp/Humidity // #define USESHT21 // SHT21 / HTU21D Temp/Humidity // #define USEBMP180 // BMP180 Temp/Pressure/Altitude (replaces BMP085) https://www.adafruit.com/product/1603 @@ -78,6 +81,13 @@ Interface: I2C #include void init_env(){ + bool ret = false; + ret = env.begin(); + if(!ret){ + Logger.println("[ERROR] xxxxxx init failed"); + } + else Logger.println("[ENV] xxxxx initialized!"); + return ret; } void print_env(){ @@ -92,7 +102,7 @@ float get_env(uint8_t channel = 0){ #endif */ -/* +/***************************************** #ifdef ENV_TEMPLATE #include @@ -109,7 +119,86 @@ float get_env(uint8_t channel = 0){ if(channel == 2) return ; #endif -*/ +*********************************************/ + +#ifdef MPU6050 +#include +#include + +Adafruit_MPU6050 mpu; + +bool init_mpu6050(){ + bool ret = false; + ret = mpu.begin(); + + // mpu.setAccelerometerRange(MPU6050_RANGE_2_G); + // mpu.setAccelerometerRange(MPU6050_RANGE_4_G); + mpu.setAccelerometerRange(MPU6050_RANGE_8_G); + // mpu.setAccelerometerRange(MPU6050_RANGE_16_G); + + // mpu.setGyroRange(MPU6050_RANGE_250_DEG); + mpu.setGyroRange(MPU6050_RANGE_500_DEG); + // mpu.setGyroRange(MPU6050_RANGE_1000_DEG); + // mpu.setGyroRange(MPU6050_RANGE_2000_DEG); + + // mpu.setFilterBandwidth(MPU6050_BAND_260_HZ); + // mpu.setFilterBandwidth(MPU6050_BAND_184_HZ); + // mpu.setFilterBandwidth(MPU6050_BAND_94_HZ); + // mpu.setFilterBandwidth(MPU6050_BAND_44_HZ); + mpu.setFilterBandwidth(MPU6050_BAND_21_HZ); + // mpu.setFilterBandwidth(MPU6050_BAND_10_HZ); + // mpu.setFilterBandwidth(MPU6050_BAND_5_HZ); + + + if(!ret){ + Logger.println("[ERROR] MPU6050 init failed"); + } + else Logger.println("[ENV] MPU6050 gyro/accel initialized!"); + return ret; +} + +void print_mpu6050(){ + sensors_event_t a, g, temp; + mpu.getEvent(&a, &g, &temp); + + /* Print out the values */ + Logger.print("Acceleration X: "); + Logger.print(a.acceleration.x); + Logger.print(", Y: "); + Logger.print(a.acceleration.y); + Logger.print(", Z: "); + Logger.print(a.acceleration.z); + Logger.println(" m/s^2"); + + Logger.print("Rotation X: "); + Logger.print(g.gyro.x); + Logger.print(", Y: "); + Logger.print(g.gyro.y); + Logger.print(", Z: "); + Logger.print(g.gyro.z); + Logger.println(" rad/s"); + + Logger.print("Temperature: "); + Logger.print(temp.temperature); + Logger.println(" degC"); +} + +float get_mpu6050(uint8_t channel = 0){ + print_mpu6050(); + sensors_event_t a, g, temp; + mpu.getEvent(&a, &g, &temp); + // accel m/s^2 + if(channel == 0) return a.acceleration.x; + if(channel == 1) return a.acceleration.y; + if(channel == 2) return a.acceleration.z; + + // gyro rad/s + if(channel == 3) return g.gyro.x; + if(channel == 4) return g.gyro.y; + if(channel == 5) return g.gyro.z; +} + +#endif #ifdef BH1750 #include //inlude the library From 7e366319cc67aeaed63e23fa5588748110db8317 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 17 Mar 2021 23:29:29 -0500 Subject: [PATCH 082/186] Log hostname --- log_syslog.h | 1 + 1 file changed, 1 insertion(+) diff --git a/log_syslog.h b/log_syslog.h index c7d2a98..1568fa2 100644 --- a/log_syslog.h +++ b/log_syslog.h @@ -27,6 +27,7 @@ const char* syslog_appname; void init_syslog(const char* hostname){ Serial.println("[LOG] syslog init"); + Serial.println("[LOG] syslog devicename: " + (String)hostname); Serial.println("[LOG] syslog hostname: " + getHostname()); Serial.println("[LOG] syslog appname: " + logTopic); From 4d8a4c9738c3b1aa8fa0a94acde581a107375167 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 17 Mar 2021 23:29:40 -0500 Subject: [PATCH 083/186] I have no idea why so many linker issues --- log.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/log.h b/log.h index 206869a..1e4eba6 100644 --- a/log.h +++ b/log.h @@ -4,6 +4,7 @@ #define USESYSLOG #ifdef USESYSLOG +#include #include #endif @@ -33,7 +34,7 @@ void sendToSyslog(String msg){ if(msgb.indexOf("warning") != -1) level = LOG_WARNING; if(msgb.indexOf("fatal") != -1) level = LOG_CRIT; - syslog.log(level,msg); + // syslog.log(level,msg); // todo clean up string, remove whitespace such as CR LF \t // reset buffer logbuffer[0] = (char)0; From 33b64ba734922ba2c6657656c0a815b586dbad8d Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 17 Mar 2021 23:29:55 -0500 Subject: [PATCH 084/186] this again ugh --- buzzer.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/buzzer.h b/buzzer.h index c4e8f8e..80fa7f8 100644 --- a/buzzer.h +++ b/buzzer.h @@ -139,6 +139,8 @@ void soundalarm(){ #else +#include + bool init_buzzer(){ pinMode(BUZ_PIN,OUTPUT); } From 18322b7f301eace7f50faf8f1f1c722fa6b66a75 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 18 Mar 2021 10:57:38 -0500 Subject: [PATCH 085/186] esp32 reset reason --- wifi_funcs.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index 8e67269..f0f06ea 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -8,6 +8,7 @@ #include #define WIFI_getChipId() ESP.getChipId() #elif defined(ESP32) + #include #include #include #include @@ -161,7 +162,7 @@ void init_WiFi(int timeout){ else { Serial.println("[WIFI] Connecting to wifi, waiting..... "); while(WiFi.waitForConnectResult() != WL_CONNECTED){ - // Serial.print("."); + Serial.print("."); delay(100); } } @@ -346,7 +347,7 @@ String getResetReason(){ return ESP.getResetReason(); #elif defined(ESP32) && defined(_ROM_RTC_H_) // requires #include - p = FPSTR(HTTP_INFO_lastreset); + // String p = FPSTR(HTTP_INFO_lastreset); for(int i=0;i<2;i++){ int reason = rtc_get_reset_reason(i); return (String)reason; @@ -355,7 +356,7 @@ String getResetReason(){ // } } #else - return ""; + return "UNSET"; #endif } From 63f7b15ceeb4615c7a2933de55aa9851e5bbe634 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 18 Mar 2021 10:57:54 -0500 Subject: [PATCH 086/186] mqtt check wifi --- mqtt.h | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/mqtt.h b/mqtt.h index 68aafe2..f269c3f 100644 --- a/mqtt.h +++ b/mqtt.h @@ -32,7 +32,8 @@ void MQTTreconnect() { // Loop until we're reconnected // this is blocking - while (!client.connected()) { + if (!client.connected()) { + // while (!client.connected()) { Logger.println("[MQTT] Connecting..."); // Attempt to connect if (client.connect(clientID.c_str())) { @@ -100,11 +101,13 @@ void process_MQTT_nb(){ } void process_MQTT(){ + if(!wifiIsConnected()) return; MQTTreconnect(); client.loop(); // will wait loop reconnect to mqtt } void init_MQTT(){ + if(!wifiIsConnected()) return; client.setServer(mqtt_server_ip, mqtt_server_port); client.setCallback(MQTTcallback); if (client.connect(clientID.c_str())) Logger.println("[MQTT] connected"); @@ -123,6 +126,10 @@ void init_MQTT(String clientid){ #ifdef USEJSON void MQTT_pub(String topic, String sensor, String value){ + if(!wifiIsConnected()){ + // Logger.print("[MQTT] OFFLINE: "); + return; + } #ifdef debug_mqtt Logger.print("[MQTT] Publish: "); Logger.print(sensor); @@ -250,4 +257,15 @@ void MQTT_pub(String topic, String sensor, String value){ } #endif +void MQTT_pub_device(){ + MQTT_pub("device","rssi",(String)getRSSIasQuality()); + #ifdef ESP32 + MQTT_pub("device","hall",(String)hallRead()); + MQTT_pub("device","temp",(String)temperatureRead()); + MQTT_pub("device","adc_1",(String)analogRead(39)); + #endif + MQTT_pub("device","uptime_s",(String)(millis()/1000)); + MQTT_pub_send("device"); +} + #endif \ No newline at end of file From 72e731f8a8e4e1d5b8eace07b9eed501ecacef51 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 19 Mar 2021 12:42:46 -0500 Subject: [PATCH 087/186] esp32 reset reasons --- wifi_funcs.h | 83 +++++++++++++++++++++------------------------------- 1 file changed, 33 insertions(+), 50 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index f0f06ea..50d2976 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -19,7 +19,7 @@ bool debug_wifi = false; -long downtimeRestart = 300000; +long downtimeRestart = 1*3600; // 5 minutes long downtime = 0; @@ -200,7 +200,14 @@ int getRSSIasQuality() { void checkWifi(){ if(WiFi.status() != WL_CONNECTED ){ if(downtime == 0) downtime = millis(); - if(millis() > downtime + downtimeRestart) ESP.restart(); + if(millis() > downtime + downtimeRestart){ + #ifdef USENEOIND + indSetColor(255,0,0); + #endif + Serial.println("[ERROR] wifi not found, rebooting after timeout"); + delay(1000); + ESP.restart(); + } #ifdef USENEOIND indSetColor(255,0,0); #endif @@ -263,50 +270,30 @@ void disableWiFi(){ // strcpy_P(buff, PSTR("Unknown")); -// String ESP32GetResetReason(uint32_t cpu_no) { -// // tools\sdk\include\esp32\rom\rtc.h -// switch (rtc_get_reset_reason( (RESET_REASON) cpu_no)) { -// case POWERON_RESET : return F("Vbat power on reset"); // 1 -// case SW_RESET : return F("Software reset digital core"); // 3 -// case OWDT_RESET : return F("Legacy watch dog reset digital core"); // 4 -// case DEEPSLEEP_RESET : return F("Deep Sleep reset digital core"); // 5 -// case SDIO_RESET : return F("Reset by SLC module, reset digital core"); // 6 -// case TG0WDT_SYS_RESET : return F("Timer Group0 Watch dog reset digital core"); // 7 -// case TG1WDT_SYS_RESET : return F("Timer Group1 Watch dog reset digital core"); // 8 -// case RTCWDT_SYS_RESET : return F("RTC Watch dog Reset digital core"); // 9 -// case INTRUSION_RESET : return F("Instrusion tested to reset CPU"); // 10 -// case TGWDT_CPU_RESET : return F("Time Group reset CPU"); // 11 -// case SW_CPU_RESET : return F("Software reset CPU"); // 12 -// case RTCWDT_CPU_RESET : return F("RTC Watch dog Reset CPU"); // 13 -// case EXT_CPU_RESET : return F("or APP CPU, reseted by PRO CPU"); // 14 -// case RTCWDT_BROWN_OUT_RESET : return F("Reset when the vdd voltage is not stable"); // 15 -// case RTCWDT_RTC_RESET : return F("RTC Watch dog reset digital core and rtc module"); // 16 -// default : return F("NO_MEAN"); // 0 -// } -// } +String ESP32GetResetReason(uint32_t cpu_no) { + // tools\sdk\include\esp32\rom\rtc.h + switch (rtc_get_reset_reason( (RESET_REASON) cpu_no)) { + case POWERON_RESET : return F("Vbat power on reset"); // 1 + case SW_RESET : return F("Software reset digital core"); // 3 + case OWDT_RESET : return F("Legacy watch dog reset digital core"); // 4 + case DEEPSLEEP_RESET : return F("Deep Sleep reset digital core"); // 5 + case SDIO_RESET : return F("Reset by SLC module, reset digital core"); // 6 + case TG0WDT_SYS_RESET : return F("Timer Group0 Watch dog reset digital core"); // 7 + case TG1WDT_SYS_RESET : return F("Timer Group1 Watch dog reset digital core"); // 8 + case RTCWDT_SYS_RESET : return F("RTC Watch dog Reset digital core"); // 9 + case INTRUSION_RESET : return F("Instrusion tested to reset CPU"); // 10 + case TGWDT_CPU_RESET : return F("Time Group reset CPU"); // 11 + case SW_CPU_RESET : return F("Software reset CPU"); // 12 + case RTCWDT_CPU_RESET : return F("RTC Watch dog Reset CPU"); // 13 + case EXT_CPU_RESET : return F("or APP CPU, reseted by PRO CPU"); // 14 + case RTCWDT_BROWN_OUT_RESET : return F("Reset when the vdd voltage is not stable"); // 15 + case RTCWDT_RTC_RESET : return F("RTC Watch dog reset digital core and rtc module"); // 16 + default : return F("NO_MEAN"); // 0 + } +} -// switch ( reason) -// { -// case 1 : Serial.println ("POWERON_RESET");break; /**<1, Vbat power on reset*/ -// case 3 : Serial.println ("SW_RESET");break; /**<3, Software reset digital core*/ -// case 4 : Serial.println ("OWDT_RESET");break; /**<4, Legacy watch dog reset digital core*/ -// case 5 : Serial.println ("DEEPSLEEP_RESET");break; /**<5, Deep Sleep reset digital core*/ -// case 6 : Serial.println ("SDIO_RESET");break; /**<6, Reset by SLC module, reset digital core*/ -// case 7 : Serial.println ("TG0WDT_SYS_RESET");break; /**<7, Timer Group0 Watch dog reset digital core*/ -// case 8 : Serial.println ("TG1WDT_SYS_RESET");break; /**<8, Timer Group1 Watch dog reset digital core*/ -// case 9 : Serial.println ("RTCWDT_SYS_RESET");break; /**<9, RTC Watch dog Reset digital core*/ -// case 10 : Serial.println ("INTRUSION_RESET");break; /**<10, Instrusion tested to reset CPU*/ -// case 11 : Serial.println ("TGWDT_CPU_RESET");break; /**<11, Time Group reset CPU*/ -// case 12 : Serial.println ("SW_CPU_RESET");break; /**<12, Software reset CPU*/ -// case 13 : Serial.println ("RTCWDT_CPU_RESET");break; /**<13, RTC Watch dog Reset CPU*/ -// case 14 : Serial.println ("EXT_CPU_RESET");break; /**<14, for APP CPU, reseted by PRO CPU*/ -// case 15 : Serial.println ("RTCWDT_BROWN_OUT_RESET");break;*<15, Reset when the vdd voltage is not stable -// case 16 : Serial.println ("RTCWDT_RTC_RESET");break; /**<16, RTC Watch dog reset digital core and rtc module*/ -// default : Serial.println ("NO_MEAN"); -// } -// } -// void verbose_print_reset_reason(RESET_REASON reason) +// void esp32_resetreason(RESET_REASON reason) // { // switch ( reason) // { @@ -347,13 +334,9 @@ String getResetReason(){ return ESP.getResetReason(); #elif defined(ESP32) && defined(_ROM_RTC_H_) // requires #include - // String p = FPSTR(HTTP_INFO_lastreset); for(int i=0;i<2;i++){ - int reason = rtc_get_reset_reason(i); - return (String)reason; - // switch (reason) - // { - // } + return ESP32GetResetReason(i); + // return (String)reason; } #else return "UNSET"; From a1efa7dc9a4e84f1fbbbe36232d26ad397d59880 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 23 Mar 2021 16:18:15 -0500 Subject: [PATCH 088/186] add glyphs --- oled_i2c_sh1106.h | 102 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 101 insertions(+), 1 deletion(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index 57cf39a..96574af 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -1,3 +1,6 @@ +#ifndef old_i2c_sh1106_h +#define old_i2c_sh1106_h + /*oled_i2c*/ #include @@ -16,6 +19,101 @@ #include #endif + +// const char WIFI_SYMBOL[] = { 93,94,123,168, 176, 247, 253, 263, 277,278,279,280,281, '\0'}; +#define GLYPH_BELL 93 // bell +#define GLYPH_BT 94 // bt +#define GLYPH_CLOCK 123 // clock +#define GLYPH_FLAME 168 // flame +#define GLYPH_CHART 176 // chart +#define GLYPH_SIGNAL 253 // bell +#define GLYPH_SPARK 96 // bell +#define GLYPH_GEAR 129 // bell +#define GLYPH_ALERT 0x118 // bell +#define GLYPH_SPKOFF 0x117 // bell +#define GLYPH_SPKHI 0x115 // bell +#define GLYPH_SPKLO 0x116 // bell +#define GLYPH_HASHF 177 // bell +#define GLYPH_HASHM 178 // bell +#define GLYPH_HASHC 179 // bell +#define GLYPH_HDOTS 155 // bell +#define GLYPH_HBAR 221 // bell +#define GLYPH_CROSS 218 // bell +#define GLYPH_CROSSB 234 // bell +#define GLYPH_EKG 238 // bell +#define GLYPH_WIFI 0x119 // bell +#define GLYPH_WRENCH 0x120 // bell +#define GLYPH_TARGET 0x107 // bell +#define GLYPH_LISTINV 0x101 // bell +#define GLYPH_STAR 0x102 // bell +#define GLYPH_SUN 0x103 // bell +#define GLYPH_STPWTCH 269 // bell +#define GLYPH_TERM 0x109 // bell +#define GLYPH_DEL 0x121 // bell +#define GLYPH_GOOD 120 // bell +#define GLYPH_BAD 121 // bell +#define GLYPH_HEART 183 // bell +#define GLYPH_HOUSE 184 // bell +#define GLYPH_SQUARE 217 // bell +#define GLYPH_SPACE 287 // bell +#define GLYPH_NO 87 // busted + +// const char* testing = u8"\u0263\u0BA3\u0B82"; + +// lcd.setFont(u8g2_font_open_iconic_embedded_1x_t); +// lcd.setFont(u8g2_font_open_iconic_all_1x_t); +// lcd.drawStr(0,y,WIFI_SYMBOL); +// lcd.drawUTF8(0,y,testing); +// lcd.drawGlyph(0,y, 93); // bell +// lcd.drawGlyph(10,y, 94); // bluetooth +// lcd.drawGlyph(20,y, 123); // clock +// lcd.drawGlyph(30,y, 168); // flame +// lcd.drawGlyph(40,y, 176); // chart +// lcd.drawGlyph(50,y, 253); // signal +// lcd.drawGlyph(60,y, 96); // terminus +// lcd.drawGlyph(70,y, 129); // gear +// lcd.drawGlyph(80,y, 0x118); // alert +// lcd.drawGlyph(90,y, 0x117); // speaker off +// lcd.drawGlyph(100,y, 0x115); // speaker high +// lcd.drawGlyph(110,y, 0x116); // speaker med + +// lcd.drawGlyph(0,y, 177); // hash fine +// lcd.drawGlyph(10,y, 178); // hash med +// lcd.drawGlyph(20,y, 179); // hash low +// lcd.drawGlyph(30,y, 155); // 3 dots +// lcd.drawGlyph(40,y, 221); // mid bar +// lcd.drawGlyph(50,y, 218); // cross +// lcd.drawGlyph(60,y, 234); // cross +// lcd.drawGlyph(60,y, 238); // heartbeat + +// lcd.drawGlyph(40,y,0x119); // wifi +// lcd.drawGlyph(50,y,0x120); // wrench not working +// lcd.drawGlyph(60,y,0x107); // target +// lcd.drawGlyph(70,y,0x101); // list inverted +// lcd.drawGlyph(80,y,0x102); // star +// lcd.drawGlyph(90,y,0x103); // sunshine +// lcd.drawGlyph(100,y,269); // stopwatch +// lcd.drawGlyph(110,y,0x109); // terminal +// lcd.drawGlyph(120,y,0x121); // delete +// +// +// lcd.drawGlyph(70,y, 120); // good +// lcd.drawGlyph(80,y, 121); // bad +// lcd.drawGlyph(90,y, 183); // heart +// lcd.drawGlyph(100,y, 184); // house +// lcd.drawGlyph(110,y, 217); // square +// // lcd.drawGlyph(110,y, 287); // space + +// if(glyphanimstate==0){ +// lcd.drawGlyph(120,y, 155); // +// glyphanimstate = 1; +// } +// else{ +// lcd.drawGlyph(120,y, 287); // +// glyphanimstate = 0; +// } + + // https://github.com/olikraus/u8g2/wiki/fntlistall#24-pixel-height // U8g2 Font names // '_' '_' @@ -226,4 +324,6 @@ void oled_test(uint8_t num = 0){ // lcd.setFontMode(1); // lcd.setDrawColor(2); // lcd.drawBox(posx, (posy-lh)+pady, strw+(padx*2),lh); // x,y(POSITIVE GOING!),w,h - // lcd.setDrawColor(1); // restore default \ No newline at end of file + // lcd.setDrawColor(1); // restore default + + #endif \ No newline at end of file From 6c744300aedcead7a8f635eaf7859912ddd3166c Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sat, 27 Mar 2021 00:30:40 -0500 Subject: [PATCH 089/186] renable syslog --- creds.h | 14 +++++++------- log.h | 4 ++-- wifi_funcs.h | 6 +++--- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/creds.h b/creds.h index 7f1f181..7b5debd 100644 --- a/creds.h +++ b/creds.h @@ -1,12 +1,12 @@ #ifndef creds_h #define creds_h -String apikeya = ""; -const char* SSID_B = ""; -const char* PASS_B = ""; +String apikeya = "741F4992029440228F7B6B1F270728D4"; +const char* SSID_B = "harlet"; +const char* PASS_B = "turdtron"; -const char* SSID = ""; -const char* PASS = ""; +const char* SSID = "leela"; +const char* PASS = "Turdtr0n"; const char* STASSID = SSID; const char* STAPSK = PASS; @@ -15,8 +15,8 @@ const char* ssid = SSID; // your network SSID (name) const char* password = PASS; // mqtt -const char* mqtt_server_host = ""; -const char* mqtt_server_ip = ""; +const char* mqtt_server_host = "zerbert.local"; +const char* mqtt_server_ip = "192.168.100.17"; const int mqtt_server_port = 1883; // syslog diff --git a/log.h b/log.h index 1e4eba6..823bc34 100644 --- a/log.h +++ b/log.h @@ -14,6 +14,7 @@ char logbuffer[256]; int logbufferidx = 0; // end char // might need a ring buffer here, so we can keep logging mutiple messages and send delayed +bool syslogactive = true; void sendToSyslog(String msg){ #ifdef USESYSLOG @@ -33,8 +34,7 @@ void sendToSyslog(String msg){ if(msgb.indexOf("error") != -1) level = LOG_ERR; if(msgb.indexOf("warning") != -1) level = LOG_WARNING; if(msgb.indexOf("fatal") != -1) level = LOG_CRIT; - - // syslog.log(level,msg); + if(syslogactive) syslog.log(level,msg); // SEND IT // todo clean up string, remove whitespace such as CR LF \t // reset buffer logbuffer[0] = (char)0; diff --git a/wifi_funcs.h b/wifi_funcs.h index 50d2976..ba333f4 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -217,7 +217,7 @@ void checkWifi(){ if(debug_wifi){ Serial.println("[WIFI] WiFi is CONNECTED"); Serial.println("[WIFI] RSSI: "+(String)getRSSIasQuality()); - } + } #ifdef USENEOIND indSetColor(0,255,0); #endif @@ -269,7 +269,7 @@ void disableWiFi(){ // } else { // strcpy_P(buff, PSTR("Unknown")); - +#ifdef ESP32 String ESP32GetResetReason(uint32_t cpu_no) { // tools\sdk\include\esp32\rom\rtc.h switch (rtc_get_reset_reason( (RESET_REASON) cpu_no)) { @@ -291,7 +291,7 @@ String ESP32GetResetReason(uint32_t cpu_no) { default : return F("NO_MEAN"); // 0 } } - +#endif // void esp32_resetreason(RESET_REASON reason) // { From d28bff01f80d62c54d54b8cac22f1a57630c03d4 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Mar 2021 21:29:26 -0500 Subject: [PATCH 090/186] disable debugging --- button_abs.h | 42 +++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/button_abs.h b/button_abs.h index 9b9f2e3..ec063c4 100644 --- a/button_abs.h +++ b/button_abs.h @@ -23,6 +23,7 @@ bool useInt = false; // use interrupts, via interruptPin bool encoderHasPress = false; bool encoderHasHold = false; +bool debug_enc = false; volatile bool PCFInterruptFlag = false; @@ -32,40 +33,43 @@ void encoderClear(){ encoderHasChange = false; } -void ICACHE_RAM_ATTR onEncoderChange(int newValue) { +void IRAM_ATTR onEncoderChange(int newValue) { // @todo always a false trigger on start // if(encoderLast < 0){ - // Logger.println("[ENC] init fired"); + // Serial.println("[ENC] init fired"); // encoderLast = newValue; // encoderClear(); // return; // init // } if(_maximumEncoderValue > 0){ - Logger.print("[ENCODER] change to "); - Logger.print(newValue); - Logger.print(" from "); - Logger.print(encoderLast); - if(encoderLast == newValue){ - Logger.println("\n"); - return; + if(debug_enc){ + Serial.print("[ENCODER] change to "); + Serial.print(newValue); + Serial.print(" from "); + Serial.print(encoderLast); + if(encoderLast == newValue){ + Serial.println("\n"); + return; + } } bool dir = (encoderLast > newValue); - Logger.println(" dir: " + String(dir ? "CC" : "CW")); + if(debug_enc) Serial.println(" dir: " + String(dir ? "CC" : "CW")); encoderStale = encoderLast; encoderLast = newValue; encoderHasChange = true; } else{ if(newValue == 0){ - Logger.print("[ENCODER] no change"); + if(debug_enc) Serial.print("[ENCODER] no change"); return; } - Logger.print("[ENCODER] change by "); - Logger.print(newValue); + if(debug_enc){ + Serial.print("[ENCODER] change by "); + Serial.print(newValue); + } bool dir = (newValue == 1); - Logger.println(" dir: " + String(dir ? "CW" : "CC")); // for plotting use 10,20 etc - + if(debug_enc) Serial.println(" dir: " + String(dir ? "CW" : "CC")); // for plotting use 10,20 etc encoderStale = encoderLast; encoderLast = newValue; encoderHasChange = true; @@ -73,8 +77,8 @@ void ICACHE_RAM_ATTR onEncoderChange(int newValue) { } void ICACHE_RAM_ATTR onEncoderSWPressed(uint8_t pin, bool heldDown) { - Logger.print("[ENCODER] Button "); - Logger.println(heldDown ? "Held" : "Pressed"); + Serial.print("[ENCODER] Button "); + Serial.println(heldDown ? "Held" : "Pressed"); encoderHasPress = true; encoderHasHold = heldDown; } @@ -142,10 +146,10 @@ void checkAnalogSW(uint8_t pin, uint16_t value,uint32_t hold){ // IoAbstractionRef iodev = switches.getIoAbstraction(); // iodev->pinDirection(7,OUTPUT); // bool res = iodev->runLoop(); - // if(res!=1) Logger.println("devsync: " + (String)res); + // if(res!=1) Serial.println("devsync: " + (String)res); // taskManager.runLoop(); // if(!res){ - // Logger.println("error"); + // Serial.println("error"); // delay(500); // } #endif \ No newline at end of file From 0eb09bfa017ba911d4af0f3bf147ff2453007fa9 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Mar 2021 21:29:34 -0500 Subject: [PATCH 091/186] better esp32 tones --- buzzer.h | 77 +++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 68 insertions(+), 9 deletions(-) diff --git a/buzzer.h b/buzzer.h index 80fa7f8..1ae6ff7 100644 --- a/buzzer.h +++ b/buzzer.h @@ -1,9 +1,12 @@ #ifndef buzzer_h #define buzzer_h +int BUZZ_VOLUME = 100; +int buzzer_pin = -1; + #ifdef ESP8266 -#include +#include // https://github.com/Mottramlabs/ESP8266-Tone-Generator #include ESP8266_Tones BUZZER_TONE(BUZ_PIN); char szBuf[128]; // serial buffer seems to be only 128 bytes on ESP, only 64 on ATmega @@ -11,7 +14,6 @@ char szBuf[128]; // serial buffer seems to be only 128 bytes on ESP, only 64 on #include // requires #include // define the pin used and initialize a MusicEngine object MmlMusicPWM BUZZER_MUSIC(BUZ_PIN); -int BUZZ_VOLUME = 100; bool init_buzzer(){ pinMode(BUZ_PIN,OUTPUT); @@ -139,26 +141,83 @@ void soundalarm(){ #else +#include +#define BUZ_CHAN 0 + +void Chirp() { + tone(BUZ_PIN, NOTE_A7, 10); // F6 + tone(BUZ_PIN, NOTE_C8, 20); // F5 + noTone(BUZ_PIN, BUZ_CHAN); +} // End of beep + +void Bleep() { + tone(BUZ_PIN, NOTE_C7, 50, BUZ_CHAN); // F6 + tone(BUZ_PIN, NOTE_C8, 100, BUZ_CHAN); // F5 +} // End of beep + +void Tone_Down() { + tone(BUZ_PIN, NOTE_F6, 200, BUZ_CHAN); // F6 + tone(BUZ_PIN, NOTE_F5, 200, BUZ_CHAN); // F5 + tone(BUZ_PIN, NOTE_C6, 200, BUZ_CHAN); // C6 +} // End of beep + +void Tone_Up() { + tone(BUZ_PIN, NOTE_C6, 200, BUZ_CHAN); // C6 + tone(BUZ_PIN, NOTE_F5, 200, BUZ_CHAN); // F5 + tone(BUZ_PIN, NOTE_F6, 200, BUZ_CHAN); // F6 +} // End of beep + +void buzzer_test() { + Chirp(); + delay(500); + Bleep(); + delay(500); + Tone_Down(); + delay(500); + Tone_Up(); + delay(500); + + tone(BUZ_PIN, NOTE_C4, 500, BUZ_CHAN); + noTone(BUZ_PIN, BUZ_CHAN); + tone(BUZ_PIN, NOTE_D4, 500, BUZ_CHAN); + noTone(BUZ_PIN, BUZ_CHAN); + tone(BUZ_PIN, NOTE_E4, 500, BUZ_CHAN); + noTone(BUZ_PIN, BUZ_CHAN); + tone(BUZ_PIN, NOTE_F4, 500, BUZ_CHAN); + noTone(BUZ_PIN, BUZ_CHAN); + tone(BUZ_PIN, NOTE_G4, 500, BUZ_CHAN); + noTone(BUZ_PIN, BUZ_CHAN); + tone(BUZ_PIN, NOTE_A4, 500, BUZ_CHAN); + noTone(BUZ_PIN, BUZ_CHAN); + tone(BUZ_PIN, NOTE_B4, 500, BUZ_CHAN); + noTone(BUZ_PIN, BUZ_CHAN); +} + #include +bool init_buzzer(int pin){ + buzzer_pin = pin; + pinMode(buzzer_pin,OUTPUT); +} + bool init_buzzer(){ - pinMode(BUZ_PIN,OUTPUT); + init_buzzer(BUZ_PIN); } bool chime(){ - analogWrite(BUZ_PIN,500); + analogWrite(buzzer_pin,500); delay(100); - analogWrite(BUZ_PIN,500); + analogWrite(buzzer_pin,500); delay(100); - analogWrite(BUZ_PIN,0); + analogWrite(buzzer_pin,0); } bool soundalarm(){ - analogWrite(BUZ_PIN,500); + analogWrite(buzzer_pin,500); delay(100); - analogWrite(BUZ_PIN,500); + analogWrite(buzzer_pin,500); delay(100); - analogWrite(BUZ_PIN,0); + analogWrite(buzzer_pin,0); } #endif From cea53cd9596eaf59f062f3007695613a363120b5 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Mar 2021 21:29:48 -0500 Subject: [PATCH 092/186] isr test --- io_utils.h | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/io_utils.h b/io_utils.h index 1a9082f..d7fc1d8 100644 --- a/io_utils.h +++ b/io_utils.h @@ -147,4 +147,45 @@ Logger.println(analogRead(33)); } #endif + +// //ISR test +// struct Button { +// const uint8_t PIN; +// uint32_t numberKeyPresses; +// bool pressed; +// }; + +// Button button1 = {36, 0, false}; +// Button button2 = {32, 0, false}; + +// void isr_begin(){ +// pinMode(button1.PIN, INPUT_PULLUP); +// attachInterruptArg(button1.PIN, isr, &button1, FALLING); +// pinMode(button2.PIN, INPUT_PULLUP); +// attachInterrupt(button2.PIN, isr, FALLING); +// } + +// void IRAM_ATTR isr_test_a(void* arg) { +// Button* s = static_cast(arg); +// s->numberKeyPresses += 1; +// s->pressed = true; +// } + +// void IRAM_ATTR isr_test_b() { +// button2.numberKeyPresses += 1; +// button2.pressed = true; +// } + +// void process_isr_test(){ +// if (button1.pressed) { +// Serial.printf("Button 1 has been pressed %u times\n", button1.numberKeyPresses); +// button1.pressed = false; +// } +// // Serial.print(digitalRead(ENC_PINA)); +// // Serial.print(digitalRead(ENC_PINB)); +// // Serial.print(digitalRead(ENC_SW)); +// // Serial.println(" <- ENC"); +// } + + #endif \ No newline at end of file From cf2f9027238313e0380f69d601dd818f6efa6866 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Mar 2021 21:30:12 -0500 Subject: [PATCH 093/186] change pins, add re init todo --- max31855.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/max31855.h b/max31855.h index f2239f3..eee6042 100644 --- a/max31855.h +++ b/max31855.h @@ -17,11 +17,12 @@ // HW cs D8 15 // #define MAXDO 5 // HWMISO -#define MAXCS 16 // 2 +#define MAXCS 15 // 2 #define MAXCLK 14 // HWSLK -#define MAXMISO 4 -// Adafruit_MAX31855 tc(MAXCLK,MAXCS,MAXMISO); -Adafruit_MAX31855 tc(14,15,12); +#define MAXMISO 13 +Adafruit_MAX31855 tc(MAXCLK,MAXCS,MAXMISO); + +// Adafruit_MAX31855 tc(14,15,12); #ifdef TC2 Adafruit_MAX31855 tcB(1); From ce607d68119d69381315dc97072ff284545cee00 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Mar 2021 21:30:22 -0500 Subject: [PATCH 094/186] disable debug --- mqtt.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/mqtt.h b/mqtt.h index f269c3f..c908875 100644 --- a/mqtt.h +++ b/mqtt.h @@ -25,7 +25,7 @@ WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = true; +bool debug_mqtt = false; String clientID = ""; void MQTTreconnect() { @@ -221,7 +221,7 @@ void MQTT_pub_send(String topic){ char message[2048]; serializeJson(pubjson, message); - Serial.println((String)message); + // Serial.println((String)message); client.publish(topic.c_str(),message); delay(500); // pubjson.clear(); @@ -258,11 +258,12 @@ void MQTT_pub(String topic, String sensor, String value){ #endif void MQTT_pub_device(){ + Serial.println("[TASK] doMQTT Device"); MQTT_pub("device","rssi",(String)getRSSIasQuality()); #ifdef ESP32 - MQTT_pub("device","hall",(String)hallRead()); + // MQTT_pub("device","hall",(String)hallRead()); // USES PINS 36,39 MQTT_pub("device","temp",(String)temperatureRead()); - MQTT_pub("device","adc_1",(String)analogRead(39)); + // MQTT_pub("device","adc_1",(String)analogRead(39)); #endif MQTT_pub("device","uptime_s",(String)(millis()/1000)); MQTT_pub_send("device"); From 115ee1740c3b1802987eb682bc37fcaf686cdab3 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Mar 2021 21:30:38 -0500 Subject: [PATCH 095/186] task logging --- wifi_funcs.h | 1 + 1 file changed, 1 insertion(+) diff --git a/wifi_funcs.h b/wifi_funcs.h index ba333f4..b6746a7 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -198,6 +198,7 @@ int getRSSIasQuality() { } void checkWifi(){ + Serial.println("[TASK] checkWiFi"); if(WiFi.status() != WL_CONNECTED ){ if(downtime == 0) downtime = millis(); if(millis() > downtime + downtimeRestart){ From 1662ac9aa0d6ec7fa86cfbe63ee5a04046a06ef7 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 28 Mar 2021 21:30:51 -0500 Subject: [PATCH 096/186] disable pid fullpower if not needed --- pid.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pid.h b/pid.h index 2f126a0..9318089 100644 --- a/pid.h +++ b/pid.h @@ -191,7 +191,7 @@ void init_PID(){ void pidStart(){ pidTimerStart = millis(); - if(fullPowerStartup){ + if((currentTemp Date: Mon, 29 Mar 2021 23:14:46 -0500 Subject: [PATCH 097/186] Fixing up some stuff, ssr sanity fatal issue --- buzzer.h | 40 +++++++++++++++++++++------------------- ssr.h | 13 +++++++++---- 2 files changed, 30 insertions(+), 23 deletions(-) diff --git a/buzzer.h b/buzzer.h index 1ae6ff7..c473d79 100644 --- a/buzzer.h +++ b/buzzer.h @@ -169,6 +169,7 @@ void Tone_Up() { void buzzer_test() { Chirp(); + return; delay(500); Bleep(); delay(500); @@ -177,20 +178,20 @@ void buzzer_test() { Tone_Up(); delay(500); - tone(BUZ_PIN, NOTE_C4, 500, BUZ_CHAN); - noTone(BUZ_PIN, BUZ_CHAN); - tone(BUZ_PIN, NOTE_D4, 500, BUZ_CHAN); - noTone(BUZ_PIN, BUZ_CHAN); - tone(BUZ_PIN, NOTE_E4, 500, BUZ_CHAN); - noTone(BUZ_PIN, BUZ_CHAN); - tone(BUZ_PIN, NOTE_F4, 500, BUZ_CHAN); - noTone(BUZ_PIN, BUZ_CHAN); - tone(BUZ_PIN, NOTE_G4, 500, BUZ_CHAN); - noTone(BUZ_PIN, BUZ_CHAN); - tone(BUZ_PIN, NOTE_A4, 500, BUZ_CHAN); - noTone(BUZ_PIN, BUZ_CHAN); - tone(BUZ_PIN, NOTE_B4, 500, BUZ_CHAN); - noTone(BUZ_PIN, BUZ_CHAN); + // tone(BUZ_PIN, NOTE_C4, 500, BUZ_CHAN); + // noTone(BUZ_PIN, BUZ_CHAN); + // tone(BUZ_PIN, NOTE_D4, 500, BUZ_CHAN); + // noTone(BUZ_PIN, BUZ_CHAN); + // tone(BUZ_PIN, NOTE_E4, 500, BUZ_CHAN); + // noTone(BUZ_PIN, BUZ_CHAN); + // tone(BUZ_PIN, NOTE_F4, 500, BUZ_CHAN); + // noTone(BUZ_PIN, BUZ_CHAN); + // tone(BUZ_PIN, NOTE_G4, 500, BUZ_CHAN); + // noTone(BUZ_PIN, BUZ_CHAN); + // tone(BUZ_PIN, NOTE_A4, 500, BUZ_CHAN); + // noTone(BUZ_PIN, BUZ_CHAN); + // tone(BUZ_PIN, NOTE_B4, 500, BUZ_CHAN); + // noTone(BUZ_PIN, BUZ_CHAN); } #include @@ -213,11 +214,12 @@ bool chime(){ } bool soundalarm(){ - analogWrite(buzzer_pin,500); - delay(100); - analogWrite(buzzer_pin,500); - delay(100); - analogWrite(buzzer_pin,0); + Bleep(); + delay(500); + Bleep(); + delay(500); + Bleep(); + delay(500); } #endif diff --git a/ssr.h b/ssr.h index 3592324..77a1ece 100644 --- a/ssr.h +++ b/ssr.h @@ -16,17 +16,22 @@ bool DEBUG_ssr = false; bool ssrDisabled = true; // safety ON float currentDuty = 0; // ssrpower -bool invertDuty = true; // invert logic vcc range +bool invertDuty = true; // invert duty logic vcc range bool invertLOW = false; // Drive SSR with VCC int _ssrRelayPin = -1; void ssr_off(){ - if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,!invertLOW ? HIGH : LOW); + if(_ssrRelayPin >= 0){ + Logger.println("[SSR] off"); + digitalWrite(_ssrRelayPin, invertLOW ? LOW : HIGH); // @todo esp32 issue? must do analogwrite first + // analogWrite( _ssrRelayPin, 255); + } } void ssr_on(){ - if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin,!invertLOW ? LOW : HIGH); + Logger.println("[SSR] on"); + if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin, invertLOW ? HIGH : LOW); } void ssr_init(uint16_t pin){ @@ -74,7 +79,7 @@ void SetSSRFrequency( int duty,int power =1) if(duty!=currentDuty){ // if(DEBUG_ssr) Logger.println("[SSR] " + (String)duty); - if(duty<1 && DEBUG_ssr) Logger.println("[SSR]: OFF"); + if(duty<1 && DEBUG_ssr) Logger.println("[SSR]: duty OFF - " + (String)out); else{ if(DEBUG_ssr) Logger.print("[SSR] ON"); if(DEBUG_ssr) Logger.println( " - duty: " + (String)duty + " " + String( ( duty / 256.0 ) * 100) + "%" +" pow:" + String( round_f( power * 100 )) + "%" ); From d2e8766eb05470c0931dc186f5ca1cd161841571 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 31 Mar 2021 23:00:11 -0500 Subject: [PATCH 098/186] logging --- oled_i2c_sh1106.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index 96574af..d0edb24 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -204,13 +204,13 @@ void print_oled(String str,uint8_t size,bool flush){ void init_oled(bool preamble,bool pinswap = false){ Logger.println("[OLED] Initializing SSD1106 OLED"); - Logger.println("[I2C] SDA: "+(String)SDA); - Logger.println("[I2C] SCL: "+(String)SCL); + Logger.println("[OLED] SDA: "+(String)SDA); + Logger.println("[OLED] SCL: "+(String)SCL); if(pinswap){ Wire.begin(5,4); // begin(sda, scl) SWAP! - Logger.println("[I2C] pinswapped"); - Logger.println("[I2C] SDA: "+(String)SDA); - Logger.println("[I2C] SCL: "+(String)SCL); + Logger.println("[OLED] pinswapped"); + Logger.println("[OLED] SDA: "+(String)SDA); + Logger.println("[OLED] SCL: "+(String)SCL); } // Wire.setClock(400000L); #ifdef ROT From 50f896efeb5a6ec2a98d0c3c998ab12277e468d3 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 31 Mar 2021 23:01:17 -0500 Subject: [PATCH 099/186] reworking pid and ssr libs add 3 level safety control handle invert duty and logic with esp32 analogwrite shim lib --- pid.h | 5 ++- ssr.h | 115 +++++++++++++++++++++++++++++++++++++++------------------- 2 files changed, 80 insertions(+), 40 deletions(-) diff --git a/pid.h b/pid.h index 9318089..228bde9 100644 --- a/pid.h +++ b/pid.h @@ -24,7 +24,7 @@ // da fuq? uint16_t fullPowerPeriod = 8000; // full power startup pulse period -bool fullPowerStartup = true; // enable full power period +bool fullPowerStartup = true; // enable full power period if startup wanted temp is greater than 5 degrees(arb) bool pidEnabled = false; int long pidTimerStart = 0; @@ -191,7 +191,7 @@ void init_PID(){ void pidStart(){ pidTimerStart = millis(); - if((currentTemp5) && fullPowerStartup){ myPID.SetMode(MANUAL); Output = 250; // output never returns to normal !!!! } @@ -225,6 +225,7 @@ void run_PID(){ // Logger.print(Output); if(fullPowerStartup){ if(millis()-pidTimerStart < fullPowerPeriod){ + // handled on startup atm } else if(myPID.GetMode() == MANUAL){ Output = 0; diff --git a/ssr.h b/ssr.h index 77a1ece..43f71b0 100644 --- a/ssr.h +++ b/ssr.h @@ -13,39 +13,29 @@ bool DEBUG_ssr = true; #else bool DEBUG_ssr = false; #endif - + bool ssrDisabled = true; // safety ON float currentDuty = 0; // ssrpower -bool invertDuty = true; // invert duty logic vcc range -bool invertLOW = false; // Drive SSR with VCC +bool invertDuty = true; // invert duty logic vcc range, true for low side sinking, pwm is high pulse +bool invertLOW = !invertDuty; // Drive SSR with VCC // invert logic for 2 state relay, this is usually opposite of invertDuty int _ssrRelayPin = -1; -void ssr_off(){ - if(_ssrRelayPin >= 0){ - Logger.println("[SSR] off"); - digitalWrite(_ssrRelayPin, invertLOW ? LOW : HIGH); // @todo esp32 issue? must do analogwrite first - // analogWrite( _ssrRelayPin, 255); - } -} - -void ssr_on(){ - Logger.println("[SSR] on"); - if(_ssrRelayPin > 0) digitalWrite(_ssrRelayPin, invertLOW ? HIGH : LOW); -} - void ssr_init(uint16_t pin){ - Logger.println("[SSR] ready on pin " + (String)_ssrRelayPin); - _ssrRelayPin = pin; - pinMode( _ssrRelayPin, OUTPUT ); - delay(600); - ssr_off(); - #ifdef ESP8266 analogWriteRange(255); // esp8266 // analogWriteFreq(120); // min 100hz #elif defined(ESP32) - #endif + // analogWriteResolution(_ssrRelayPin, 8); + #endif + + //ssr enable + + Serial.println("[SSR] READY on pin " + (String)_ssrRelayPin); + _ssrRelayPin = pin; + // ssr_off(); + digitalWrite(_ssrRelayPin, invertLOW ? LOW : HIGH); + pinMode( _ssrRelayPin, OUTPUT ); } void ssr_init(){ @@ -55,6 +45,7 @@ void ssr_init(){ // This is where the SSR is controlled via PWM void SetSSRFrequency( int duty,int power =1) { + if(duty!=currentDuty){ // calculate the wanted duty based on settings power override duty = ((float)duty * power ); // power adjust duty = constrain( round_f( duty ), 0, 255); // round and clamp @@ -69,25 +60,43 @@ void SetSSRFrequency( int duty,int power =1) #ifdef ESP8266 analogWrite( _ssrRelayPin, out); #elif defined(ESP32) + Serial.println("[DAC] - " + (String)out); analogWrite( _ssrRelayPin, out); // dacWrite(_ssrRelayPin,out); #endif // if(duty == 0)ssr_off(); // if(duty == 255)ssr_on(); } - else ssr_off(); // ENFORCE SAFETY + // else ssr_off(); // ENFORCE SAFETY - if(duty!=currentDuty){ // if(DEBUG_ssr) Logger.println("[SSR] " + (String)duty); - if(duty<1 && DEBUG_ssr) Logger.println("[SSR]: duty OFF - " + (String)out); + if(duty<1 && DEBUG_ssr) Logger.println("[SSR]: Duty OFF - " + (String)out); else{ - if(DEBUG_ssr) Logger.print("[SSR] ON"); + if(DEBUG_ssr) Logger.print("[SSR] Duty ON"); if(DEBUG_ssr) Logger.println( " - duty: " + (String)duty + " " + String( ( duty / 256.0 ) * 100) + "%" +" pow:" + String( round_f( power * 100 )) + "%" ); } } currentDuty = duty; } +void ssr_off(){ + if(_ssrRelayPin >= 0){ + Logger.println("[SSR] OFF"); + SetSSRFrequency(0); //working + analogWrite( _ssrRelayPin, invertDuty ? 255 : 0 ); // MUST use analogwrite if using shim lib + // digitalWrite(_ssrRelayPin, invertLOW ? LOW : HIGH); // @todo esp32 issue? must do analogwrite first + } +} + +void ssr_on(){ + if(_ssrRelayPin > 0) { + Logger.println("[SSR] ON"); + SetSSRFrequency(255); // working + analogWrite( _ssrRelayPin, invertDuty ? 0: 255); + // digitalWrite(_ssrRelayPin, invertLOW ? HIGH : LOW); + } +} + void setSSR(int duty){ SetSSRFrequency(duty); } @@ -107,11 +116,27 @@ float getSSRPower(){ } void ssr_resume(){ - if(_ssrRelayPin > 0) setSSR(currentDuty); + Serial.println("[SSR] ssr_resume"); + if(_ssrRelayPin >= 0) setSSR(currentDuty); } void disableSSR(bool disabled = true){ + Serial.println("[SSR] disable ssr - " + (String)disabled); + setSSR(0); + ssr_off(); ssrDisabled = disabled; + // init safe state, lockdown + pinMode(_ssrRelayPin,INPUT_PULLUP); +} + +void enableSSR(bool disabled = true){ + Serial.println("[SSR] disable ssr - " + (String)disabled); + setSSR(0); + ssr_off(); + ssrDisabled = disabled; + // init safe state + pinMode(_ssrRelayPin,OUTPUT); + ssr_off(); } void toggleSSR(){ @@ -154,21 +179,35 @@ void ssrTest(int speed){ } void ssrPing(int speed){ - + Serial.println("[SSR] PING"); + + ssrDisabled = false; + ssr_off(); + ssr_off(); + + delay(500); ssr_on(); - delay(1000); + delay(speed*3); ssr_off(); + delay(speed*3); + ssr_on(); + delay(speed*2); + ssr_off(); + delay(speed*2); + ssr_on(); + delay(speed); - for(int i=0;i<255;i+20){ - SetSSRFrequency( i ); - delay(100); - } + // for(int i=0;i<255;i+20){ + // SetSSRFrequency( i ); + // delay(100); + // } - for(int i=0;i<255;i+20){ - SetSSRFrequency( 255-i ); - delay(100); - } + // for(int i=0;i<255;i+20){ + // SetSSRFrequency( 255-i ); + // delay(100); + // } ssr_off(); + ssrDisabled = true; } #endif \ No newline at end of file From 684a8b7ea375207462805961e9caba13409eb52b Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 4 Apr 2021 22:26:44 -0500 Subject: [PATCH 100/186] minor stuff --- httpportal.h | 10 +++++++--- sense_env.h | 2 +- temp_logger.h | 1 - wifi_funcs.h | 10 +++++++--- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/httpportal.h b/httpportal.h index 939c64d..b93de8b 100644 --- a/httpportal.h +++ b/httpportal.h @@ -1,18 +1,22 @@ #ifndef httpportal_h #define httpportal_h -#include +// @USES wifimanager portal +#include #include + WiFiManager portal(Logger); void init_httpportal(String title = ""){ - portal.setDebugOutput(true,"[HTTPP] "); + portal.setDebugOutput(true,"[HTTPP] "); // invert theme, dark portal.setDarkMode(true); std::vector menu = {"wifi","param","info","sep","update","restart","exit"}; portal.setMenu(menu); // custom menu, pass vector portal.setTitle(title); + // portal.setBackButton(true); + // portal.setHostname(getHostname()); } void begin_httpportal(){ @@ -20,7 +24,7 @@ void begin_httpportal(){ } void stop_httpportal(){ - + portal.stopWebPortal(); } void process_httpportal(){ diff --git a/sense_env.h b/sense_env.h index ab0099e..20d7637 100644 --- a/sense_env.h +++ b/sense_env.h @@ -3,7 +3,7 @@ #include -Average avg_a(10); +Average avg_a(20); // supported sensors // SHT31 diff --git a/temp_logger.h b/temp_logger.h index f77438e..0ca1532 100644 --- a/temp_logger.h +++ b/temp_logger.h @@ -6,7 +6,6 @@ // #include // #endif -#include #include #include diff --git a/wifi_funcs.h b/wifi_funcs.h index b6746a7..075f23c 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -106,6 +106,7 @@ String getDeviecID(){ } void setWiFiHostname(const char* hostname){ + // @todo add string templ #ifdef ESP32 WiFi.setHostname(hostname); #else @@ -115,7 +116,7 @@ void setWiFiHostname(const char* hostname){ String getHostname(){ #ifdef ESP32 - return WiFi.getHostname(); // getHostName ( @todo return string of c.str?) + return WiFi.getHostname(); // getHostName ( @todo return string or c.str?) #else return WiFi.hostname(); // getHostName #endif @@ -140,6 +141,9 @@ void init_WiFi(int timeout){ // WiFi_print_sta(); // return; // } + + WiFi.printDiag(Serial); + Serial.println("[WIFI] mode STA"); WiFi.mode(WIFI_STA); #ifdef ESP8266 WiFi.setSleepMode(WIFI_NONE_SLEEP); @@ -150,8 +154,8 @@ void init_WiFi(int timeout){ // WiFi.hostname(hostname); unsigned long start = millis(); - if(wifiIsAutoConnect) WiFi.begin(); - else WiFi.begin(SSID,PASS); + // if(wifiIsAutoConnect) WiFi.begin(); + WiFi.begin(SSID,PASS); if(timeout > 0){ Serial.println("[WIFI] Connecting to wifi... [" + (String)timeout + " ms]\n"); while((WiFi.status() != WL_CONNECTED) && (millis()-start < timeout)){ From bbb7153b1a140ac722601994ca275552085eeefb Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 7 Apr 2021 21:07:06 -0500 Subject: [PATCH 101/186] adds json and littlefs storage --- json.h | 46 +++++++++++++++++ storage.h | 148 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 json.h create mode 100644 storage.h diff --git a/json.h b/json.h new file mode 100644 index 0000000..9d2b943 --- /dev/null +++ b/json.h @@ -0,0 +1,46 @@ +#ifndef json_h +#define json_h + +#include + + +void json_test(){ + char json[] = + "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; + + // Deserialize the JSON document + DeserializationError error = deserializeJson(doc, json); + // deserializeJson(doc, STREAM); + + // Test if parsing succeeds. + if (error) { + Serial.print(F("deserializeJson() failed: ")); + Serial.println(error.f_str()); + return; + } + + serializeJsonPretty(json, Serial); + + const char* sensor = doc["sensor"]; + long time = doc["time"]; + double latitude = doc["data"][0]; + double longitude = doc["data"][1]; + + // Print values. + Serial.println(sensor); + Serial.println(time); + Serial.println(latitude, 6); + Serial.println(longitude, 6); + + // The filter: it contains "true" for each value we want to keep + // StaticJsonDocument<200> filter; + // filter["list"][0]["dt"] = true; + // filter["list"][0]["main"]["temp"] = true; + + // // Deserialize the document + // StaticJsonDocument<400> doc; + // deserializeJson(doc, input_json, DeserializationOption::Filter(filter)); + +} + +#endif \ No newline at end of file diff --git a/storage.h b/storage.h new file mode 100644 index 0000000..ac12ae8 --- /dev/null +++ b/storage.h @@ -0,0 +1,148 @@ +#ifndef storage_h +#define storage_h + +#include +#include + + + + +void listDir(const char * dirname) { + Serial.printf("Listing directory: %s\n", dirname); + + Dir root = LittleFS.openDir(dirname); + + while (root.next()) { + File file = root.openFile("r"); + Serial.print(" FILE: "); + Serial.print(root.fileName()); + Serial.print(" SIZE: "); + Serial.print(file.size()); + time_t cr = file.getCreationTime(); + time_t lw = file.getLastWrite(); + file.close(); + struct tm * tmstruct = localtime(&cr); + Serial.printf(" CREATION: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec); + tmstruct = localtime(&lw); + Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec); + } +} + + +void readFile(const char * path) { + Serial.printf("Reading file: %s\n", path); + + File file = LittleFS.open(path, "r"); + if (!file) { + Serial.println("Failed to open file for reading"); + return; + } + + Serial.print("Read from file: "); + while (file.available()) { + Serial.write(file.read()); + } + file.close(); +} + +void writeFile(const char * path, const char * message) { + Serial.printf("Writing file: %s\n", path); + + File file = LittleFS.open(path, "w"); + if (!file) { + Serial.println("Failed to open file for writing"); + return; + } + if (file.print(message)) { + Serial.println("File written"); + } else { + Serial.println("Write failed"); + } + delay(2000); // Make sure the CREATE and LASTWRITE times are different + file.close(); +} + +void appendFile(const char * path, const char * message) { + Serial.printf("Appending to file: %s\n", path); + + File file = LittleFS.open(path, "a"); + if (!file) { + Serial.println("Failed to open file for appending"); + return; + } + if (file.print(message)) { + Serial.println("Message appended"); + } else { + Serial.println("Append failed"); + } + file.close(); +} + +void renameFile(const char * path1, const char * path2) { + Serial.printf("Renaming file %s to %s\n", path1, path2); + if (LittleFS.rename(path1, path2)) { + Serial.println("File renamed"); + } else { + Serial.println("Rename failed"); + } +} + +void deleteFile(const char * path) { + Serial.printf("Deleting file: %s\n", path); + if (LittleFS.remove(path)) { + Serial.println("File deleted"); + } else { + Serial.println("Delete failed"); + } +} + +void storage_test_basic(){ + if (!LittleFS.begin()) { + Serial.println("LittleFS mount failed"); + return; + } + const char * path = "/hello.txt"; + File file = LittleFS.open(path, "r"); + if (!file) { + Serial.println("Failed to open file for reading"); + return; + } + + Serial.print("Read from file: "); + while (file.available()) { + Serial.write(file.read()); + // read into buffer or use stream + } + file.close(); + LittleFS.end(); +} + +void storage_test_full(){ + Serial.println("Formatting LittleFS filesystem"); + LittleFS.format(); + Serial.println("Mount LittleFS"); + if (!LittleFS.begin()) { + Serial.println("LittleFS mount failed"); + return; + } + listDir("/"); + deleteFile("/hello.txt"); + writeFile("/hello.txt", "Hello "); + appendFile("/hello.txt", "World!\n"); + listDir("/"); + + Serial.println("The timestamp should be valid above"); + + Serial.println("Now unmount and remount and perform the same operation."); + Serial.println("Timestamp should be valid, data should be good."); + LittleFS.end(); + Serial.println("Now mount it"); + if (!LittleFS.begin()) { + Serial.println("LittleFS mount failed"); + return; + } + readFile("/hello.txt"); + listDir("/"); +} + +#endif \ No newline at end of file From d3dd84153a7b4285543219cc71f183949756a978 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 8 Apr 2021 22:48:33 -0500 Subject: [PATCH 102/186] change hostname to const char This might have to adjust later if setting via web ui --- mqtt.h | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/mqtt.h b/mqtt.h index c908875..049bb83 100644 --- a/mqtt.h +++ b/mqtt.h @@ -26,7 +26,7 @@ WiFiClient espClient; PubSubClient client(espClient); bool debug_mqtt = false; -String clientID = ""; +const char* clientID = ""; void MQTTreconnect() { @@ -34,9 +34,9 @@ void MQTTreconnect() { // this is blocking if (!client.connected()) { // while (!client.connected()) { - Logger.println("[MQTT] Connecting..."); + if(debug_mqtt) Logger.println("[MQTT] Connecting..."); // Attempt to connect - if (client.connect(clientID.c_str())) { + if (client.connect(clientID)) { Logger.println("[MQTT] Connected"); // Once connected, publish an announcement... client.publish("TESTOUT", "hello world"); @@ -44,8 +44,7 @@ void MQTTreconnect() { client.subscribe("TESTIN"); } else { Logger.print("[ERROR] [MQTT] failed, rc="); - Logger.print(client.state()); - Logger.println(" try again in 5 seconds"); + Logger.println(client.state()); // Wait 5 seconds before retrying // delay(5000); } @@ -84,7 +83,7 @@ void mqtt_checkconn(){ // Attempt to reconnect if (mqttReconnect()) { lastReconnectAttempt = 0; - client.connect(clientID.c_str()); + client.connect(clientID); } } } else { @@ -102,7 +101,7 @@ void process_MQTT_nb(){ void process_MQTT(){ if(!wifiIsConnected()) return; - MQTTreconnect(); + MQTTreconnect(); // @todo throttle client.loop(); // will wait loop reconnect to mqtt } @@ -110,7 +109,7 @@ void init_MQTT(){ if(!wifiIsConnected()) return; client.setServer(mqtt_server_ip, mqtt_server_port); client.setCallback(MQTTcallback); - if (client.connect(clientID.c_str())) Logger.println("[MQTT] connected"); + if (client.connect(clientID)) Logger.println("[MQTT] connected"); client.setBufferSize(2048); client.subscribe("downstream"); process_MQTT(); @@ -118,11 +117,16 @@ void init_MQTT(){ // jsondata = pubjson.createNestedArray(); } -void init_MQTT(String clientid){ +void init_MQTT(const char* clientid){ clientID = clientid; // global init_MQTT(); } +void init_MQTT(String clientid){ + clientID = clientid.c_str(); // global + init_MQTT(); +} + #ifdef USEJSON void MQTT_pub(String topic, String sensor, String value){ From befd43e6ea0e678acae23d01de5b370de4299122 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 11 Apr 2021 22:46:48 -0500 Subject: [PATCH 103/186] fixup strip neopixel --- neopixel_helper.h | 53 ++++++++++++++++++++++++++++++++++++++++++++++- wifi_funcs.h | 2 +- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/neopixel_helper.h b/neopixel_helper.h index 3233a27..9c1c68f 100644 --- a/neopixel_helper.h +++ b/neopixel_helper.h @@ -8,7 +8,7 @@ bool DEBUG_neohelp = false; #endif uint16_t NEOBRIGHTNESS = 100; -int NEONUMPIXELS = 1; +int NEONUMPIXELS = 5; #define NEOPIXELSTYPE NEO_GRB + NEO_KHZ800 #include @@ -345,6 +345,31 @@ void NEO_nb_animate(){ if(millis() - NEO_lastUpdate > NEO_ANIMDELAY) NEO_nb_rainbow(); } +void rainbow(int wait) { + // Hue of first pixel runs 3 complete loops through the color wheel. + // Color wheel has a range of 65536 but it's OK if we roll over, so + // just count from 0 to 3*65536. Adding 256 to firstPixelHue each time + // means we'll make 3*65536/256 = 768 passes through this outer loop: + for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) { + // for(int i=0; i Date: Fri, 30 Apr 2021 18:36:20 -0500 Subject: [PATCH 104/186] jsontest --- jsontest.cpp => jsontest.h | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename jsontest.cpp => jsontest.h (100%) diff --git a/jsontest.cpp b/jsontest.h similarity index 100% rename from jsontest.cpp rename to jsontest.h From 468539fd4859dcf71b4cd3b040410c9f4624ca3d Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 30 Apr 2021 18:36:32 -0500 Subject: [PATCH 105/186] Create i2c_identify.h --- i2c_identify.h | 181 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 i2c_identify.h diff --git a/i2c_identify.h b/i2c_identify.h new file mode 100644 index 0000000..9e68f6f --- /dev/null +++ b/i2c_identify.h @@ -0,0 +1,181 @@ +I2CDiscoverDevice + +enum { + DEVICE_UNKNOWN = 0, + DEVICE_SSD1306, + DEVICE_SH1106, + DEVICE_VL53L0X, + DEVICE_BMP180, + DEVICE_BMP280, + DEVICE_BME280, + DEVICE_MPU6000, + DEVICE_MPU9250, + DEVICE_MCP9808, + DEVICE_LSM6DS3, + DEVICE_ADXL345, + DEVICE_ADS1115, + DEVICE_MAX44009, + DEVICE_MAG3110, + DEVICE_CCS811, + DEVICE_HTS221, + DEVICE_LPS25H, + DEVICE_LSM9DS1, + DEVICE_LM8330, + DEVICE_DS3231, + DEVICE_LIS3DH, + DEVICE_LIS3DSH, + DEVICE_INA219, + DEVICE_SHT3X, + DEVICE_HDC1080, + DEVICE_MPU6886, + DEVICE_BME680 +}; + +int I2CReadRegister(BBI2C *pI2C, uint8_t iAddr, uint8_t u8Register, uint8_t *pData, int iLen){ + +} + +// Figure out what device is at that address +// returns the enumerated value +// +int I2CDiscoverDevice(BBI2C *pI2C, uint8_t i) +{ +uint8_t j, cTemp[8]; +int iDevice = DEVICE_UNKNOWN; + + if (i == 0x3c || i == 0x3d) // Probably an OLED display + { + I2CReadRegister(pI2C, i, 0x00, cTemp, 1); + cTemp[0] &= 0xbf; // mask off power on/off bit + if (cTemp[0] == 0x8) // SH1106 + iDevice = DEVICE_SH1106; + else if (cTemp[0] == 3 || cTemp[0] == 6) + iDevice = DEVICE_SSD1306; + return iDevice; + } + if (i >= 0x40 && i <= 0x4f) // check for TI INA219 power measurement sensor + { + I2CReadRegister(pI2C, i, 0x00, cTemp, 2); + if (cTemp[0] == 0x39 && cTemp[1] == 0x9f) + return DEVICE_INA219; + } +// else if (i == 0x5b) // MLX90615? +// { +// I2CReadRegister(pI2C, i, 0x10, cTemp, 3); +// for (j=0; j<3; j++) Serial.println(cTemp[j], HEX); +// } + // try to identify it from the known devices using register contents + { + // Check for TI HDC1080 + I2CReadRegister(pI2C, i, 0xff, cTemp, 2); + if (cTemp[0] == 0x10 && cTemp[1] == 0x50) + return DEVICE_HDC1080; + + // Check for BME680 + if (i == 0x76 || i == 0x77) + { + I2CReadRegister(pI2C, i, 0xd0, cTemp, 1); // chip ID + if (cTemp[0] == 0x61) // BME680 + return DEVICE_BME680; + } + // Check for VL53L0X + I2CReadRegister(pI2C, i, 0xc0, cTemp, 3); + if (cTemp[0] == 0xee && cTemp[1] == 0xaa && cTemp[2] == 0x10) + return DEVICE_VL53L0X; + + // Check for CCS811 + I2CReadRegister(pI2C, i, 0x20, cTemp, 1); + if (cTemp[0] == 0x81) // Device ID + return DEVICE_CCS811; + + // Check for LIS3DSH accelerometer from STMicro + I2CReadRegister(pI2C, i, 0x0f, cTemp, 1); + if (cTemp[0] == 0x3f) // WHO_AM_I + return DEVICE_LIS3DSH; + + // Check for LIS3DH accelerometer from STMicro + I2CReadRegister(pI2C, i, 0x0f, cTemp, 1); + if (cTemp[0] == 0x33) // WHO_AM_I + return DEVICE_LIS3DH; + + // Check for LSM9DS1 magnetometer/gyro/accel sensor from STMicro + I2CReadRegister(pI2C, i, 0x0f, cTemp, 1); + if (cTemp[0] == 0x68) // WHO_AM_I + return DEVICE_LSM9DS1; + + // Check for LPS25H pressure sensor from STMicro + I2CReadRegister(pI2C, i, 0x0f, cTemp, 1); + if (cTemp[0] == 0xbd) // WHO_AM_I + return DEVICE_LPS25H; + + // Check for HTS221 temp/humidity sensor from STMicro + I2CReadRegister(pI2C, i, 0x0f, cTemp, 1); + if (cTemp[0] == 0xbc) // WHO_AM_I + return DEVICE_HTS221; + + // Check for MAG3110 + I2CReadRegister(pI2C, i, 0x07, cTemp, 1); + if (cTemp[0] == 0xc4) // WHO_AM_I + return DEVICE_MAG3110; + + // Check for LM8330 keyboard controller + I2CReadRegister(pI2C, i, 0x80, cTemp, 2); + if (cTemp[0] == 0x0 && cTemp[1] == 0x84) // manufacturer code + software revision + return DEVICE_LM8330; + + // Check for MAX44009 + if (i == 0x4a || i == 0x4b) + { + for (j=0; j<8; j++) + I2CReadRegister(pI2C, i, j, &cTemp[j], 1); // check for power-up reset state of registers + if ((cTemp[2] == 3 || cTemp[2] == 2) && cTemp[6] == 0 && cTemp[7] == 0xff) + return DEVICE_MAX44009; + } + + // Check for ADS1115 + I2CReadRegister(pI2C, i, 0x02, cTemp, 2); // Lo_thresh defaults to 0x8000 + I2CReadRegister(pI2C, i, 0x03, &cTemp[2], 2); // Hi_thresh defaults to 0x7fff + if (cTemp[0] == 0x80 && cTemp[1] == 0x00 && cTemp[2] == 0x7f && cTemp[3] == 0xff) + return DEVICE_ADS1115; + + // Check for MCP9808 + I2CReadRegister(pI2C, i, 0x06, cTemp, 2); // manufacturer ID && get device ID/revision + I2CReadRegister(pI2C, i, 0x07, &cTemp[2], 2); // need to read them individually + if (cTemp[0] == 0 && cTemp[1] == 0x54 && cTemp[2] == 0x04 && cTemp[3] == 0x00) + return DEVICE_MCP9808; + + // Check for BMP280/BME280 + I2CReadRegister(pI2C, i, 0xd0, cTemp, 1); + if (cTemp[0] == 0x55) // BMP180 + return DEVICE_BMP180; + else if (cTemp[0] == 0x58) + return DEVICE_BMP280; + else if (cTemp[0] == 0x60) // BME280 + return DEVICE_BME280; + + // Check for LSM6DS3 + I2CReadRegister(pI2C, i, 0x0f, cTemp, 1); // WHO_AM_I + if (cTemp[0] == 0x69) + return DEVICE_LSM6DS3; + + // Check for ADXL345 + I2CReadRegister(pI2C, i, 0x00, cTemp, 1); // DEVID + if (cTemp[0] == 0xe5) + return DEVICE_ADXL345; + + // Check for MPU-60x0i, MPU-688x, and MPU-9250 + I2CReadRegister(pI2C, i, 0x75, cTemp, 1); + if (cTemp[0] == (i & 0xfe)) // Current I2C address (low bit set to 0) + return DEVICE_MPU6000; + else if (cTemp[0] == 0x71) + return DEVICE_MPU9250; + else if (cTemp[0] == 0x19) + return DEVICE_MPU6886; + + // Check for DS3231 RTC + I2CReadRegister(pI2C, i, 0x0e, cTemp, 1); // read the control register + if (i == 0x68 && cTemp[0] == 0x1c) // fixed I2C address and power on reset value + return DEVICE_DS3231; + } + return iDevice; +} /* I2CDiscoverDevice() */ \ No newline at end of file From 8f73f4bcf85dc835e2abe3ba05f5670777e8d483 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 30 Apr 2021 18:36:58 -0500 Subject: [PATCH 106/186] mdns ? --- mqtt.h | 2 +- neopixel_helper.h | 2 +- ota.h | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/mqtt.h b/mqtt.h index 049bb83..7b08e75 100644 --- a/mqtt.h +++ b/mqtt.h @@ -43,7 +43,7 @@ void MQTTreconnect() { // ... and resubscribe client.subscribe("TESTIN"); } else { - Logger.print("[ERROR] [MQTT] failed, rc="); + Logger.print("[ERROR] [MQTT] failed, rc="); // @todo we get here but no actual reconnnect loop, why? Logger.println(client.state()); // Wait 5 seconds before retrying // delay(5000); diff --git a/neopixel_helper.h b/neopixel_helper.h index 9c1c68f..ee77988 100644 --- a/neopixel_helper.h +++ b/neopixel_helper.h @@ -327,7 +327,7 @@ void flasherSmooth(uint32_t colorA, uint32_t colorB,int waitA, int waitB){ } unsigned long NEO_lastUpdate = 0 ; // for millis() when last update occoured -uint32_t NEO_ANIMDELAY = 60; +uint32_t NEO_ANIMDELAY = 10; void NEO_nb_rainbow() { // modified from Adafruit example to make it a state machine static uint16_t neo_j=128; diff --git a/ota.h b/ota.h index 09232e7..467abb8 100644 --- a/ota.h +++ b/ota.h @@ -20,7 +20,9 @@ uint lastprogress = 0; // micros timestamp uint progressthrottle = 0;// progress serial throttle, should make ota faster void handleOTA(){ - // MDNS.update(); // handled by ota, not required + #ifdef ESP8266 + MDNS.update(); // handled by ota, not required + #endif ArduinoOTA.handle(); } From 77c7fde24a5646678c765b8a5b32b7838094a296 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 30 Apr 2021 18:37:10 -0500 Subject: [PATCH 107/186] add pcf8591 --- sense_env.h | 129 ++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 119 insertions(+), 10 deletions(-) diff --git a/sense_env.h b/sense_env.h index 20d7637..3afecec 100644 --- a/sense_env.h +++ b/sense_env.h @@ -69,13 +69,25 @@ Lux Range: 188 uLux sensitivity, up to 88,000 Lux input measurements. Temperature range: -30 to 80 *C Voltage range: 3.3-5V into onboard regulator Interface: I2C + */ +#define INA219 // INA219 current sense + +#define PCF8591 // PCF8591 // [I2C] Device found - ADDR: 0x23 // BH1750 // [I2C] Device found - ADDR: 0x39 // APDS9960 / TSL2561 // [I2C] Device found - ADDR: 0x5A // // [I2C] Device found - ADDR: 0x76 // +// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x23 0x46 +// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x39 0x72 +// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x44 0x88 +// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x48 0x90 +// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x5A 0xB4 +// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x68 0xD0 +// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x76 0xEC + /* #ifdef ENV_TEMPLATE #include @@ -102,24 +114,121 @@ float get_env(uint8_t channel = 0){ #endif */ -/***************************************** -#ifdef ENV_TEMPLATE -#include +#ifdef PCF8591 +#include +// Make sure that this is set to the value in volts of VCC +#define ADC_REFERENCE_VOLTAGE 5.0 +Adafruit_PCF8591 pcf = Adafruit_PCF8591(); -bool init_env(){ +bool init_PCF8591(){ + bool ret = false; + ret = pcf.begin(); + if(!ret){ + Logger.println("[ERROR] PCF8591 init failed"); + return false; + } + else Logger.println("[ENV] PCF8591 initialized!"); + pcf.enableDAC(true); + return ret; } -void print_env(){ +float int_to_volts(uint16_t dac_value, uint8_t bits, float logic_level) { + return (((float)dac_value / ((1 << bits) - 1)) * logic_level); } -float get_env(uint8_t channel = 0){ +void print_PCF8591(){ + pcf.analogWrite(random(255)); + // Make a triangle wave on the DAC output + // pcf.analogWrite(dac_counter++); + Logger.print((pcf.analogRead(0))); + Logger.print(", "); + Logger.print((pcf.analogRead(1))); + Logger.print(", "); + Logger.print((pcf.analogRead(2))); + Logger.print(", "); + Logger.print((pcf.analogRead(3))); + Logger.print(""); + Logger.println(""); + + Logger.print(int_to_volts(pcf.analogRead(0), 8, ADC_REFERENCE_VOLTAGE)); + Logger.print("V, "); + Logger.print(int_to_volts(pcf.analogRead(1), 8, ADC_REFERENCE_VOLTAGE)); + Logger.print("V, "); + Logger.print(int_to_volts(pcf.analogRead(2), 8, ADC_REFERENCE_VOLTAGE)); + Logger.print("V, "); + Logger.print(int_to_volts(pcf.analogRead(3), 8, ADC_REFERENCE_VOLTAGE)); + Logger.print("V"); + Logger.println(""); +} + + +float get_PCF8591(uint8_t channel = 0, bool volts=false){ // print_env(); - if(channel == 0) return ; - if(channel == 1) return ; - if(channel == 2) return ; + if(volts){ + if(channel == 0) return int_to_volts(pcf.analogRead(0), 8, ADC_REFERENCE_VOLTAGE); + if(channel == 1) return int_to_volts(pcf.analogRead(1), 8, ADC_REFERENCE_VOLTAGE); + if(channel == 2) return int_to_volts(pcf.analogRead(2), 8, ADC_REFERENCE_VOLTAGE); + if(channel == 3) return int_to_volts(pcf.analogRead(3), 8, ADC_REFERENCE_VOLTAGE); + } + else { + if(channel == 0) return pcf.analogRead(0); + if(channel == 1) return pcf.analogRead(1); + if(channel == 2) return pcf.analogRead(2); + if(channel == 3) return pcf.analogRead(3); + } +} #endif -*********************************************/ + + +#ifdef INA219 +#include + +Adafruit_INA219 ina219; + +bool init_INA219(){ + bool ret = false; + ret = ina219.begin(); + if(!ret){ + Logger.println("[ERROR] INA219 init failed"); + } + else Logger.println("[ENV] INA219 initialized!"); + return ret; +} + +void print_INA219(){ + float shuntvoltage = 0; + float busvoltage = 0; + float current_mA = 0; + float loadvoltage = 0; + float power_mW = 0; + + shuntvoltage = ina219.getShuntVoltage_mV(); + busvoltage = ina219.getBusVoltage_V(); + current_mA = ina219.getCurrent_mA(); + power_mW = ina219.getPower_mW(); + loadvoltage = busvoltage + (shuntvoltage / 1000); + + Logger.print("Bus Voltage: "); Logger.print(busvoltage); Logger.println(" V"); + Logger.print("Shunt Voltage: "); Logger.print(shuntvoltage); Logger.println(" mV"); + Logger.print("Load Voltage: "); Logger.print(loadvoltage); Logger.println(" V"); + Logger.print("Current: "); Logger.print(current_mA); Logger.println(" mA"); + Logger.print("Power: "); Logger.print(power_mW); Logger.println(" mW"); + Logger.println(""); +} + +float get_INA219(uint8_t channel = 0){ + print_INA219(); + float shuntvoltage = ina219.getShuntVoltage_mV(); + float busvoltage = ina219.getBusVoltage_V(); + if(channel == 0) return shuntvoltage; + if(channel == 1) return busvoltage; + if(channel == 2) return ina219.getCurrent_mA(); + if(channel == 3) return ina219.getPower_mW(); + if(channel == 4) return busvoltage + (shuntvoltage / 1000); +} +#endif + #ifdef MPU6050 #include From 7ea385ca3d8fa101480a951a6a8a3ef0a53d708a Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 30 Apr 2021 18:37:19 -0500 Subject: [PATCH 108/186] fixup --- oled_i2c_sh1106.h | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index d0edb24..bd1e2fb 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -19,6 +19,8 @@ #include #endif +// Wire.begin(SDA,SCL); +// Wire.setClock(400000L); // const char WIFI_SYMBOL[] = { 93,94,123,168, 176, 247, 253, 263, 277,278,279,280,281, '\0'}; #define GLYPH_BELL 93 // bell @@ -57,6 +59,7 @@ #define GLYPH_SQUARE 217 // bell #define GLYPH_SPACE 287 // bell #define GLYPH_NO 87 // busted +#define GLYPH_COFFEE 2615 // busted // const char* testing = u8"\u0263\u0BA3\u0B82"; @@ -248,8 +251,8 @@ void init_oled(bool preamble,bool pinswap = false){ lcd.println("Booting...."); lcd.display(); delay(1000); - lcd.clearDisplay(); - lcd.display(); + lcd.clearBuffer(); + lcd.sendBuffer(); } void displayFPS(){ @@ -301,20 +304,20 @@ int printValuePair(const char* str,String strb,int x,int y){ void oled_test(uint8_t num = 0){ // print_oled_line(msg, line, size); for(uint8_t i=0;i Date: Sun, 2 May 2021 21:30:40 -0500 Subject: [PATCH 109/186] ntc and pcf8591 mods --- max31855.h | 1 - ntc.h | 12 ++++++++---- ntc_multi.h | 53 ++++++++++++++++++++++++++++++++++++++++++++--------- ntc_test.h | 17 +++++++++++++++++ sense_env.h | 50 +++++++++++++++++++++++--------------------------- 5 files changed, 92 insertions(+), 41 deletions(-) create mode 100644 ntc_test.h diff --git a/max31855.h b/max31855.h index eee6042..e7ba7d7 100644 --- a/max31855.h +++ b/max31855.h @@ -6,7 +6,6 @@ #include // #include // @todo test quickstats, add child class for container // #include // https://github.com/provideyourown/statistics -#include #include #include diff --git a/ntc.h b/ntc.h index a498f9f..58c9298 100644 --- a/ntc.h +++ b/ntc.h @@ -12,7 +12,7 @@ * https://en.wikipedia.org/wiki/Thermistor#Steinhart.E2.80.93Hart_equation * * * See the example for more information. * - * + * * Example of use with panStamp: * https://github.com/panStamp/panstamp/wiki/Temperature-measurement-with-cheap-NTC's */ @@ -27,7 +27,7 @@ int rt = 330000/V - 320000; // Thermistor object THERMISTOR thermistor(NTC_PIN, // Analog pin - 10000, // Nominal resistance at 25 ºC + 100000, // Nominal resistance at 25 ºC 3950, // thermistor's beta coefficient 10000); // Value of the series resistor @@ -49,6 +49,10 @@ float get_ntc(){ return ntc_temp; } +void calc_ntc(int value){ + ntc_temp = thermistor.read(value); +} + /** * loop * @@ -64,9 +68,9 @@ void read_ntc() } void printNTC(){ - read_ntc(); + // read_ntc(); float tempf = (((ntc_temp/10)*1.8)+32); - Serial.println("[NTC]: " + (String)(get_ntc()/10) + "ºC " + tempf + "ºF"); + Logger.println("[NTC]: " + (String)(get_ntc()/10) + "ºC " + tempf + "ºF"); } #endif \ No newline at end of file diff --git a/ntc_multi.h b/ntc_multi.h index 6b37666..470002d 100644 --- a/ntc_multi.h +++ b/ntc_multi.h @@ -1,5 +1,5 @@ -#ifndef ntc_h -#define ntc_h +#ifndef ntc_multi_h +#define ntc_multi_h #include "thermistor.h" /** @@ -34,25 +34,30 @@ int rt = 330000/V - 320000; // 3950, // thermistor's beta coefficient // 10000); // Value of the series resistor -uint16_t resist = 100000; +uint16_t resist = 100000; uint16_t ntcnominal = 100000; -uint16_t betaco = 3950; -bool lowside = true; +uint16_t betaco = 3950; + +// Does not properly compensate for non balanced reisstance #ifdef local_thermistor_h +bool lowside = true; THERMISTOR ntc(NTC_PIN,ntcnominal,betaco,resist,lowside); THERMISTOR ntcB(NTC_BPIN,ntcnominal,betaco,resist,!lowside); THERMISTOR ntcC(NTC_CPIN,ntcnominal,betaco,resist,lowside); +THERMISTOR ntcD(NTC_CPIN,ntcnominal,betaco,resist,lowside); #else -THERMISTOR ntc(NTC_PIN,ntcnominal,betaco,resist); +THERMISTOR ntc(NTC_PIN ,ntcnominal,betaco,resist); THERMISTOR ntcB(NTC_BPIN,ntcnominal,betaco,resist); THERMISTOR ntcC(NTC_CPIN,ntcnominal,betaco,resist); +THERMISTOR ntcD(NTC_CPIN,ntcnominal,betaco,resist); #endif // Global temperature reading float ntc_temp; float ntc_temp_b; float ntc_temp_c; +float ntc_temp_d; /** * setup @@ -75,6 +80,11 @@ float get_ntc_B(){ float get_ntc_C(){ return ntc_temp_c; } + +float get_ntc_D(){ + return ntc_temp_d; +} + /** * loop * @@ -85,6 +95,7 @@ void read_ntc() ntc_temp = ntc.read(); // Read temperature ntc_temp_b = ntcB.read(); ntc_temp_c = ntcC.read(); + ntc_temp_d = ntcD.read(); // Serial.print("Temp in 1/10 ºC : "); // Serial.println(ntc_temp); // Serial.print("Temp in ºF : "); @@ -92,9 +103,33 @@ void read_ntc() } void printNTC(){ - read_ntc(); - float tempf = (((ntc_temp/10)*1.8)+32); - Serial.println("[NTC]: " + (String)(get_ntc()/10) + "ºC " + tempf + "ºF"); + // read_ntc(); + float tempf; + tempf = (((ntc_temp/10)*1.8)+32); + Serial.println("[NTC]: " + (String)(get_ntc()/10) + "ºC " + tempf + "ºF"); + + tempf = (((ntc_temp_b/10)*1.8)+32); + Serial.println("[NTC]: " + (String)(get_ntc_B()/10) + "ºC " + tempf + "ºF"); + + tempf = (((ntc_temp_c/10)*1.8)+32); + Serial.println("[NTC]: " + (String)(get_ntc_C()/10) + "ºC " + tempf + "ºF"); + + tempf = (((ntc_temp_d/10)*1.8)+32); + Serial.println("[NTC]: " + (String)(get_ntc_D()/10) + "ºC " + tempf + "ºF"); +} + + +void calc_ntc(int value){ + ntc_temp = ntc.read(value); +} +void calc_ntc_B(int value){ + ntc_temp_b = ntcB.read(value); +} +void calc_ntc_C(int value){ + ntc_temp_c = ntcC.read(value); +} +void calc_ntc_D(int value){ + ntc_temp_d = ntcD.read(value); } #endif \ No newline at end of file diff --git a/ntc_test.h b/ntc_test.h new file mode 100644 index 0000000..b8ee6fc --- /dev/null +++ b/ntc_test.h @@ -0,0 +1,17 @@ +#include + +void setup(){ + +} + +void loop(){ + printNTC(); + calc_ntc(get_PCF8591(0)*16); + calc_ntc_B(get_PCF8591(1)*16); + calc_ntc_C(get_PCF8591(2)*16); + calc_ntc_D(get_PCF8591(3)*16); + Serial.println(String(get_ntc()/10)); + Serial.println(String(get_ntc_B()/10)); + Serial.println(String(get_ntc_C()/10)); + Serial.println(String(get_ntc_D()/10)); +} \ No newline at end of file diff --git a/sense_env.h b/sense_env.h index 3afecec..ec6ee8a 100644 --- a/sense_env.h +++ b/sense_env.h @@ -116,6 +116,12 @@ float get_env(uint8_t channel = 0){ #ifdef PCF8591 #include + +// TwoWire Wire_B = TwoWire(); +// Wire_B.setClock(100000); +// Wire_B.setClockStretchLimit(); +// adafruit_i2c bool setSpeed(uint32_t desiredclk); + // Make sure that this is set to the value in volts of VCC #define ADC_REFERENCE_VOLTAGE 5.0 Adafruit_PCF8591 pcf = Adafruit_PCF8591(); @@ -136,33 +142,8 @@ float int_to_volts(uint16_t dac_value, uint8_t bits, float logic_level) { return (((float)dac_value / ((1 << bits) - 1)) * logic_level); } -void print_PCF8591(){ - pcf.analogWrite(random(255)); - // Make a triangle wave on the DAC output - // pcf.analogWrite(dac_counter++); - Logger.print((pcf.analogRead(0))); - Logger.print(", "); - Logger.print((pcf.analogRead(1))); - Logger.print(", "); - Logger.print((pcf.analogRead(2))); - Logger.print(", "); - Logger.print((pcf.analogRead(3))); - Logger.print(""); - Logger.println(""); - - Logger.print(int_to_volts(pcf.analogRead(0), 8, ADC_REFERENCE_VOLTAGE)); - Logger.print("V, "); - Logger.print(int_to_volts(pcf.analogRead(1), 8, ADC_REFERENCE_VOLTAGE)); - Logger.print("V, "); - Logger.print(int_to_volts(pcf.analogRead(2), 8, ADC_REFERENCE_VOLTAGE)); - Logger.print("V, "); - Logger.print(int_to_volts(pcf.analogRead(3), 8, ADC_REFERENCE_VOLTAGE)); - Logger.print("V"); - Logger.println(""); -} - - float get_PCF8591(uint8_t channel = 0, bool volts=false){ + Wire.setClock(100000L); // print_env(); if(volts){ if(channel == 0) return int_to_volts(pcf.analogRead(0), 8, ADC_REFERENCE_VOLTAGE); @@ -176,6 +157,19 @@ float get_PCF8591(uint8_t channel = 0, bool volts=false){ if(channel == 2) return pcf.analogRead(2); if(channel == 3) return pcf.analogRead(3); } + Wire.setClock(400000L); +} + +void print_PCF8591(){ + pcf.analogWrite(random(128)+128); + for(int i=0;i<4;i++){ + Logger.print(get_PCF8591(i)); + } + Logger.println(""); + for(int i=0;i<4;i++){ + Logger.print(get_PCF8591(i,true)); + } + Logger.println(""); } #endif @@ -293,7 +287,7 @@ void print_mpu6050(){ } float get_mpu6050(uint8_t channel = 0){ - print_mpu6050(); + // print_mpu6050(); sensors_event_t a, g, temp; mpu.getEvent(&a, &g, &temp); // accel m/s^2 @@ -809,4 +803,6 @@ float getVoltage(){ } #endif + + #endif \ No newline at end of file From 8960df83a0e64e516a8c057a0d451ca1d32dbd3f Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 2 May 2021 21:30:49 -0500 Subject: [PATCH 110/186] oled fps --- oled_i2c_sh1106.h | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index bd1e2fb..39d2c7c 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -218,7 +218,8 @@ void init_oled(bool preamble,bool pinswap = false){ // Wire.setClock(400000L); #ifdef ROT lcd.setDisplayRotation(U8G2_R2); - #endif + #endif + lcd.setBusClock(100000L); lcd.begin(); // lcd.setI2CAddress(0x78); // if(!lcd.begin()) { // Address 0x3C for 128x32 @@ -256,9 +257,13 @@ void init_oled(bool preamble,bool pinswap = false){ } void displayFPS(){ - lcd.print((String)(1000000/((micros()-oledfpsmicros)/2))); + String str = (String)(1000000/((micros()-oledfpsmicros)/2)); + lcd.clearBuffer(); // clear the internal memory + lcd.drawStr(0,10,String(str+ "fps").c_str()); + // lcd.drawStr(60,px,String(micros()).c_str()); // write something to the internal memory + lcd.sendBuffer(); // println(" FPS"); - oledfpsmicros = micros(); + oledfpsmicros = micros(); } // void printInverted(const char* str){ From c97c2460795a38b17df0c19a09b4562ac68aed29 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 9 Jun 2021 07:00:28 -0500 Subject: [PATCH 111/186] speed up tests --- neo_ind_accent.h | 2 +- neoindicator.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/neo_ind_accent.h b/neo_ind_accent.h index 158a815..04cab2f 100644 --- a/neo_ind_accent.h +++ b/neo_ind_accent.h @@ -41,7 +41,7 @@ void rainbowAccent(int wait) { void indAccentTest(){ bool quicktest = true; - int wait = quicktest ? 5 : 50; + int wait = quicktest ? 5 : 100; ind.setBrightness(255); // full bright for(size_t i=0;i<20;i++){ diff --git a/neoindicator.h b/neoindicator.h index 5c0ad80..93cf66a 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -202,7 +202,7 @@ void indClear(){ void indTest(){ bool quicktest = true; - int wait = quicktest ? 1 : 50; + int wait = quicktest ? 1 : 100; ind.setBrightness(255); // full bright indSetColor(255,0,0); From 3a71227ddf581df4004471b4dfec16c63d6af39b Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 9 Jun 2021 21:57:39 -0500 Subject: [PATCH 112/186] add quicktest params --- neoindicator.h | 4 ++-- neopixel_helper.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/neoindicator.h b/neoindicator.h index 93cf66a..5fae296 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -200,8 +200,8 @@ void indClear(){ } } -void indTest(){ - bool quicktest = true; +void indTest(bool quicktest = true){ + // bool quicktest = true; int wait = quicktest ? 1 : 100; ind.setBrightness(255); // full bright diff --git a/neopixel_helper.h b/neopixel_helper.h index ee77988..e64ecb8 100644 --- a/neopixel_helper.h +++ b/neopixel_helper.h @@ -394,8 +394,8 @@ void demo(){ } -void stripTest(){ - bool quicktest = true; +void stripTest(bool quicktest = true){ + // bool quicktest = true; int wait = quicktest ? 1 : 10; strip.setBrightness(255); // full bright From 12be5f5e712ec27bd14ee7b7a6d086e92ca167ca Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 9 Jun 2021 22:00:29 -0500 Subject: [PATCH 113/186] bug --- oled_i2c.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oled_i2c.h b/oled_i2c.h index ec62c2c..b23b5c4 100644 --- a/oled_i2c.h +++ b/oled_i2c.h @@ -124,7 +124,7 @@ void oled_test(uint8_t num = 0){ } void displayFPS(){ - lcd.print((String)(1000000/((micros()-fpsmicros)/2))); + lcd.print((String)(1000000/((micros()-oledfpsmicros)/2))); // println(" FPS"); oledfpsmicros = micros(); } From c847f8e1a04b6561b023e95e7a0cfcf0f3e0c3fc Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 11 Jun 2021 16:23:48 -0500 Subject: [PATCH 114/186] encoder priority --- button_abs.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/button_abs.h b/button_abs.h index ec063c4..e6640c3 100644 --- a/button_abs.h +++ b/button_abs.h @@ -21,6 +21,9 @@ int encoderLast = -1; // prev value bool encoderHasChange = false; // flag enc change bool useInt = false; // use interrupts, via interruptPin +long int encoderLastChange = 0; // timestamp of last encoder change +int encoderThrottleDuration = 500; // how long to defer loop for encoder waits + bool encoderHasPress = false; bool encoderHasHold = false; bool debug_enc = false; @@ -31,6 +34,7 @@ void encoderClear(){ encoderHasPress = false; encoderHasHold = false; encoderHasChange = false; + encoderLastChange = millis(); } void IRAM_ATTR onEncoderChange(int newValue) { From 5b24d2aa665e5ef4ace74bf159689e9d808a6841 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 11 Jun 2021 16:24:01 -0500 Subject: [PATCH 115/186] debug adjustments --- mqtt.h | 46 +++++++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/mqtt.h b/mqtt.h index 7b08e75..903afab 100644 --- a/mqtt.h +++ b/mqtt.h @@ -25,7 +25,7 @@ WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = false; +bool debug_mqtt = true; const char* clientID = ""; void MQTTreconnect() { @@ -52,7 +52,6 @@ void MQTTreconnect() { } } - void MQTTcallback(char* topic, byte* payload, unsigned int length) { Logger.print("[MQTT] IN Message arrived ["); Logger.print(topic); @@ -122,7 +121,7 @@ void init_MQTT(const char* clientid){ init_MQTT(); } -void init_MQTT(String clientid){ +void init_MQTT(const String& clientid){ clientID = clientid.c_str(); // global init_MQTT(); } @@ -132,18 +131,18 @@ void init_MQTT(String clientid){ void MQTT_pub(String topic, String sensor, String value){ if(!wifiIsConnected()){ // Logger.print("[MQTT] OFFLINE: "); - return; + // return; } - #ifdef debug_mqtt + if(debug_mqtt){ Logger.print("[MQTT] Publish: "); Logger.print(sensor); Logger.print(" "); Logger.println(value); if(value == "") { - Logger.println("[ERROR] MQTT value is empty"); - return; + Logger.println("[ERROR] MQTT value is empty"); + return; + } } - #endif // JsonArray data = payload.createNestedArray(topic); payload["topic"] = topic; payload["clientid"] = clientID; @@ -164,16 +163,16 @@ void MQTT_pub(String topic, String sensor, String value){ } void MQTT_pub(String topic, String sensor, String value, bool json){ - #ifdef debug_mqtt - Logger.print("[MQTT] Publish: "); - Logger.print(sensor); - Logger.print(" "); - Logger.println(value); - if(value == "") { - Logger.println("[ERROR] MQTT value is empty"); - return; + if(debug_mqtt){ + Logger.print("[MQTT] Publish: "); + Logger.print(sensor); + Logger.print(" "); + Logger.println(value); + if(value == "") { + Logger.println("[ERROR] MQTT value is empty"); + return; + } } - #endif JsonArray data = payload.createNestedArray(topic); payload["topic"] = data; // tag key = tag value payload["clientid"] = clientID; @@ -210,9 +209,9 @@ void MQTT_pub(String topic, String sensor, String value, bool json){ } void MQTT_pub_send(String topic){ - #ifdef debug_mqtt - Logger.println("[MQTT] sending json for topic " + topic); - #endif + if(debug_mqtt){ + Serial.println("[MQTT] sending json for topic " + topic); + } // serializeJson(jsondata, Logger); // rootdoc.createNestedObject(); // rootdoc.add(pubjson); @@ -225,7 +224,10 @@ void MQTT_pub_send(String topic){ char message[2048]; serializeJson(pubjson, message); - // Serial.println((String)message); + if(debug_mqtt){ + Serial.println((String)message); + Serial.flush(); + } client.publish(topic.c_str(),message); delay(500); // pubjson.clear(); @@ -261,6 +263,8 @@ void MQTT_pub(String topic, String sensor, String value){ } #endif +// todo +// add free heap void MQTT_pub_device(){ Serial.println("[TASK] doMQTT Device"); MQTT_pub("device","rssi",(String)getRSSIasQuality()); From bc337f88524e931c195f9e6553cf577dbdcc8bda Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 14 Jun 2021 22:16:38 -0500 Subject: [PATCH 116/186] doc dependancies --- button_abs.h | 9 +++++---- dependancies.txt | 32 ++++++++++++++++++++++++++++++-- io_utils.h | 2 +- log_syslog.h | 4 ++-- serialcmd.h | 6 +++--- snippets.h | 2 ++ storage.h | 3 --- 7 files changed, 43 insertions(+), 15 deletions(-) diff --git a/button_abs.h b/button_abs.h index e6640c3..a669285 100644 --- a/button_abs.h +++ b/button_abs.h @@ -5,7 +5,9 @@ #define buttons_abs_h -#include +#include // davetcc/TaskManagerIO + +#include // davetcc/ioabstraction #include const int interruptPin = 3; // if motor.h stalldetect, Real interrupt for io expander USES SERIAL RX!!! @@ -26,7 +28,7 @@ int encoderThrottleDuration = 500; // how long to defer loop for encoder waits bool encoderHasPress = false; bool encoderHasHold = false; -bool debug_enc = false; +bool debug_enc = true; volatile bool PCFInterruptFlag = false; @@ -100,7 +102,7 @@ void setEncoderAccel(HWAccelerationMode accel){ void init_encoder(int encoderAPin, int encoderBPin, int encoderSWPin,uint8_t addr=0){ if(addr){ - // First we set up the switches library, giving it the task manager and tell it where the pins are located + // First we set up the switches library, giving it the task manager and tell it where the pins are located // We could also of chosen IO through an i2c device that supports interrupts. // the second parameter is a flag to use pull up switching, (true is pull up). if(useInt)switches.initialiseInterrupt(ioFrom8574(0x20, interruptPin), true); @@ -127,7 +129,6 @@ void init_encoder(int encoderAPin, int encoderBPin, int encoderSWPin,uint8_t add // interrupt for any // taskManager.setInterruptCallback(onInterrupt); - // now we add the switches, we dont want the spinwheel button to repeat, so leave off the last parameter // which is the repeat interval (millis / 20 basically) Repeat button does repeat as we can see. diff --git a/dependancies.txt b/dependancies.txt index fde9921..bf0a8ee 100644 --- a/dependancies.txt +++ b/dependancies.txt @@ -2,6 +2,34 @@ dependancies panstamp/thermistor MajenkoLibraries/Average -ug82 + jackw01/PIDAutotuner -luisllamasbinaburo/Arduino-Interpolation \ No newline at end of file +luisllamasbinaburo/Arduino-Interpolation + +Chris--A/PrintEx (NI) +bblanchon/ArduinoStreamUtils +arcao/Syslog + +davetcc/taskmanagerio +davetcc/ioabstraction + + +ug82 +Adafruit_NeoPixel + +bblanchon/ArduinoJson +knolleary/pubsubclient + +Mottramlabs/ESP8266-Tone-Generator + + // requires #include + + + +soligen2010/encoder + +"Adafruit_MAX31855.h" + + +// NI #include // @todo test quickstats, add child class for container +// NI #include // https://github.com/provideyourown/statistics \ No newline at end of file diff --git a/io_utils.h b/io_utils.h index d7fc1d8..c239e4c 100644 --- a/io_utils.h +++ b/io_utils.h @@ -5,7 +5,7 @@ #include #ifdef ESP32 -#include +#include // ERROPiX/ESP32_AnalogWrite #endif bool swap = false; diff --git a/log_syslog.h b/log_syslog.h index 1568fa2..10c55c2 100644 --- a/log_syslog.h +++ b/log_syslog.h @@ -19,8 +19,8 @@ Syslog syslog(udpClient, SYSLOG_PROTO_IETF); // SYSLOG_PROTO_BSD String logTopic = "ESP"; int iteration = 1; -#define DEVICE_HOSTNAME "my-device" -#define APP_NAME "my-app" +#define DEVICE_HOSTNAME "unknown-device" +#define APP_NAME "unkown-app" const char* syslog_hostname; const char* syslog_appname; diff --git a/serialcmd.h b/serialcmd.h index d534dbd..3c4050a 100644 --- a/serialcmd.h +++ b/serialcmd.h @@ -2,9 +2,9 @@ #define serialcmd_h #include -#include -#include -#include +#include // @todo remove +#include // @todo remove +#include // @todo remove // HardwareSerial DebugOut = Serial; // HardwareSerial DebugOut(0); diff --git a/snippets.h b/snippets.h index d072aa6..3692f43 100644 --- a/snippets.h +++ b/snippets.h @@ -1,3 +1,5 @@ + +// proper rollover handling if (micros () - then > some_interval) { // do something diff --git a/storage.h b/storage.h index ac12ae8..cec61c1 100644 --- a/storage.h +++ b/storage.h @@ -4,9 +4,6 @@ #include #include - - - void listDir(const char * dirname) { Serial.printf("Listing directory: %s\n", dirname); From 38641c34934d35b8d16f65e083c0b5fbc068456b Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 14 Jun 2021 22:16:51 -0500 Subject: [PATCH 117/186] lower hot temp alert --- reflow_pid.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/reflow_pid.h b/reflow_pid.h index a8bcddd..37e4be9 100644 --- a/reflow_pid.h +++ b/reflow_pid.h @@ -1,6 +1,9 @@ #ifndef reflow_pid_h #define reflow_pid_h +// remove all reflowoven methods, use for all SSR pid control generic +// + #include "InterpolationLib.h" unsigned long stateStartMS = 0; // state start timers @@ -11,7 +14,7 @@ int reflowGraphCounter = 0; // counter period for graphing graphInterval // temperature vars int hotTemp = 70; // C burn temperature for HOT indication, 0=disable -int coolTemp = 50; // C safe temperature for HOT indication, 0=disable +int coolTemp = 48; // C safe temperature for HOT indication, 0=disable int lowTemp = 30; // C of TC warmed than typical CJ int shutDownTemp = 210; // degrees C int fanTemp = lowTemp+5; // cooldown complete fan off low temp From d32a54c90dd4508fbbb91a5ca05adf787440c9f9 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 14 Jun 2021 22:17:00 -0500 Subject: [PATCH 118/186] add json debugging --- mqtt.h | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/mqtt.h b/mqtt.h index 903afab..4de4997 100644 --- a/mqtt.h +++ b/mqtt.h @@ -5,7 +5,8 @@ #define USEJSON #ifdef USEJSON -#include +#include // bblanchon/ArduinoJson + StaticJsonDocument<2048> payload; StaticJsonDocument<2048> rootdoc; // payload["sensor"] = "gps"; @@ -18,14 +19,15 @@ StaticJsonDocument<2048> rootdoc; JsonArray jsondata = pubjson.to(); #endif -#include +#include // knolleary/pubsubclient #define MQTT_MAX_PACKET_SIZE 2048 WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = true; +bool debug_mqtt = false; +bool debug_mqtt_json = true; const char* clientID = ""; void MQTTreconnect() { @@ -179,7 +181,7 @@ void MQTT_pub(String topic, String sensor, String value, bool json){ payload["type"] = sensor; // field key = field value payload["value"] = value.toFloat(); // payload["unit"] = ""; - if(debug_mqtt) serializeJson(payload, Serial); + // if(debug_mqtt_json) serializeJson(payload, Logger); // serializeJsonPretty(payload, Serial); String output; @@ -224,9 +226,9 @@ void MQTT_pub_send(String topic){ char message[2048]; serializeJson(pubjson, message); - if(debug_mqtt){ - Serial.println((String)message); - Serial.flush(); + if(debug_mqtt_json){ + Logger.println((String)message); + Logger.flush(); } client.publish(topic.c_str(),message); delay(500); @@ -266,7 +268,7 @@ void MQTT_pub(String topic, String sensor, String value){ // todo // add free heap void MQTT_pub_device(){ - Serial.println("[TASK] doMQTT Device"); + if(debug_mqtt) Logger.println("[MQTT] Publish Device"); MQTT_pub("device","rssi",(String)getRSSIasQuality()); #ifdef ESP32 // MQTT_pub("device","hall",(String)hallRead()); // USES PINS 36,39 From 7686b81917c40dddb08732e2aff8fa86d8e3b47e Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Nov 2021 13:06:35 -0600 Subject: [PATCH 119/186] playing with sensor class --- dependancies.txt | 9 +++- sense_env_class.h | 114 +++++++++++++++++++++++++++++++++++++++++++ sensor_env_class.cpp | 5 ++ 3 files changed, 127 insertions(+), 1 deletion(-) create mode 100644 sense_env_class.h create mode 100644 sensor_env_class.cpp diff --git a/dependancies.txt b/dependancies.txt index bf0a8ee..3e5ef8a 100644 --- a/dependancies.txt +++ b/dependancies.txt @@ -32,4 +32,11 @@ soligen2010/encoder // NI #include // @todo test quickstats, add child class for container -// NI #include // https://github.com/provideyourown/statistics \ No newline at end of file +// NI #include // https://github.com/provideyourown/statistics + + + +ArduinoBufferedStreams +stream buffer +https://github.com/paulo-raca/ArduinoBufferedStreams + diff --git a/sense_env_class.h b/sense_env_class.h new file mode 100644 index 0000000..67e60ce --- /dev/null +++ b/sense_env_class.h @@ -0,0 +1,114 @@ +// sense env class + +// create sensor instance + +// sensor add +// max num samples +// ring buffer +// ring index +// sensor id +// sensor i2c addr +// sensor unit +// sensor values or sensor group by type + +// sensor calc +// avg +// mean +// mode +// running avg +// khalman filter +// validation/rejection/clamping + +// timestamp or period reconstructor + +// sensor alarms/threshholds + +// offline mode/collection/logging to sd, maybe add a second buffer with long term ogging interval + + +// depencandies +// average +// statsistics +// filter + +// ability to grab a sample window for deferred submission to mqtt for a series ( useful for battery operated devices or offline ) +// ability to grab lastvalue as running average over last n samples/n times + +#ifndef sensorsdlog_h +#define sensorsdlog_h + +#include +#include +using namespace std; + +#include +// Average avg_a(20); + +#include +// Statistic myStats; + +// collections of sensors +template +class sensorcollection { + // vector or list of sensor objects + // group by type for sensors with many metrics + // addSensor(char* id, char* name, char* unit, T datatype); + // removeSensor(char* id); + // getSensorByID(char* id); + // vector sensors; // how to use a templated class here? + + private: + // template datatype; + vector*> sensors; + // vector sensors; + int _numsamples = 20; + + sensorcollection(){ + // examples, will be via management methods + // BUT how to create many new instances and retain them in class? + Average avg_a(_numsamples); // scope this in class? + sensors.push_back(&avg_a); // use temp obj or smart pointers? + } + + +}; + +// individual sensor log, one per value +// or find a way to create anonymous objects, but each one might have different units so might as well keep them seperate. +template +class sensordlog { + private: + + const char* _id; // unique id of collection + const char* _name; // name + char* _unit; // units of values eg. ug/L + T datatype; // template of typename of sample, float, int etc + int _numsamples = 20; // number of samples to store in buffer + + public: + sensordlog(); // add inializer list or use setters? + ~sensordlog(); + + // setSensorRange(T min, T max); + // setSensorNumSamples(int numSamples); + + // getValue(char* id); // self.value() + // getAvg(); //self.avg() + // getMean(); + // getMode(); + // getMax(); + // getMin(); + + // extended + // pass in pointer funcs for specific library methods + // init() + // update() +}; + + +template sensordlog::sensordlog(){ + Serial.println("constructor"); + // sensors.push_back(Statistic myStats1); // ? how to use an anoymous object pointer in vector? +} + +#endif \ No newline at end of file diff --git a/sensor_env_class.cpp b/sensor_env_class.cpp new file mode 100644 index 0000000..47cf379 --- /dev/null +++ b/sensor_env_class.cpp @@ -0,0 +1,5 @@ +// #include "sense_env_class.h" + +// void sensordlog::sensordlog(){ +// Serial.println("constructor"); +// } \ No newline at end of file From b6493da626c91757872605d54f2990c6053a8295 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Nov 2021 16:37:22 -0600 Subject: [PATCH 120/186] compiling --- sense_env_class.h | 52 ++++++++++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/sense_env_class.h b/sense_env_class.h index 67e60ce..5e14013 100644 --- a/sense_env_class.h +++ b/sense_env_class.h @@ -47,32 +47,46 @@ using namespace std; #include // Statistic myStats; +// vector or list of sensor objects +// group by type for sensors with many metrics +// addSensor(char* id, char* name, char* unit, T datatype); +// removeSensor(char* id); +// getSensorByID(char* id); +// vector sensors; // how to use a templated class here? + // collections of sensors -template +// T datatype +template class sensorcollection { - // vector or list of sensor objects - // group by type for sensors with many metrics - // addSensor(char* id, char* name, char* unit, T datatype); - // removeSensor(char* id); - // getSensorByID(char* id); - // vector sensors; // how to use a templated class here? - private: - // template datatype; - vector*> sensors; - // vector sensors; - int _numsamples = 20; - - sensorcollection(){ - // examples, will be via management methods - // BUT how to create many new instances and retain them in class? - Average avg_a(_numsamples); // scope this in class? - sensors.push_back(&avg_a); // use temp obj or smart pointers? - } + vector> sensors; + int _numsamples = 20; + public: + sensorcollection(); + void addSensorValue(int idx,float value); + // float getSensorValue(int idx); + }; + template + sensorcollection::sensorcollection(){ + // testing in constructor for now + // BUT how to create many new instances and retain them in class? + // Average avg_x(_numsamples); // scope this in class?, surely this will go bye bye + sensors.push_back(Average(_numsamples)); // use temp obj or smart pointers? + } + + template + void sensorcollection::addSensorValue(int idx,float value){ + sensors[idx].push(value); + } + + // template float sensorcollection::getSensorValue(int idx){ + // return sensors[idx].average(); + // } + // individual sensor log, one per value // or find a way to create anonymous objects, but each one might have different units so might as well keep them seperate. template From e26bf3c1e6b75bc6d10a55dbae8c08da717e7a90 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Nov 2021 16:43:38 -0600 Subject: [PATCH 121/186] Update sense_env_class.h --- sense_env_class.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/sense_env_class.h b/sense_env_class.h index 5e14013..f1fcbc2 100644 --- a/sense_env_class.h +++ b/sense_env_class.h @@ -66,7 +66,7 @@ class sensorcollection { public: sensorcollection(); void addSensorValue(int idx,float value); - // float getSensorValue(int idx); + float getSensorValue(int idx); }; @@ -83,9 +83,10 @@ class sensorcollection { sensors[idx].push(value); } - // template float sensorcollection::getSensorValue(int idx){ - // return sensors[idx].average(); - // } + template + float sensorcollection::getSensorValue(int idx){ + return sensors[idx].mean(); + } // individual sensor log, one per value // or find a way to create anonymous objects, but each one might have different units so might as well keep them seperate. From 7e8db94a37d1891476a99fa97f7a21fec91bba6c Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Mon, 15 Nov 2021 09:11:03 -0600 Subject: [PATCH 122/186] remove for s2 --- io_utils.h | 90 +++++++++++++++++++++++++++++----------------------- wifi_funcs.h | 66 ++++++++++++++++++++++---------------- 2 files changed, 88 insertions(+), 68 deletions(-) diff --git a/io_utils.h b/io_utils.h index c239e4c..5e161dd 100644 --- a/io_utils.h +++ b/io_utils.h @@ -5,7 +5,7 @@ #include #ifdef ESP32 -#include // ERROPiX/ESP32_AnalogWrite +// #include // ERROPiX/ESP32_AnalogWrite #endif bool swap = false; @@ -30,11 +30,21 @@ void debugPin(uint8_t pin){ Logger.println(" pinstate: " + (String)digitalRead(pin)); } + + +// i2c scanner +// @todo add oled support, remember device addrs and lookup indexes, +// detect new device, shows list of devices when it gets to your device press button or unplug device , +// it will then be stored and automatically setup. + + +// #include + void scani2c(bool pinswap = false){ swap = pinswap; byte error, address; int nDevices; - if(!swap)Wire.begin(); + if(!swap) Wire.begin(); else Wire.begin(SCL,SDA); // begin(sda, scl) SWAP! Logger.print("[I2C] SDA:"+(String) SDA); Logger.print(" SCL:"+(String) SCL); @@ -67,7 +77,7 @@ void scani2c(bool pinswap = false){ Logger.println(""); nDevices++; } - else if(res!=2) + else if(res!=2 && res !=255) { Logger.println("[ERROR]:" + (String)res); Logger.print("Unknown error ADDR: 0x"); @@ -108,44 +118,44 @@ void pinregister(){ // and on esp32 etc set the pins desired specs and avoid conflicts with multiple adc reads } -#ifdef ESP32 - -#define ADC_1 36 -#define ADC_2 38 // missing from some boards? -#define ADC_3 39 -#define ADC_4 32 -#define ADC_5 33 -#define ADC_6 34 -#define ADC_7 37 - -// ADC2 restoring procedure -// This is a Workaround to use ADC2 Pins on ESP32 when Wifi or Bluetooth is on. -// (usually only ADC1 Pins are usable for analogRead() when Wifi or Bluetooth is on.) -// -- We save the ADC2 control register before WifiBegin() or BluetoothBegin() -// -- then restore its original value, then set a specific bit of the ADC2 control register -//to avoid inverted readings: we do the latter two before every analogRead() cycle. -// -- This achieves ADC2 usability even when Wifi/Bluetooth are turned on! - -#include "esp32-hal-adc.h" // needed for adc pin reset -#include "soc/sens_reg.h" // needed for manipulating ADC2 control register -uint64_t reg_b; // Used to store ADC2 control register -int value; - -void storeADC() { -// Save ADC2 control register value : Do this before begin Wifi/Bluetooth -reg_b = READ_PERI_REG(SENS_SAR_READ_CTRL2_REG); -// Wifi.Begin(); // or similar wifi init function or Bluetooth begin() -} +// #ifdef ESP32 + +// #define ADC_1 36 +// #define ADC_2 38 // missing from some boards? +// #define ADC_3 39 +// #define ADC_4 32 +// #define ADC_5 33 +// #define ADC_6 34 +// #define ADC_7 37 + +// // ADC2 restoring procedure +// // This is a Workaround to use ADC2 Pins on ESP32 when Wifi or Bluetooth is on. +// // (usually only ADC1 Pins are usable for analogRead() when Wifi or Bluetooth is on.) +// // -- We save the ADC2 control register before WifiBegin() or BluetoothBegin() +// // -- then restore its original value, then set a specific bit of the ADC2 control register +// //to avoid inverted readings: we do the latter two before every analogRead() cycle. +// // -- This achieves ADC2 usability even when Wifi/Bluetooth are turned on! + +// #include "esp32-hal-adc.h" // needed for adc pin reset +// #include "soc/sens_reg.h" // needed for manipulating ADC2 control register +// uint64_t reg_b; // Used to store ADC2 control register +// int value; + +// void storeADC() { +// // Save ADC2 control register value : Do this before begin Wifi/Bluetooth +// reg_b = READ_PERI_REG(SENS_SAR_READ_CTRL2_REG); +// // Wifi.Begin(); // or similar wifi init function or Bluetooth begin() +// } -void restoreADC() { -// ADC2 control register restoring -WRITE_PERI_REG(SENS_SAR_READ_CTRL2_REG, reg_b); -//VERY IMPORTANT: DO THIS TO NOT HAVE INVERTED VALUES! -SET_PERI_REG_MASK(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_DATA_INV); -Logger.println(analogRead(4)); -Logger.println(analogRead(33)); -} -#endif +// void restoreADC() { +// // ADC2 control register restoring +// WRITE_PERI_REG(SENS_SAR_READ_CTRL2_REG, reg_b); +// //VERY IMPORTANT: DO THIS TO NOT HAVE INVERTED VALUES! +// SET_PERI_REG_MASK(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_DATA_INV); +// Logger.println(analogRead(4)); +// Logger.println(analogRead(33)); +// } +// #endif // //ISR test diff --git a/wifi_funcs.h b/wifi_funcs.h index bac9c0b..92cf1a4 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -110,6 +110,7 @@ void setWiFiHostname(const char* hostname){ #ifdef ESP32 WiFi.setHostname(hostname); #else + MDNS.begin(hostname); WiFi.hostname(hostname); #endif } @@ -128,7 +129,7 @@ void WiFi_print_sta(){ Serial.print("[WIFI] IP: "); Serial.println(WiFi.localIP()); Serial.print("[WIFI] HOST: "); - getHostname(); + Serial.println(getHostname()); } } @@ -187,8 +188,7 @@ void init_wifi(){ init_WiFi(0); } -int getRSSIasQuality() { - int RSSI = WiFi.RSSI(); +int getRSSIasQuality(int RSSI) { int quality = 0; if (RSSI <= -100) { @@ -201,6 +201,11 @@ int getRSSIasQuality() { return quality; } +int getRSSIasQuality() { + return getRSSIasQuality(WiFi.RSSI()); +} + + void checkWifi(){ Serial.println("[TASK] checkWiFi"); if(WiFi.status() != WL_CONNECTED ){ @@ -274,29 +279,29 @@ void disableWiFi(){ // } else { // strcpy_P(buff, PSTR("Unknown")); -#ifdef ESP32 -String ESP32GetResetReason(uint32_t cpu_no) { - // tools\sdk\include\esp32\rom\rtc.h - switch (rtc_get_reset_reason( (RESET_REASON) cpu_no)) { - case POWERON_RESET : return F("Vbat power on reset"); // 1 - case SW_RESET : return F("Software reset digital core"); // 3 - case OWDT_RESET : return F("Legacy watch dog reset digital core"); // 4 - case DEEPSLEEP_RESET : return F("Deep Sleep reset digital core"); // 5 - case SDIO_RESET : return F("Reset by SLC module, reset digital core"); // 6 - case TG0WDT_SYS_RESET : return F("Timer Group0 Watch dog reset digital core"); // 7 - case TG1WDT_SYS_RESET : return F("Timer Group1 Watch dog reset digital core"); // 8 - case RTCWDT_SYS_RESET : return F("RTC Watch dog Reset digital core"); // 9 - case INTRUSION_RESET : return F("Instrusion tested to reset CPU"); // 10 - case TGWDT_CPU_RESET : return F("Time Group reset CPU"); // 11 - case SW_CPU_RESET : return F("Software reset CPU"); // 12 - case RTCWDT_CPU_RESET : return F("RTC Watch dog Reset CPU"); // 13 - case EXT_CPU_RESET : return F("or APP CPU, reseted by PRO CPU"); // 14 - case RTCWDT_BROWN_OUT_RESET : return F("Reset when the vdd voltage is not stable"); // 15 - case RTCWDT_RTC_RESET : return F("RTC Watch dog reset digital core and rtc module"); // 16 - default : return F("NO_MEAN"); // 0 - } -} -#endif +// #ifdef ESP32 +// String ESP32GetResetReason(uint32_t cpu_no) { +// // tools\sdk\include\esp32\rom\rtc.h +// switch (rtc_get_reset_reason( (RESET_REASON) cpu_no)) { +// case POWERON_RESET : return F("Vbat power on reset"); // 1 +// case SW_RESET : return F("Software reset digital core"); // 3 +// case OWDT_RESET : return F("Legacy watch dog reset digital core"); // 4 +// case DEEPSLEEP_RESET : return F("Deep Sleep reset digital core"); // 5 +// case SDIO_RESET : return F("Reset by SLC module, reset digital core"); // 6 +// case TG0WDT_SYS_RESET : return F("Timer Group0 Watch dog reset digital core"); // 7 +// case TG1WDT_SYS_RESET : return F("Timer Group1 Watch dog reset digital core"); // 8 +// case RTCWDT_SYS_RESET : return F("RTC Watch dog Reset digital core"); // 9 +// case INTRUSION_RESET : return F("Instrusion tested to reset CPU"); // 10 +// case TGWDT_CPU_RESET : return F("Time Group reset CPU"); // 11 +// case SW_CPU_RESET : return F("Software reset CPU"); // 12 +// case RTCWDT_CPU_RESET : return F("RTC Watch dog Reset CPU"); // 13 +// case EXT_CPU_RESET : return F("or APP CPU, reseted by PRO CPU"); // 14 +// case RTCWDT_BROWN_OUT_RESET : return F("Reset when the vdd voltage is not stable"); // 15 +// case RTCWDT_RTC_RESET : return F("RTC Watch dog reset digital core and rtc module"); // 16 +// default : return F("NO_MEAN"); // 0 +// } +// } +// #endif // void esp32_resetreason(RESET_REASON reason) // { @@ -340,13 +345,18 @@ String getResetReason(){ #elif defined(ESP32) && defined(_ROM_RTC_H_) // requires #include for(int i=0;i<2;i++){ - return ESP32GetResetReason(i); - // return (String)reason; + // return ESP32GetResetReason(i); + return "NA"; } #else return "UNSET"; #endif } +void processWiFi(){ + #ifdef ESP8266 + MDNS.update(); + #endif +} #endif \ No newline at end of file From 29df61ed47d6b332a12d151637dc1ce582cde028 Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Mon, 15 Nov 2021 09:11:45 -0600 Subject: [PATCH 123/186] increase mwtt size --- mqtt.h | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/mqtt.h b/mqtt.h index 4de4997..420d912 100644 --- a/mqtt.h +++ b/mqtt.h @@ -7,15 +7,15 @@ #ifdef USEJSON #include // bblanchon/ArduinoJson -StaticJsonDocument<2048> payload; -StaticJsonDocument<2048> rootdoc; +StaticJsonDocument<4096> payload; +StaticJsonDocument<4096> rootdoc; // payload["sensor"] = "gps"; // payload["time"] = 1351824120; // const size_t CAPACITY = JSON_ARRAY_SIZE(1); // StaticJsonDocument docH; // JsonArray arrayH = docH.to(); - DynamicJsonDocument pubjson(2048); + DynamicJsonDocument pubjson(4096); JsonArray jsondata = pubjson.to(); #endif @@ -26,8 +26,8 @@ WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = false; -bool debug_mqtt_json = true; +bool debug_mqtt = true; +bool debug_mqtt_json = false; const char* clientID = ""; void MQTTreconnect() { @@ -101,7 +101,10 @@ void process_MQTT_nb(){ } void process_MQTT(){ - if(!wifiIsConnected()) return; + if(!wifiIsConnected()){ + Logger.println("[MQTT] wifi not connected"); + return; + } MQTTreconnect(); // @todo throttle client.loop(); // will wait loop reconnect to mqtt } @@ -110,7 +113,7 @@ void init_MQTT(){ if(!wifiIsConnected()) return; client.setServer(mqtt_server_ip, mqtt_server_port); client.setCallback(MQTTcallback); - if (client.connect(clientID)) Logger.println("[MQTT] connected"); + if (client.connect(clientID)) Logger.println("[MQTT] connected to " + (String)mqtt_server_ip); client.setBufferSize(2048); client.subscribe("downstream"); process_MQTT(); @@ -212,7 +215,7 @@ void MQTT_pub(String topic, String sensor, String value, bool json){ void MQTT_pub_send(String topic){ if(debug_mqtt){ - Serial.println("[MQTT] sending json for topic " + topic); + Logger.println("[MQTT] sending json for topic: " + topic); } // serializeJson(jsondata, Logger); // rootdoc.createNestedObject(); @@ -224,7 +227,7 @@ void MQTT_pub_send(String topic){ // Serial.println(output); // Serial.flush(); - char message[2048]; + char message[4096]; serializeJson(pubjson, message); if(debug_mqtt_json){ Logger.println((String)message); From 61b3317dd4efef33543374a6487beb0c90a79578 Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Mon, 15 Nov 2021 09:12:02 -0600 Subject: [PATCH 124/186] update sensors add class --- sense_env.h | 458 ++++++++++++++++++++++++++++++++++++++-------- sense_env_class.h | 103 ++++++----- 2 files changed, 439 insertions(+), 122 deletions(-) diff --git a/sense_env.h b/sense_env.h index ec6ee8a..141f418 100644 --- a/sense_env.h +++ b/sense_env.h @@ -5,7 +5,7 @@ Average avg_a(20); -// supported sensors +// SUPPORTED SENSORS // SHT31 // SHT21 // HTU21D @@ -13,13 +13,26 @@ Average avg_a(20); // BMP280 // BME280 // CS811 -// GP2Y // TSL2561 -// BH1750 -// +// BH1750 https://github.com/claws/BH1750 +// APDS9960 +// GP2Y +// PM Dust sensors https://github.com/avaldebe/PMserial +// MPU6050 +// PCF8591 + + +// NOT IMPLEMENTED @TODO +// VEML6070 +// HMC5883L +// MAX9814 +// MCP3421 +// INA219 +// MCP4725 +// MCP3421 // BUGS -// sensors do not reinit is they drop out +// sensors do not reinit is they drop out, add heathcheck() // co2 voc, resubmits the same value over and over if device is lost // use real temp and humidity to compensate other sensors @@ -28,7 +41,14 @@ Average avg_a(20); // I2C +//MOTION #define MPU6050 // MPU 6050 GY521 3axis gyro/accel +#define HMC5883L // NI Honeywell HMC5883L + + +// TEMP/HUMIDITY/GAS +#define SI7021 +#define AHT10 #define USESHT31 // SHT31 Temp/Humidity // #define USESHT21 // SHT21 / HTU21D Temp/Humidity @@ -46,13 +66,49 @@ This board/chip uses I2C 7-bit address 0x77. // #define USEBME280 // BME280 Humidity/Pressure/Altitude // Pressure: 300...1100 hPa + #define USECS811 // CCS811 Temp/CO2/VOC -#define USEGP2Y // Sharp Particle/Dust sensor GP2Y1010AU0F, GP2Y1014AU0F +// #define USEGP2Y // Sharp Particle/Dust sensor GP2Y1010AU0F, GP2Y1014AU0F +#define PMSx + +// LIGHT #define APDS9960 // Proximity, Light, RGB, and Gesture Sensor -#define BH1750 // Light Sensor +#define USEBH1750 // Light Sensor +/* + BH1750 has six different measurement modes. They are divided in two groups; + continuous and one-time measurements. In continuous mode, sensor continuously + measures lightness value. In one-time mode the sensor makes only one + measurement and then goes into Power Down mode. + + Each mode, has three different precisions: + + - Low Resolution Mode - (4 lx precision, 16ms measurement time) + - High Resolution Mode - (1 lx precision, 120ms measurement time) + - High Resolution Mode 2 - (0.5 lx precision, 120ms measurement time) + + By default, the library uses Continuous High Resolution Mode, but you can + set any other mode, by passing it to BH1750.begin() or BH1750.configure() + functions. -#define TSL2561 // Luminosity/Lux/Light Address = 0x39 //Slave addr also 0x29 or 0x49 + [!] Remember, if you use One-Time mode, your sensor will go to Power Down + mode each time, when it completes a measurement and you've read it. + + Full mode list: + + BH1750_CONTINUOUS_LOW_RES_MODE + BH1750_CONTINUOUS_HIGH_RES_MODE (default) + BH1750_CONTINUOUS_HIGH_RES_MODE_2 + + BH1750_ONE_TIME_LOW_RES_MODE + BH1750_ONE_TIME_HIGH_RES_MODE + BH1750_ONE_TIME_HIGH_RES_MODE_2 +*/ + +#define VEML6070 // UV Sensor + + +// #define TSL2561 // Luminosity/Lux/Light Address = 0x39 //Slave addr also 0x29 or 0x49 /* TSL2561 Approximates Human eye Response @@ -71,22 +127,35 @@ Voltage range: 3.3-5V into onboard regulator Interface: I2C */ + +// SOUND +#define MAX9814 // MAX9814 Auto GC amplifier +#define MAX4466 // MAX4466 Adj GC amplifier + + +// Energy #define INA219 // INA219 current sense -#define PCF8591 // PCF8591 +// IO +#define MCP4725 // 12bit DAC with EEPROM +#define MCP3421 // 18bit delta-sigma ADC +// #define PCF8591 // PCF8591 io expander + // [I2C] Device found - ADDR: 0x23 // BH1750 // [I2C] Device found - ADDR: 0x39 // APDS9960 / TSL2561 // [I2C] Device found - ADDR: 0x5A // // [I2C] Device found - ADDR: 0x76 // -// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x23 0x46 -// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x39 0x72 -// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x44 0x88 -// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x48 0x90 -// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x5A 0xB4 -// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x68 0xD0 -// Apr 29 16:37:07 ESP_env 192.168.20.33 ESP:[INFO]- [I2C] Device found - ADDR: 0x76 0xEC +// [I2C] Device found - ADDR: 0x23 0x46 +// [I2C] Device found - ADDR: 0x38 0x70 +// [I2C] Device found - ADDR: 0x39 0x72 +// [I2C] Device found - ADDR: 0x3C 0x78 +// [I2C] Device found - ADDR: 0x44 0x88 +// [I2C] Device found - ADDR: 0x48 0x90 +// [I2C] Device found - ADDR: 0x5A 0xB4 +// [I2C] Device found - ADDR: 0x68 0xD0 +// [I2C] Device found - ADDR: 0x76 0xEC /* #ifdef ENV_TEMPLATE @@ -96,10 +165,10 @@ void init_env(){ bool ret = false; ret = env.begin(); if(!ret){ - Logger.println("[ERROR] xxxxxx init failed"); + Logger.println("[ERROR] _env init FAILED"); } - else Logger.println("[ENV] xxxxx initialized!"); - return ret; + else Logger.println("[ENV] _env is ACTIVE"); + // return ret; } void print_env(){ @@ -107,13 +176,204 @@ void print_env(){ float get_env(uint8_t channel = 0){ // print_env(); - if(channel == 0) return ; - if(channel == 1) return ; - if(channel == 2) return ; - + if(channel == 0) return _env.readvalue(); + // if(channel == 1) return ; + // if(channel == 2) return ; +} #endif */ + +#ifdef VEML6070 + +// PRODUCT SUMMARY +// PART NUMBER +// OPERATING VOLTAGE RANGE +// (V)2.7 to 5.5 +// I2C BUS VOLTAGE RANGE +// (V) 1.7 to 5.5 +// PEAK SENSITIVITY +// (nm) 355 +// RANGE OF SPECTRAL BANDWIDTH λ0.5 +// (nm) ± 20 +// OUTPUT CODE 16 bit, I2C +// VEML6070 + +// Slave Address and Function Description +// The VEML6070 has one slave address used for write functions (command) and two slave addresses used for read functions +// (UV data LSB and MSB). +// The 7-bit address for write functions is 38h = 0111000x resulting in a 70h = 01110000 8-bit address. The 7-bit addresses +// for read functions are 38h = 0111000x for the UV Data LSB and 39h = 0111001x for the UV data MSB. This results in a +// 71h = 01110001 and 73h = 01110011 8-bit address, respectively. The 7-bit address 39h should not be used for a write function. + +#include "Adafruit_VEML6070.h" + +Adafruit_VEML6070 env_veml6070 = Adafruit_VEML6070(); + +void init_veml6070(){ + bool ret = true; // NI + env_veml6070.begin(VEML6070_1_T); // pass in the integration time constant + if(!ret){ + Logger.println("[ERROR] _veml6070 init FAILED"); + } + else Logger.println("[ENV] _veml6070 is ~ACTIVE"); + // return ret; +} + +void print_veml6070(){ +} + +float get_veml6070(uint8_t channel = 0){ + // print_env(); + if(channel == 0) return env_veml6070.readUV(); +} +#endif + + +#ifdef PMSx // particulate matter / DUST sensor + +#ifndef ESP32 +#include +#endif + +#include // Arduino library for PM sensors with serial interface + +bool pms_debug = false; +#if !defined(PMS_RX) && !defined(PMS_TX) +constexpr auto PMS_RX = 14; +constexpr auto PMS_TX = 17; +#endif + +#ifndef ESP32 +SerialPM pms(PMS5003, PMS_RX, PMS_TX); // PMSx003, RX, TX + +// Alternative: +//SoftwareSerial SoftSerial1(PMS_RX, PMS_TX); +//SerialPM pms(PMS5003, SoftSerial1); +#else +SerialPM pms(PMS5003, PMS_RX, PMS_TX); // PMSx003, RX, TX +#endif + +bool init_pms(){ + // Logger.println(F("PMS sensor on SWSerial")); + // Logger.print(F(" RX:")); + // Logger.println(PMS_RX); + // Logger.print(F(" TX:")); + // Logger.println(PMS_TX); + bool ret = true; + pms.init(); + if(!ret){ + Logger.println("[ERROR] pms init FAILED"); + } + else Logger.println("[ENV] pms is ACTIVE"); + return ret; +} + +void print_pms_status(){ + Logger.print("[ENV] pms status: "); + switch (pms.status) + { + case pms.OK: // should never come here + Logger.println("OK"); + break; // included to compile without warnings + case pms.ERROR_TIMEOUT: + Logger.println(F(PMS_ERROR_TIMEOUT)); + break; + case pms.ERROR_MSG_UNKNOWN: + Logger.println(F(PMS_ERROR_MSG_UNKNOWN)); + break; + case pms.ERROR_MSG_HEADER: + Logger.println(F(PMS_ERROR_MSG_HEADER)); + break; + case pms.ERROR_MSG_BODY: + Logger.println(F(PMS_ERROR_MSG_BODY)); + break; + case pms.ERROR_MSG_START: + Logger.println(F(PMS_ERROR_MSG_START)); + break; + case pms.ERROR_MSG_LENGTH: + Logger.println(F(PMS_ERROR_MSG_LENGTH)); + break; + case pms.ERROR_MSG_CKSUM: + Logger.println(F(PMS_ERROR_MSG_CKSUM)); + break; + case pms.ERROR_PMS_TYPE: + Logger.println(F(PMS_ERROR_PMS_TYPE)); + break; + } + } + +void print_pms(){ + // print the results + Logger.print(F("PM1.0 ")); + Logger.print(pms.pm01); + Logger.print(F(", ")); + Logger.print(F("PM2.5 ")); + Logger.print(pms.pm25); + Logger.print(F(", ")); + Logger.print(F("PM10 ")); + Logger.print(pms.pm10); + Logger.println(F(" [ug/m3]")); + + if(!pms_debug) return; + + print_pms_status(); + + if (pms.has_number_concentration()) + { + Serial.print(F("N0.3 ")); + Serial.print(pms.n0p3); + Serial.print(F(", ")); + Serial.print(F("N0.5 ")); + Serial.print(pms.n0p5); + Serial.print(F(", ")); + Serial.print(F("N1.0 ")); + Serial.print(pms.n1p0); + Serial.print(F(", ")); + Serial.print(F("N2.5 ")); + Serial.print(pms.n2p5); + Serial.print(F(", ")); + Serial.print(F("N5.0 ")); + Serial.print(pms.n5p0); + Serial.print(F(", ")); + Serial.print(F("N10 ")); + Serial.print(pms.n10p0); + Serial.println(F(" [#/100cc]")); + } + + if (pms.has_temperature_humidity() || pms.has_formaldehyde()) + { + Serial.print(pms.temp, 1); + Serial.print(F(" °C")); + Serial.print(F(", ")); + Serial.print(pms.rhum, 1); + Serial.print(F(" %rh")); + Serial.print(F(", ")); + Serial.print(pms.hcho, 2); + Serial.println(F(" mg/m3 HCHO")); + } +} + + +float get_pms(uint8_t channel = 0){ + // print_env(); + if(channel == 0){ + pms.read(); + return pms.pm01; + } + if(channel == 1) return pms.pm25; + if(channel == 2) return pms.pm10; + if(channel == 3) return pms.n0p3; + if(channel == 4) return pms.n0p5; + if(channel == 5) return pms.n1p0; + if(channel == 6) return pms.n2p5; + if(channel == 7) return pms.n5p0; + if(channel == 8) return pms.n10p0; +} + +#endif + + #ifdef PCF8591 #include @@ -130,10 +390,10 @@ bool init_PCF8591(){ bool ret = false; ret = pcf.begin(); if(!ret){ - Logger.println("[ERROR] PCF8591 init failed"); + Logger.println("[ERROR] PCF8591 init FAILED"); return false; } - else Logger.println("[ENV] PCF8591 initialized!"); + else Logger.println("[ENV] PCF8591 is ACTIVE"); pcf.enableDAC(true); return ret; } @@ -184,9 +444,9 @@ bool init_INA219(){ bool ret = false; ret = ina219.begin(); if(!ret){ - Logger.println("[ERROR] INA219 init failed"); + Logger.println("[ERROR] INA219 init FAILED"); } - else Logger.println("[ENV] INA219 initialized!"); + else Logger.println("[ENV] INA219 is ACTIVE"); return ret; } @@ -254,9 +514,9 @@ bool init_mpu6050(){ if(!ret){ - Logger.println("[ERROR] MPU6050 init failed"); + Logger.println("[ERROR] MPU6050 init FAILED"); } - else Logger.println("[ENV] MPU6050 gyro/accel initialized!"); + else Logger.println("[ENV] MPU6050 gyro/accel is ACTIVE"); return ret; } @@ -303,71 +563,107 @@ float get_mpu6050(uint8_t channel = 0){ #endif -#ifdef BH1750 -#include //inlude the library -hp_BH1750 env_BH1750; -// BH1750Address addr = BH1750_TO_VCC; -// BH1750Address BH1750addr = BH1750_TO_GROUND; -// 0x23/0x5A , or 0X5C -// BH1750_TO_GROUND = 0x23, -// BH1750_TO_VCC = 0x5C -bool init_bh1750(){ - Logger.println("[ENV] hp_BH175 init"); - bool status = env_BH1750.begin(BH1750_TO_GROUND); // will be false no sensor found - // use BH1750_TO_GROUND or BH1750_TO_VCC depending how you wired the address pin of the sensor. - - // BH1750.calibrateTiming(); //uncomment this line if you want to speed up your sensor - env_BH1750.start(); - // BH1750.start(BH1750_QUALITY_HIGH2, mtreg); - // BH1750.setQuality(mode); - - if(!status) Logger.println("[ERROR] bh1750 failed to initialize device! Please check your wiring."); - else Logger.println("[ENV] bh1750 Device initialized!"); - return status; +#ifdef USEBH1750 +#include +BH1750 lightMeter(0x23); + +bool init_BH1750(){ + bool ret = false; + ret = lightMeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE); + if(!ret){ + Logger.println("[ERROR] BH1750 init FAILED"); + } + else Logger.println("[ENV] BH1750 is ACTIVE"); + return ret; } -void print_bh1750(){ - if (env_BH1750.hasValue() == true) { // non blocking reading - float lux = env_BH1750.getLux(); - Logger.println(lux); - env_BH1750.start(); - } +void print_BH1750(){ } -float get_bh1750(uint8_t channel = 0){ - float lux; - if(channel == 0){ - if (env_BH1750.hasValue() == true) { // non blocking reading - lux = env_BH1750.getLux(); - env_BH1750.start(); - Logger.println(lux); - } - } - else{ - env_BH1750.start(); //starts a measurement - lux=env_BH1750.getLux(); - Logger.println(lux); +float get_BH1750(uint8_t channel = 0){ + // print_env(); + if (lightMeter.measurementReady()){ + if(channel == 0) return (float)lightMeter.readLightLevel(); + if(channel == 1) return 0; + if(channel == 2) return 0; } - return lux; + return 0; } #endif +// #ifdef BH1750_B +// #include //inlude the library +// hp_BH1750 env_BH1750_B; + +// // BH1750Address addr = BH1750_TO_VCC; +// // BH1750Address BH1750addr = BH1750_TO_GROUND; +// // 0x23/0x5A , or 0X5C +// // BH1750_TO_GROUND = 0x23, +// // BH1750_TO_VCC = 0x5C + +// void print_bh1750(){ +// if (env_BH1750_B.hasValue() == true) { // non blocking reading +// float lux = env_BH1750_B.getLux(); +// Logger.println("[ENV] lux"); +// Logger.println(lux); +// env_BH1750_B.start(); +// } +// } + +// bool init_bh1750(){ +// bool status = env_BH1750_B.begin(BH1750_TO_GROUND); // will be false no sensor found +// // use BH1750_TO_GROUND or BH1750_TO_VCC depending how you wired the address pin of the sensor. + +// // BH1750.calibrateTiming(); //uncomment this line if you want to speed up your sensor +// env_BH1750_B.start(); +// // BH1750.start(BH1750_QUALITY_HIGH2, mtreg); +// // BH1750.setQuality(mode); + +// if(!status) Logger.println("[ERROR] BH1750 init FAILED"); +// else Logger.println("[ENV] BH1750 Device is ACTIVE"); + +// return status; +// } + +// float get_bh1750(uint8_t channel = 0){ +// float lux; +// if(channel == 0){ +// Logger.println("env_BH1750_B get channel 0"); +// if (env_BH1750_B.hasValue() == true) { // non blocking reading +// Logger.println("env_BH1750_B has value"); +// lux = env_BH1750_B.getLux(); +// env_BH1750_B.start(); +// Logger.println(lux); +// } +// } +// else{ +// env_BH1750_B.start(); //starts a measurement +// lux=env_BH1750_B.getLux(); +// Logger.println(lux); +// } +// return lux; +// } +// #endif + + #ifdef APDS9960 #include "Adafruit_APDS9960.h" Adafruit_APDS9960 apds; uint8_t apds_int_pin = -1; +// apds_addr = ; + bool init_apds(){ bool ret = false; ret = apds.begin(); if(!ret){ - Logger.println("[ERROR] APDS9960 init failed"); + Logger.println("[ERROR] APDS9960 init FAILED"); } - else Logger.println("[ENV] APDS9960 initialized!"); + else Logger.println("[ENV] APDS9960 is ACTIVE"); if(apds_int_pin > 0) pinMode(apds_int_pin, INPUT_PULLUP); return ret; } @@ -534,9 +830,9 @@ Adafruit_BMP280 bmp; // I2C #ifdef USEBMP280 void init_bmp280(){ if (!bmp.begin(BMP280_ADDRESS_ALT)) { - Logger.println(F("[ERROR] Could not find a valid BMP280 sensor, check wiring!")); + Logger.println(F("[ERROR] BMP280 init FAILED")); } - else Logger.println(F("[ENV] BMP280 sensor is active")); + else Logger.println(F("[ENV] BMP280 is ACTIVE")); /* Default settings from datasheet. */ bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */ @@ -581,11 +877,11 @@ uint8_t loopCnt = 0; void init_sht31(){ bool init = sht31.begin(0x44); if(init){ - Logger.println(F("[ENV] SHT31 sensor is active")); + Logger.println(F("[ENV] SHT31 is ACTIVE")); } else { - Logger.println(F("[ERROR] SHT31 init failed")); + Logger.println(F("[ERROR] SHT31 init FAILED")); } Logger.print("Heater Enabled State: "); @@ -628,7 +924,7 @@ void sht31_process(){ if (++loopCnt == 30) { enableHeater = !enableHeater; sht31.heater(enableHeater); - Logger.print("Heater Enabled State: "); + Logger.print("[ENV] SHT31 Heater State: "); if (sht31.isHeaterEnabled()) Logger.println("ENABLED"); else @@ -643,11 +939,11 @@ void sht31_process(){ void init_sht21(){ bool init = myHTU21D.begin(); if(init){ - Logger.println(F("[ENV] HTU21D, SHT21 sensor initialized")); + Logger.println(F("[ENV] HTU21D, SHT21 is ACTIVE")); } else { - Logger.println(F("[ERROR] HTU21D, SHT21 sensor is failed or not connected")); //(F()) saves string to flash & keeps dynamic memory free + Logger.println(F("[ERROR] HTU21D, SHT21 init FAILED")); //(F()) saves string to flash & keeps dynamic memory free } delay(1000); @@ -722,11 +1018,11 @@ void print_LM75(){ Adafruit_CCS811 ccs; void init_cs811(){ - Logger.println("[ENV] cs811 init"); if(!ccs.begin()){ - Logger.println("[ERROR] CS811 Begin Failed"); + Logger.println("[ERROR] CS811 init FAILED"); } else { + Logger.println("[ENV] CS811 is ACTIVE"); //calibrate temperature sensor while(!ccs.available() && millis() < 30000); float temp = ccs.calculateTemperature(); diff --git a/sense_env_class.h b/sense_env_class.h index f1fcbc2..5f71201 100644 --- a/sense_env_class.h +++ b/sense_env_class.h @@ -37,14 +37,14 @@ #ifndef sensorsdlog_h #define sensorsdlog_h -#include +// #include #include -using namespace std; +// using namespace std; #include // Average avg_a(20); -#include +// #include // Statistic myStats; // vector or list of sensor objects @@ -59,27 +59,48 @@ using namespace std; template class sensorcollection { private: - vector> sensors; - int _numsamples = 20; - + std::vector> sensors; + // sensors.resize() + uint32_t _numsamples = 20; public: sensorcollection(); - void addSensorValue(int idx,float value); + ~sensorcollection(); + void begin(); + void addSensor(int idx, uint8_t size); + void addSensorValue(int idx, T value); float getSensorValue(int idx); }; template sensorcollection::sensorcollection(){ + Serial.println("sensorcollection constructor"); // testing in constructor for now // BUT how to create many new instances and retain them in class? // Average avg_x(_numsamples); // scope this in class?, surely this will go bye bye + } + + template + sensorcollection::~sensorcollection(){ + Serial.println("sensorcollection de-constructor"); + sensors.clear(); + } + + template + void sensorcollection::begin(){ sensors.push_back(Average(_numsamples)); // use temp obj or smart pointers? } template - void sensorcollection::addSensorValue(int idx,float value){ + void sensorcollection::addSensor(int idx, uint8_t size){ + Average *avg_x = new Average(size); + sensors.push_back(*avg_x); // use temp obj or smart pointers? + Serial.println("added sensor: " + (String)idx); + } + + template + void sensorcollection::addSensorValue(int idx, T value){ sensors[idx].push(value); } @@ -88,42 +109,42 @@ class sensorcollection { return sensors[idx].mean(); } -// individual sensor log, one per value -// or find a way to create anonymous objects, but each one might have different units so might as well keep them seperate. -template -class sensordlog { - private: +// // individual sensor log, one per value +// // or find a way to create anonymous objects, but each one might have different units so might as well keep them seperate. +// template +// class sensordlog { +// private: - const char* _id; // unique id of collection - const char* _name; // name - char* _unit; // units of values eg. ug/L - T datatype; // template of typename of sample, float, int etc - int _numsamples = 20; // number of samples to store in buffer - - public: - sensordlog(); // add inializer list or use setters? - ~sensordlog(); - - // setSensorRange(T min, T max); - // setSensorNumSamples(int numSamples); - - // getValue(char* id); // self.value() - // getAvg(); //self.avg() - // getMean(); - // getMode(); - // getMax(); - // getMin(); +// const char* _id; // unique id of collection +// const char* _name; // name +// char* _unit; // units of values eg. ug/L +// T datatype; // template of typename of sample, float, int etc +// int _numsamples = 20; // number of samples to store in buffer + +// public: +// sensordlog(); // add inializer list or use setters? +// ~sensordlog(); + +// // setSensorRange(T min, T max); +// // setSensorNumSamples(int numSamples); + +// // getValue(char* id); // self.value() +// // getAvg(); //self.avg() +// // getMean(); +// // getMode(); +// // getMax(); +// // getMin(); - // extended - // pass in pointer funcs for specific library methods - // init() - // update() -}; +// // extended +// // pass in pointer funcs for specific library methods +// // init() +// // update() +// }; -template sensordlog::sensordlog(){ - Serial.println("constructor"); - // sensors.push_back(Statistic myStats1); // ? how to use an anoymous object pointer in vector? -} +// template sensordlog::sensordlog(){ +// Serial.println("constructor"); +// // sensors.push_back(Statistic myStats1); // ? how to use an anoymous object pointer in vector? +// } #endif \ No newline at end of file From 69bf035b5e7b054e79637efe5d400306fbc87de9 Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Mon, 27 Dec 2021 12:56:32 -0600 Subject: [PATCH 125/186] minor updates --- .gitignore | 4 +- encoder.h | 1 + lcd_i2c.h | 829 +++++++++++++++++++++++++------------------------ led_funcs.h | 26 +- neoindicator.h | 22 +- wifi_funcs.h | 2 +- 6 files changed, 454 insertions(+), 430 deletions(-) diff --git a/.gitignore b/.gitignore index 9860452..437b8ff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ - -creds.h + +creds.h diff --git a/encoder.h b/encoder.h index 099e6cd..6f84d95 100644 --- a/encoder.h +++ b/encoder.h @@ -3,6 +3,7 @@ * // https://github.com/soligen2010/encoder */ #include +// : error: 'ClickEncoder::buttonHeldEnabled' will be initialized after [-Werror=reorder] #define ENCODER_PINA 2 // not working #define ENCODER_PINB 16 // working diff --git a/lcd_i2c.h b/lcd_i2c.h index bbc4e48..10f460a 100755 --- a/lcd_i2c.h +++ b/lcd_i2c.h @@ -1,413 +1,418 @@ -// #include <../LiquidCrystal_I2C/LiquidCrystal_I2C.h> - -const int numRows = 2; -const int numCols = 16; -int backlightState = true; - -uint8_t _SCL = 15; -uint8_t _SDA = 13; - -// i2c pins nodemcu -// SCL D1 -// SDA D2 -LiquidCrystal_I2C lcd(0x27,numCols,numRows); // set the LCD address to 0x27 for a 16 chars and 2 line display - -// quality icon 0-6 0x - 100% -/* - * XXXXX - * X X - * X - * X X - * XXX - * XXXXX - * XXXXXX - */ -byte qualityIco[][8] = { -{ - 0b11100, - 0b10100, - 0b01000, - 0b01000, - 0b00000, - 0b10100, - 0b01000, - 0b10100 -}, -{ - 0b11100, - 0b10100, - 0b01000, - 0b01000, - 0b00000, - 0b00000, - 0b00000, - 0b10000 -}, -{ - 0b11100, - 0b10100, - 0b01000, - 0b01000, - 0b00000, - 0b00000, - 0b01000, - 0b11000 -}, -{ - 0b11100, - 0b10100, - 0b01000, - 0b01000, - 0b00000, - 0b00100, - 0b01100, - 0b11100 -}, -{ - 0b11100, - 0b10100, - 0b01000, - 0b01000, - 0b00010, - 0b00110, - 0b01110, - 0b11110 -}, -{ - 0b11100, - 0b10100, - 0b01000, - 0b01001, - 0b00011, - 0b00111, - 0b01111, - 0b11111 -} -}; - - - -byte block4[4][8] = { -{ - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b00000, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b11111 -} -}; - -byte block[8][8] = { -{ - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b00000, - 0b11111, - 0b11111, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b11111, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b11111, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b11111, - 0b11111 -}, -{ - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b00000, - 0b11111 -} -}; - -// degrees F -byte degF[8] = { - 0b01000, - 0b10100, - 0b01000, - 0b00000, - 0b00011, - 0b00100, - 0b00111, - 0b00100 -}; - -// dergees C -byte degC[8] = { - 0b01000, - 0b10100, - 0b01000, - 0b00000, - 0b00011, - 0b00100, - 0b00100, - 0b00011 -}; - -// thermometer -byte thermico[8] = { - 0b00100, - 0b01010, - 0b01010, - 0b01110, - 0b01110, - 0b11111, - 0b11111, - 0b01110 -}; - -// droplet -byte humico[8] = { - 0b00100, - 0b00100, - 0b01010, - 0b01010, - 0b10001, - 0b10001, - 0b10001, - 0b01110 -}; - -// small % -byte perc[8] = { - 0b00000, - 0b00000, - 0b10010, - 0b00100, - 0b01000, - 0b10010, - 0b00000, - 0b00000 -}; - -byte arial[8] = { - 0b11111, - 0b10101, - 0b01110, - 0b00100, - 0b00100, - 0b00100, - 0b00100, - 0b00000 -}; - -byte wifi[8] = { - 0b01110, - 0b10001, - 0b00100, - 0b01010, - 0b00000, - 0b00100, - 0b00000, - 0b00000 -}; - -byte db[8] = { - 0b00000, - 0b00000, - 0b11100, - 0b00000, - 0b00110, - 0b11111, - 0b10101, - 0b11111 -}; - -byte link[4][8] = { -{ - 0b00000, - 0b00111, - 0b11101, - 0b10111, - 0b10000, - 0b10101, - 0b11010, - 0b00101 -}, -{ - 0b00000, - 0b00111, - 0b11101, - 0b10111, - 0b10000, - 0b10111, - 0b11101, - 0b00111 -}, -{ - 0b11100, - 0b10111, - 0b11101, - 0b00000, - 0b00000, - 0b11101, - 0b10111, - 0b11100 -}, -{ - 0b10100, - 0b01011, - 0b10101, - 0b00001, - 0b00001, - 0b11101, - 0b10111, - 0b11100 -} -}; - - -const uint8_t WIFIQICO = 0; -const uint8_t ARIALICO = 1; -const uint8_t WIFIDBICO = 32; // space -const uint8_t WIFILINKICO = 2; // space -const uint8_t GRAPHICO = 2; - -// dynamic icon -uint8_t getQualityIcon(int rssi){ - if(rssi >=0 || rssi<-96) rssi = 0; // -96 unusable signal, +int invalid rssi - else rssi = map(rssi,-1,-100,5,1); - Serial.println("quality: " + (String)rssi); - lcd.createChar(0,qualityIco[rssi]); - return 0; -} -// dynamic icon -uint8_t getConnectIcon(int connState){ - return 32; - // Serial.println("connect: " + (String)connState); - lcd.createChar(WIFILINKICO,link[connState]); - return WIFILINKICO; -} - -void initLcdChars(){ - lcd.createChar(WIFIQICO, qualityIco[0]); - lcd.createChar(ARIALICO, arial); - lcd.createChar(WIFILINKICO, link[0]); - lcd.createChar(WIFIDBICO, db); -} - -uint8_t getGraphIcon(int in){ - int value = map(in,100,0,GRAPHICO,GRAPHICO+5); - if(value == GRAPHICO) return 255; // 0 - return value; -} - -void initLcdGraphChars(){ - // lcd.createChar(GRAPHICO, block[1]); // char 255 - lcd.createChar(GRAPHICO+1, block[2]); - lcd.createChar(GRAPHICO+2, block[3]); - lcd.createChar(GRAPHICO+3, block[4]); - lcd.createChar(GRAPHICO+4, block[5]); - lcd.createChar(GRAPHICO+5, block[6]); - // lcd.createChar(range+6, block[3]); -} - -void initLCD(){ - Wire.setClock(400000L); // set i2c speed 400khz - Wire.begin(_SDA,_SCL); - lcd.init(); // initialize the lcd - - if(backlightState) lcd.backlight(); - else lcd.noBacklight(); - - lcd.clear(); - delay(500); - lcd.print("Booting......"); - - // create a new custom character - initLcdChars(); - initLcdGraphChars(); +#include + +const int numRows = 2; +const int numCols = 16; +int backlightState = true; + +uint8_t _SCL = 15; +uint8_t _SDA = 13; + +// i2c pins nodemcu +// SCL D1 +// SDA D2 +LiquidCrystal_I2C lcd(0x27,numCols,numRows); // set the LCD address to 0x27 for a 16 chars and 2 line display + +// quality icon 0-6 0x - 100% +/* + * XXXXX + * X X + * X + * X X + * XXX + * XXXXX + * XXXXXX + */ +byte qualityIco[][8] = { +{ + 0b11100, + 0b10100, + 0b01000, + 0b01000, + 0b00000, + 0b10100, + 0b01000, + 0b10100 +}, +{ + 0b11100, + 0b10100, + 0b01000, + 0b01000, + 0b00000, + 0b00000, + 0b00000, + 0b10000 +}, +{ + 0b11100, + 0b10100, + 0b01000, + 0b01000, + 0b00000, + 0b00000, + 0b01000, + 0b11000 +}, +{ + 0b11100, + 0b10100, + 0b01000, + 0b01000, + 0b00000, + 0b00100, + 0b01100, + 0b11100 +}, +{ + 0b11100, + 0b10100, + 0b01000, + 0b01000, + 0b00010, + 0b00110, + 0b01110, + 0b11110 +}, +{ + 0b11100, + 0b10100, + 0b01000, + 0b01001, + 0b00011, + 0b00111, + 0b01111, + 0b11111 +} +}; + + + +byte block4[4][8] = { +{ + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b00000, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b11111 +} +}; + +byte block[8][8] = { +{ + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b00000, + 0b11111, + 0b11111, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b11111, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b11111, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b11111, + 0b11111 +}, +{ + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b00000, + 0b11111 +} +}; + +// degrees F +byte degF[8] = { + 0b01000, + 0b10100, + 0b01000, + 0b00000, + 0b00011, + 0b00100, + 0b00111, + 0b00100 +}; + +// dergees C +byte degC[8] = { + 0b01000, + 0b10100, + 0b01000, + 0b00000, + 0b00011, + 0b00100, + 0b00100, + 0b00011 +}; + +// thermometer +byte thermico[8] = { + 0b00100, + 0b01010, + 0b01010, + 0b01110, + 0b01110, + 0b11111, + 0b11111, + 0b01110 +}; + +// droplet +byte humico[8] = { + 0b00100, + 0b00100, + 0b01010, + 0b01010, + 0b10001, + 0b10001, + 0b10001, + 0b01110 +}; + +// small % +byte perc[8] = { + 0b00000, + 0b00000, + 0b10010, + 0b00100, + 0b01000, + 0b10010, + 0b00000, + 0b00000 +}; + +byte arial[8] = { + 0b11111, + 0b10101, + 0b01110, + 0b00100, + 0b00100, + 0b00100, + 0b00100, + 0b00000 +}; + +byte wifi[8] = { + 0b01110, + 0b10001, + 0b00100, + 0b01010, + 0b00000, + 0b00100, + 0b00000, + 0b00000 +}; + +byte db[8] = { + 0b00000, + 0b00000, + 0b11100, + 0b00000, + 0b00110, + 0b11111, + 0b10101, + 0b11111 +}; + +byte wlink[4][8] = { +{ + 0b00000, + 0b00111, + 0b11101, + 0b10111, + 0b10000, + 0b10101, + 0b11010, + 0b00101 +}, +{ + 0b00000, + 0b00111, + 0b11101, + 0b10111, + 0b10000, + 0b10111, + 0b11101, + 0b00111 +}, +{ + 0b11100, + 0b10111, + 0b11101, + 0b00000, + 0b00000, + 0b11101, + 0b10111, + 0b11100 +}, +{ + 0b10100, + 0b01011, + 0b10101, + 0b00001, + 0b00001, + 0b11101, + 0b10111, + 0b11100 +} +}; + + +const uint8_t WIFIQICO = 0; +const uint8_t ARIALICO = 1; +const uint8_t WIFIDBICO = 32; // space +const uint8_t WIFILINKICO = 2; // space +const uint8_t GRAPHICO = 2; + +// dynamic icon +uint8_t getQualityIcon(int rssi){ + if(rssi >=0 || rssi<-96) rssi = 0; // -96 unusable signal, +int invalid rssi + else rssi = map(rssi,-1,-100,5,1); + Serial.println("quality: " + (String)rssi); + lcd.createChar(0,qualityIco[rssi]); + return 0; +} +// dynamic icon +uint8_t getConnectIcon(int connState){ + return 32; + // Serial.println("connect: " + (String)connState); + lcd.createChar(WIFILINKICO,wlink[connState]); + return WIFILINKICO; +} + +void initLcdChars(){ + lcd.createChar(WIFIQICO, qualityIco[0]); + lcd.createChar(ARIALICO, arial); + lcd.createChar(WIFILINKICO, wlink[0]); + lcd.createChar(WIFIDBICO, db); +} + +uint8_t getGraphIcon(int in){ + int value = map(in,100,0,GRAPHICO,GRAPHICO+5); + if(value == GRAPHICO) return 255; // 0 + return value; +} + +void initLcdGraphChars(){ + // lcd.createChar(GRAPHICO, block[1]); // char 255 + lcd.createChar(GRAPHICO+1, block[2]); + lcd.createChar(GRAPHICO+2, block[3]); + lcd.createChar(GRAPHICO+3, block[4]); + lcd.createChar(GRAPHICO+4, block[5]); + lcd.createChar(GRAPHICO+5, block[6]); + // lcd.createChar(range+6, block[3]); +} + +void initLCD(){ + // Wire.begin(_SDA,_SCL); + Wire.begin(); + Wire.setClock(1700000L); // set i2c speed 400khz + lcd.init(); // initialize the lcd + + lcd.noBacklight(); + delay(1000); + lcd.backlight(); + + if(backlightState) lcd.backlight(); + else lcd.noBacklight(); + + lcd.clear(); + delay(500); + lcd.print("Booting......"); + + // create a new custom character + initLcdChars(); + initLcdGraphChars(); } \ No newline at end of file diff --git a/led_funcs.h b/led_funcs.h index c005117..9e343e5 100755 --- a/led_funcs.h +++ b/led_funcs.h @@ -1,14 +1,14 @@ -/** - * LED STUFF - */ - -// #include <../bit_bang_neopixel_binary/bit_bang_neopixel_binary.h> -#include -#include <../bit_bang_neopixel_binary/custom_color_funcs.h> - -// #ifdef ESP8266 -// #ifdef NEOHIGHSPEED -// // ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution -// extern "C" void ICACHE_RAM_ATTR espShow( -// uint8_t pin, uint8_t *pixels, uint32_t numBytes, uint8_t type); +/** + * LED STUFF + */ + +// #include <../bit_bang_neopixel_binary/bit_bang_neopixel_binary.h> +#include +#include <../bit_bang_neopixel_binary/custom_color_funcs.h> + +// #ifdef ESP8266 +// #ifdef NEOHIGHSPEED +// // ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution +// extern "C" void ICACHE_RAM_ATTR espShow( +// uint8_t pin, uint8_t *pixels, uint32_t numBytes, uint8_t type); // #endif \ No newline at end of file diff --git a/neoindicator.h b/neoindicator.h index 5fae296..efbe5bb 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -41,8 +41,8 @@ Adafruit_NeoPixel ind = Adafruit_NeoPixel(); // palevioletred #DB7093 rgb(219,112,147) // mediumvioletred #C71585 rgb(199,21,133) -uint16_t INDBRIGHTNESS = 60; -int INDNUMPIXELS = 1; +uint16_t INDBRIGHTNESS = 255; +int INDNUMPIXELS = 2; #define INDPIXELSTYPE NEO_GRB + NEO_KHZ800 bool INDPINRESET = false; @@ -75,9 +75,27 @@ void debugColor(uint32_t c){ Serial.println("[RGB] Blue: " + (String)blue(c)); } +void indSetColorB(uint32_t c){ + if(DEBUG_neoind)Serial.println("[IND] set ind color:" + (String)c); + // debugColor(c); + // uint32_t color = ColorRGBA(red(c),green(c),blue(c),255); + ind.setPixelColor( 1, c); + if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset + #ifdef ESP32 + if(noInterrupts) portDISABLE_INTERRUPTS(); + #endif + ind.show(); + if(showTwice) ind.show(); + #ifdef ESP32 + if(noInterrupts) portENABLE_INTERRUPTS(); + #endif + // #endif +} + void indSetColor(uint32_t c){ if(DEBUG_neoind)Serial.println("[IND] set ind color:" + (String)c); // debugColor(c); + // uint32_t color = ColorRGBA(red(c),green(c),blue(c),255); ind.setPixelColor( 0, c ); if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset #ifdef ESP32 diff --git a/wifi_funcs.h b/wifi_funcs.h index 92cf1a4..7c195b1 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -184,7 +184,7 @@ void init_WiFi(int timeout){ delay(500); } -void init_wifi(){ +void init_WiFi(){ init_WiFi(0); } From e4992077ff5443cd01c5f45b6d5b024ff013f9a6 Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Sun, 2 Jan 2022 19:38:39 -0600 Subject: [PATCH 126/186] minor updates, wifi fast connect and neopixel aux --- httpportal.h | 7 ++++- log.h | 2 ++ mqtt.h | 2 +- neoindicator.h | 14 ++++----- pid.h | 3 +- wifi_funcs.h | 84 ++++++++++++++++++++++++++++++++++---------------- 6 files changed, 76 insertions(+), 36 deletions(-) diff --git a/httpportal.h b/httpportal.h index b93de8b..d977b70 100644 --- a/httpportal.h +++ b/httpportal.h @@ -6,7 +6,8 @@ #include #include -WiFiManager portal(Logger); +// WiFiManager portal(Logger); +WiFiManager portal; void init_httpportal(String title = ""){ portal.setDebugOutput(true,"[HTTPP] "); @@ -31,4 +32,8 @@ void process_httpportal(){ portal.process(); } +void begin_httpportalap(){ + portal.startConfigPortal(); +} + #endif diff --git a/log.h b/log.h index 823bc34..dc43b5f 100644 --- a/log.h +++ b/log.h @@ -35,6 +35,7 @@ void sendToSyslog(String msg){ if(msgb.indexOf("warning") != -1) level = LOG_WARNING; if(msgb.indexOf("fatal") != -1) level = LOG_CRIT; if(syslogactive) syslog.log(level,msg); // SEND IT + // if(syslogactive) syslog.log(level,(String)millis()+" "+msg); // SEND IT // todo clean up string, remove whitespace such as CR LF \t // reset buffer logbuffer[0] = (char)0; @@ -209,6 +210,7 @@ void debugPlatformInfo(){ size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); DEBUGGER("Free heap: ", freeHeap); DEBUGGER("ESP-IDF version: ", esp_get_idf_version()); + // log_v("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model, chipInfo.cores, chipInfo.revision); #endif } diff --git a/mqtt.h b/mqtt.h index 420d912..ee1a982 100644 --- a/mqtt.h +++ b/mqtt.h @@ -26,7 +26,7 @@ WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = true; +bool debug_mqtt = false; bool debug_mqtt_json = false; const char* clientID = ""; diff --git a/neoindicator.h b/neoindicator.h index efbe5bb..4f6dce5 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -41,7 +41,7 @@ Adafruit_NeoPixel ind = Adafruit_NeoPixel(); // palevioletred #DB7093 rgb(219,112,147) // mediumvioletred #C71585 rgb(199,21,133) -uint16_t INDBRIGHTNESS = 255; +uint16_t INDBRIGHTNESS = 60; int INDNUMPIXELS = 2; #define INDPIXELSTYPE NEO_GRB + NEO_KHZ800 @@ -54,7 +54,7 @@ void init_indicator(uint16_t pin){ // Adafruit_NeoPixel // strip = ind; ind.setPin(pin); - ind.setBrightness(INDBRIGHTNESS); + ind.setBrightness(255); ind.updateLength(INDNUMPIXELS); ind.updateType(NEO_GRB + NEO_KHZ800); ind.begin(); @@ -78,7 +78,6 @@ void debugColor(uint32_t c){ void indSetColorB(uint32_t c){ if(DEBUG_neoind)Serial.println("[IND] set ind color:" + (String)c); // debugColor(c); - // uint32_t color = ColorRGBA(red(c),green(c),blue(c),255); ind.setPixelColor( 1, c); if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset #ifdef ESP32 @@ -95,8 +94,8 @@ void indSetColorB(uint32_t c){ void indSetColor(uint32_t c){ if(DEBUG_neoind)Serial.println("[IND] set ind color:" + (String)c); // debugColor(c); - // uint32_t color = ColorRGBA(red(c),green(c),blue(c),255); - ind.setPixelColor( 0, c ); + uint32_t color = ColorRGBA(red(c),green(c),blue(c),INDBRIGHTNESS); + ind.setPixelColor( 0, color ); if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset #ifdef ESP32 if(noInterrupts) portDISABLE_INTERRUPTS(); @@ -113,7 +112,8 @@ void indSetColor(uint32_t c){ // alias void setIndBrightness(uint16_t alpha = INDBRIGHTNESS){ - ind.setBrightness(alpha); + INDBRIGHTNESS = alpha; + // ind.setBrightness(alpha); } void setIndColor(uint32_t c){ @@ -240,7 +240,7 @@ void indTest(bool quicktest = true){ rainbowInd(wait); indSetColor(0,0,0); // set black - ind.setBrightness(INDBRIGHTNESS); // set normal brightness + // ind.setBrightness(INDBRIGHTNESS); // set normal brightness Serial.println("[IND] indtest complete"); } diff --git a/pid.h b/pid.h index 228bde9..cc96892 100644 --- a/pid.h +++ b/pid.h @@ -24,7 +24,7 @@ // da fuq? uint16_t fullPowerPeriod = 8000; // full power startup pulse period -bool fullPowerStartup = true; // enable full power period if startup wanted temp is greater than 5 degrees(arb) +bool fullPowerStartup = false; // enable full power period if startup wanted temp is greater than 5 degrees(arb) bool pidEnabled = false; int long pidTimerStart = 0; @@ -108,6 +108,7 @@ float integatorReset = 0.75; // when to reset Ki percent of delta 75% double KpLite = 4, KiLite = .5, KdLite = 0; // slight undershoot, needs a little more power on ramp and peak double Kp = 13, Ki = .5, Kd = 0; // slight undershoot, needs a little more power on ramp and peak +// double Kp = 5, Ki = .1, Kd = 0; // slight undershoot, needs a little more power on ramp and peak // agressive double KpAgr = 28, KiAgr = .5, KdAgr = 0; // slight undershoot, needs a little more power on ramp and peak diff --git a/wifi_funcs.h b/wifi_funcs.h index 7c195b1..bb39bd1 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -17,12 +17,12 @@ // const char* hostname = "esp8266REFLOW"; -bool debug_wifi = false; +bool debug_wifi = true; -long downtimeRestart = 1*3600; // 5 minutes +bool rebootAfterDowntime = true; +long downtimeRestart = 1*3600; // n minutes long downtime = 0; - /** IP to String? */ String toStringIp(IPAddress ip) { String res = ""; @@ -96,6 +96,13 @@ bool wifiIsConnected(){ return WiFi.status() == WL_CONNECTED; } +void setWiFiFastConnect(){ + //fast scan + // set channel + // set bssid + // WiFi.begin(SSID,PASS,WiFi.channel(),WiFi.BSSID(),true); +} + String getDeviecID(){ String _wifissidprefix = "ESP"; String hostString = String(WIFI_getChipId(),HEX); @@ -130,6 +137,10 @@ void WiFi_print_sta(){ Serial.println(WiFi.localIP()); Serial.print("[WIFI] HOST: "); Serial.println(getHostname()); + Serial.print("[WIFI] BSSID: "); + Serial.println(WiFi.BSSIDstr()); + Serial.print("[WIFI] RSSI: "); + Serial.println(WiFi.RSSI()); } } @@ -142,44 +153,53 @@ void init_WiFi(int timeout){ // WiFi_print_sta(); // return; // } - + unsigned long start = millis(); Serial.println("[WIFI] mode STA"); WiFi.mode(WIFI_STA); - WiFi.printDiag(Serial); + if(debug_wifi) WiFi.printDiag(Serial); #ifdef ESP8266 WiFi.setSleepMode(WIFI_NONE_SLEEP); #elif defined(ESP32) // btStop(); - WiFi.setSleep(false); + // WiFi.setSleep(false); #endif - +// // WiFi.hostname(hostname); - unsigned long start = millis(); // if(wifiIsAutoConnect) WiFi.begin(); + // esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_11B| WIFI_PROTOCOL_11G|WIFI_PROTOCOL_11N|WIFI_PROTOCOL_LR); + WiFi.begin(SSID,PASS); if(timeout > 0){ - Serial.println("[WIFI] Connecting to wifi... [" + (String)timeout + " ms]\n"); + // use local timer loop + if(debug_wifi) Serial.println("[WIFI] Connecting to wifi, wait for timeout... [" + (String)timeout + " ms]\n"); while((WiFi.status() != WL_CONNECTED) && (millis()-start < timeout)){ - Serial.print("."); + if(debug_wifi) Serial.print("."); delay(100); } } else { - Serial.println("[WIFI] Connecting to wifi, waiting..... "); - while(WiFi.waitForConnectResult() != WL_CONNECTED){ - Serial.print("."); - delay(100); - } + // waitForConnecrtResult default 60000 + if(debug_wifi) Serial.println("[WIFI] Connecting to wifi, waitForConnectResult waiting..... "); + uint8_t status = WiFi.waitForConnectResult(); + // while(status() != WL_CONNECTED){ + // Serial.print("."); + // delay(500); + Serial.println((String)WiFi.status()); + // } } - Serial.println(""); + if(debug_wifi) Serial.println(""); if(wifiIsConnected()){ - WiFi_print_sta(); + setWiFiFastConnect(); + Serial.println("[WIFI] connected in " + (String)(millis()-start/1000) + " ms"); + if(debug_wifi) WiFi_print_sta(); } else{ Serial.println("[ERROR] WIFI CONNECT FAILED"); - Serial.println("[WIFI] waited for " + (String)(millis()-start/1000) + " seconds"); + Serial.println("[WIFI] waited for " + (String)(millis()-start/1000) + " ms"); + // delay(1000); + // WiFi.begin(SSID,PASS); } delay(500); } @@ -188,6 +208,10 @@ void init_WiFi(){ init_WiFi(0); } +void init_WiFi_saved(){ + WiFi.begin(); +} + int getRSSIasQuality(int RSSI) { int quality = 0; @@ -210,16 +234,16 @@ void checkWifi(){ Serial.println("[TASK] checkWiFi"); if(WiFi.status() != WL_CONNECTED ){ if(downtime == 0) downtime = millis(); - if(millis() > downtime + downtimeRestart){ + if(rebootAfterDowntime && (millis() > downtime + downtimeRestart)){ #ifdef USENEOIND - indSetColor(255,0,0); + indSetColor(np_red); #endif Serial.println("[ERROR] wifi not found, rebooting after timeout"); delay(1000); ESP.restart(); - } + } #ifdef USENEOIND - indSetColor(255,0,0); + indSetColor(np_red); #endif Serial.println("[WIFI] WiFi is Disconnected"); WiFi.reconnect(); @@ -229,7 +253,7 @@ void checkWifi(){ Serial.println("[WIFI] RSSI: "+(String)getRSSIasQuality()); } #ifdef USENEOIND - indSetColor(0,255,0); + indSetColor(np_green); #endif } } @@ -338,16 +362,24 @@ void disableWiFi(){ // if (SW_RESET == reason) { return REASON_EXT_SYS_RST; } // } + // esp_wifi_get_mac((wifi_interface_t)interface, mac); + // sprintf(winstance, "%s [%02x:%02x:%02x:%02x:%02x:%02x]", _hostname.c_str(), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + + // esp_wifi_get_mac((wifi_interface_t)WIFI_IF_STA, eth_mac); + // snprintf(default_hostname, 32, "%s%02X%02X%02X", CONFIG_IDF_TARGET "-", eth_mac[3], eth_mac[4], eth_mac[5]); + + +// @todo String getResetReason(){ int reason; #ifdef ESP8266 return ESP.getResetReason(); #elif defined(ESP32) && defined(_ROM_RTC_H_) // requires #include - for(int i=0;i<2;i++){ + // for(int i=0;i<2;i++){ // return ESP32GetResetReason(i); - return "NA"; - } + // } + return "NA"; #else return "UNSET"; #endif From dd30ca96a741623829a74a7455b366c7143c95a5 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 4 Jan 2022 15:51:04 -0600 Subject: [PATCH 127/186] add neoind state nb --- neoindicator.h | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/neoindicator.h b/neoindicator.h index 5fae296..5563919 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -31,6 +31,7 @@ bool noInterrupts = false; #include Adafruit_NeoPixel ind = Adafruit_NeoPixel(); + // Adafruit_NeoPixel strip = Adafruit_NeoPixel(1, PIN, NEO_GRB + NEO_KHZ800); // Adafruit_NeoPixel strip *= ind; @@ -48,7 +49,7 @@ int INDNUMPIXELS = 1; bool INDPINRESET = false; uint8_t neoIndTaskID; // timer task -uint32_t indColor; +uint32_t indColor; // save color void init_indicator(uint16_t pin){ // Adafruit_NeoPixel @@ -64,6 +65,10 @@ void init_indicator(uint16_t pin){ // init_strip(); } +/** + * [indSetNextColor description] + * @param c [description] + */ void indSetNextColor(uint32_t c){ indColor = c; } @@ -121,6 +126,7 @@ void stop_indicator(){ // @todo unset object } +// non blocking stepped color setter void updateIndColor(){ if(indColor != ind.getPixelColor(0)){ ind.setPixelColor(0,indColor); @@ -261,4 +267,9 @@ void IND_nb_animate(){ if(millis() - IND_lastUpdate > IND_ANIMDELAY) IND_nb_rainbow(); } + +void processNeoInd(){ + updateIndColor(); +} + #endif \ No newline at end of file From 66808836319b2a2dcad016bbed2476ef64b3db82 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 4 Jan 2022 15:51:39 -0600 Subject: [PATCH 128/186] add new hsv, and passing np objects --- neopixel_helper.h | 77 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 62 insertions(+), 15 deletions(-) diff --git a/neopixel_helper.h b/neopixel_helper.h index e64ecb8..5c6dc5a 100644 --- a/neopixel_helper.h +++ b/neopixel_helper.h @@ -17,22 +17,31 @@ int NEONUMPIXELS = 5; Adafruit_NeoPixel strip = Adafruit_NeoPixel(); // these are const, so they don't eat RAM -const uint32_t np_white = strip.Color(255,255,255); -const uint32_t np_black = strip.Color(0 ,0,0); -const uint32_t np_red = strip.Color(255,0,0); -const uint32_t np_orange = strip.Color(255,128,0); -const uint32_t np_yellow = strip.Color(255,100,0); // 255,100,0 -const uint32_t np_green = strip.Color(0 ,255,0); -const uint32_t np_cyan = strip.Color(0 ,255,128); -const uint32_t np_blue = strip.Color(0 ,0,255); -const uint32_t np_purple = strip.Color(128,0,255); -const uint32_t np_turquoise = strip.Color(0,80,80); - +const uint32_t np_white = strip.Color(255, 255, 255); +const uint32_t np_black = strip.Color( 0, 0, 0); +const uint32_t np_red = strip.Color(255, 0, 0); +const uint32_t np_orange = strip.Color(255, 128, 0); +const uint32_t np_yellow = strip.Color(255, 100, 0); // 255,100,0 +const uint32_t np_green = strip.Color( 0, 255, 0); +const uint32_t np_cyan = strip.Color( 0, 255, 128); +const uint32_t np_blue = strip.Color( 0, 0, 255); +const uint32_t np_purple = strip.Color(128, 0, 255); +const uint32_t np_pink = strip.Color(128, 0, 255); +const uint32_t np_turquoise = strip.Color( 0, 80, 80); + + // pink #FFC0CB rgb(255,192,203) + // lightpink #FFB6C1 rgb(255,182,193) + // hotpink #FF69B4 rgb(255,105,180) + // deeppink #FF1493 rgb(255,20,147) + // palevioletred #DB7093 rgb(219,112,147) + // mediumvioletred #C71585 rgb(199,21,133) + // /** * collection of helper functions */ -void init_strip(int pin){ +void init_strip(int pin, Adafruit_NeoPixel& ind){ + strip = ind; return; strip.setPin(pin); strip.setBrightness(NEOBRIGHTNESS); strip.updateLength(NEONUMPIXELS); @@ -370,6 +379,35 @@ void rainbow(int wait) { } } +// Rainbow cycle along whole strip. Pass delay time (in ms) between frames. +void rainbowHue(int wait) { + // Hue of first pixel runs 5 complete loops through the color wheel. + // Color wheel has a range of 65536 but it's OK if we roll over, so + // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time + // means we'll make 5*65536/256 = 1280 passes through this outer loop: + for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) { + for(int i=0; i Date: Tue, 4 Jan 2022 15:51:47 -0600 Subject: [PATCH 129/186] add begin flag --- httpportal.h | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/httpportal.h b/httpportal.h index b93de8b..fc9a996 100644 --- a/httpportal.h +++ b/httpportal.h @@ -8,17 +8,6 @@ WiFiManager portal(Logger); -void init_httpportal(String title = ""){ - portal.setDebugOutput(true,"[HTTPP] "); - // invert theme, dark - portal.setDarkMode(true); - std::vector menu = {"wifi","param","info","sep","update","restart","exit"}; - portal.setMenu(menu); // custom menu, pass vector - portal.setTitle(title); - // portal.setBackButton(true); - // portal.setHostname(getHostname()); -} - void begin_httpportal(){ portal.startWebPortal(); } @@ -31,4 +20,16 @@ void process_httpportal(){ portal.process(); } +void init_httpportal(String title = "",bool begin = true){ + portal.setDebugOutput(true,"[HTTPP] "); + // invert theme, dark + portal.setDarkMode(true); + std::vector menu = {"wifi","param","info","sep","update","restart","exit"}; + portal.setMenu(menu); // custom menu, pass vector + portal.setTitle(title); + // portal.setBackButton(true); + // portal.setHostname(getHostname()); + if(begin) begin_httpportal(); +} + #endif From d919581902e135268ea7bad94127b57d9f2cbbf7 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 4 Jan 2022 15:52:06 -0600 Subject: [PATCH 130/186] add restart wifi timer option --- wifi_funcs.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index 92cf1a4..cb997df 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -206,18 +206,19 @@ int getRSSIasQuality() { } -void checkWifi(){ +void checkWifi(bool restart = false){ Serial.println("[TASK] checkWiFi"); if(WiFi.status() != WL_CONNECTED ){ if(downtime == 0) downtime = millis(); - if(millis() > downtime + downtimeRestart){ + if(restart && millis() > downtime + downtimeRestart){ #ifdef USENEOIND indSetColor(255,0,0); #endif Serial.println("[ERROR] wifi not found, rebooting after timeout"); + Serial.flush(); delay(1000); ESP.restart(); - } + } #ifdef USENEOIND indSetColor(255,0,0); #endif From e703a44b5bfa263c735523a10cd617632aebdec8 Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Fri, 7 Jan 2022 09:01:02 -0600 Subject: [PATCH 131/186] enable sleep esp32 --- wifi_funcs.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index bb39bd1..85e4777 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -161,7 +161,7 @@ void init_WiFi(int timeout){ WiFi.setSleepMode(WIFI_NONE_SLEEP); #elif defined(ESP32) // btStop(); - // WiFi.setSleep(false); + WiFi.setSleep(false); #endif // // WiFi.hostname(hostname); From 07ac92b13d70f240a464d8082e12f5d117d2e60a Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 10 Jan 2022 13:00:03 -0600 Subject: [PATCH 132/186] add definitiomns --- definitions.h | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/definitions.h b/definitions.h index 47f5f12..c326389 100755 --- a/definitions.h +++ b/definitions.h @@ -1,4 +1,34 @@ -#define INDLEDPIN 13 -#define INDLEDISRGBW true +#define ESP32BASICUSB + +#ifdef ESP32BASICUSB +typedef enum { + INDLEDPIN = 19, + INDLEDISRGBW = 1, + IOE1 = 32, + IOE2 = 33, + IOE3 = 36, // ADC + IOE4 = 39, // ADC + ADCEX = 27, + BUTTON1 = 0, + SPIBUS = 2, +} PIN_DEFS; +#else +typedef enum { + INDLEDPIN = 19, + INDLEDISRGBW = 1, + IOE1 = 1, + IOE2 = 2, + IOE3 = 3, + IOE4 = 6, + ADCEX = 14, + BUTTON1 = 0, + SPIBUS = 2, + JTAG1 = 39, // TCK + JTAG2 = 40, // TDO + JTAG3 = 41, // TDI + JTAG4 = 42, // TMS +} PIN_DEFS; +#endif + From a0012f51c5b5edb62bcf01567467d2c70a2d147f Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 10 Jan 2022 13:00:23 -0600 Subject: [PATCH 133/186] esp32 reset reasons --- wifi_funcs.h | 77 ++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 6 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index 2b29426..e2d44b0 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -140,7 +140,11 @@ void WiFi_print_sta(){ Serial.print("[WIFI] BSSID: "); Serial.println(WiFi.BSSIDstr()); Serial.print("[WIFI] RSSI: "); - Serial.println(WiFi.RSSI()); + Serial.println(WiFi.RSSI()); + Serial.print("[WIFI] CHANNEL: "); + Serial.println(WiFi.channel()); + } else { + Serial.println("[WIFI] NOT CONNECTED"); } } @@ -370,17 +374,78 @@ void disableWiFi(){ // snprintf(default_hostname, 32, "%s%02X%02X%02X", CONFIG_IDF_TARGET "-", eth_mac[3], eth_mac[4], eth_mac[5]); +// typedef enum { +// NO_MEAN = 0, +// POWERON_RESET = 1, /**<1, Vbat power on reset*/ +// RTC_SW_SYS_RESET = 3, /**<3, Software reset digital core*/ +// DEEPSLEEP_RESET = 5, /**<5, Deep Sleep reset digital core*/ +// TG0WDT_SYS_RESET = 7, /**<7, Timer Group0 Watch dog reset digital core*/ +// TG1WDT_SYS_RESET = 8, /**<8, Timer Group1 Watch dog reset digital core*/ +// RTCWDT_SYS_RESET = 9, /**<9, RTC Watch dog Reset digital core*/ +// INTRUSION_RESET = 10, /**<10, Instrusion tested to reset CPU*/ +// TG0WDT_CPU_RESET = 11, /**<11, Time Group0 reset CPU*/ +// RTC_SW_CPU_RESET = 12, /**<12, Software reset CPU*/ +// RTCWDT_CPU_RESET = 13, /**<13, RTC Watch dog Reset CPU*/ +// RTCWDT_BROWN_OUT_RESET = 15, /**<15, Reset when the vdd voltage is not stable*/ +// RTCWDT_RTC_RESET = 16, /**<16, RTC Watch dog reset digital core and rtc module*/ +// TG1WDT_CPU_RESET = 17, /**<17, Time Group1 reset CPU*/ +// SUPER_WDT_RESET = 18, /**<18, super watchdog reset digital core and rtc module*/ +// GLITCH_RTC_RESET = 19, /**<19, glitch reset digital core and rtc module*/ +// } RESET_REASON; + +const char * const RESET_REASON_STR[] PROGMEM +{ + "NO_MEAN" , + "POWERON_RESET" , /**<1, Vbat power on reset*/ + "", + "RTC_SW_SYS_RESET" , /**<3, Software reset digital core*/ + "", + "DEEPSLEEP_RESET" , /**<5, Deep Sleep reset digital core*/ + "", + "TG0WDT_SYS_RESET" , /**<7, Timer Group0 Watch dog reset digital core*/ + "TG1WDT_SYS_RESET" , /**<8, Timer Group1 Watch dog reset digital core*/ + "RTCWDT_SYS_RESET" , /**<9, RTC Watch dog Reset digital core*/ + "INTRUSION_RESET" , /**<10, Instrusion tested to reset CPU*/ + "TG0WDT_CPU_RESET" , /**<11, Time Group0 reset CPU*/ + "RTC_SW_CPU_RESET" , /**<12, Software reset CPU*/ + "RTCWDT_CPU_RESET" , /**<13, RTC Watch dog Reset CPU*/ + "", + "RTCWDT_BROWN_OUT_RESET" , /**<15, Reset when the vdd voltage is not stable*/ + "RTCWDT_RTC_RESET" , /**<16, RTC Watch dog reset digital core and rtc module*/ + "TG1WDT_CPU_RESET" , /**<17, Time Group1 reset CPU*/ + "SUPER_WDT_RESET" , /**<18, super watchdog reset digital core and rtc module*/ + "GLITCH_RTC_RESET" /**<19, glitch reset digital core and rtc module*/ +}; + +// typedef enum { +// NO_MEAN = "NO_MEAN", +// POWERON_RESET = "Vbat power on reset", +// RTC_SW_SYS_RESET = "Software reset digital core", +// DEEPSLEEP_RESET = "Deep Sleep reset digital core", +// TG0WDT_SYS_RESET = "Timer Group0 Watch dog reset digital core", +// TG1WDT_SYS_RESET = "Timer Group1 Watch dog reset digital core", +// RTCWDT_SYS_RESET = "RTC Watch dog Reset digital core", +// INTRUSION_RESET = "Instrusion tested to reset CPU", +// TG0WDT_CPU_RESET = "Time Group0 reset CPU", +// RTC_SW_CPU_RESET = "Software reset CPU", +// RTCWDT_CPU_RESET = "RTC Watch dog Reset CPU", +// RTCWDT_BROWN_OUT_RESET = "Reset when the vdd voltage is not stable", +// RTCWDT_RTC_RESET = "RTC Watch dog reset digital core and rtc module", +// TG1WDT_CPU_RESET = "Time Group1 reset CPU", +// SUPER_WDT_RESET = "super watchdog reset digital core and rtc module", +// GLITCH_RTC_RESET = "glitch reset digital core and rtc module" +// } RESET_REASON_STR_v; + + // @todo -String getResetReason(){ +String getResetReason(uint8_t cpu = 0){ int reason; #ifdef ESP8266 return ESP.getResetReason(); #elif defined(ESP32) && defined(_ROM_RTC_H_) // requires #include - // for(int i=0;i<2;i++){ - // return ESP32GetResetReason(i); - // } - return "NA"; + return RESET_REASON_STR[rtc_get_reset_reason(cpu)]; + // return "NA"; #else return "UNSET"; #endif From bb8ad588af45110da68981964155ce2a2f42de59 Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Sat, 22 Jan 2022 10:18:17 -0600 Subject: [PATCH 134/186] some defs --- .DS_Store | Bin 0 -> 6148 bytes wifi_funcs.h | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..e12b2e2f590792f18f66aae8a9aaefeb6b7a4462 GIT binary patch literal 6148 zcmeHKJx;?=47MRdB$ked>74+n7eKF3$_07=P^r`+rAh|avvCA2(+v*B=O0j_sEi$2 zTk`wzY=3#lH^ea!arM5L6U~UIgbUJ#EK`%b_{6R}QUF=*(QN0dmv-MxDvt+*ThKji z>6P9_{JZXHnA^8?y>8kyV&y|~_p}=J-fSxT@ z-WbLj3WNfoz@Gy0eMoS@?AROXrvrc5rMH$fktH?G1%yc zC$Gzny`j;G^<><~PiCJ`SWibhX*qE=j5QPp1;z?o+jb`Xe+fS_|Bp$r3k5=fvr>SI zdR13=CGV}1my=$b;Lq@1L#>u$(N+x9R*a3b;@d%8l56C%V{fQ*#FY+=9|6%NEEG6} F0zXybDLViF literal 0 HcmV?d00001 diff --git a/wifi_funcs.h b/wifi_funcs.h index aa63487..8484646 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -370,6 +370,47 @@ void disableWiFi(){ // snprintf(default_hostname, 32, "%s%02X%02X%02X", CONFIG_IDF_TARGET "-", eth_mac[3], eth_mac[4], eth_mac[5]); +// const char * const WIFI_STA_STATUS[] PROGMEM +// { +// "WL_IDLE_STATUS", // 0 STATION_IDLE +// "WL_NO_SSID_AVAIL", // 1 STATION_NO_AP_FOUND +// "WL_SCAN_COMPLETED", // 2 +// "WL_CONNECTED", // 3 STATION_GOT_IP +// "WL_CONNECT_FAILED", // 4 STATION_CONNECT_FAIL, STATION_WRONG_PASSWORD(NI) +// "WL_CONNECTION_LOST", // 5 +// "WL_DISCONNECTED", // 6 +// "WL_STATION_WRONG_PASSWORD" // 7 KLUDGE +// }; + +// #ifdef ESP32 +// const char * const AUTH_MODE_NAMES[] PROGMEM +// { +// "OPEN", +// "WEP", +// "WPA_PSK", +// "WPA2_PSK", +// "WPA_WPA2_PSK", +// "WPA2_ENTERPRISE", +// "MAX" +// }; +// #elif defined(ESP8266) +// const char * const AUTH_MODE_NAMES[] PROGMEM +// { +// "", +// "", +// "WPA_PSK", // 2 ENC_TYPE_TKIP +// "", +// "WPA2_PSK", // 4 ENC_TYPE_CCMP +// "WEP", // 5 ENC_TYPE_WEP +// "", +// "OPEN", //7 ENC_TYPE_NONE +// "WPA_WPA2_PSK", // 8 ENC_TYPE_AUTO +// }; +// #endif + +// const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; + + // @todo String getResetReason(){ int reason; From ab167f2162e7cd84789625760a7771143e51ca29 Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Wed, 13 Apr 2022 15:20:10 -0500 Subject: [PATCH 135/186] Delete .DS_Store --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index e12b2e2f590792f18f66aae8a9aaefeb6b7a4462..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKJx;?=47MRdB$ked>74+n7eKF3$_07=P^r`+rAh|avvCA2(+v*B=O0j_sEi$2 zTk`wzY=3#lH^ea!arM5L6U~UIgbUJ#EK`%b_{6R}QUF=*(QN0dmv-MxDvt+*ThKji z>6P9_{JZXHnA^8?y>8kyV&y|~_p}=J-fSxT@ z-WbLj3WNfoz@Gy0eMoS@?AROXrvrc5rMH$fktH?G1%yc zC$Gzny`j;G^<><~PiCJ`SWibhX*qE=j5QPp1;z?o+jb`Xe+fS_|Bp$r3k5=fvr>SI zdR13=CGV}1my=$b;Lq@1L#>u$(N+x9R*a3b;@d%8l56C%V{fQ*#FY+=9|6%NEEG6} F0zXybDLViF From e69d92ccc72bc707a8e94f3513b5f6b716a9a79b Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Wed, 13 Apr 2022 15:20:28 -0500 Subject: [PATCH 136/186] Update .gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 437b8ff..74a792b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ - +.DS_Store creds.h From 76434f77af6a6be6fbc95eb438ab4a3095ff4bed Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Wed, 13 Apr 2022 15:22:28 -0500 Subject: [PATCH 137/186] Update creds.h --- creds.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/creds.h b/creds.h index 7b5debd..ab9ac5c 100644 --- a/creds.h +++ b/creds.h @@ -2,11 +2,11 @@ #define creds_h String apikeya = "741F4992029440228F7B6B1F270728D4"; -const char* SSID_B = "harlet"; -const char* PASS_B = "turdtron"; +const char* SSID_B = "wifib"; +const char* PASS_B = "password1234"; -const char* SSID = "leela"; -const char* PASS = "Turdtr0n"; +const char* SSID = "wifia"; +const char* PASS = "password1234"; const char* STASSID = SSID; const char* STAPSK = PASS; @@ -15,8 +15,8 @@ const char* ssid = SSID; // your network SSID (name) const char* password = PASS; // mqtt -const char* mqtt_server_host = "zerbert.local"; -const char* mqtt_server_ip = "192.168.100.17"; +const char* mqtt_server_host = "mqtt.local"; +const char* mqtt_server_ip = "192.168.100.1"; const int mqtt_server_port = 1883; // syslog @@ -24,4 +24,4 @@ const char* syslog_server_host = mqtt_server_host; const char* syslog_server_ip = mqtt_server_ip; const int syslog_server_port = 514; -#endif \ No newline at end of file +#endif From d99dc65dacb12672da727eabedca6ef8403903ab Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 14 Apr 2022 22:13:39 -0500 Subject: [PATCH 138/186] add onewire and adc --- sense_env.h | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/sense_env.h b/sense_env.h index 141f418..31f2e97 100644 --- a/sense_env.h +++ b/sense_env.h @@ -183,6 +183,88 @@ float get_env(uint8_t channel = 0){ #endif */ +// ADC Sensors +// ADC I2C + +// MCP3421 +// + +/* +ANALOG PRESSURE SENDER +--30 psi +Input: 0-30 psi +Output: 0.5V~4.5V linear voltage output. 0 psi outputs 0.5V, 15psi outputs 2.5V, 30 psi outputs 4.5V. +Accuracy: within 2% of reading (full scale). +Thread: 1/8"-27 NPT. +Wiring Connector: Water sealed quick disconnect. Mating connector is included. +Wiring: Red for +5V; Black for ground; Blue for signal output. +*/ + + +//ONEWIRE + +#ifdef DS18B20 +#include +// The DallasTemperature library can do all this work for you! +// http://milesburton.com/Dallas_Temperature_Control_Library +#define ONE_WIRE_BUS 14 +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); + +// url=https://github.com/milesburton/Arduino-Temperature-Control-Library + +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature _DS18B20(&oneWire); +// DallasTemperature _DS18B20[oneWireCount]; +DeviceAddress _DS18B20Addr[3]; + +void init_DS18B20(){ + bool ret = false; + ret = _DS18B20.begin(); + + //oneWire.reset_search(); + + printAddress(_DS18B20Addr[0]); + _DS18B20.getAddress(_DS18B20Addr[0], 0); + _DS18B20.setResolution(_DS18B20Addr[0], TEMPERATURE_PRECISION); + _DS18B20.getResolution(_DS18B20Addr[0], DEC); + + if(!ret){ + Logger.println("[ERROR] _DS18B20 init FAILED"); + } + else Logger.println("[ENV] _DS18B20 is ACTIVE"); + // return ret; +} + +void print_DS18B20(){ + float tempC = _DS18B20.getTempCByIndex(0); + + // Check if reading was successful + if(tempC != DEVICE_DISCONNECTED_C) + { + Serial.print("Temperature for the device 1 (index 0) is: "); + Serial.println(tempC); + } + else + { + Serial.println("Error: Could not read temperature data"); + } +} + +float get_DS18B20(uint8_t channel = 0){ + _DS18B20.requestTemperatures(); + // for (int i = 0; i < oneWireCount; i++) { + // sensor[i].requestTemperatures(); + // } + // print_env(); + if(channel == 0) return _DS18B20.getTempCByIndex(0); + if(channel == 1) return _DS18B20.getTempCByIndex(1); + if(channel == 2) return _DS18B20.getTempCByIndex(2); + // if(channel == 1) return ; + // if(channel == 2) return ; +} +#endif + #ifdef VEML6070 From e8daa69498c18f45a4f1d84b7ba1bd98a1e8ccab Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 14 Apr 2022 22:13:56 -0500 Subject: [PATCH 139/186] fix return --- neopixel_helper.h | 1 + 1 file changed, 1 insertion(+) diff --git a/neopixel_helper.h b/neopixel_helper.h index 5c6dc5a..f515bbe 100644 --- a/neopixel_helper.h +++ b/neopixel_helper.h @@ -104,6 +104,7 @@ uint32_t Wheel(byte WheelPos) { uint8_t getRGBA(uint8_t rgb, uint16_t A){ if(A > 255 || rgb == 0) return rgb; if(A < 255) return floor(A*rgb/255); + return rgb; } // RGB to binary with MAXBRIGHTNESS brightness scaling From a96bf32aa3c073fd55efa99656a2950420e7024a Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 14 Apr 2022 22:14:09 -0500 Subject: [PATCH 140/186] update preable arg --- oled_i2c.h | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/oled_i2c.h b/oled_i2c.h index b23b5c4..8be3b32 100644 --- a/oled_i2c.h +++ b/oled_i2c.h @@ -72,7 +72,7 @@ void print_oled_line(String str,uint16_t no = 1,uint16_t size = 1){ lcd.println(str); } -void init_oled(bool preamble){ +void init_oled(bool preamble = true){ Serial.println("\nInitializing SSD1306 OLED"); Serial.println("SDA: "+(String)SDA); Serial.println("SCL: "+(String)SCL); @@ -96,14 +96,14 @@ void init_oled(bool preamble){ lcd.setTextSize(1); lcd.setCursor(0,0); - lcd.println("Booting...."); + lcd.println("Booting...."); // show init lcd.display(); delay(1000); - lcd.clearDisplay(); + lcd.clearDisplay(); // clear display lcd.display(); } -void oled_test(uint8_t num = 0){ +void oled_test(uint8_t num = 1){ // print_oled_line(msg, line, size); for(uint8_t i=0;i Date: Thu, 14 Apr 2022 22:14:12 -0500 Subject: [PATCH 141/186] Update oled_i2c_sh1106.h --- oled_i2c_sh1106.h | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index 39d2c7c..cc4c03f 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -205,7 +205,7 @@ void print_oled(String str,uint8_t size,bool flush){ if(flush)lcd.sendBuffer(); // transfer internal memory to the display } -void init_oled(bool preamble,bool pinswap = false){ +void init_oled(bool preamble = true,bool pinswap = false){ Logger.println("[OLED] Initializing SSD1106 OLED"); Logger.println("[OLED] SDA: "+(String)SDA); Logger.println("[OLED] SCL: "+(String)SCL); @@ -219,7 +219,7 @@ void init_oled(bool preamble,bool pinswap = false){ #ifdef ROT lcd.setDisplayRotation(U8G2_R2); #endif - lcd.setBusClock(100000L); + // lcd.setBusClock(100000L); lcd.begin(); // lcd.setI2CAddress(0x78); // if(!lcd.begin()) { // Address 0x3C for 128x32 @@ -257,13 +257,16 @@ void init_oled(bool preamble,bool pinswap = false){ } void displayFPS(){ - String str = (String)(1000000/((micros()-oledfpsmicros)/2)); - lcd.clearBuffer(); // clear the internal memory - lcd.drawStr(0,10,String(str+ "fps").c_str()); + String str = (String)((1000000/((micros()-oledfpsmicros)))); + // String str = (String)((micros()-oledfpsmicros)); + oledfpsmicros = micros(); + lcd.clearBuffer(); // clear the internal memory + lcd.drawStr(0,10,String(str+ " FPS").c_str()); // lcd.drawStr(60,px,String(micros()).c_str()); // write something to the internal memory lcd.sendBuffer(); // println(" FPS"); - oledfpsmicros = micros(); + // delay(300); + // delay(950); } // void printInverted(const char* str){ From 02c6ad3403733ba7282c869749c288530f43cb64 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 15 Apr 2022 16:31:01 -0500 Subject: [PATCH 142/186] fixing up ds18b20 --- sense_env.h | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/sense_env.h b/sense_env.h index 31f2e97..d089013 100644 --- a/sense_env.h +++ b/sense_env.h @@ -205,35 +205,43 @@ Wiring: Red for +5V; Black for ground; Blue for signal output. #ifdef DS18B20 #include +#include // The DallasTemperature library can do all this work for you! // http://milesburton.com/Dallas_Temperature_Control_Library -#define ONE_WIRE_BUS 14 +#define _DS18B20Pin 14 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); -// url=https://github.com/milesburton/Arduino-Temperature-Control-Library +// url=https://github.com/milesburton/Arduino-Temperature-Control-Library // Pass our oneWire reference to Dallas Temperature. DallasTemperature _DS18B20(&oneWire); // DallasTemperature _DS18B20[oneWireCount]; -DeviceAddress _DS18B20Addr[3]; + +uint8_t _DS18B20_num_sensors = 3; +DeviceAddress _DS18B20Addr[_DS18B20_num_sensors]; void init_DS18B20(){ bool ret = false; - ret = _DS18B20.begin(); - //oneWire.reset_search(); - - printAddress(_DS18B20Addr[0]); - _DS18B20.getAddress(_DS18B20Addr[0], 0); - _DS18B20.setResolution(_DS18B20Addr[0], TEMPERATURE_PRECISION); - _DS18B20.getResolution(_DS18B20Addr[0], DEC); + // oneWire.setPin(_DS18B20Pin); + _DS18B20.setOneWire(_DS18B20Pin); + ret = _DS18B20.begin(); if(!ret){ Logger.println("[ERROR] _DS18B20 init FAILED"); } else Logger.println("[ENV] _DS18B20 is ACTIVE"); - // return ret; + // return ret; + + //oneWire.reset_search(); + + for(size_t i=0; i<_DS18B20_num_sensors; i++){ + _DS18B20.getAddress(_DS18B20Addr[i], i); // get address + _DS18B20.setResolution(_DS18B20Addr[i], 9); // set precision + // _DS18B20.getResolution(_DS18B20Addr[i], DEC); + } + } void print_DS18B20(){ From a3cd1cf25f8e4804c1e3c2ef43f7da478b51f2c9 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Wed, 27 Jul 2022 06:48:33 -0500 Subject: [PATCH 143/186] add veml, htu21, scd4x --- sense_env.h | 182 +++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 146 insertions(+), 36 deletions(-) diff --git a/sense_env.h b/sense_env.h index d089013..8b3117a 100644 --- a/sense_env.h +++ b/sense_env.h @@ -5,6 +5,10 @@ Average avg_a(20); +// @todo +// add global env_debug +// add local status for each sensor, avoid sending bad values if init failed + // SUPPORTED SENSORS // SHT31 // SHT21 @@ -20,10 +24,10 @@ Average avg_a(20); // PM Dust sensors https://github.com/avaldebe/PMserial // MPU6050 // PCF8591 - +// scd4x C02 sensor +// VEML6070 // UV // NOT IMPLEMENTED @TODO -// VEML6070 // HMC5883L // MAX9814 // MCP3421 @@ -50,8 +54,9 @@ Average avg_a(20); #define SI7021 #define AHT10 -#define USESHT31 // SHT31 Temp/Humidity -// #define USESHT21 // SHT21 / HTU21D Temp/Humidity +// #define USESHT31 // SHT31 Temp/Humidity +#define USESHT21 // SHT21 / HTU21D Temp/Humidity + // #define USEBMP180 // BMP180 Temp/Pressure/Altitude (replaces BMP085) https://www.adafruit.com/product/1603 /* Vin: 3 to 5VDC @@ -66,7 +71,7 @@ This board/chip uses I2C 7-bit address 0x77. // #define USEBME280 // BME280 Humidity/Pressure/Altitude // Pressure: 300...1100 hPa - +#define SDC4X // SDC40 Co2/Temp/Humidity #define USECS811 // CCS811 Temp/CO2/VOC // #define USEGP2Y // Sharp Particle/Dust sensor GP2Y1010AU0F, GP2Y1014AU0F #define PMSx @@ -142,20 +147,16 @@ Interface: I2C // #define PCF8591 // PCF8591 io expander -// [I2C] Device found - ADDR: 0x23 // BH1750 -// [I2C] Device found - ADDR: 0x39 // APDS9960 / TSL2561 -// [I2C] Device found - ADDR: 0x5A // -// [I2C] Device found - ADDR: 0x76 // - -// [I2C] Device found - ADDR: 0x23 0x46 -// [I2C] Device found - ADDR: 0x38 0x70 -// [I2C] Device found - ADDR: 0x39 0x72 -// [I2C] Device found - ADDR: 0x3C 0x78 -// [I2C] Device found - ADDR: 0x44 0x88 -// [I2C] Device found - ADDR: 0x48 0x90 -// [I2C] Device found - ADDR: 0x5A 0xB4 -// [I2C] Device found - ADDR: 0x68 0xD0 -// [I2C] Device found - ADDR: 0x76 0xEC +// 0x23 0x46 BH1750 +// 0x38 0x70 +// 0x39 0x72 APDS9960 / TSL2561 +// 0x3C 0x78 +// 0x44 0x88 +// 0x48 0x90 +// 0x5A 0xB4 CS811 +// 0x62 0xC4 SCD4X +// 0x68 0xD0 +// 0x76 0xEC /* #ifdef ENV_TEMPLATE @@ -186,6 +187,8 @@ float get_env(uint8_t channel = 0){ // ADC Sensors // ADC I2C +// ESP32 ADC + // MCP3421 // @@ -316,6 +319,7 @@ void print_veml6070(){ float get_veml6070(uint8_t channel = 0){ // print_env(); if(channel == 0) return env_veml6070.readUV(); + return 0; } #endif @@ -444,7 +448,6 @@ void print_pms(){ } } - float get_pms(uint8_t channel = 0){ // print_env(); if(channel == 0){ @@ -459,11 +462,11 @@ float get_pms(uint8_t channel = 0){ if(channel == 6) return pms.n2p5; if(channel == 7) return pms.n5p0; if(channel == 8) return pms.n10p0; + return 0; } #endif - #ifdef PCF8591 #include @@ -570,11 +573,13 @@ float get_INA219(uint8_t channel = 0){ if(channel == 2) return ina219.getCurrent_mA(); if(channel == 3) return ina219.getPower_mW(); if(channel == 4) return busvoltage + (shuntvoltage / 1000); + return 0; } #endif #ifdef MPU6050 +// 3.3V onboard ldo for 5v #include #include @@ -649,6 +654,7 @@ float get_mpu6050(uint8_t channel = 0){ if(channel == 3) return g.gyro.x; if(channel == 4) return g.gyro.y; if(channel == 5) return g.gyro.z; + return 0; } #endif @@ -657,6 +663,7 @@ float get_mpu6050(uint8_t channel = 0){ #ifdef USEBH1750 #include +// 2.4V to 3.6V BH1750 lightMeter(0x23); bool init_BH1750(){ @@ -740,7 +747,7 @@ float get_BH1750(uint8_t channel = 0){ #ifdef APDS9960 - +// 2.4V to 3.6V #include "Adafruit_APDS9960.h" Adafruit_APDS9960 apds; uint8_t apds_int_pin = -1; @@ -786,6 +793,7 @@ String get_apds_proximity(){ //clear the interrupt apds.clearInterrupt(); } + return ""; } String get_apds_gesture(){ @@ -892,19 +900,6 @@ LM75A lm75(true, //A0 LM75A pin state true); //A2 LM75A pin state #endif -// SHT21 / HTU21D Temp/Humidity -#ifdef USESHT21 -#include -/* -resolution: -HTU21D_RES_RH12_TEMP14 - RH: 12Bit, Temperature: 14Bit, by default -HTU21D_RES_RH8_TEMP12 - RH: 8Bit, Temperature: 12Bit -HTU21D_RES_RH10_TEMP13 - RH: 10Bit, Temperature: 13Bit -HTU21D_RES_RH11_TEMP11 - RH: 11Bit, Temperature: 11Bit -*/ -HTU21D myHTU21D(HTU21D_RES_RH12_TEMP14); // 0x40 -#endif - // SHT31 Temp/Humidity #ifdef USESHT31 #include @@ -956,6 +951,7 @@ float get_bmp280(uint8_t channel = 0){ if(channel == 0) return bmp.readTemperature(); if(channel == 1) return bmp.readPressure(); if(channel == 2) return bmp.readAltitude(1013.25); + return 0; } #endif @@ -1025,7 +1021,18 @@ void sht31_process(){ } #endif +// SHT21 / HTU21D Temp/Humidity #ifdef USESHT21 +#include +/* +resolution: +HTU21D_RES_RH12_TEMP14 - RH: 12Bit, Temperature: 14Bit, by default +HTU21D_RES_RH8_TEMP12 - RH: 8Bit, Temperature: 12Bit +HTU21D_RES_RH10_TEMP13 - RH: 10Bit, Temperature: 13Bit +HTU21D_RES_RH11_TEMP11 - RH: 11Bit, Temperature: 11Bit +*/ +HTU21D myHTU21D(HTU21D_RES_RH12_TEMP14); // 0x40 + void init_sht21(){ bool init = myHTU21D.begin(); if(init){ @@ -1103,18 +1110,20 @@ void print_LM75(){ // ************************************************************* // CCS811 Temp/CO2/VOC +// 0x5A or 0x5B #ifdef USECS811 #include "Adafruit_CCS811.h" Adafruit_CCS811 ccs; void init_cs811(){ + int starttime = millis(); if(!ccs.begin()){ Logger.println("[ERROR] CS811 init FAILED"); } else { Logger.println("[ENV] CS811 is ACTIVE"); //calibrate temperature sensor - while(!ccs.available() && millis() < 30000); + while(!ccs.available() && millis() < starttime+5000); float temp = ccs.calculateTemperature(); Logger.println("[ENV] CS811 set offset " + String(temp-25.0)); ccs.setTempOffset(temp - 25.0); @@ -1191,4 +1200,105 @@ float getVoltage(){ +#ifdef SDC4X +#include +SensirionI2CScd4x scd4x; +// CO2 0x62 +void init_scd4x(){ + bool ret = false; + Wire.begin(); + scd4x.begin(Wire); + + // stop potentially previously started measurement + ret != scd4x.stopPeriodicMeasurement(); + // if (ret) { + // Serial.print("Error trying to execute stopPeriodicMeasurement(): "); + // errorToString(error, errorMessage, 256); + // Serial.println(errorMessage); + // } else ret = true; + + ret != scd4x.startPeriodicMeasurement(); + + if(!ret){ + Logger.println("[ERROR] SCD4X init FAILED"); + } + else Logger.println("[ENV] SCD4X is ACTIVE"); + // return ret; +} + +void print_scd4x(){ +} + +float get_scd4x(uint8_t channel = 0){ + uint16_t co2; + float temperature; + float humidity; + uint16_t error; + + error = scd4x.readMeasurement(co2, temperature, humidity); + + // print_env(); + if(channel == 0) return co2; + if(channel == 1) return temperature; + if(channel == 2) return humidity; + return 0; +} +#endif + + +#ifdef USEBMP180 +#include +Adafruit_BMP085 bmp180; +void init_bmp180(){ + bool ret = false; + ret = bmp180.begin(); + if(!ret){ + Logger.println("[ERROR] BMP180 init FAILED"); + } + else Logger.println("[ENV] BMP180 is ACTIVE"); + // return ret; +} + +void print_bmp180(){ + Logger.print("Temperature = "); + Logger.print(bmp.readTemperature()); + Logger.println(" *C"); + + Logger.print("Pressure = "); + Logger.print(bmp.readPressure()); + Logger.println(" Pa"); + + // Calculate altitude assuming 'standard' barometric + // pressure of 1013.25 millibar = 101325 Pascal + Logger.print("Altitude = "); + Logger.print(bmp.readAltitude()); + Logger.println(" meters"); + + Logger.print("Pressure at sealevel (calculated) = "); + Logger.print(bmp.readSealevelPressure()); + Logger.println(" Pa"); + + // you can get a more precise measurement of altitude + // if you know the current sea level pressure which will + // vary with weather and such. If it is 1015 millibars + // that is equal to 101500 Pascals. + Logger.print("Real altitude = "); + Logger.print(bmp.readAltitude(101500)); + Logger.println(" meters"); + + Logger.println(); +} + +float get_bmp180(uint8_t channel = 0){ + // print_env(); + if(channel == 0) return bmp180.readTemperature(); + if(channel == 1) return bmp180.readPressure(); + if(channel == 2) return bmp180.readAltitude(); + if(channel == 3) return bmp180.readSealevelPressure(); + if(channel == 4) return bmp180.readAltitude(101500); + return 0; +} +#endif + + #endif \ No newline at end of file From 8bc684deb2ffed32ba9f9e5e741bac00683e2f6e Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Wed, 27 Jul 2022 15:53:41 -0500 Subject: [PATCH 144/186] clean up --- sense_env.h | 51 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/sense_env.h b/sense_env.h index 8b3117a..635a78f 100644 --- a/sense_env.h +++ b/sense_env.h @@ -1060,45 +1060,72 @@ String getSHT21Humidity(){ void print_sht21(){ /* DEMO - 1 */ Logger.println(F("DEMO 1: 12-Bit Resolution")); - Logger.print(F("Humidity............: ")); Logger.print(myHTU21D.readHumidity()); Logger.println(F(" +-2%")); - Logger.print(F("Compensated Humidity: ")); Logger.print(myHTU21D.readCompensatedHumidity()); Logger.println(F(" +-2%")); + Logger.print(F("Humidity............: ")); + Logger.print(myHTU21D.readHumidity()); + Logger.println(F(" +-2%")); + + Logger.print(F("Compensated Humidity: ")); + Logger.print(myHTU21D.readCompensatedHumidity()); + Logger.println(F(" +-2%")); Logger.println(F("DEMO 1: 14-Bit Resolution")); - Logger.print(F("Temperature.........: ")); Logger.print(myHTU21D.readTemperature()); Logger.println(F(" +-0.3C")); + Logger.print(F("Temperature.........: ")); + Logger.print(myHTU21D.readTemperature()); + Logger.println(F(" +-0.3C")); /* DEMO - 2 */ Logger.println(F("DEMO 2: 11-Bit Resolution")); myHTU21D.setResolution(HTU21D_RES_RH11_TEMP11); - Logger.print(F("Humidity............: ")); Logger.print(myHTU21D.readHumidity()); Logger.println(F(" +-2%")); - Logger.print(F("Compensated Humidity: ")); Logger.print(myHTU21D.readCompensatedHumidity()); Logger.println(F(" +-2%")); + Logger.print(F("Humidity............: ")); + Logger.print(myHTU21D.readHumidity()); + Logger.println(F(" +-2%")); - Logger.println(F("DEMO 2: 11-Bit Resolution")); - Logger.print(F("Temperature.........: ")); Logger.print(myHTU21D.readTemperature()); Logger.println(F(" +-0.3C")); + Logger.print(F("Compensated Humidity: ")); + Logger.print(myHTU21D.readCompensatedHumidity()); + Logger.println(F(" +-2%")); + Logger.println(F("DEMO 2: 11-Bit Resolution")); + Logger.print(F("Temperature.........: ")); + Logger.print(myHTU21D.readTemperature()); + Logger.println(F(" +-0.3C")); /* DEMO - 3 */ Logger.println(F("DEMO 3: Battery Status")); - if (myHTU21D.batteryStatus() == true) Logger.println(F("Battery.............: OK. Level > 2.25v")); - else Logger.println(F("Battery.............: LOW. Level < 2.25v")); - + if (myHTU21D.batteryStatus() == true){ + Logger.println(F("Battery.............: OK. Level > 2.25v")); + else { + Logger.println(F("Battery.............: LOW. Level < 2.25v")); + } /* DEMO - 4 */ Logger.println(F("DEMO 4:")); - Logger.print(F("Firmware version....: ")); Logger.println(myHTU21D.readFirmwareVersion()); + Logger.print(F("Firmware version....: ")); + Logger.println(myHTU21D.readFirmwareVersion()); /* DEMO - 5 */ Logger.println(F("DEMO 5:")); - Logger.print(F("Sensor's ID.........: ")); Logger.println(myHTU21D.readDeviceID()); + Logger.print(F("Sensor's ID.........: ")); + Logger.println(myHTU21D.readDeviceID()); /* back to lib. default resolution */ myHTU21D.softReset(); myHTU21D.setResolution(HTU21D_RES_RH12_TEMP14); } + + +float get_sht21(uint8_t channel = 0){ + if(channel == 1) return myHTU21D.readTemperature(); + if(channel == 0) return myHTU21D.readHumidity(); + return 0; +} + #endif + + #ifdef USELM75 void init_LM75(){ } From 0ca0c3ea7650f4f4c23a39205639250bbcb24728 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 16:29:14 -0500 Subject: [PATCH 145/186] add lib_dep information --- include_sensor_libraries.h | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 include_sensor_libraries.h diff --git a/include_sensor_libraries.h b/include_sensor_libraries.h new file mode 100644 index 0000000..10629a7 --- /dev/null +++ b/include_sensor_libraries.h @@ -0,0 +1,34 @@ +#include // https:github.com/MajenkoLibraries/Average + + +#include +#include //https://github.com/arcao/Syslog.git +#include +#include // https://github.com/bblanchon/ArduinoStreamUtils.git + + +#include + +#include + +#include // https://github.com/ +#include // https://github.com/ +#include // https://github.com/ +#include // https://github.com/avaldebe/PMserial +#include // https://github.com/adafruit/Adafruit_VEML6070 +#include // https://github.com/adafruit/Adafruit_PCF8591 +#include // https://github.com/adafruit/Adafruit_INA219 +#include // https://github.com/adafruit/Adafruit_MPU6050 +#include // https://github.com/adafruit/Adafruit_Sensor +#include // https://github.com/adafruit/Adafruit_APDS9960 +#include // https://github.com/adafruit/Adafruit_SHT31 +#include // https://github.com/adafruit/Adafruit_BMP280 +#include // https://github.com/adafruit/Adafruit_CCS811 +#include // https://github.com/adafruit/Adafruit_BMP085 +#include // https://github.com/claws/BH1750 +#include // https://github.com/ +#include // https://github.com/QuentinCG/Arduino-LM75A-Temperature-Sensor-Library +#include // https://github.com/adafruit/Adafruit_HTU21DF_Library +#include // https://github.com/ + +// #include //inlude the library \ No newline at end of file From a82261693a403db53e23bdd901911260b95f54a0 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 16:29:52 -0500 Subject: [PATCH 146/186] trying to fix sdc sensor, this is probably a conflict --- oled_i2c.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/oled_i2c.h b/oled_i2c.h index 8be3b32..bbb6061 100644 --- a/oled_i2c.h +++ b/oled_i2c.h @@ -8,8 +8,8 @@ #include // #define SH1106_128_64 -#define SCREEN_WIDTH 128 // OLED display width, in pixels -#define SCREEN_HEIGHT 32 // OLED display height, in pixels +#define SCREEN_WIDTH 32 // OLED display width, in pixels +#define SCREEN_HEIGHT 128 // OLED display height, in pixels #define OLED_RESET -1 // Adafruit_SSD1306 lcd(OLED_RESET); @@ -82,7 +82,7 @@ void init_oled(bool preamble = true){ if(!lcd.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 Serial.println(F("SSD1306 allocation failed")); } - lcd.setRotation(2); + // lcd.setRotation(2); // Wire.setClock(400000L); // set i2c speed 400khz // Wire.setClock(100000L); // set i2c speed 400khz From 46366f59a33056f3c7806296bde29ac313af2fc1 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 16:30:16 -0500 Subject: [PATCH 147/186] ugh this file --- sense_env.h | 72 ++++++++++++++++++++++++++++++++++------------------- 1 file changed, 47 insertions(+), 25 deletions(-) diff --git a/sense_env.h b/sense_env.h index 635a78f..3b2f43c 100644 --- a/sense_env.h +++ b/sense_env.h @@ -1094,6 +1094,7 @@ void print_sht21(){ Logger.println(F("DEMO 3: Battery Status")); if (myHTU21D.batteryStatus() == true){ Logger.println(F("Battery.............: OK. Level > 2.25v")); + } else { Logger.println(F("Battery.............: LOW. Level < 2.25v")); } @@ -1232,44 +1233,65 @@ float getVoltage(){ SensirionI2CScd4x scd4x; // CO2 0x62 void init_scd4x(){ - bool ret = false; - Wire.begin(); + uint16_t error; + char errorMessage[256]; + Wire.begin(); scd4x.begin(Wire); // stop potentially previously started measurement - ret != scd4x.stopPeriodicMeasurement(); - // if (ret) { - // Serial.print("Error trying to execute stopPeriodicMeasurement(): "); - // errorToString(error, errorMessage, 256); - // Serial.println(errorMessage); - // } else ret = true; - - ret != scd4x.startPeriodicMeasurement(); - - if(!ret){ + error = scd4x.stopPeriodicMeasurement(); + if (error) { + Serial.print("Error trying to execute stopPeriodicMeasurement(): "); + errorToString(error, errorMessage, 256); + Serial.println(errorMessage); + } else error = true; + + error = scd4x.startPeriodicMeasurement(); + + if(error){ + Serial.print("Error trying to execute startPeriodicMeasurement(): "); + errorToString(error, errorMessage, 256); + Serial.println(errorMessage); Logger.println("[ERROR] SCD4X init FAILED"); } else Logger.println("[ENV] SCD4X is ACTIVE"); // return ret; } -void print_scd4x(){ +float get_scd4x(uint8_t channel = 0,bool update=true){ + static uint16_t scd4x_co2; + static float scd4x_temperature; + static float scd4x_humidity; + static uint16_t scd4x_error = 0; + if(update){ + char errorMessage[256]; + scd4x_error = scd4x.readMeasurement(scd4x_co2, scd4x_temperature, scd4x_humidity); + if(scd4x_error){ + Serial.print("Error trying to execute readMeasurement(): "); + errorToString(scd4x_error, errorMessage, 256); + Serial.println(errorMessage); + } + } + if(channel == 0) return scd4x_co2; + if(channel == 1) return scd4x_temperature; + if(channel == 2) return scd4x_humidity; + if(channel == 3) return scd4x_error; + return 0; } -float get_scd4x(uint8_t channel = 0){ - uint16_t co2; - float temperature; - float humidity; - uint16_t error; - - error = scd4x.readMeasurement(co2, temperature, humidity); +void print_scd4x(){ - // print_env(); - if(channel == 0) return co2; - if(channel == 1) return temperature; - if(channel == 2) return humidity; - return 0; + Serial.print(__FUNCTION__); + Serial.print(" co2: "); + Serial.print(get_scd4x(0)); + Serial.print(" temp: "); + Serial.print(get_scd4x(1,false)); + Serial.print(" humidity: "); + Serial.print(get_scd4x(2,false)); + Serial.print(" error: "); + Serial.println(); } + #endif From 41f68877255df38a4dec921474c4897edb10f256 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 16:32:29 -0500 Subject: [PATCH 148/186] sample ini --- include_sensor_libraries.h | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/include_sensor_libraries.h b/include_sensor_libraries.h index 10629a7..2772e3f 100644 --- a/include_sensor_libraries.h +++ b/include_sensor_libraries.h @@ -31,4 +31,28 @@ #include // https://github.com/adafruit/Adafruit_HTU21DF_Library #include // https://github.com/ -// #include //inlude the library \ No newline at end of file +// #include //inlude the library +// +// +[env:esp32doit-devkit-v1] +platform = espressif32 +board = esp32doit-devkit-v1 +framework = arduino +lib_deps = + avaldebe/PMSerial@^1.2.0 + https://github.com/adafruit/Adafruit_INA219 + https://github.com/adafruit/Adafruit_MPU6050 + https://github.com/avaldebe/PMserial + https://github.com/adafruit/Adafruit_VEML6070 + https://github.com/adafruit/Adafruit_PCF8591 + https://github.com/adafruit/Adafruit_INA219 + https://github.com/adafruit/Adafruit_Sensor + https://github.com/adafruit/Adafruit_APDS9960 + https://github.com/adafruit/Adafruit_SHT31 + https://github.com/adafruit/Adafruit_BMP280 + https://github.com/adafruit/Adafruit_CCS811 + ; https://github.com/adafruit/Adafruit_HTU21DF_Library + ; https://github.com/RobTillaart/SHT2x + https://github.com/enjoyneering/HTU21D + https://github.com/claws/BH1750 +lib_extra_dirs = /Users/alverson/projects/microcontrollers/dev/libraries From c6cbf065715a586b3ba654f090f671a80e484d55 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:12:05 -0500 Subject: [PATCH 149/186] use logger for wm --- httpportal.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/httpportal.h b/httpportal.h index ac7fddd..509ba8b 100644 --- a/httpportal.h +++ b/httpportal.h @@ -6,8 +6,8 @@ #include #include -// WiFiManager portal(Logger); -WiFiManager portal; +WiFiManager portal(Logger); // use netlog for logging wm +// WiFiManager portal; void begin_httpportal(){ portal.startWebPortal(); From 45d71e3c6fa04c506d50d0a8d6853e25e04a7067 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:12:18 -0500 Subject: [PATCH 150/186] i2c scan returns count --- io_utils.h | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/io_utils.h b/io_utils.h index 5e161dd..29dc394 100644 --- a/io_utils.h +++ b/io_utils.h @@ -40,7 +40,7 @@ void debugPin(uint8_t pin){ // #include -void scani2c(bool pinswap = false){ +uint16_t scani2c(bool pinswap = false){ swap = pinswap; byte error, address; int nDevices; @@ -89,9 +89,12 @@ void scani2c(bool pinswap = false){ } if (nDevices == 0) Logger.println("[ERROR] No I2C devices found\n"); - else + else{ Logger.print("[I2C] scan done found "); Logger.println(nDevices); + } + + return nDevices; } void scanPins(){ @@ -118,6 +121,14 @@ void pinregister(){ // and on esp32 etc set the pins desired specs and avoid conflicts with multiple adc reads } + +// The ADC firmware driver API supports ADC1 (8 channels, attached to GPIOs 32 – 39), +// and ADC2 (10 channels, attached to GPIOs 0, 2, 4, 12 – 15, and 25 – 27). +// However, the usage of ADC2 has some restrictions for the application: + +// ADC2 is used by the Wi-Fi driver. Therefore the application can only use ADC2 when the Wi-Fi driver has not been started. +// Some of the ADC2 pins are used as strapping pins (GPIO 0, 2, 15) thus cannot be used freely. + // #ifdef ESP32 // #define ADC_1 36 From f354e98575bce5345e0cef7724e174c8dd0658fb Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:13:12 -0500 Subject: [PATCH 151/186] add json buffer size definition for now, adds cmd downstream --- mqtt.h | 92 ++++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 57 insertions(+), 35 deletions(-) diff --git a/mqtt.h b/mqtt.h index ee1a982..e6a6a62 100644 --- a/mqtt.h +++ b/mqtt.h @@ -7,15 +7,21 @@ #ifdef USEJSON #include // bblanchon/ArduinoJson -StaticJsonDocument<4096> payload; -StaticJsonDocument<4096> rootdoc; +// #define _JSONSIZE 4096 + +#ifndef _JSONSIZE +#define _JSONSIZE 1024 +#endif + +StaticJsonDocument<_JSONSIZE> payload; +StaticJsonDocument<_JSONSIZE> rootdoc; // payload["sensor"] = "gps"; // payload["time"] = 1351824120; // const size_t CAPACITY = JSON_ARRAY_SIZE(1); // StaticJsonDocument docH; // JsonArray arrayH = docH.to(); - DynamicJsonDocument pubjson(4096); + DynamicJsonDocument pubjson(_JSONSIZE); JsonArray jsondata = pubjson.to(); #endif @@ -26,10 +32,15 @@ WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = false; -bool debug_mqtt_json = false; +bool debug_mqtt = true; +bool debug_mqtt_json = true; const char* clientID = ""; +bool mqttconnected = false; + +long lastReconnectAttempt = 0; +uint16_t mqttretry = 5000; + void MQTTreconnect() { // Loop until we're reconnected @@ -43,15 +54,15 @@ void MQTTreconnect() { // Once connected, publish an announcement... client.publish("TESTOUT", "hello world"); // ... and resubscribe - client.subscribe("TESTIN"); + client.subscribe("CMD"); } else { Logger.print("[ERROR] [MQTT] failed, rc="); // @todo we get here but no actual reconnnect loop, why? Logger.println(client.state()); // Wait 5 seconds before retrying - // delay(5000); + delay(5000); } delay(100); - } +} } void MQTTcallback(char* topic, byte* payload, unsigned int length) { @@ -64,14 +75,16 @@ void MQTTcallback(char* topic, byte* payload, unsigned int length) { } Logger.println(""); if ((char)payload[0] == '1') { - Logger.println("[MQTT] payload: TRIGGERED"); + Logger.println("[MQTT] payload: 1 TRIGGERED"); + ESP.restart(); } + if ((char)payload[0] == '2') { + Logger.println("[MQTT] payload: 2 TRIGGERED"); + WiFi.disconnect(); + } } -long lastReconnectAttempt = 0; -uint16_t mqttretry = 5000; - -boolean mqttReconnect() { +boolean mqttWiFiReconnect() { WiFi.reconnect(); return WiFi.status() == 'WL_CONNECTED'; } @@ -80,33 +93,42 @@ void mqtt_checkconn(){ if (!client.connected()) { long now = millis(); if (now - lastReconnectAttempt > mqttretry) { + Logger.println("[MQTT] try client re-connect"); lastReconnectAttempt = now; // Attempt to reconnect - if (mqttReconnect()) { + // if (mqttWiFiReconnect()) { lastReconnectAttempt = 0; - client.connect(clientID); - } + MQTTreconnect(); + // client.connect(clientID); + // } } } else { // Client connected client.loop(); - } + } } -void process_MQTT_nb(){ +bool process_MQTT_nb(){ if (!client.connected()) { mqtt_checkconn(); } client.loop(); // will wait loop reconnect to mqtt + return client.connected(); } -void process_MQTT(){ +bool process_MQTT(){ if(!wifiIsConnected()){ - Logger.println("[MQTT] wifi not connected"); - return; + // Logger.println("[MQTT] wifi not connected"); + return false; + } + if(!client.connected()){ + mqttconnected = false; + Logger.println("[MQTT] client not connected"); + MQTTreconnect(); // @todo throttle + return false; } - MQTTreconnect(); // @todo throttle client.loop(); // will wait loop reconnect to mqtt + return true; } void init_MQTT(){ @@ -114,8 +136,8 @@ void init_MQTT(){ client.setServer(mqtt_server_ip, mqtt_server_port); client.setCallback(MQTTcallback); if (client.connect(clientID)) Logger.println("[MQTT] connected to " + (String)mqtt_server_ip); - client.setBufferSize(2048); - client.subscribe("downstream"); + client.setBufferSize(_JSONSIZE); + client.subscribe("CMD"); process_MQTT(); // jsondata = pubjson.to(); // jsondata = pubjson.createNestedArray(); @@ -139,14 +161,14 @@ void MQTT_pub(String topic, String sensor, String value){ // return; } if(debug_mqtt){ - Logger.print("[MQTT] Publish: "); - Logger.print(sensor); - Logger.print(" "); - Logger.println(value); + Logger.print("[MQTT] Publish: "); + Logger.print(sensor); + Logger.print(" "); + Logger.println(value); + } if(value == "") { - Logger.println("[ERROR] MQTT value is empty"); + // Logger.println("[ERROR] MQTT value is empty"); return; - } } // JsonArray data = payload.createNestedArray(topic); payload["topic"] = topic; @@ -173,10 +195,10 @@ void MQTT_pub(String topic, String sensor, String value, bool json){ Logger.print(sensor); Logger.print(" "); Logger.println(value); - if(value == "") { - Logger.println("[ERROR] MQTT value is empty"); - return; - } + } + if(value == "") { + // Logger.println("[ERROR] MQTT value is empty"); + return; } JsonArray data = payload.createNestedArray(topic); payload["topic"] = data; // tag key = tag value @@ -227,7 +249,7 @@ void MQTT_pub_send(String topic){ // Serial.println(output); // Serial.flush(); - char message[4096]; + char message[_JSONSIZE]; serializeJson(pubjson, message); if(debug_mqtt_json){ Logger.println((String)message); From 6ca5d9012983a896dac4259f3ce83533a2418512 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:13:39 -0500 Subject: [PATCH 152/186] clean up font sizes --- oled_i2c.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/oled_i2c.h b/oled_i2c.h index 8be3b32..1055b9d 100644 --- a/oled_i2c.h +++ b/oled_i2c.h @@ -8,8 +8,8 @@ #include // #define SH1106_128_64 -#define SCREEN_WIDTH 128 // OLED display width, in pixels -#define SCREEN_HEIGHT 32 // OLED display height, in pixels +#define SCREEN_WIDTH 64 // OLED display width, in pixels +#define SCREEN_HEIGHT 48 // OLED display height, in pixels #define OLED_RESET -1 // Adafruit_SSD1306 lcd(OLED_RESET); From ed01ee871710c0bf125ab2bc022a77e4926ebc02 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:14:15 -0500 Subject: [PATCH 153/186] clean up oled --- oled_i2c.h | 16 +++++++++------- oled_i2c_sh1106.h | 4 ++-- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/oled_i2c.h b/oled_i2c.h index 1055b9d..4977ee3 100644 --- a/oled_i2c.h +++ b/oled_i2c.h @@ -13,10 +13,11 @@ #define OLED_RESET -1 // Adafruit_SSD1306 lcd(OLED_RESET); -Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT); -// Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET,800000,800000); +// Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT); +Adafruit_SSD1306 lcd(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET,800000,800000); int oledfpsmicros = 0; +int fontlineheight = 9; void invertText(){ lcd.setTextColor(BLACK, WHITE); // 'inverted' text @@ -65,8 +66,8 @@ void print_oled(String str,uint8_t size,bool flush){ */ void print_oled_line(String str,uint16_t no = 1,uint16_t size = 1){ uint16_t y = 0; - if(size == 1) y = 9*no; - if(size == 2) y = 18*no; + if(size == 1) y = fontlineheight*no; + if(size == 2) y = (fontlineheight*2)*no; lcd.setCursor(0,y); lcd.setTextSize(size); lcd.println(str); @@ -82,7 +83,7 @@ void init_oled(bool preamble = true){ if(!lcd.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 Serial.println(F("SSD1306 allocation failed")); } - lcd.setRotation(2); + // lcd.setRotation(2); // Wire.setClock(400000L); // set i2c speed 400khz // Wire.setClock(100000L); // set i2c speed 400khz @@ -111,14 +112,15 @@ void oled_test(uint8_t num = 1){ print_oled_line((String)millis(),1); lcd.display(); delay(1000); + lcd.clearDisplay(); print_oled_line("Line One",0); print_oled_line("Line Two",1); print_oled_line("Line Three",2); lcd.display(); delay(1000); lcd.clearDisplay(); - print_oled_line("Line One",0,2); - print_oled_line("Line Two",2); + // print_oled_line("Line One",0,2); + // print_oled_line("Line Two",2); lcd.display(); } } diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index cc4c03f..d0d0dd8 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -195,12 +195,12 @@ void print_oled_line(String str,uint16_t no = 1,uint16_t size = 1){ lcd.println(str); } -void print_oled(String str,uint8_t size,bool flush){ +void print_oled(String str,uint8_t size = 1,bool flush = true){ lcd.clearBuffer(); // clear the internal memory lcd.setFont(u8g2_font_ncenB08_tr); // lcd.drawStr(0,10,String(micros()).c_str()); // write something to the internal memory lcd.setFont(u8g2_font_inb30_mn); - lcd.drawStr(0,60,str.c_str()); + lcd.drawStr(10,30,str.c_str()); // lcd.drawStr(0,10,micros().c_str(); // write something to the internal memory if(flush)lcd.sendBuffer(); // transfer internal memory to the display } From 97dacd823c975e6a7fe47cc16d80226fc7a04e6f Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:14:26 -0500 Subject: [PATCH 154/186] logging --- ota.h | 1 + 1 file changed, 1 insertion(+) diff --git a/ota.h b/ota.h index 467abb8..9cb9913 100644 --- a/ota.h +++ b/ota.h @@ -52,6 +52,7 @@ void startOTA(){ type = "filesystem"; } otastarted = true; + Logger.println("\n[OTA] onStart " + type); Serial.println("\n[OTA] onStart " + type); }); From 0c1d3f7849364111e22b36f054ff9d927dd47a10 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:15:13 -0500 Subject: [PATCH 155/186] fix reboot --- wifi_funcs.h | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index 764b6cf..d364124 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -233,12 +233,16 @@ int getRSSIasQuality() { return getRSSIasQuality(WiFi.RSSI()); } - +/** + * [checkWifi description] + * @param restart [description] + */ void checkWifi(bool restart = false){ Serial.println("[TASK] checkWiFi"); if(WiFi.status() != WL_CONNECTED ){ if(downtime == 0) downtime = millis(); if(restart && millis() > downtime + downtimeRestart){ + // reboot #ifdef USENEOIND indSetColor(np_red); #endif @@ -247,11 +251,14 @@ void checkWifi(bool restart = false){ delay(1000); ESP.restart(); } - #ifdef USENEOIND - indSetColor(np_red); - #endif - Serial.println("[WIFI] WiFi is Disconnected"); - WiFi.reconnect(); + else{ + // reconnect + #ifdef USENEOIND + indSetColor(np_red); + #endif + Serial.println("[WIFI] WiFi is Disconnected"); + WiFi.reconnect(); + } } else { if(debug_wifi){ Serial.println("[WIFI] WiFi is CONNECTED"); From dffa793e5fc097b1fdf4f80974ad52ab160214c8 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:15:40 -0500 Subject: [PATCH 156/186] adds truncate sensor, and remove logging --- sense_env.h | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/sense_env.h b/sense_env.h index 635a78f..0a219d9 100644 --- a/sense_env.h +++ b/sense_env.h @@ -54,7 +54,7 @@ Average avg_a(20); #define SI7021 #define AHT10 -// #define USESHT31 // SHT31 Temp/Humidity +#define USESHT31 // SHT31 Temp/Humidity #define USESHT21 // SHT21 / HTU21D Temp/Humidity // #define USEBMP180 // BMP180 Temp/Pressure/Altitude (replaces BMP085) https://www.adafruit.com/product/1603 @@ -1038,8 +1038,7 @@ void init_sht21(){ if(init){ Logger.println(F("[ENV] HTU21D, SHT21 is ACTIVE")); } - else - { + else{ Logger.println(F("[ERROR] HTU21D, SHT21 init FAILED")); //(F()) saves string to flash & keeps dynamic memory free } @@ -1059,20 +1058,20 @@ String getSHT21Humidity(){ void print_sht21(){ /* DEMO - 1 */ - Logger.println(F("DEMO 1: 12-Bit Resolution")); + // Logger.println(F("DEMO 1: 12-Bit Resolution")); Logger.print(F("Humidity............: ")); - Logger.print(myHTU21D.readHumidity()); - Logger.println(F(" +-2%")); + Logger.println(myHTU21D.readHumidity()); + // Logger.println(F(" +-2%")); Logger.print(F("Compensated Humidity: ")); - Logger.print(myHTU21D.readCompensatedHumidity()); - Logger.println(F(" +-2%")); + Logger.println(myHTU21D.readCompensatedHumidity()); + // Logger.println(F(" +-2%")); - Logger.println(F("DEMO 1: 14-Bit Resolution")); + // Logger.println(F("DEMO 1: 14-Bit Resolution")); Logger.print(F("Temperature.........: ")); - Logger.print(myHTU21D.readTemperature()); - Logger.println(F(" +-0.3C")); - + Logger.println(myHTU21D.readTemperature()); + // Logger.println(F(" +-0.3C")); + return; /* DEMO - 2 */ Logger.println(F("DEMO 2: 11-Bit Resolution")); @@ -1092,8 +1091,9 @@ void print_sht21(){ /* DEMO - 3 */ Logger.println(F("DEMO 3: Battery Status")); - if (myHTU21D.batteryStatus() == true){ + if(myHTU21D.batteryStatus() == true){ Logger.println(F("Battery.............: OK. Level > 2.25v")); + } else { Logger.println(F("Battery.............: LOW. Level < 2.25v")); } @@ -1117,8 +1117,9 @@ void print_sht21(){ float get_sht21(uint8_t channel = 0){ - if(channel == 1) return myHTU21D.readTemperature(); - if(channel == 0) return myHTU21D.readHumidity(); + if(channel == 0) return myHTU21D.readTemperature(); + if(channel == 1) return myHTU21D.readCompensatedHumidity(); + if(channel == 2) return myHTU21D.readHumidity(); return 0; } @@ -1210,6 +1211,10 @@ String filterSensor( float n, float a,float b,String c = ""){ return (String)n; } +String truncateSensor(float n,uint8_t precision = 0){ + if(precision = 0) return (String)(int)n; + return (String)n; +} // #define USEINTVCC #ifdef USEINTVCC From 653cef0de9f1bd49f611ade5ce2aa4afc98b6cdf Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 2 Sep 2022 20:16:42 -0500 Subject: [PATCH 157/186] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 74a792b..a8c01b3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .DS_Store creds.h +creds.h From 1e0221868b295ffc34385159a85a19ffec1c45bd Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Wed, 21 Sep 2022 22:05:25 -0500 Subject: [PATCH 158/186] misc fixes --- httpportal.h | 4 +- mqtt.h | 38 ++--- neoindicator.h | 11 ++ neopixel_helper.h | 9 +- oled_i2c_ssd1306.h | 337 +++++++++++++++++++++++++++++++++++++++++++++ wifi_funcs.h | 41 +++--- 6 files changed, 402 insertions(+), 38 deletions(-) create mode 100644 oled_i2c_ssd1306.h diff --git a/httpportal.h b/httpportal.h index 509ba8b..925a0eb 100644 --- a/httpportal.h +++ b/httpportal.h @@ -10,6 +10,8 @@ WiFiManager portal(Logger); // use netlog for logging wm // WiFiManager portal; void begin_httpportal(){ + // portal.setDebugLevel(); + // portal.setDebugOutput(true); portal.startWebPortal(); } @@ -22,7 +24,7 @@ void process_httpportal(){ } void init_httpportal(String title = "",bool begin = true){ - portal.setDebugOutput(true,"[HTTPP] "); + portal.setDebugOutput(true,"[HTTPD] "); // invert theme, dark portal.setDarkMode(true); std::vector menu = {"wifi","param","info","sep","update","restart","exit"}; diff --git a/mqtt.h b/mqtt.h index e6a6a62..b5cf8ae 100644 --- a/mqtt.h +++ b/mqtt.h @@ -39,30 +39,37 @@ const char* clientID = ""; bool mqttconnected = false; long lastReconnectAttempt = 0; -uint16_t mqttretry = 5000; +uint32_t mqttretry = 10000; + +// Possible values for client.state() +// #define MQTT_CONNECTION_TIMEOUT -4 +// #define MQTT_CONNECTION_LOST -3 +// #define MQTT_CONNECT_FAILED -2 +// #define MQTT_DISCONNECTED -1 +// #define MQTT_CONNECTED 0 +// #define MQTT_CONNECT_BAD_PROTOCOL 1 +// #define MQTT_CONNECT_BAD_CLIENT_ID 2 +// #define MQTT_CONNECT_UNAVAILABLE 3 +// #define MQTT_CONNECT_BAD_CREDENTIALS 4 +// #define MQTT_CONNECT_UNAUTHORIZED 5 void MQTTreconnect() { - - // Loop until we're reconnected - // this is blocking if (!client.connected()) { // while (!client.connected()) { if(debug_mqtt) Logger.println("[MQTT] Connecting..."); // Attempt to connect if (client.connect(clientID)) { + mqttconnected = true; Logger.println("[MQTT] Connected"); // Once connected, publish an announcement... client.publish("TESTOUT", "hello world"); // ... and resubscribe client.subscribe("CMD"); } else { - Logger.print("[ERROR] [MQTT] failed, rc="); // @todo we get here but no actual reconnnect loop, why? + Logger.print("[ERROR] [MQTT] failed, rc="); // @todo we get here but no actual reconnnect Logger.println(client.state()); - // Wait 5 seconds before retrying - delay(5000); } - delay(100); -} + } } void MQTTcallback(char* topic, byte* payload, unsigned int length) { @@ -95,12 +102,7 @@ void mqtt_checkconn(){ if (now - lastReconnectAttempt > mqttretry) { Logger.println("[MQTT] try client re-connect"); lastReconnectAttempt = now; - // Attempt to reconnect - // if (mqttWiFiReconnect()) { - lastReconnectAttempt = 0; - MQTTreconnect(); - // client.connect(clientID); - // } + MQTTreconnect(); } } else { // Client connected @@ -294,13 +296,13 @@ void MQTT_pub(String topic, String sensor, String value){ // add free heap void MQTT_pub_device(){ if(debug_mqtt) Logger.println("[MQTT] Publish Device"); + MQTT_pub("device","uptime_s",(String)(millis()/1000)); MQTT_pub("device","rssi",(String)getRSSIasQuality()); + MQTT_pub("device","heap",(String)ESP.getFreeHeap()); + // MQTT_pub("device","hall",(String)hallRead()); #ifdef ESP32 - // MQTT_pub("device","hall",(String)hallRead()); // USES PINS 36,39 MQTT_pub("device","temp",(String)temperatureRead()); - // MQTT_pub("device","adc_1",(String)analogRead(39)); #endif - MQTT_pub("device","uptime_s",(String)(millis()/1000)); MQTT_pub_send("device"); } diff --git a/neoindicator.h b/neoindicator.h index bb9b3be..98c01cf 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -131,6 +131,17 @@ void indSetColor(uint8_t r,uint8_t g,uint8_t b){ indSetColor(ind.Color(r,g,b)); } +// void setPixelBrightness(uint32_t n, uint32_t a){ +// } + +// void indSetBrightness(uint8_t a){ +// uint32_t c = strip.getPixelColor(0); +// // if(DEBUG_neoind)Serial.println("[IND] set ind color brightness:"+(String) ind.Color(r,g,b)); +// setPixelColorAlpha(n,c,a); +// ind.setPixelBrightness +// } + + void setIndColor(uint8_t r,uint8_t g,uint8_t b){ indSetColor(r,g,b); } diff --git a/neopixel_helper.h b/neopixel_helper.h index f515bbe..052bece 100644 --- a/neopixel_helper.h +++ b/neopixel_helper.h @@ -1,3 +1,7 @@ +/** + * All helpers need to be refactored to use neopixel objected passed in + * kludge reassign strip to your obj etc and use as a shadow + */ #ifndef NEOPIXEL_HELPER_H #define NEOPIXEL_HELPER_H @@ -159,6 +163,7 @@ uint16_t randomBrightness(uint16_t a,uint8_t range){ return b; } +// does not allow offsets 0-255 uint16_t getBrightnessStep(uint8_t step, uint16_t numsteps){ uint16_t brightness; // brightness = 255 - (step * (255/numsteps)); // linear @@ -303,6 +308,7 @@ void fadeTo(uint32_t c,uint16_t duration){ fade(getPixelColor(0),c,duration); } +// stepping non blocking fader uint32_t getFadeStep(uint32_t startColor, uint32_t endColor, uint16_t steps, uint16_t step){ int16_t redDiff = red(endColor) - red(startColor); int16_t greenDiff = green(endColor) - green(startColor); @@ -315,7 +321,8 @@ uint32_t getFadeStep(uint32_t startColor, uint32_t endColor, uint16_t steps, uin blueValue = (int16_t)blue(startColor) + (blueDiff * step / steps); whiteValue = (int16_t)white(startColor) + (whiteDiff * step / steps); - return color(redValue, greenValue, blueValue,whiteValue); + // return color(redValue, greenValue, blueValue,whiteValue); + return color(redValue, greenValue, blueValue); } void flasher(uint32_t colorA, uint32_t colorB,int waitA, int waitB){ diff --git a/oled_i2c_ssd1306.h b/oled_i2c_ssd1306.h new file mode 100644 index 0000000..7eeec9c --- /dev/null +++ b/oled_i2c_ssd1306.h @@ -0,0 +1,337 @@ +#ifndef old_i2c_sh1106_h +#define old_i2c_sh1106_h + +/*oled_i2c*/ + +#include +#include + +#include + +#ifdef U8X8_HAVE_HW_SPI +#include +#endif +#ifdef U8X8_HAVE_HW_I2C +#include +#endif + + +// const char WIFI_SYMBOL[] = { 93,94,123,168, 176, 247, 253, 263, 277,278,279,280,281, '\0'}; +#define GLYPH_BELL 93 // bell +#define GLYPH_BT 94 // bt +#define GLYPH_CLOCK 123 // clock +#define GLYPH_FLAME 168 // flame +#define GLYPH_CHART 176 // chart +#define GLYPH_SIGNAL 253 // bell +#define GLYPH_SPARK 96 // bell +#define GLYPH_GEAR 129 // bell +#define GLYPH_ALERT 0x118 // bell +#define GLYPH_SPKOFF 0x117 // bell +#define GLYPH_SPKHI 0x115 // bell +#define GLYPH_SPKLO 0x116 // bell +#define GLYPH_HASHF 177 // bell +#define GLYPH_HASHM 178 // bell +#define GLYPH_HASHC 179 // bell +#define GLYPH_HDOTS 155 // bell +#define GLYPH_HBAR 221 // bell +#define GLYPH_CROSS 218 // bell +#define GLYPH_CROSSB 234 // bell +#define GLYPH_EKG 238 // bell +#define GLYPH_WIFI 0x119 // bell +#define GLYPH_WRENCH 0x120 // bell +#define GLYPH_TARGET 0x107 // bell +#define GLYPH_LISTINV 0x101 // bell +#define GLYPH_STAR 0x102 // bell +#define GLYPH_SUN 0x103 // bell +#define GLYPH_STPWTCH 269 // bell +#define GLYPH_TERM 0x109 // bell +#define GLYPH_DEL 0x121 // bell +#define GLYPH_GOOD 120 // bell +#define GLYPH_BAD 121 // bell +#define GLYPH_HEART 183 // bell +#define GLYPH_HOUSE 184 // bell +#define GLYPH_SQUARE 217 // bell +#define GLYPH_SPACE 287 // bell +#define GLYPH_NO 87 // busted +#define GLYPH_COFFEE 2615 // busted + +// const char* testing = u8"\u0263\u0BA3\u0B82"; + +// lcd.setFont(u8g2_font_open_iconic_embedded_1x_t); +// lcd.setFont(u8g2_font_open_iconic_all_1x_t); +// lcd.drawStr(0,y,WIFI_SYMBOL); +// lcd.drawUTF8(0,y,testing); +// lcd.drawGlyph(0,y, 93); // bell +// lcd.drawGlyph(10,y, 94); // bluetooth +// lcd.drawGlyph(20,y, 123); // clock +// lcd.drawGlyph(30,y, 168); // flame +// lcd.drawGlyph(40,y, 176); // chart +// lcd.drawGlyph(50,y, 253); // signal +// lcd.drawGlyph(60,y, 96); // terminus +// lcd.drawGlyph(70,y, 129); // gear +// lcd.drawGlyph(80,y, 0x118); // alert +// lcd.drawGlyph(90,y, 0x117); // speaker off +// lcd.drawGlyph(100,y, 0x115); // speaker high +// lcd.drawGlyph(110,y, 0x116); // speaker med + +// lcd.drawGlyph(0,y, 177); // hash fine +// lcd.drawGlyph(10,y, 178); // hash med +// lcd.drawGlyph(20,y, 179); // hash low +// lcd.drawGlyph(30,y, 155); // 3 dots +// lcd.drawGlyph(40,y, 221); // mid bar +// lcd.drawGlyph(50,y, 218); // cross +// lcd.drawGlyph(60,y, 234); // cross +// lcd.drawGlyph(60,y, 238); // heartbeat + +// lcd.drawGlyph(40,y,0x119); // wifi +// lcd.drawGlyph(50,y,0x120); // wrench not working +// lcd.drawGlyph(60,y,0x107); // target +// lcd.drawGlyph(70,y,0x101); // list inverted +// lcd.drawGlyph(80,y,0x102); // star +// lcd.drawGlyph(90,y,0x103); // sunshine +// lcd.drawGlyph(100,y,269); // stopwatch +// lcd.drawGlyph(110,y,0x109); // terminal +// lcd.drawGlyph(120,y,0x121); // delete +// +// +// lcd.drawGlyph(70,y, 120); // good +// lcd.drawGlyph(80,y, 121); // bad +// lcd.drawGlyph(90,y, 183); // heart +// lcd.drawGlyph(100,y, 184); // house +// lcd.drawGlyph(110,y, 217); // square +// // lcd.drawGlyph(110,y, 287); // space + +// if(glyphanimstate==0){ +// lcd.drawGlyph(120,y, 155); // +// glyphanimstate = 1; +// } +// else{ +// lcd.drawGlyph(120,y, 287); // +// glyphanimstate = 0; +// } + + +// https://github.com/olikraus/u8g2/wiki/fntlistall#24-pixel-height +// U8g2 Font names +// '_' '_' +// Description +// t Transparent font, Do not use a background color. +// h All glyphs have common height. +// m All glyphs have common height and width (monospace). +// 8 All glyphs fit into a 8x8 pixel box. +// Description +// f The font includes up to 256 glyphs. +// r Only glyphs on the range of the ASCII codes 32 to 127 are included in the font. +// u Only glyphs on the range of the ASCII codes 32 to 95 (uppercase chars) are included in the font. +// n Only numbers and extra glyphs for writing date and time strings are included in the font. +// ... Other custom character list. + +// #define WHITE SH110X_WHITE +// #define BLACK SH110X_BLACK + +// #define SH1106_128_64 +// #define SCREEN_WIDTH 128 // OLED display width, in pixels +// #define SCREEN_HEIGHT 64 // OLED display height, in pixels + + +// U8G2_SSD1306_128X64_NONAME_F_SW_I2C lcd(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display +U8G2_SSD1306_128X64_NONAME_F_HW_I2C lcd(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); + +int oledfpsmicros = 0; + +// #if (SSD1306_LCDHEIGHT != 64) +// #error("Height incorrect, please fix Adafruit_SSD1306.h!"); +// #endif + +void invertText(){ + lcd.setDrawColor(2); + // lcd.setTextColor(BLACK, WHITE); // 'inverted' text +} + +void whiteText(){ + lcd.setDrawColor(1); + // lcd.setTextColor(WHITE); // 'inverted' text +} + +// void init_oled(){ +// init_oled(false); +// } + +// void init_oled(){ +// Wire.begin(SCL,SDA); // begin(sda, scl) SWAP! +// // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally +// if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 +// Serial.println(F("SSD1306 allocation failed")); +// } + +// display.clearDisplay(); +// display.setTextSize(1); // Normal 1:1 pixepl scale +// display.setTextColor(WHITE); // Draw white text +// display.setCursor(0,0); // Start at top-left corner +// display.display(); +// } + +/** + * print oled lines + * @param str string to print + * @param no line 0-3 + * @param size text size 1-2 + */ +void print_oled_line(String str,uint16_t no = 1,uint16_t size = 1){ + uint16_t y = 10; + if(size == 1) y += 9*no; + if(size == 2) y += 18*no; + lcd.setCursor(10,y); + // lcd.setTextSize(size); + lcd.println(str); +} + +void print_oled(String str,uint8_t size = 1,bool flush = true){ + lcd.clearBuffer(); // clear the internal memory + // lcd.setFont(u8g2_font_ncenB08_tr); + // lcd.drawStr(0,10,String(micros()).c_str()); // write something to the internal memory + lcd.setFont(u8g2_font_inb30_mn); + lcd.drawStr(10,30,str.c_str()); + // lcd.drawStr(0,10,micros().c_str(); // write something to the internal memory + if(flush)lcd.sendBuffer(); // transfer internal memory to the display +} + +void init_oled(bool preamble = true,bool pinswap = false,uint16_t rotate = 2){ + Logger.println("[OLED] Initializing SSD1106 OLED"); + Logger.println("[OLED] SDA: "+(String)SDA); + Logger.println("[OLED] SCL: "+(String)SCL); + if(pinswap){ + Wire.begin(SDA,SCL); // begin(sda, scl) SWAP! + Logger.println("[OLED] pinswapped"); + Logger.println("[OLED] SDA: "+(String)SDA); + Logger.println("[OLED] SCL: "+(String)SCL); + } + // Wire.setClock(400000L); + if(rotate==2){ + // #define U8G2_R0 (&u8g2_cb_r0) + // #define U8G2_R1 (&u8g2_cb_r1) + // #define U8G2_R2 (&u8g2_cb_r2) + // #define U8G2_R3 (&u8g2_cb_r3) + // #define U8G2_MIRROR (&u8g2_cb_mirror) + lcd.setDisplayRotation(U8G2_R2); + } + + // lcd.setBusClock(100000L); + lcd.begin(); + // lcd.setI2CAddress(0x78); + // if(!lcd.begin()) { // Address 0x3C for 128x32 + // Serial.println(F("SSD1106 begin failed")); + // } + lcd.setFont(u8g2_font_ncenB08_tr); + // u8g2_font_inb30_mn + lcd.clearBuffer(); // clear the internal memory + + int px = 10; + lcd.clearBuffer(); // clear the internal memory + lcd.drawStr(0,px,"Starting..."); + // lcd.drawStr(60,px,String(micros()).c_str()); // write something to the internal memory + lcd.sendBuffer(); // transfer internal memory to the display + + return; + // Wire.setClock(400000L); // set i2c speed 400khz + // Wire.setClock(100000L); // set i2c speed 400khz + + // lcd.clearDisplay(); + // lcd.setTextSize(1); // Normal 1:1 pixepl scale + // lcd.setCursor(0,0); // Start at top-left corner + // lcd.setTextColor(WHITE); // REQUIRED! + // lcd.display(); + // delay(1000); + if(!preamble) return; + + // lcd.setTextSize(1); + lcd.setCursor(0,0); + lcd.println("Booting...."); + lcd.display(); + delay(1000); + lcd.clearBuffer(); + lcd.sendBuffer(); +} + +void displayFPS(){ + String str = (String)((1000000/((micros()-oledfpsmicros)))); + // String str = (String)((micros()-oledfpsmicros)); + oledfpsmicros = micros(); + lcd.clearBuffer(); // clear the internal memory + lcd.drawStr(10,10,String(str+ " FPS").c_str()); + lcd.drawStr(30,10,String(micros()).c_str()); // write something to the internal memory + lcd.sendBuffer(); + // println(" FPS"); + // delay(300); + // delay(950); +} + +// void printInverted(const char* str){ +// lcd.setFontMode(1); +// lcd.print(str); +// lcd.setFontMode(0); +// } + + +int printInverted(const char* str,uint16_t posx,uint16_t posy){ + int lh = lcd.getAscent()+abs(lcd.getDescent()); // font height ? + + // int posy = px*2; // posy VAR + // int posx = 0; // posy VAR +// Serial.println(lcd.getStrWidth("OFF")); +// Serial.println(lcd.getStrWidth("ON")); + int padx = (lcd.getStrWidth("OFF")-lcd.getStrWidth("ON"))/2; // w padding + // int pady = 2; // h padding + int pady = 1; // h padding + // Serial.println(padx); + lcd.setDrawColor(1); + uint16_t strw = lcd.drawStr(posx+padx, posy, str); // x,y(NEGATIVE GOING!) + + lcd.setFontMode(1); + lcd.setDrawColor(2); + lcd.drawBox(posx, (posy-lh)+pady, strw+(padx*2),lh); // x,y(POSITIVE GOING!),w,h + + lcd.setDrawColor(1); // restore default + return strw+(padx*2); +} + +void printInvertedStr(String str,uint16_t posx,uint16_t posy){ + printInverted(str.c_str(),posx,posy); +} + +int printValuePair(const char* str,String strb,int x,int y){ + int xoff = printInverted(str,x,y); + lcd.setCursor(x+xoff+5, y); + lcd.print(strb.c_str()); + return xoff; // get new cursor? +} + +void oled_test(uint8_t num = 0){ + // print_oled_line(msg, line, size); + for(uint8_t i=0;i downtime + downtimeRestart){ - // reboot - #ifdef USENEOIND - indSetColor(np_red); - #endif - Serial.println("[ERROR] wifi not found, rebooting after timeout"); - Serial.flush(); - delay(1000); - ESP.restart(); - } - else{ - // reconnect - #ifdef USENEOIND - indSetColor(np_red); - #endif - Serial.println("[WIFI] WiFi is Disconnected"); - WiFi.reconnect(); + if(millis() > downtime + downtimeRestart){ + if(restart){ + // reboot + #ifdef USENEOIND + indSetColor(np_red); + #endif + Serial.println("[ERROR] wifi not found, rebooting after timeout"); + Serial.flush(); + delay(1000); + ESP.restart(); + // WiFi.reconnect(); + } + else{ + // reconnect + #ifdef USENEOIND + indSetColor(np_red); + #endif + Serial.println("[WIFI] WiFi is Disconnected"); + downtime = millis(); + WiFi.reconnect(); + } } - } else { + } + else { if(debug_wifi){ Serial.println("[WIFI] WiFi is CONNECTED"); Serial.println("[WIFI] RSSI: "+(String)getRSSIasQuality()); From fe4d4560fa8aff3834b9a684aa1ef9fe8b3c4191 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Wed, 30 Nov 2022 16:53:53 -0600 Subject: [PATCH 159/186] fixes --- buzzer.h | 112 +++++++++++++++++++++++++++++----------------- neopixel_helper.h | 3 ++ 2 files changed, 75 insertions(+), 40 deletions(-) diff --git a/buzzer.h b/buzzer.h index c473d79..74a8bcb 100644 --- a/buzzer.h +++ b/buzzer.h @@ -141,35 +141,44 @@ void soundalarm(){ #else -#include +// #include +#include "pitches.h" + #define BUZ_CHAN 0 +void plugged() { + tone(buzzer_pin, NOTE_C5, 150); // F6 + tone(buzzer_pin, NOTE_A5, 100); // F5 + tone(buzzer_pin, NOTE_F4, 100); // F5 + tone(buzzer_pin, NOTE_E5, 200); // F5 + noTone(buzzer_pin); +} // End of beep + void Chirp() { - tone(BUZ_PIN, NOTE_A7, 10); // F6 - tone(BUZ_PIN, NOTE_C8, 20); // F5 - noTone(BUZ_PIN, BUZ_CHAN); + tone(buzzer_pin, NOTE_A7, 10); // F6 + tone(buzzer_pin, NOTE_C8, 20); // F5 + noTone(buzzer_pin); } // End of beep void Bleep() { - tone(BUZ_PIN, NOTE_C7, 50, BUZ_CHAN); // F6 - tone(BUZ_PIN, NOTE_C8, 100, BUZ_CHAN); // F5 + tone(buzzer_pin, NOTE_C7, 50); // F6 + tone(buzzer_pin, NOTE_C8, 100); // F5 } // End of beep void Tone_Down() { - tone(BUZ_PIN, NOTE_F6, 200, BUZ_CHAN); // F6 - tone(BUZ_PIN, NOTE_F5, 200, BUZ_CHAN); // F5 - tone(BUZ_PIN, NOTE_C6, 200, BUZ_CHAN); // C6 + tone(buzzer_pin, NOTE_F6, 200); // F6 + tone(buzzer_pin, NOTE_F5, 200); // F5 + tone(buzzer_pin, NOTE_C6, 200); // C6 } // End of beep void Tone_Up() { - tone(BUZ_PIN, NOTE_C6, 200, BUZ_CHAN); // C6 - tone(BUZ_PIN, NOTE_F5, 200, BUZ_CHAN); // F5 - tone(BUZ_PIN, NOTE_F6, 200, BUZ_CHAN); // F6 + tone(buzzer_pin, NOTE_C6, 200); // C6 + tone(buzzer_pin, NOTE_F5, 200); // F5 + tone(buzzer_pin, NOTE_F6, 200); // F6 } // End of beep void buzzer_test() { Chirp(); - return; delay(500); Bleep(); delay(500); @@ -178,42 +187,65 @@ void buzzer_test() { Tone_Up(); delay(500); - // tone(BUZ_PIN, NOTE_C4, 500, BUZ_CHAN); - // noTone(BUZ_PIN, BUZ_CHAN); - // tone(BUZ_PIN, NOTE_D4, 500, BUZ_CHAN); - // noTone(BUZ_PIN, BUZ_CHAN); - // tone(BUZ_PIN, NOTE_E4, 500, BUZ_CHAN); - // noTone(BUZ_PIN, BUZ_CHAN); - // tone(BUZ_PIN, NOTE_F4, 500, BUZ_CHAN); - // noTone(BUZ_PIN, BUZ_CHAN); - // tone(BUZ_PIN, NOTE_G4, 500, BUZ_CHAN); - // noTone(BUZ_PIN, BUZ_CHAN); - // tone(BUZ_PIN, NOTE_A4, 500, BUZ_CHAN); - // noTone(BUZ_PIN, BUZ_CHAN); - // tone(BUZ_PIN, NOTE_B4, 500, BUZ_CHAN); - // noTone(BUZ_PIN, BUZ_CHAN); -} - -#include - -bool init_buzzer(int pin){ + tone(buzzer_pin, NOTE_C4, 500); + noTone(buzzer_pin); + tone(buzzer_pin, NOTE_D4, 500); + noTone(buzzer_pin); + tone(buzzer_pin, NOTE_E4, 500); + noTone(buzzer_pin); + tone(buzzer_pin, NOTE_F4, 500); + noTone(buzzer_pin); + tone(buzzer_pin, NOTE_G4, 500); + noTone(buzzer_pin); + tone(buzzer_pin, NOTE_A4, 500); + noTone(buzzer_pin); + tone(buzzer_pin, NOTE_B4, 500); + noTone(buzzer_pin); +} + +// #include + +void init_buzzer(int pin){ buzzer_pin = pin; - pinMode(buzzer_pin,OUTPUT); + // pinMode(buzzer_pin,OUTPUT); + // setToneChannel(BUZ_CHAN); + setToneChannel(BUZ_CHAN); } -bool init_buzzer(){ +void init_buzzer(){ init_buzzer(BUZ_PIN); } -bool chime(){ - analogWrite(buzzer_pin,500); - delay(100); - analogWrite(buzzer_pin,500); - delay(100); +void buzzer_test_DAC(){ + analogWrite(buzzer_pin,100); + delay(500); + analogWrite(buzzer_pin,1200); + delay(500); + analogWrite(buzzer_pin,0); +} + +void buzzer_test_tone(){ + setToneChannel(BUZ_CHAN); + tone(buzzer_pin, NOTE_A7, 10); // F6 + tone(buzzer_pin, NOTE_C8, 20); // F5 + noTone(buzzer_pin); +} + +void chime(){ + analogWrite(buzzer_pin,100); + delay(500); + analogWrite(buzzer_pin,200); + delay(500); + analogWrite(buzzer_pin,400); + delay(500); + analogWrite(buzzer_pin,800); + delay(500); + analogWrite(buzzer_pin,1200); + delay(500); analogWrite(buzzer_pin,0); } -bool soundalarm(){ +void soundalarm(){ Bleep(); delay(500); Bleep(); diff --git a/neopixel_helper.h b/neopixel_helper.h index 052bece..3cd0f60 100644 --- a/neopixel_helper.h +++ b/neopixel_helper.h @@ -46,6 +46,9 @@ const uint32_t np_turquoise = strip.Color( 0, 80, 80); void init_strip(int pin, Adafruit_NeoPixel& ind){ strip = ind; return; +} + +void init_strip(int pin){ strip.setPin(pin); strip.setBrightness(NEOBRIGHTNESS); strip.updateLength(NEONUMPIXELS); From b532d98f51c05715cf71d636f5da31104ef52ec3 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Wed, 30 Nov 2022 16:58:54 -0600 Subject: [PATCH 160/186] fixup checkwifi --- wifi_funcs.h | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index a110291..0735dc4 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -20,8 +20,8 @@ bool debug_wifi = true; bool rebootAfterDowntime = true; -long downtimeRestart = 1*3600; // n minutes -long downtime = 0; +long downtimeRestart = 1*60000; // millis +long downms = 0; /** IP to String? */ String toStringIp(IPAddress ip) { @@ -237,11 +237,12 @@ int getRSSIasQuality() { * [checkWifi description] * @param restart [description] */ -void checkWifi(bool restart = false){ + +void checkWifi(bool recon = true, bool restart = false){ Serial.println("[TASK] checkWiFi"); if(WiFi.status() != WL_CONNECTED ){ - if(downtime == 0) downtime = millis(); - if(millis() > downtime + downtimeRestart){ + if(downms == 0) downms = millis(); + if(millis() > downms + downtimeRestart){ if(restart){ // reboot #ifdef USENEOIND @@ -251,16 +252,15 @@ void checkWifi(bool restart = false){ Serial.flush(); delay(1000); ESP.restart(); - // WiFi.reconnect(); } else{ // reconnect #ifdef USENEOIND indSetColor(np_red); #endif - Serial.println("[WIFI] WiFi is Disconnected"); - downtime = millis(); - WiFi.reconnect(); + Serial.println("[WIFI] WiFi is Disconnected for " + (String)(millis()-downms)); + downms = millis(); + if(recon) WiFi.reconnect(); } } } @@ -275,6 +275,10 @@ void checkWifi(bool restart = false){ } } +void checkWifi(){ + checkWifi(true,false); +} + void enableWiFi(){ WiFi.mode(WIFI_STA); init_WiFi(0); From f56976f8633d0c84b3fbea40efb717437819bfd5 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 1 Dec 2022 06:48:37 -0600 Subject: [PATCH 161/186] connected checks --- mqtt.h | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/mqtt.h b/mqtt.h index b5cf8ae..171eec1 100644 --- a/mqtt.h +++ b/mqtt.h @@ -32,8 +32,8 @@ WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = true; -bool debug_mqtt_json = true; +bool debug_mqtt = false; +bool debug_mqtt_json = false; const char* clientID = ""; bool mqttconnected = false; @@ -41,6 +41,7 @@ bool mqttconnected = false; long lastReconnectAttempt = 0; uint32_t mqttretry = 10000; +void MQTTGetErrorMessage(){ // Possible values for client.state() // #define MQTT_CONNECTION_TIMEOUT -4 // #define MQTT_CONNECTION_LOST -3 @@ -52,6 +53,7 @@ uint32_t mqttretry = 10000; // #define MQTT_CONNECT_UNAVAILABLE 3 // #define MQTT_CONNECT_BAD_CREDENTIALS 4 // #define MQTT_CONNECT_UNAUTHORIZED 5 +} void MQTTreconnect() { if (!client.connected()) { @@ -64,7 +66,7 @@ void MQTTreconnect() { // Once connected, publish an announcement... client.publish("TESTOUT", "hello world"); // ... and resubscribe - client.subscribe("CMD"); + client.subscribe("ESP_env_c/CMD"); } else { Logger.print("[ERROR] [MQTT] failed, rc="); // @todo we get here but no actual reconnnect Logger.println(client.state()); @@ -81,10 +83,12 @@ void MQTTcallback(char* topic, byte* payload, unsigned int length) { Logger.print((char)payload[i]); } Logger.println(""); + // RESTART if ((char)payload[0] == '1') { Logger.println("[MQTT] payload: 1 TRIGGERED"); ESP.restart(); } + // WIFI off if ((char)payload[0] == '2') { Logger.println("[MQTT] payload: 2 TRIGGERED"); WiFi.disconnect(); @@ -112,6 +116,7 @@ void mqtt_checkconn(){ bool process_MQTT_nb(){ if (!client.connected()) { + mqttconnected = false; mqtt_checkconn(); } client.loop(); // will wait loop reconnect to mqtt @@ -137,9 +142,14 @@ void init_MQTT(){ if(!wifiIsConnected()) return; client.setServer(mqtt_server_ip, mqtt_server_port); client.setCallback(MQTTcallback); - if (client.connect(clientID)) Logger.println("[MQTT] connected to " + (String)mqtt_server_ip); + if (client.connect(clientID)){ + mqttconnected = true; + Logger.println("[MQTT] connected to " + (String)mqtt_server_ip); + } + else Logger.println("[MQTT] init failed to connect to " + (String)mqtt_server_ip); client.setBufferSize(_JSONSIZE); - client.subscribe("CMD"); + // client.subscribe("CMD"); + client.subscribe("ESP_env_c/CMD"); process_MQTT(); // jsondata = pubjson.to(); // jsondata = pubjson.createNestedArray(); @@ -162,6 +172,7 @@ void MQTT_pub(String topic, String sensor, String value){ // Logger.print("[MQTT] OFFLINE: "); // return; } + if(!mqttconnected)return; if(debug_mqtt){ Logger.print("[MQTT] Publish: "); Logger.print(sensor); @@ -192,6 +203,7 @@ void MQTT_pub(String topic, String sensor, String value){ } void MQTT_pub(String topic, String sensor, String value, bool json){ + if(!mqttconnected)return; if(debug_mqtt){ Logger.print("[MQTT] Publish: "); Logger.print(sensor); @@ -238,6 +250,7 @@ void MQTT_pub(String topic, String sensor, String value, bool json){ } void MQTT_pub_send(String topic){ + if(!mqttconnected)return; if(debug_mqtt){ Logger.println("[MQTT] sending json for topic: " + topic); } @@ -270,6 +283,7 @@ void MQTT_pub_send(String topic){ #else void MQTT_pub(String topic, String msg){ + if(!mqttconnected)return; Logger.print("[MQTT] Publish message: "); Logger.print("topic: "); Logger.print(topic); @@ -279,6 +293,7 @@ void MQTT_pub(String topic, String msg){ } void MQTT_pub(String topic, String sensor, String value){ + if(!mqttconnected)return; Logger.print("[MQTT] Publish message: "); Logger.print("topic: "); Logger.print(topic+"/"+clientID+"/"+sensor); @@ -295,6 +310,7 @@ void MQTT_pub(String topic, String sensor, String value){ // todo // add free heap void MQTT_pub_device(){ + if(!mqttconnected)return; if(debug_mqtt) Logger.println("[MQTT] Publish Device"); MQTT_pub("device","uptime_s",(String)(millis()/1000)); MQTT_pub("device","rssi",(String)getRSSIasQuality()); From 3b260b6b58ee7ca3084034036c25b2746f4e8170 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 1 Dec 2022 06:49:02 -0600 Subject: [PATCH 162/186] add ahtx --- sense_env.h | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/sense_env.h b/sense_env.h index a4bfa99..4ad3d0c 100644 --- a/sense_env.h +++ b/sense_env.h @@ -52,7 +52,7 @@ Average avg_a(20); // TEMP/HUMIDITY/GAS #define SI7021 -#define AHT10 +#define AHTX0 #define USESHT31 // SHT31 Temp/Humidity #define USESHT21 // SHT21 / HTU21D Temp/Humidity @@ -1354,4 +1354,31 @@ float get_bmp180(uint8_t channel = 0){ #endif +#ifdef AHTX0 +#include +Adafruit_AHTX0 aht; + +void init_aht(){ + bool ret = false; + ret = aht.begin(); + if(!ret){ + Logger.println("[ERROR] aht init FAILED"); + } + else Logger.println("[ENV] aht is ACTIVE"); + // return ret; +} + +void print_aht(){ +} + +float get_aht(uint8_t channel = 0){ + sensors_event_t humidity, temp; + aht.getEvent(&humidity, &temp); + // print_env(); + if(channel == 0) return temp.temperature; + if(channel == 1) return temp.relative_humidity; + return 0; +} +#endif + #endif \ No newline at end of file From 7309a29625abc39f549d7c3a2af8435abc40d9f6 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 1 Dec 2022 06:49:19 -0600 Subject: [PATCH 163/186] fix ssr safety --- ssr.h | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/ssr.h b/ssr.h index 43f71b0..bf2a693 100644 --- a/ssr.h +++ b/ssr.h @@ -31,7 +31,7 @@ void ssr_init(uint16_t pin){ //ssr enable - Serial.println("[SSR] READY on pin " + (String)_ssrRelayPin); + Logger.println("[SSR] READY on pin " + (String)_ssrRelayPin); _ssrRelayPin = pin; // ssr_off(); digitalWrite(_ssrRelayPin, invertLOW ? LOW : HIGH); @@ -60,13 +60,12 @@ void SetSSRFrequency( int duty,int power =1) #ifdef ESP8266 analogWrite( _ssrRelayPin, out); #elif defined(ESP32) - Serial.println("[DAC] - " + (String)out); + Logger.println("[SSR] - " + (String)out); analogWrite( _ssrRelayPin, out); // dacWrite(_ssrRelayPin,out); #endif // if(duty == 0)ssr_off(); // if(duty == 255)ssr_on(); - } // else ssr_off(); // ENFORCE SAFETY // if(DEBUG_ssr) Logger.println("[SSR] " + (String)duty); @@ -76,6 +75,7 @@ void SetSSRFrequency( int duty,int power =1) if(DEBUG_ssr) Logger.println( " - duty: " + (String)duty + " " + String( ( duty / 256.0 ) * 100) + "%" +" pow:" + String( round_f( power * 100 )) + "%" ); } } + } currentDuty = duty; } @@ -89,7 +89,7 @@ void ssr_off(){ } void ssr_on(){ - if(_ssrRelayPin > 0) { + if(_ssrRelayPin >= 0) { Logger.println("[SSR] ON"); SetSSRFrequency(255); // working analogWrite( _ssrRelayPin, invertDuty ? 0: 255); @@ -116,26 +116,28 @@ float getSSRPower(){ } void ssr_resume(){ - Serial.println("[SSR] ssr_resume"); + Logger.println("[SSR] ssr_resume"); if(_ssrRelayPin >= 0) setSSR(currentDuty); } void disableSSR(bool disabled = true){ - Serial.println("[SSR] disable ssr - " + (String)disabled); + Logger.println("[SSR] disable ssr"); setSSR(0); ssr_off(); - ssrDisabled = disabled; + ssrDisabled = true; // init safe state, lockdown - pinMode(_ssrRelayPin,INPUT_PULLUP); + // pinMode(_ssrRelayPin,INPUT_PULLUP); } -void enableSSR(bool disabled = true){ - Serial.println("[SSR] disable ssr - " + (String)disabled); +void enableSSR(bool disabled = false){ + Logger.println("[SSR] enable ssr"); setSSR(0); ssr_off(); - ssrDisabled = disabled; + ssrDisabled = false; // init safe state - pinMode(_ssrRelayPin,OUTPUT); + // pinMode(_ssrRelayPin,OUTPUT); // PINMODE BREAKS ANALOGWRITE LEDC CHANNEL + ssr_on(); + delay(500); // test pulse ssr_off(); } @@ -147,6 +149,7 @@ void toggleSSR(){ void ssrTest(int speed){ + ssrDisabled = false; ssr_on(); delay(1000); ssr_off(); @@ -176,6 +179,7 @@ void ssrTest(int speed){ } ssr_off(); + ssrDisabled = true; } void ssrPing(int speed){ From 0d33df3a2b15f50c74e9621891a044a7082c3b2d Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 1 Dec 2022 06:49:31 -0600 Subject: [PATCH 164/186] minor tests --- oled_i2c_sh1106.h | 4 ++-- pid.h | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index d0d0dd8..ac8dfc1 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -197,9 +197,9 @@ void print_oled_line(String str,uint16_t no = 1,uint16_t size = 1){ void print_oled(String str,uint8_t size = 1,bool flush = true){ lcd.clearBuffer(); // clear the internal memory - lcd.setFont(u8g2_font_ncenB08_tr); + // lcd.setFont(u8g2_font_ncenB08_tr); // lcd.drawStr(0,10,String(micros()).c_str()); // write something to the internal memory - lcd.setFont(u8g2_font_inb30_mn); + // lcd.setFont(u8g2_font_inb30_mn); lcd.drawStr(10,30,str.c_str()); // lcd.drawStr(0,10,micros().c_str(); // write something to the internal memory if(flush)lcd.sendBuffer(); // transfer internal memory to the display diff --git a/pid.h b/pid.h index cc96892..39ac5a5 100644 --- a/pid.h +++ b/pid.h @@ -167,15 +167,20 @@ PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT); void pid_reset_I(){ myPID.SetTunings(Kp, 0, Kd); + // Logger.println("[PID] reset I"); + // Logger.println("[PID] PID : " + (String)Kp + " 0 " + (String)Kd); } void pid_preset_I(){ myPID.SetTunings(Kp, Ki, Kd); + // Logger.println("[PID] preset I"); + // Logger.println("[PID] PID : " + (String)Kp + " " + (String)Ki + " " + (String)Kd); } void pid_peak(){ - Logger.println("[PID] adjust tunings"); myPID.SetTunings(KpAgr, KiAgr, KdAgr); + Logger.println("[PID] adjust tunings"); + Logger.println("[PID] PID : " + (String)KpAgr + " " + (String)KiAgr + " " + (String)KdAgr); // @todo confirm tunings } From f4b70ecd91525d276e35596645451c0ff87eccce Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Mon, 5 Dec 2022 12:57:47 -0600 Subject: [PATCH 165/186] lastrrsi --- oled_i2c_sh1106.h | 2 ++ wifi_funcs.h | 12 ++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index ac8dfc1..fec75a1 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -60,6 +60,8 @@ #define GLYPH_SPACE 287 // bell #define GLYPH_NO 87 // busted #define GLYPH_COFFEE 2615 // busted +#define GLYPH_TRENDUP 112 // up arrow +#define GLYPH_TRENDDN 110 // down arrow // const char* testing = u8"\u0263\u0BA3\u0B82"; diff --git a/wifi_funcs.h b/wifi_funcs.h index 0735dc4..607137f 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -23,6 +23,8 @@ bool rebootAfterDowntime = true; long downtimeRestart = 1*60000; // millis long downms = 0; +uint8_t _lastrssiperc = 0; // store rssi + /** IP to String? */ String toStringIp(IPAddress ip) { String res = ""; @@ -216,8 +218,8 @@ void init_WiFi_saved(){ WiFi.begin(); } -int getRSSIasQuality(int RSSI) { - int quality = 0; +uint8_t getRSSIasQuality(int8_t RSSI) { + uint8_t quality = 0; if (RSSI <= -100) { quality = 0; @@ -226,10 +228,11 @@ int getRSSIasQuality(int RSSI) { } else { quality = 2 * (RSSI + 100); } + _lastrssiperc = quality; return quality; } -int getRSSIasQuality() { +uint8_t getRSSIasQuality() { return getRSSIasQuality(WiFi.RSSI()); } @@ -265,9 +268,10 @@ void checkWifi(bool recon = true, bool restart = false){ } } else { + getRSSIasQuality(); if(debug_wifi){ Serial.println("[WIFI] WiFi is CONNECTED"); - Serial.println("[WIFI] RSSI: "+(String)getRSSIasQuality()); + Serial.println("[WIFI] RSSI: "+(String)_lastrssiperc); } #ifdef USENEOIND indSetColor(np_green); From c4631464efd12857558a1f1b4d637a448da19afe Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 8 Dec 2022 16:12:13 -0600 Subject: [PATCH 166/186] cleaning up logging functions --- log.h | 65 +++++++++++++++++++++++++++++++++++++++++++++++----- log_syslog.h | 9 +++++--- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/log.h b/log.h index dc43b5f..8cfb4d0 100644 --- a/log.h +++ b/log.h @@ -1,15 +1,30 @@ - #ifndef log_h #define log_h +/** + * Local logging solutions, using steamutils and syslog + * StreamUtils + * https://github.com/Chris--A/PrintEx + * Allows for stream buffering, redirection, mirroring etc. + * + * syslog + * https://github.com/arcao/Syslog.git + * An Arduino library for logging to Syslog server via `UDP` protocol in + * [IETF (RFC 5424)] and [BSD (RFC 3164)] message format + */ + #define USESYSLOG + #ifdef USESYSLOG #include #include #endif -// https://github.com/Chris--A/PrintEx -// StreamUtils +/** + * syslog preparer + * @todo, streamutils should have buffering capabilities already, replace our buffer + * @param msg [description] + */ char logbuffer[256]; int logbufferidx = 0; // end char @@ -24,6 +39,8 @@ void sendToSyslog(String msg){ // } // Serial.print("[RAW] "); // Serial.println(String(logbuffer).substring(0,logbufferidx)); + + // Log to buffer, do string matching for LOG LEVEL msg = String(logbuffer).substring(0,logbufferidx-2); String msgb = msg; msgb.toLowerCase(); // lowercase for string match levels @@ -35,14 +52,19 @@ void sendToSyslog(String msg){ if(msgb.indexOf("warning") != -1) level = LOG_WARNING; if(msgb.indexOf("fatal") != -1) level = LOG_CRIT; if(syslogactive) syslog.log(level,msg); // SEND IT - // if(syslogactive) syslog.log(level,(String)millis()+" "+msg); // SEND IT - // todo clean up string, remove whitespace such as CR LF \t + // if(syslogactive) syslog.log(level,(String)millis()+" "+msg); + // @todo clean up string, remove whitespace such as CR LF \t + // reset buffer logbuffer[0] = (char)0; logbufferidx = 0; #endif } + +/** + * setup logger stream wrapper, redirection + */ class print2syslog : public Stream { public: bool begun = true; // allow muting via availability @@ -75,6 +97,23 @@ class print2syslog : public Stream { print2syslog syslogger; // syslogger.begin(); +/** + * Setup streamutils stream redirection/mirroring + * @todo abstract into init class + * + * This library provides some helper classes and functions for dealing with streams. + * For example, with this library, you can: + * speed of your program by buffering the data it reads from a file + * reduce the number of packets sent over WiFi by buffering the data you send + * improve the reliability of a serial connection by adding error correction codes + * debug your program more easily by logging what it sends to a Web service + * send large data with the [Wire library](https://www.arduino.cc/en/reference/wire) + * use a `String` or EEPROM with a stream interface + * + * Logger + + * |-> syslogger -> syslog UDP netlog + * |-> Serial -> (uart/usbserial) + */ #include Stream &_Logger = Serial; @@ -93,6 +132,20 @@ LoggingStream Logger(syslogger, _Logger); // loggingClient.println("GET / HTTP/1.1"); // loggingClient.println("User-Agent: Arduino"); + +/** + * Basic Debug logging methods + * DEBUGGER(debuglevel_t LOG_LEVEL,F(msg)); + * DEBUGGER(debuglevel_t LOG_LEVEL,F(msg),value); // for msg value pairs + * + * #DEBUG_LEVEL + * #DEBUG_PORT + * + * PREFIX:[LOGLEVEL] msg + * MAX will output timestamps and memory info + */ + + #include #ifdef ESP8266 @@ -183,7 +236,7 @@ void DEBUGGER(debuglevel_t level,Generic text,Genericb textb) { _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); #endif } - _debugPort.print("*WM: "); + _debugPort.print("*DLOG: "); if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); _debugPort.print(text); if(textb){ diff --git a/log_syslog.h b/log_syslog.h index 10c55c2..2872d36 100644 --- a/log_syslog.h +++ b/log_syslog.h @@ -25,6 +25,8 @@ int iteration = 1; const char* syslog_hostname; const char* syslog_appname; + +// Setup netlog logging void init_syslog(const char* hostname){ Serial.println("[LOG] syslog init"); Serial.println("[LOG] syslog devicename: " + (String)hostname); @@ -42,11 +44,12 @@ void init_syslog(const char* hostname){ syslog.appName(syslog_appname); // syslog.deviceHostname(DEVICE_HOSTNAME); // syslog.appName(APP_NAME); - syslog.defaultPriority(LOG_INFO); + syslog.defaultPriority(LOG_INFO); // default log level if none } +// a tester void sendLogTest(){ - String startmsg = "[BOOT] Device Started"; + String startmsg = "[LOG] SYSLOG TEST"; syslog.log(LOG_INFO, startmsg); return; // Log message can be formated like with printf function. @@ -75,7 +78,7 @@ void sendLogTest(){ } void sendSyslog(){ - syslog.log(LOG_INFO, F("End loop")); + syslog.log(LOG_INFO, F("Test")); } // // Syslog protocol format From 9a37a9ec63066986e41b37bdc575e4269a5e9763 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 8 Dec 2022 16:25:41 -0600 Subject: [PATCH 167/186] syslog cleaning, add local abstractions --- log_syslog.h | 43 ++++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/log_syslog.h b/log_syslog.h index 2872d36..c7824ba 100644 --- a/log_syslog.h +++ b/log_syslog.h @@ -7,10 +7,6 @@ #include #include - -// @todo add print println stream capability -// add manual flush, ammend to buffer send buffer at once instead of real time, or batch sending. - WiFiUDP udpClient; Syslog syslog(udpClient, SYSLOG_PROTO_IETF); // SYSLOG_PROTO_BSD @@ -25,30 +21,43 @@ int iteration = 1; const char* syslog_hostname; const char* syslog_appname; +bool debug_syslog = true; +bool syslog_begun = false; // Setup netlog logging void init_syslog(const char* hostname){ - Serial.println("[LOG] syslog init"); - Serial.println("[LOG] syslog devicename: " + (String)hostname); - Serial.println("[LOG] syslog hostname: " + getHostname()); - Serial.println("[LOG] syslog appname: " + logTopic); - // syslog_hostname = getHostname().c_str(); // gibberish not working + if(debug_syslog){ + Serial.println("[LOG] syslog init"); + Serial.println("[LOG] syslog devicehostname: " + (String)syslog_hostname); + Serial.println("[LOG] syslog appname: " + logTopic); + } + syslog_hostname = hostname; - // : getHostname().c_str(); syslog_appname = logTopic.c_str(); - // prepare syslog configuration here (can be anywhere before first call of - // log/logf method) + // prepare syslog configuration here + // (can be anywhere before first call of log/logf method) syslog.server(syslog_server_ip, syslog_server_port); syslog.deviceHostname(syslog_hostname); syslog.appName(syslog_appname); - // syslog.deviceHostname(DEVICE_HOSTNAME); - // syslog.appName(APP_NAME); syslog.defaultPriority(LOG_INFO); // default log level if none } -// a tester +// bool log(uint16_t pri, const String &message); +// bool log(uint16_t pri, const char *message); +bool sendSysLog(uint16_t level, const String &msg){ + if(!syslog_begun) return false; + return syslog.log(level,msg); +} + +bool sendSysLog(uint16_t level, const char *msg){ + if(!syslog_begun) return false; + return syslog.log(level,msg); +} + +// tester void sendLogTest(){ + if(!syslog_begun) return false; String startmsg = "[LOG] SYSLOG TEST"; syslog.log(LOG_INFO, startmsg); return; @@ -77,10 +86,6 @@ void sendLogTest(){ iteration++; } -void sendSyslog(){ - syslog.log(LOG_INFO, F("Test")); -} - // // Syslog protocol format // #define SYSLOG_PROTO_IETF 0 // RFC 5424 // #define SYSLOG_PROTO_BSD 1 // RFC 3164 From a14a81ae45188b1cc05e0136c267e90f8f3be2eb Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 9 Dec 2022 18:09:30 -0600 Subject: [PATCH 168/186] Update .gitignore --- .gitignore | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index a8c01b3..265f8aa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,2 @@ -.DS_Store -creds.h +.DS_Store creds.h From 32beb42b3dbe071d0c6957e1a0a25bf36694facf Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 9 Dec 2022 18:09:53 -0600 Subject: [PATCH 169/186] minor --- buzzer.h | 1 + neopixel_helper.h | 4 ++-- wifi_funcs.h | 5 ++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/buzzer.h b/buzzer.h index 74a8bcb..413aae5 100644 --- a/buzzer.h +++ b/buzzer.h @@ -147,6 +147,7 @@ void soundalarm(){ #define BUZ_CHAN 0 void plugged() { + // usb melody tone(buzzer_pin, NOTE_C5, 150); // F6 tone(buzzer_pin, NOTE_A5, 100); // F5 tone(buzzer_pin, NOTE_F4, 100); // F5 diff --git a/neopixel_helper.h b/neopixel_helper.h index 3cd0f60..0fa617f 100644 --- a/neopixel_helper.h +++ b/neopixel_helper.h @@ -13,7 +13,7 @@ bool DEBUG_neohelp = false; uint16_t NEOBRIGHTNESS = 100; int NEONUMPIXELS = 5; -#define NEOPIXELSTYPE NEO_GRB + NEO_KHZ800 +#define NEOPIXELSTYPE NEO_RGB + NEO_KHZ800 #include // Adafruit_NeoPixel strip = Adafruit_NeoPixel(); @@ -52,7 +52,7 @@ void init_strip(int pin){ strip.setPin(pin); strip.setBrightness(NEOBRIGHTNESS); strip.updateLength(NEONUMPIXELS); - strip.updateType(NEO_GRB + NEO_KHZ800); + strip.updateType(NEOPIXELSTYPE); strip.begin(); strip.show(); strip.show(); // on purpose, ensure its blanked for glitched resets diff --git a/wifi_funcs.h b/wifi_funcs.h index 0735dc4..18992b1 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -23,6 +23,8 @@ bool rebootAfterDowntime = true; long downtimeRestart = 1*60000; // millis long downms = 0; +uint16_t _lastrssiperc =0; + /** IP to String? */ String toStringIp(IPAddress ip) { String res = ""; @@ -265,9 +267,10 @@ void checkWifi(bool recon = true, bool restart = false){ } } else { + _lastrssiperc = getRSSIasQuality(); if(debug_wifi){ Serial.println("[WIFI] WiFi is CONNECTED"); - Serial.println("[WIFI] RSSI: "+(String)getRSSIasQuality()); + Serial.println("[WIFI] RSSI: "+(String)_lastrssiperc); } #ifdef USENEOIND indSetColor(np_green); From 8ed580890e1dabaae130976952077a5aa0fa8279 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 9 Dec 2022 18:39:02 -0600 Subject: [PATCH 170/186] fix error --- log_syslog.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/log_syslog.h b/log_syslog.h index c7824ba..1b13400 100644 --- a/log_syslog.h +++ b/log_syslog.h @@ -57,7 +57,7 @@ bool sendSysLog(uint16_t level, const char *msg){ // tester void sendLogTest(){ - if(!syslog_begun) return false; + if(!syslog_begun) return; String startmsg = "[LOG] SYSLOG TEST"; syslog.log(LOG_INFO, startmsg); return; From 57059f380cd5c05052cfcd75db981b9b004c96ef Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Sun, 11 Dec 2022 11:18:15 -0600 Subject: [PATCH 171/186] dumb --- sense_env.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sense_env.h b/sense_env.h index 4ad3d0c..678add3 100644 --- a/sense_env.h +++ b/sense_env.h @@ -1376,7 +1376,7 @@ float get_aht(uint8_t channel = 0){ aht.getEvent(&humidity, &temp); // print_env(); if(channel == 0) return temp.temperature; - if(channel == 1) return temp.relative_humidity; + if(channel == 1) return humidity.relative_humidity; return 0; } #endif From 0f1dedf40d055b4266eceecabfab2de66409b01e Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Sun, 11 Dec 2022 11:18:28 -0600 Subject: [PATCH 172/186] some ota info for debuggin --- ota.h | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/ota.h b/ota.h index 9cb9913..b3afcb7 100644 --- a/ota.h +++ b/ota.h @@ -29,20 +29,25 @@ void handleOTA(){ void processOTA(){ handleOTA(); } - // Port defaults to 8266 - // ArduinoOTA.setPort(8266); - // Hostname defaults to esp8266-[ChipID] - // ArduinoOTA.setHostname("myesp8266"); +/* +Port defaults to 8266 or 3232 +ArduinoOTA.setPort(8266); - // No authentication by default - // ArduinoOTA.setPassword("admin"); +test port +sudo nmap -sU -p 8266,3232 -O 192.168.20.124 - // Password can be set with it's md5 value as `nm - // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 - // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); - // ArduinoOTA.setRebootOnSuccess(bool reboot); +Hostname defaults to esp8266-[ChipID] +ArduinoOTA.setHostname("myesp8266"); +No authentication by default +ArduinoOTA.setPassword("admin"); + +Password can be set with it's md5 value as `nm +MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 +ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); +ArduinoOTA.setRebootOnSuccess(bool reboot); +*/ void startOTA(){ ArduinoOTA.onStart([]() { String type; From 17e1c7f9bdb6a4d53a4657635efec7a1721f9367 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Mon, 26 Dec 2022 12:19:18 -0600 Subject: [PATCH 173/186] Create power_funcs.h --- power_funcs.h | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 power_funcs.h diff --git a/power_funcs.h b/power_funcs.h new file mode 100644 index 0000000..9f3c4a3 --- /dev/null +++ b/power_funcs.h @@ -0,0 +1,77 @@ +#ifndef power_funcs_h +#define power_funcs_h + +#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */ +#define TIME_TO_SLEEP 5 /* Time ESP32 will go to sleep (in seconds) */ + +RTC_DATA_ATTR int bootCount = 0; + +/* +Method to print the reason by which ESP32 +has been awaken from sleep +*/ +void print_wakeup_reason(esp_sleep_wakeup_cause_t wakeup_reason){ + switch(wakeup_reason) + { + case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; + case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; + case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; + case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; + case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; + default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; + } +} + +void awoken(){ + //Increment boot number and print it every reboot + ++bootCount; + Serial.println("Boot number: " + String(bootCount)); + + + esp_sleep_wakeup_cause_t wakeup_reason; + wakeup_reason = esp_sleep_get_wakeup_cause(); + + if(!wakeup_reason) Serial.println("I Was not sleeping"); + else print_wakeup_reason(wakeup_reason); +} + +void shhhhhh_gotoSleep(){ + shhhhhh_gotoSleep(); +} +void shhhhhh_gotoSleep(uint32_t seconds = 60){ + + esp_sleep_enable_ext0_wakeup(GPIO_NUM_0,1); //1 = High, 0 = Low + Serial.println("Setup ESP32 to sleep with IO wake"); + + // esp_sleep_enable_timer_wakeup(seconds * uS_TO_S_FACTOR); + // Serial.println("Setup ESP32 to sleep for " + String(seconds) + " Seconds"); + + /* + Next we decide what all peripherals to shut down/keep on + By default, ESP32 will automatically power down the peripherals + not needed by the wakeup source, but if you want to be a poweruser + this is for you. Read in detail at the API docs + http://esp-idf.readthedocs.io/en/latest/api-reference/system/deep_sleep.html + Left the line commented as an example of how to configure peripherals. + The line below turns off all RTC peripherals in deep sleep. + */ + //esp_deep_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF); + //Serial.println("Configured all RTC Peripherals to be powered down in sleep"); + + /* + Now that we have setup a wake cause and if needed setup the + peripherals state in deep sleep, we can now start going to + deep sleep. + In the case that no wake up sources were provided but deep + sleep was started, it will sleep forever unless hardware + reset occurs. + */ + Serial.println("Going to sleep now"); + Serial.flush(); + esp_deep_sleep_start(); + // zzzzzzzzzz +} + + + +#endif \ No newline at end of file From 4c4557215f4988a0c487d7c19eac159a61ded7ae Mon Sep 17 00:00:00 2001 From: Shawn A <807787+tablatronix@users.noreply.github.com> Date: Sat, 11 Feb 2023 10:29:36 -0600 Subject: [PATCH 174/186] Create README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..c11d832 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# arduino_utils +selection of snippets/libraries/abstractions for arduino + +Just random collection of loose methods I am working on to use in my projects, constsantly in progress, very dirty, trying to make portable independant abstraction methods as helpers for building apps +No where close to production code From ab670a97507a6861433ca5c5c20142e268f962fc Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 11 Aug 2023 06:33:41 -0500 Subject: [PATCH 175/186] nothing major --- buzzer.h | 276 ++++++++++++++++++++++++------------------------- definitions.h | 4 + max31855.h | 74 +++++++++---- mqtt.h | 47 +++++++-- neoindicator.h | 4 +- ota.h | 2 +- 6 files changed, 235 insertions(+), 172 deletions(-) diff --git a/buzzer.h b/buzzer.h index 413aae5..dd58b9e 100644 --- a/buzzer.h +++ b/buzzer.h @@ -4,142 +4,142 @@ int BUZZ_VOLUME = 100; int buzzer_pin = -1; -#ifdef ESP8266 - -#include // https://github.com/Mottramlabs/ESP8266-Tone-Generator -#include -ESP8266_Tones BUZZER_TONE(BUZ_PIN); -char szBuf[128]; // serial buffer seems to be only 128 bytes on ESP, only 64 on ATmega - -#include // requires #include -// define the pin used and initialize a MusicEngine object -MmlMusicPWM BUZZER_MUSIC(BUZ_PIN); - -bool init_buzzer(){ - pinMode(BUZ_PIN,OUTPUT); -} - -void soundSiren(int nTimes=10) -{ - for(int nLoop=0; nLoop100; nFreq-=10) - { - BUZZER_MUSIC.tone(nFreq); - delay(1); - } - } -} - -void soundNoise(int nLength=30) -{ - srand(analogRead(A0)); - for(int nLoop=0; nLoopC, T240 O4 L32 CBA V0 A \0\0")); // give a short beep -} - -void blurp4(){ - BUZZER_MUSIC.play("T240 O8 E64"); // give a short beep -} - -void blurp5(){ - BUZZER_MUSIC.play("V20 T240 O8 G64\0\0"); // give a short beep - // BUZZER_MUSIC.play("T240 O8 G64\0\0"); // give a short beep -} - -void blurp6(){ - BUZZER_MUSIC.play("V5 T250 L64 O7 B"); -} - -void playBlurpA(){ - blurp5(); - delay(50); - blurp5(); - delay(50); - blurp5(); - delay(50); -} - -void chime(){ - blurp4(); -} - -void soundalarm(){ - for(int i=0; i<6; i++){ - blurp6(); - delay(50); - } -} - -#else +// #ifdef ESP8266 + +// #include // https://github.com/Mottramlabs/ESP8266-Tone-Generator +// #include +// ESP8266_Tones BUZZER_TONE(BUZ_PIN); +// char szBuf[128]; // serial buffer seems to be only 128 bytes on ESP, only 64 on ATmega + +// #include // requires #include +// // define the pin used and initialize a MusicEngine object +// MmlMusicPWM BUZZER_MUSIC(BUZ_PIN); + +// bool init_buzzer(){ +// pinMode(BUZ_PIN,OUTPUT); +// } + +// void soundSiren(int nTimes=10) +// { +// for(int nLoop=0; nLoop100; nFreq-=10) +// { +// BUZZER_MUSIC.tone(nFreq); +// delay(1); +// } +// } +// } + +// void soundNoise(int nLength=30) +// { +// srand(analogRead(A0)); +// for(int nLoop=0; nLoopC, T240 O4 L32 CBA V0 A \0\0")); // give a short beep +// } + +// void blurp4(){ +// BUZZER_MUSIC.play("T240 O8 E64"); // give a short beep +// } + +// void blurp5(){ +// BUZZER_MUSIC.play("V20 T240 O8 G64\0\0"); // give a short beep +// // BUZZER_MUSIC.play("T240 O8 G64\0\0"); // give a short beep +// } + +// void blurp6(){ +// BUZZER_MUSIC.play("V5 T250 L64 O7 B"); +// } + +// void playBlurpA(){ +// blurp5(); +// delay(50); +// blurp5(); +// delay(50); +// blurp5(); +// delay(50); +// } + +// void chime(){ +// blurp4(); +// } + +// void soundalarm(){ +// for(int i=0; i<6; i++){ +// blurp6(); +// delay(50); +// } +// } + +// #else // #include #include "pitches.h" @@ -255,6 +255,4 @@ void soundalarm(){ delay(500); } -#endif - -#endif +#endif \ No newline at end of file diff --git a/definitions.h b/definitions.h index c326389..15cdb67 100755 --- a/definitions.h +++ b/definitions.h @@ -1,4 +1,8 @@ +// +// SPI MOSI MISO SCLK CS +// VSPI GPIO 23 GPIO 19 GPIO 18 GPIO 5 +// HSPI GPIO 13 GPIO 12 GPIO 14 GPIO 15 #define ESP32BASICUSB diff --git a/max31855.h b/max31855.h index e7ba7d7..891aae3 100644 --- a/max31855.h +++ b/max31855.h @@ -1,13 +1,7 @@ #ifndef max31855_h #define max31855_h -// #include "MAX31855.h" // by Rob Tillaart Library Manager (NO HSPI!!) -#include "Adafruit_MAX31855.h" // Seperate calls for spiread for each function, no raw bit cache! -#include -// #include // @todo test quickstats, add child class for container -// #include // https://github.com/provideyourown/statistics -#include -#include +#define DEBUG // NODEMCU hspi // HW scl D5 14 @@ -16,10 +10,27 @@ // HW cs D8 15 // #define MAXDO 5 // HWMISO -#define MAXCS 15 // 2 -#define MAXCLK 14 // HWSLK -#define MAXMISO 13 -Adafruit_MAX31855 tc(MAXCLK,MAXCS,MAXMISO); +// #define MAXCS 15 // 2 +// #define MAXCLK 14 // HWSLK +// #define MAXMISO 13 + +#define USE_max6675 + +#ifdef USE_max6675 +#include "max6675.h" + +MAX6675 tc(MAX_SCK,MAX_CS,MAX_SDO); +#else +// #include "MAX31855.h" // by Rob Tillaart Library Manager (NO HSPI!!) +#include "Adafruit_MAX31855.h" // Seperate calls for spiread for each function, no raw bit cache! +Adafruit_MAX31855 tc(MAX_SCK,MAX_CS,MAX_SDO); +#endif + +#include +// #include // @todo test quickstats, add child class for container +// #include // https://github.com/provideyourown/statistics +#include +#include // Adafruit_MAX31855 tc(14,15,12); @@ -109,11 +120,27 @@ float correctKType(){ currentTempCorr = correctedCelsius(tcmv,internalTemp); } +float readInternal(){ + #ifdef USE_max6675 + return 0; + #else + return tc.readInternal(); + #endif +} + +uint8_t readError(){ + #ifdef USE_max6675 + return 0; + #else + return tc.readError(); + #endif +} + // @todo better average library, lerp etc void ReadCurrentTempAvg() { - int status = tc.readError(); - float internal = tc.readInternal(); + int status = readError(); + float internal = readInternal(); if(useInternal) currentTempAvg += internal + tempOffset; else currentTempAvg += tc.readCelsius() + tempOffset; avgReadCount++; @@ -131,14 +158,14 @@ void ReadCurrentTempAvg() // Read the temp probe void ReadCurrentTemp() { - lastTCStatus = tc.readError(); + lastTCStatus = readError(); #ifdef DEBUG // Serial.print("tc status: "); // Serial.println( status ); #endif if(useInternal){ // use internal cj as real temp, useful for testing without tc or monitoring pcb etc - internalTemp = tc.readInternal(); + internalTemp = readInternal(); currentTemp = internalTemp + tempOffset; } else { @@ -207,8 +234,8 @@ void updateDevVars(){ } void updateAltTemps(){ - internalTemp = tc.readInternal(); - lastTCStatus = tc.readError(); + internalTemp = readInternal(); + lastTCStatus = readError(); } @@ -222,7 +249,7 @@ void updateTemps(){ // if(updateLock) return; // digitalWrite(0,LOW); // fixes DC left HIGH and data clocked to max ic causing screen artifacts. delay(TCinterval); // stabilizes temperatures ???? - internalTemp = tc.readInternal(); + internalTemp = readInternal(); ReadCurrentTemp(); if(!useAveraging)updateDevVars(); // Serial.println(currentTemp); @@ -312,17 +339,22 @@ else tft.setTextColor( YELLOW, BLACK ); void initTC(){ // Start up the MAX31855 - bool res = tc.begin(); + bool res; + #ifdef USE_max6675 + res = true; + #else + res = tc.begin(); + #endif // if(!res) add check now, see commits delay(200); - tc.readError(); + readError(); // check for sanity Serial.println("[TC] MAX31855 Thermocouple Begin..."); if(!TCSanityCheck()) Serial.println("[ERROR] Status: "+ getTcStatus()); #ifdef DEBUG printTC(); - // Serial.println("[TC] "+(String)round(tc.readInternal())); + // Serial.println("[TC] "+(String)round(readInternal())); // Serial.println("[TC] "+(String)round(tc.readCelsius())); // Serial.println("[TC] "+(String)round(readFahrenheit())); #endif diff --git a/mqtt.h b/mqtt.h index 171eec1..3b6139e 100644 --- a/mqtt.h +++ b/mqtt.h @@ -32,14 +32,14 @@ WiFiClient espClient; PubSubClient client(espClient); -bool debug_mqtt = false; +bool debug_mqtt = true; bool debug_mqtt_json = false; const char* clientID = ""; bool mqttconnected = false; long lastReconnectAttempt = 0; -uint32_t mqttretry = 10000; +uint32_t mqttretry = 5000; void MQTTGetErrorMessage(){ // Possible values for client.state() @@ -130,7 +130,8 @@ bool process_MQTT(){ } if(!client.connected()){ mqttconnected = false; - Logger.println("[MQTT] client not connected"); + Logger.print("[MQTT] client not connected => "); + Logger.println(client.state()); MQTTreconnect(); // @todo throttle return false; } @@ -140,16 +141,26 @@ bool process_MQTT(){ void init_MQTT(){ if(!wifiIsConnected()) return; + if(clientID == ""){ + Logger.println("[MQTT] clientID not set"); + // clientID = getHostname(); + } client.setServer(mqtt_server_ip, mqtt_server_port); + + // MQTT_SOCKET_TIMEOUT: socket timeout interval in Seconds. Override with setSocketTimeout() + client.setSocketTimeout(30); // #define MQTT_SOCKET_TIMEOUT 15 + // MQTT_KEEPALIVE : keepAlive interval in Seconds. Override with setKeepAlive() + client.setKeepAlive(10); // #define MQTT_KEEPALIVE 15 + client.setCallback(MQTTcallback); if (client.connect(clientID)){ mqttconnected = true; - Logger.println("[MQTT] connected to " + (String)mqtt_server_ip); + Logger.println("[MQTT] connected to " + (String)mqtt_server_ip + " as " + clientID); } else Logger.println("[MQTT] init failed to connect to " + (String)mqtt_server_ip); client.setBufferSize(_JSONSIZE); // client.subscribe("CMD"); - client.subscribe("ESP_env_c/CMD"); + // client.subscribe("ESP_env_c/CMD"); process_MQTT(); // jsondata = pubjson.to(); // jsondata = pubjson.createNestedArray(); @@ -307,19 +318,37 @@ void MQTT_pub(String topic, String sensor, String value){ } #endif -// todo -// add free heap -void MQTT_pub_device(){ + +#ifdef ESP8266 + #define ESP_getChipId() ESP.getChipId() +#elif defined(ESP32) + #define ESP_getChipId() (uint32_t)ESP.getEfuseMac() +#endif + +void MQTT_pub_device(bool verbose){ if(!mqttconnected)return; if(debug_mqtt) Logger.println("[MQTT] Publish Device"); MQTT_pub("device","uptime_s",(String)(millis()/1000)); MQTT_pub("device","rssi",(String)getRSSIasQuality()); MQTT_pub("device","heap",(String)ESP.getFreeHeap()); + if(verbose){ + // MQTT_pub("device","ip",(String)ESP.getFreeHeap()); + // MQTT_pub("device","hostname",(String)ESP.getFreeHeap()); + MQTT_pub("device","ChipType",(String)ESP.getChipModel()); + MQTT_pub("device","chipID",(String)ESP_getChipId()); + MQTT_pub("device","ESPver",(String)ESP.getSdkVersion()); + MQTT_pub("device","chipCores",(String)ESP.getChipCores()); + MQTT_pub("device","chipRev",(String)ESP.getChipRevision()); + } // MQTT_pub("device","hall",(String)hallRead()); #ifdef ESP32 - MQTT_pub("device","temp",(String)temperatureRead()); + // MQTT_pub("device","temp",(String)temperatureRead()); #endif MQTT_pub_send("device"); } +void MQTT_pub_device(){ + MQTT_pub_device(false); +} + #endif \ No newline at end of file diff --git a/neoindicator.h b/neoindicator.h index 98c01cf..dc1bffd 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -43,7 +43,7 @@ Adafruit_NeoPixel ind = Adafruit_NeoPixel(); // mediumvioletred #C71585 rgb(199,21,133) uint16_t INDBRIGHTNESS = 60; -int INDNUMPIXELS = 2; +int INDNUMPIXELS = 4; #define INDPIXELSTYPE NEO_GRB + NEO_KHZ800 bool INDPINRESET = false; @@ -55,7 +55,7 @@ void init_indicator(uint16_t pin){ // Adafruit_NeoPixel // strip = ind; ind.setPin(pin); - ind.setBrightness(255); + ind.setBrightness(100); ind.updateLength(INDNUMPIXELS); ind.updateType(NEO_GRB + NEO_KHZ800); ind.begin(); diff --git a/ota.h b/ota.h index b3afcb7..cf1d577 100644 --- a/ota.h +++ b/ota.h @@ -57,7 +57,7 @@ void startOTA(){ type = "filesystem"; } otastarted = true; - Logger.println("\n[OTA] onStart " + type); + // Logger.println("\n[OTA] onStart " + type); Serial.println("\n[OTA] onStart " + type); }); From 4bca971f812cac842f7c5c61af8fe4e46264f445 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 4 Jan 2024 22:43:22 -0600 Subject: [PATCH 176/186] fixup i2c scanner --- io_utils.h | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/io_utils.h b/io_utils.h index 29dc394..c69264c 100644 --- a/io_utils.h +++ b/io_utils.h @@ -60,31 +60,37 @@ uint16_t scani2c(bool pinswap = false){ Wire.beginTransmission(address); int res = Wire.endTransmission(); - // * Output 0 .. success - // * 1 .. length to long for buffer - // * 2 .. address send, NACK received - // * 3 .. data send, NACK received - // * 4 .. other twi error (lost bus arbitration, bus error, ..) - + // https://www.arduino.cc/reference/en/language/functions/communication/wire/endtransmission/ + // endTransmission() returns: + // 0: success. + // 1: data too long to fit in transmit buffer. + // 2: received NACK on transmit of address. + // 3: received NACK on transmit of data. + // 4: other error. + // 5: timeout + if (res == 0) { Logger.print("[I2C] Device found - ADDR: 0x"); - if (address<16) + if (address<16){ Logger.print("0x"); Logger.print(address,HEX); // 7 bit Logger.print(" 0x"); Logger.print(2*address,HEX); // 8bit Logger.println(""); + } nDevices++; } - else if(res!=2 && res !=255) - { - Logger.println("[ERROR]:" + (String)res); - Logger.print("Unknown error ADDR: 0x"); - if (address<16) - Logger.print("0"); - Logger.print(address,HEX); + else if(res!=2 && res !=255){ + Logger.print("[ERROR]: code: " + (String)res); + Logger.print(" ADDR: 0x"); + if (address<16){ + Logger.print("0x"); + Logger.print(address,HEX); // 7 bit + Logger.print(" 0x"); + Logger.print(2*address,HEX); // 8bit Logger.println(""); + } } } if (nDevices == 0) From f3b64a208e84f4a3a37d76ea761812373b1ea3be Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 4 Jan 2024 22:44:19 -0600 Subject: [PATCH 177/186] add new sensor info --- sense_env.h | 48 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/sense_env.h b/sense_env.h index 678add3..e48ffb9 100644 --- a/sense_env.h +++ b/sense_env.h @@ -14,9 +14,9 @@ Average avg_a(20); // SHT21 // HTU21D // -// BMP280 +// BMP280 - !reads 40k alt when offline, 0 psi, 0 temp // BME280 -// CS811 +// CS811 - CO2 // TSL2561 // BH1750 https://github.com/claws/BH1750 // APDS9960 @@ -24,8 +24,10 @@ Average avg_a(20); // PM Dust sensors https://github.com/avaldebe/PMserial // MPU6050 // PCF8591 -// scd4x C02 sensor +// SCD4x CO2 sensor // VEML6070 // UV +// SI7021 +// AHTx0 - T/H // NOT IMPLEMENTED @TODO // HMC5883L @@ -34,6 +36,10 @@ Average avg_a(20); // INA219 // MCP4725 // MCP3421 +// SGP30 - tvoc +// SGP40 - tvoc +// SGP41 - tvoc +// ENS160 - CO2 // BUGS // sensors do not reinit is they drop out, add heathcheck() @@ -48,15 +54,20 @@ Average avg_a(20); //MOTION #define MPU6050 // MPU 6050 GY521 3axis gyro/accel #define HMC5883L // NI Honeywell HMC5883L - +#define MLX90393 // 3 axis magnetometer // TEMP/HUMIDITY/GAS #define SI7021 + #define AHTX0 +// Sensiron #define USESHT31 // SHT31 Temp/Humidity #define USESHT21 // SHT21 / HTU21D Temp/Humidity + +// BOSCH + // #define USEBMP180 // BMP180 Temp/Pressure/Altitude (replaces BMP085) https://www.adafruit.com/product/1603 /* Vin: 3 to 5VDC @@ -66,7 +77,6 @@ Up to 0.03hPa / 0.25m resolution -40 to +85°C operational range, +-2°C temperature accuracy This board/chip uses I2C 7-bit address 0x77. */ - #define USEBMP280 // BMP280 Temp/Pressure/Altitude (upgrade for BMP085/BMP180/BMP183) // #define USEBME280 // BME280 Humidity/Pressure/Altitude // Pressure: 300...1100 hPa @@ -137,7 +147,6 @@ Interface: I2C #define MAX9814 // MAX9814 Auto GC amplifier #define MAX4466 // MAX4466 Adj GC amplifier - // Energy #define INA219 // INA219 current sense @@ -147,9 +156,11 @@ Interface: I2C // #define PCF8591 // PCF8591 io expander +// ADDRESSES + // 0x23 0x46 BH1750 -// 0x38 0x70 -// 0x39 0x72 APDS9960 / TSL2561 +// 0x38 0x70 VEML6070 / AHTx0 +// 0x39 0x72 APDS9960 / TSL2561 / VEML6070 / AHTx0 // 0x3C 0x78 // 0x44 0x88 // 0x48 0x90 @@ -157,6 +168,8 @@ Interface: I2C // 0x62 0xC4 SCD4X // 0x68 0xD0 // 0x76 0xEC +// 0x77 0xEE +// 0x0D 0x1A MLX90393 /* #ifdef ENV_TEMPLATE @@ -766,7 +779,7 @@ bool init_apds(){ } void init_apds_color(){ - //enable color sensign mode + //enable color sensing mode apds.enableColor(true); } @@ -806,11 +819,11 @@ String get_apds_gesture(){ } void print_apds_color(){ - uint16_t r, g, b, c; - + uint16_t r, g, b, c, cnt; //wait for color data to be ready - while(!apds.colorDataReady()){ + while(!apds.colorDataReady() && cnt <100){ delay(5); + cnt++; } //get the data and print the different channels @@ -826,12 +839,15 @@ void print_apds_color(){ Logger.print(" clear: "); Logger.println(c); - Logger.println(); + Logger.println(); } float get_apds_color(uint8_t channel = 0){ // print_apds_color(); uint16_t r, g, b, c; + while(!apds.colorDataReady()){ + delay(5); + } if(!apds.colorDataReady()) return 0; apds.getColorData(&r, &g, &b, &c); if(channel == 0) return r; @@ -910,11 +926,13 @@ Adafruit_SHT31 sht31 = Adafruit_SHT31(); #ifdef USEBMP280 #include Adafruit_BMP280 bmp; // I2C +// #define BMP280_ADDRESS (0x77) /**< The default I2C address for the sensor. */ +// #define BMP280_ADDRESS_ALT (0x76) #endif #ifdef USEBMP280 void init_bmp280(){ - if (!bmp.begin(BMP280_ADDRESS_ALT)) { + if (!bmp.begin(BMP280_ADDRESS)) { Logger.println(F("[ERROR] BMP280 init FAILED")); } else Logger.println(F("[ENV] BMP280 is ACTIVE")); @@ -1355,6 +1373,8 @@ float get_bmp180(uint8_t channel = 0){ #ifdef AHTX0 +// #define AHTX0_I2CADDR_DEFAULT 0x38 ///< AHT default i2c address +// #define AHTX0_I2CADDR_ALTERNATE 0x39 ///< AHT alternate i2c address #include Adafruit_AHTX0 aht; From f4db16bcdc51e5bb4e7eecd6ebf6976941ec6913 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Thu, 4 Jan 2024 22:44:41 -0600 Subject: [PATCH 178/186] some defs --- definitions.h | 25 ++++++++++++++++++++++++- neoindicator.h | 4 +++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/definitions.h b/definitions.h index 15cdb67..6c9cf62 100755 --- a/definitions.h +++ b/definitions.h @@ -1,8 +1,9 @@ -// +// ESP32 // SPI MOSI MISO SCLK CS // VSPI GPIO 23 GPIO 19 GPIO 18 GPIO 5 // HSPI GPIO 13 GPIO 12 GPIO 14 GPIO 15 +// setSpiPin(14, 12, 13, 15); #define ESP32BASICUSB @@ -18,6 +19,28 @@ typedef enum { BUTTON1 = 0, SPIBUS = 2, } PIN_DEFS; +#elif defined(ESP32BASICS3) + +// Controller SPI0 is reserved for caching external memories like Flash +// Controller SPI1 is reserved for external memories like PSRAM +// Controller SPI2 can be used as general purpose SPI (GPSPI) - SPI2_HOST (also called FSPI or HSPI) +// Controller SPI3 can be used as general purpose SPI (GPSPI) - SPI3_HOST (also called VSPI) + +typedef enum { + INDLEDPIN = 19, + INDLEDISRGBW = 1, + IOE1 = 32, + IOE2 = 33, + IOE3 = 36, // ADC + IOE4 = 39, // ADC + ADCEX = 27, + BUTTON1 = 0, + SPIBUS = 2, + SPIIOCLK = 13, + SPIIOMISO = 12, + SPIIOMOSI = 11, + SPIIOCS0 = 10, +} PIN_DEFS; #else typedef enum { INDLEDPIN = 19, diff --git a/neoindicator.h b/neoindicator.h index dc1bffd..04c8929 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -54,6 +54,7 @@ uint32_t indColor; // save color void init_indicator(uint16_t pin){ // Adafruit_NeoPixel // strip = ind; + Serial.println("[NEIND] init pin# " + (String)pin); ind.setPin(pin); ind.setBrightness(100); ind.updateLength(INDNUMPIXELS); @@ -100,7 +101,8 @@ void indSetColor(uint32_t c){ if(DEBUG_neoind)Serial.println("[IND] set ind color:" + (String)c); // debugColor(c); uint32_t color = ColorRGBA(red(c),green(c),blue(c),INDBRIGHTNESS); - ind.setPixelColor( 0, color ); + // ind.setPixelColor( 0, color ); + ind.fill(color); if(INDPINRESET) digitalWrite(ind.getPin(),HIGH); // reset #ifdef ESP32 if(noInterrupts) portDISABLE_INTERRUPTS(); From eba3923b6bb0b5045fc6a07807d9a2311857a028 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 5 Jan 2024 14:40:14 -0600 Subject: [PATCH 179/186] adds sgp30 --- sense_env.h | 120 +++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 101 insertions(+), 19 deletions(-) diff --git a/sense_env.h b/sense_env.h index e48ffb9..ad82984 100644 --- a/sense_env.h +++ b/sense_env.h @@ -52,18 +52,20 @@ Average avg_a(20); // I2C //MOTION -#define MPU6050 // MPU 6050 GY521 3axis gyro/accel -#define HMC5883L // NI Honeywell HMC5883L -#define MLX90393 // 3 axis magnetometer +// #define MPU6050 // MPU 6050 GY521 3axis gyro/accel +// #define HMC5883L // NI Honeywell HMC5883L +// #define MLX90393 // 3 axis magnetometer // TEMP/HUMIDITY/GAS -#define SI7021 +// #define SI7021 -#define AHTX0 +// #define AHTX0 + +#define SGP30 // Sensiron -#define USESHT31 // SHT31 Temp/Humidity -#define USESHT21 // SHT21 / HTU21D Temp/Humidity +// #define USESHT31 // SHT31 Temp/Humidity +// #define USESHT21 // SHT21 / HTU21D Temp/Humidity // BOSCH @@ -77,19 +79,19 @@ Up to 0.03hPa / 0.25m resolution -40 to +85°C operational range, +-2°C temperature accuracy This board/chip uses I2C 7-bit address 0x77. */ -#define USEBMP280 // BMP280 Temp/Pressure/Altitude (upgrade for BMP085/BMP180/BMP183) +// #define USEBMP280 // BMP280 Temp/Pressure/Altitude (upgrade for BMP085/BMP180/BMP183) // #define USEBME280 // BME280 Humidity/Pressure/Altitude // Pressure: 300...1100 hPa -#define SDC4X // SDC40 Co2/Temp/Humidity -#define USECS811 // CCS811 Temp/CO2/VOC +// #define SDC4X // SDC40 Co2/Temp/Humidity +// #define USECS811 // CCS811 Temp/CO2/VOC // #define USEGP2Y // Sharp Particle/Dust sensor GP2Y1010AU0F, GP2Y1014AU0F -#define PMSx +// #define PMSx // LIGHT -#define APDS9960 // Proximity, Light, RGB, and Gesture Sensor +// #define APDS9960 // Proximity, Light, RGB, and Gesture Sensor -#define USEBH1750 // Light Sensor +// #define USEBH1750 // Light Sensor /* BH1750 has six different measurement modes. They are divided in two groups; continuous and one-time measurements. In continuous mode, sensor continuously @@ -120,7 +122,7 @@ This board/chip uses I2C 7-bit address 0x77. BH1750_ONE_TIME_HIGH_RES_MODE_2 */ -#define VEML6070 // UV Sensor +// #define VEML6070 // UV Sensor // #define TSL2561 // Luminosity/Lux/Light Address = 0x39 //Slave addr also 0x29 or 0x49 @@ -144,15 +146,15 @@ Interface: I2C */ // SOUND -#define MAX9814 // MAX9814 Auto GC amplifier -#define MAX4466 // MAX4466 Adj GC amplifier +// #define MAX9814 // MAX9814 Auto GC amplifier +// #define MAX4466 // MAX4466 Adj GC amplifier // Energy -#define INA219 // INA219 current sense +// #define INA219 // INA219 current sense // IO -#define MCP4725 // 12bit DAC with EEPROM -#define MCP3421 // 18bit delta-sigma ADC +// #define MCP4725 // 12bit DAC with EEPROM +// #define MCP3421 // 18bit delta-sigma ADC // #define PCF8591 // PCF8591 io expander @@ -1401,4 +1403,84 @@ float get_aht(uint8_t channel = 0){ } #endif + + +#ifdef SGP30 +#include "Adafruit_SGP30.h" +Adafruit_SGP30 sgp; + +void init_sgp30(){ + bool ret = false; + ret = sgp.begin(); + if(!ret){ + Logger.println("[ERROR] _sgp30 init FAILED"); + } + else Logger.println("[ENV] _sgp30 is ACTIVE"); + + // If you have a baseline measurement from before you can assign it to start, to 'self-calibrate' + // sgp.setIAQBaseline(0x8E68, 0x8F41); // Will vary for each sensor! + // return ret; + + // If you have a temperature / humidity sensor, you can set the absolute humidity to enable the humditiy compensation for the air quality signals + //float temperature = 22.1; // [°C] + //float humidity = 45.2; // [%RH] + //sgp.setHumidity(getAbsoluteHumidity(temperature, humidity)); + +} + +void print_sgp30(){ + Logger.print("Found SGP30 serial #"); + Logger.print(sgp.serialnumber[0], HEX); + Logger.print(sgp.serialnumber[1], HEX); + Logger.println(sgp.serialnumber[2], HEX); + + if (! sgp.IAQmeasure()) { + Logger.println("Measurement failed"); + return; + } + Logger.print("TVOC "); Logger.print(sgp.TVOC); Logger.println(" ppb\t"); + Logger.print("eCO2 "); Logger.print(sgp.eCO2); Logger.println(" ppm"); + + if (! sgp.IAQmeasureRaw()) { + Logger.println("Raw Measurement failed"); + return; + } + Logger.print("Raw H2 "); Logger.println(sgp.rawH2); + Logger.print("Raw Ethanol "); Logger.println(sgp.rawEthanol); + + uint16_t TVOC_base, eCO2_base; + if (! sgp.getIAQBaseline(&eCO2_base, &TVOC_base)) { + Logger.println("Failed to get baseline readings"); + return; + } + Logger.print("****Baseline values: \neCO2: 0x"); Logger.println(eCO2_base, HEX); + Logger.print("TVOC: 0x"); Logger.println(TVOC_base, HEX); +} + +float get_sgp30(uint8_t channel = 0){ + print_sgp30(); + if(sgp.IAQmeasure()){ + if(channel == 0) return sgp.TVOC; + if(channel == 1) return sgp.eCO2; + + if(sgp.IAQmeasureRaw()){ + if(channel == 2) return sgp.rawH2; + if(channel == 3) return sgp.rawEthanol; + } + } + // else "error"; +} +#endif + +/* return absolute humidity [mg/m^3] with approximation formula +* @param temperature [°C] +* @param humidity [%RH] +*/ +uint32_t getAbsoluteHumidity(float temperature, float humidity) { + // approximation formula from Sensirion SGP30 Driver Integration chapter 3.15 + const float absoluteHumidity = 216.7f * ((humidity / 100.0f) * 6.112f * exp((17.62f * temperature) / (243.12f + temperature)) / (273.15f + temperature)); // [g/m^3] + const uint32_t absoluteHumidityScaled = static_cast(1000.0f * absoluteHumidity); // [mg/m^3] + return absoluteHumidityScaled; +} + #endif \ No newline at end of file From aae0c68ac8e96e64660abb1769ec6c736f363168 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 5 Jan 2024 14:40:24 -0600 Subject: [PATCH 180/186] fixup resetreason --- wifi_funcs.h | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/wifi_funcs.h b/wifi_funcs.h index d71d1c4..5a56d84 100644 --- a/wifi_funcs.h +++ b/wifi_funcs.h @@ -496,17 +496,42 @@ const char * const RESET_REASON_STR[] PROGMEM // } RESET_REASON_STR_v; +void verbose_print_reset_reason(int reason) +{ + switch ( reason) + { + case 1 : Serial.println ("Vbat power on reset");break; + case 3 : Serial.println ("Software reset digital core");break; + case 4 : Serial.println ("Legacy watch dog reset digital core");break; + case 5 : Serial.println ("Deep Sleep reset digital core");break; + case 6 : Serial.println ("Reset by SLC module, reset digital core");break; + case 7 : Serial.println ("Timer Group0 Watch dog reset digital core");break; + case 8 : Serial.println ("Timer Group1 Watch dog reset digital core");break; + case 9 : Serial.println ("RTC Watch dog Reset digital core");break; + case 10 : Serial.println ("Instrusion tested to reset CPU");break; + case 11 : Serial.println ("Time Group reset CPU");break; + case 12 : Serial.println ("Software reset CPU");break; + case 13 : Serial.println ("RTC Watch dog Reset CPU");break; + case 14 : Serial.println ("for APP CPU, reseted by PRO CPU");break; + case 15 : Serial.println ("Reset when the vdd voltage is not stable");break; + case 16 : Serial.println ("RTC Watch dog reset digital core and rtc module");break; + default : Serial.println ("NO_MEAN"); + } +} + // @todo String getResetReason(uint8_t cpu = 0){ int reason; #ifdef ESP8266 return ESP.getResetReason(); - #elif defined(ESP32) && defined(_ROM_RTC_H_) - // requires #include + #elif defined(ESP32) + // && defined(_ROM_RTC_H_) + // requires #include + Serial.print("[RESET]");verbose_print_reset_reason(rtc_get_reset_reason(cpu)); return RESET_REASON_STR[rtc_get_reset_reason(cpu)]; // return "NA"; - #else - return "UNSET"; + #else + return (String)rtc_get_reset_reason(cpu) + " - UNKNOWN"; #endif } From c36fd948cee7c0ce7dd48b4942b1ae3a29336f93 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 5 Jan 2024 22:37:18 -0600 Subject: [PATCH 181/186] fix i2c scanner output --- io_utils.h | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/io_utils.h b/io_utils.h index c69264c..33fb876 100644 --- a/io_utils.h +++ b/io_utils.h @@ -72,25 +72,23 @@ uint16_t scani2c(bool pinswap = false){ if (res == 0) { Logger.print("[I2C] Device found - ADDR: 0x"); - if (address<16){ - Logger.print("0x"); + if (address<16)Logger.print("0x"); Logger.print(address,HEX); // 7 bit Logger.print(" 0x"); Logger.print(2*address,HEX); // 8bit - Logger.println(""); - } + Logger.println(); + nDevices++; } else if(res!=2 && res !=255){ Logger.print("[ERROR]: code: " + (String)res); Logger.print(" ADDR: 0x"); - if (address<16){ - Logger.print("0x"); + if (address<16) Logger.print("0x"); Logger.print(address,HEX); // 7 bit Logger.print(" 0x"); Logger.print(2*address,HEX); // 8bit - Logger.println(""); - } + Logger.println(); + } } if (nDevices == 0) From 53067a37af50e8ec6f6c12c117e429be992ed6f5 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Sun, 7 Jan 2024 22:58:00 -0600 Subject: [PATCH 182/186] add sht4x --- sense_env.h | 193 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 157 insertions(+), 36 deletions(-) diff --git a/sense_env.h b/sense_env.h index ad82984..87ec9e5 100644 --- a/sense_env.h +++ b/sense_env.h @@ -8,8 +8,10 @@ Average avg_a(20); // @todo // add global env_debug // add local status for each sensor, avoid sending bad values if init failed +// add improved scanner, default addresses have higher weight, if sensor already detected with high probability, reduce weight // SUPPORTED SENSORS + // SHT31 // SHT21 // HTU21D @@ -18,31 +20,32 @@ Average avg_a(20); // BME280 // CS811 - CO2 // TSL2561 -// BH1750 https://github.com/claws/BH1750 +// BH1750 - https://github.com/claws/BH1750 // APDS9960 // GP2Y -// PM Dust sensors https://github.com/avaldebe/PMserial +// PMs - PM2.5 Dust sensors https://github.com/avaldebe/PMserial // MPU6050 // PCF8591 -// SCD4x CO2 sensor -// VEML6070 // UV +// SCD4x - CO2 sensor +// VEML6070 - UV (highly conflicting address space) // SI7021 -// AHTx0 - T/H +// AHTx0 - T/H (highly conflicting address space) +// SGP30 - tvoc +// INA219 - current // NOT IMPLEMENTED @TODO + // HMC5883L // MAX9814 // MCP3421 -// INA219 // MCP4725 // MCP3421 -// SGP30 - tvoc -// SGP40 - tvoc +// SGP40 - tvoc AQI // SGP41 - tvoc -// ENS160 - CO2 +// ENS160 - tvoc // BUGS -// sensors do not reinit is they drop out, add heathcheck() +// sensors do not reinit if they drop out, add heathcheck() // co2 voc, resubmits the same value over and over if device is lost // use real temp and humidity to compensate other sensors @@ -51,26 +54,31 @@ Average avg_a(20); // I2C -//MOTION +// MOTION +// =============== // #define MPU6050 // MPU 6050 GY521 3axis gyro/accel // #define HMC5883L // NI Honeywell HMC5883L // #define MLX90393 // 3 axis magnetometer // TEMP/HUMIDITY/GAS +// ================= // #define SI7021 - // #define AHTX0 +#define SGP30 // mox gas/tvoc and raw -#define SGP30 // Sensiron +// ================ +#define USESHT40 // SHT40 Temp/Humidity // #define USESHT31 // SHT31 Temp/Humidity // #define USESHT21 // SHT21 / HTU21D Temp/Humidity // BOSCH - +// ================= // #define USEBMP180 // BMP180 Temp/Pressure/Altitude (replaces BMP085) https://www.adafruit.com/product/1603 + + /* Vin: 3 to 5VDC Logic: 3 to 5V compliant @@ -79,19 +87,22 @@ Up to 0.03hPa / 0.25m resolution -40 to +85°C operational range, +-2°C temperature accuracy This board/chip uses I2C 7-bit address 0x77. */ + // #define USEBMP280 // BMP280 Temp/Pressure/Altitude (upgrade for BMP085/BMP180/BMP183) // #define USEBME280 // BME280 Humidity/Pressure/Altitude // Pressure: 300...1100 hPa -// #define SDC4X // SDC40 Co2/Temp/Humidity +#define SCD40 // SDC40 Co2/Temp/Humidity // #define USECS811 // CCS811 Temp/CO2/VOC // #define USEGP2Y // Sharp Particle/Dust sensor GP2Y1010AU0F, GP2Y1014AU0F -// #define PMSx +#define PMSx // pms7003 + // LIGHT +// ================ // #define APDS9960 // Proximity, Light, RGB, and Gesture Sensor - // #define USEBH1750 // Light Sensor + /* BH1750 has six different measurement modes. They are divided in two groups; continuous and one-time measurements. In continuous mode, sensor continuously @@ -122,6 +133,7 @@ This board/chip uses I2C 7-bit address 0x77. BH1750_ONE_TIME_HIGH_RES_MODE_2 */ + // #define VEML6070 // UV Sensor @@ -146,28 +158,32 @@ Interface: I2C */ // SOUND +// ============== // #define MAX9814 // MAX9814 Auto GC amplifier // #define MAX4466 // MAX4466 Adj GC amplifier // Energy +// =============== // #define INA219 // INA219 current sense // IO +// =============== // #define MCP4725 // 12bit DAC with EEPROM // #define MCP3421 // 18bit delta-sigma ADC // #define PCF8591 // PCF8591 io expander -// ADDRESSES - -// 0x23 0x46 BH1750 -// 0x38 0x70 VEML6070 / AHTx0 -// 0x39 0x72 APDS9960 / TSL2561 / VEML6070 / AHTx0 +// ADDRESSES +// ================ +// (7bit) (8bit) (*)typical default +// 0x23 0x46 BH1750* +// 0x38 0x70 VEML6070* / AHTx0* +// 0x39 0x72 APDS9960* / TSL2561 / VEML6070 / AHTx0 // 0x3C 0x78 // 0x44 0x88 // 0x48 0x90 -// 0x5A 0xB4 CS811 -// 0x62 0xC4 SCD4X +// 0x5A 0xB4 CS811* +// 0x62 0xC4 SCD4X* // 0x68 0xD0 // 0x76 0xEC // 0x77 0xEE @@ -348,9 +364,10 @@ float get_veml6070(uint8_t channel = 0){ #include // Arduino library for PM sensors with serial interface bool pms_debug = false; +// pass in pins, define does not work #if !defined(PMS_RX) && !defined(PMS_TX) -constexpr auto PMS_RX = 14; -constexpr auto PMS_TX = 17; +constexpr auto PMS_RX = 3; +constexpr auto PMS_TX = 4; #endif #ifndef ESP32 @@ -1041,6 +1058,111 @@ void sht31_process(){ } #endif +#ifdef USESHT40 +// SHT4x Temp/Humidity +#include "Adafruit_SHT4x.h" +Adafruit_SHT4x sht4 = Adafruit_SHT4x(); + +bool enableHeater = false; + +bool init_sht4(){ + + bool init = sht4.begin(); + if(init){ + Logger.println(F("[ENV] SHT4x is ACTIVE")); + } + else + { + Logger.println(F("[ERROR] SHT4x init FAILED")); + } + + // Logger.print("[ENV] SHT4x Serial number 0x"); + // Logger.println(sht4.readSerial()); // HEX crashes logger + + // You can have 3 different precisions, higher precision takes longer + sht4.setPrecision(SHT4X_MED_PRECISION); + // switch (sht4.getPrecision()) { + // case SHT4X_HIGH_PRECISION: + // Logger.println("High precision"); + // break; + // case SHT4X_MED_PRECISION: + // Logger.println("Med precision"); + // break; + // case SHT4X_LOW_PRECISION: + // Logger.println("Low precision"); + // break; + // } + + // You can have 6 different heater settings + // higher heat and longer times uses more power + // and reads will take longer too! + sht4.setHeater(SHT4X_NO_HEATER); + // switch (sht4.getHeater()) { + // case SHT4X_NO_HEATER: + // Logger.println("No heater"); + // break; + // case SHT4X_HIGH_HEATER_1S: + // Logger.println("High heat for 1 second"); + // break; + // case SHT4X_HIGH_HEATER_100MS: + // Logger.println("High heat for 0.1 second"); + // break; + // case SHT4X_MED_HEATER_1S: + // Logger.println("Medium heat for 1 second"); + // break; + // case SHT4X_MED_HEATER_100MS: + // Logger.println("Medium heat for 0.1 second"); + // break; + // case SHT4X_LOW_HEATER_1S: + // Logger.println("Low heat for 1 second"); + // break; + // case SHT4X_LOW_HEATER_100MS: + // Logger.println("Low heat for 0.1 second"); + // break; + // } + return init; +} + +// BUGGY returns bad values not null, or noint +float get_sht4(uint8_t channel = 0){ + // async ? + sensors_event_t humidity, temp; + sht4.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data + if(channel == 0) return temp.temperature; + if(channel == 1) return humidity.relative_humidity; + return 0; +} + +void sht4_process(){ + sensors_event_t humidity, temp; + uint32_t timestamp = millis(); + sht4.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data + timestamp = millis() - timestamp; + + Serial.print("Temperature: "); Serial.print(temp.temperature); Serial.println(" degrees C"); + Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println("% rH"); + + Serial.print("Read duration (ms): "); + Serial.println(timestamp); + + // // Toggle heater enabled state every 30 seconds + // // An ~3.0 degC temperature increase can be noted when heater is enabled + // if (++loopCnt == 30) { + // enableHeater = !enableHeater; + // sht31.heater(enableHeater); + // Logger.print("[ENV] SHT40 Heater State: "); + // if (sht4.isHeaterEnabled()) + // Logger.println("ENABLED"); + // else + // Logger.println("DISABLED"); + + // loopCnt = 0; + // } +} + +#endif + + // SHT21 / HTU21D Temp/Humidity #ifdef USESHT21 #include @@ -1252,14 +1374,13 @@ float getVoltage(){ -#ifdef SDC4X +#ifdef SCD40 #include SensirionI2CScd4x scd4x; // CO2 0x62 void init_scd4x(){ uint16_t error; char errorMessage[256]; - Wire.begin(); scd4x.begin(Wire); // stop potentially previously started measurement @@ -1403,13 +1524,12 @@ float get_aht(uint8_t channel = 0){ } #endif - - #ifdef SGP30 #include "Adafruit_SGP30.h" Adafruit_SGP30 sgp; void init_sgp30(){ + Logger.println("[ENV] init_sgp30"); bool ret = false; ret = sgp.begin(); if(!ret){ @@ -1429,10 +1549,10 @@ void init_sgp30(){ } void print_sgp30(){ - Logger.print("Found SGP30 serial #"); - Logger.print(sgp.serialnumber[0], HEX); - Logger.print(sgp.serialnumber[1], HEX); - Logger.println(sgp.serialnumber[2], HEX); + // Logger.print("Found SGP30 serial #"); + // Logger.print(sgp.serialnumber[0], HEX); + // Logger.print(sgp.serialnumber[1], HEX); + // Logger.println(sgp.serialnumber[2], HEX); if (! sgp.IAQmeasure()) { Logger.println("Measurement failed"); @@ -1458,7 +1578,7 @@ void print_sgp30(){ } float get_sgp30(uint8_t channel = 0){ - print_sgp30(); + // print_sgp30(); if(sgp.IAQmeasure()){ if(channel == 0) return sgp.TVOC; if(channel == 1) return sgp.eCO2; @@ -1468,7 +1588,8 @@ float get_sgp30(uint8_t channel = 0){ if(channel == 3) return sgp.rawEthanol; } } - // else "error"; + + return 0; } #endif From e4bb06853a64d66d5d98be465ac5a5f33d0fa929 Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Sun, 7 Jan 2024 22:58:03 -0600 Subject: [PATCH 183/186] Update neoindicator.h --- neoindicator.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neoindicator.h b/neoindicator.h index 04c8929..9433cf5 100644 --- a/neoindicator.h +++ b/neoindicator.h @@ -54,7 +54,7 @@ uint32_t indColor; // save color void init_indicator(uint16_t pin){ // Adafruit_NeoPixel // strip = ind; - Serial.println("[NEIND] init pin# " + (String)pin); + Serial.println("[NEOIND] init pin# " + (String)pin); ind.setPin(pin); ind.setBrightness(100); ind.updateLength(INDNUMPIXELS); From e672f163a6c0e69686bba1e118ce1881c566f89e Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Sun, 7 Jan 2024 22:58:06 -0600 Subject: [PATCH 184/186] Update sense_env_class.h --- sense_env_class.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/sense_env_class.h b/sense_env_class.h index 5f71201..2e38bfd 100644 --- a/sense_env_class.h +++ b/sense_env_class.h @@ -7,6 +7,8 @@ // ring buffer // ring index // sensor id +// sensor index +// sensor mqtt topic (temp/temp2/humidity) // sensor i2c addr // sensor unit // sensor values or sensor group by type @@ -24,7 +26,8 @@ // sensor alarms/threshholds // offline mode/collection/logging to sd, maybe add a second buffer with long term ogging interval - + +// interrupt for sense_env sensor // depencandies // average @@ -32,7 +35,10 @@ // filter // ability to grab a sample window for deferred submission to mqtt for a series ( useful for battery operated devices or offline ) -// ability to grab lastvalue as running average over last n samples/n times +// ability to grab lastvalue as running average over subset of last n samples/n times +// ability to reject oulier values for known bad sensor values lacking error conditions + +// get sensors by group/id for looping to displays etc #ifndef sensorsdlog_h #define sensorsdlog_h From 823870be4b68521b9c83a21ced12912cefae0bea Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 22 Mar 2024 16:30:50 -0500 Subject: [PATCH 185/186] add s2 spi --- definitions.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/definitions.h b/definitions.h index 6c9cf62..9e24d08 100755 --- a/definitions.h +++ b/definitions.h @@ -5,6 +5,14 @@ // HSPI GPIO 13 GPIO 12 GPIO 14 GPIO 15 // setSpiPin(14, 12, 13, 15); + +// BASICS2 +// #define SPIBUS 2 +// #define SPIIOCLK 12 +// #define SPIIOMISO 13 +// #define SPIIOMOSI 11 +// #define SPIIOCS0 10 + #define ESP32BASICUSB #ifdef ESP32BASICUSB From f297ffd0e3d1c4a6bd089486dcf1551058de6f0c Mon Sep 17 00:00:00 2001 From: tablatronix <807787+tablatronix@users.noreply.github.com> Date: Fri, 22 Mar 2024 16:33:04 -0500 Subject: [PATCH 186/186] add oled addy --- oled_i2c_sh1106.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/oled_i2c_sh1106.h b/oled_i2c_sh1106.h index fec75a1..747a80e 100644 --- a/oled_i2c_sh1106.h +++ b/oled_i2c_sh1106.h @@ -207,7 +207,7 @@ void print_oled(String str,uint8_t size = 1,bool flush = true){ if(flush)lcd.sendBuffer(); // transfer internal memory to the display } -void init_oled(bool preamble = true,bool pinswap = false){ +void init_oled(bool preamble = true,uint8_t addr = 0x7A,bool pinswap = false){ Logger.println("[OLED] Initializing SSD1106 OLED"); Logger.println("[OLED] SDA: "+(String)SDA); Logger.println("[OLED] SCL: "+(String)SCL); @@ -223,7 +223,7 @@ void init_oled(bool preamble = true,bool pinswap = false){ #endif // lcd.setBusClock(100000L); lcd.begin(); - // lcd.setI2CAddress(0x78); + lcd.setI2CAddress(addr); // if(!lcd.begin()) { // Address 0x3C for 128x32 // Serial.println(F("SSD1106 begin failed")); // }