Skip to content

Commit

Permalink
Move bubbles to struct
Browse files Browse the repository at this point in the history
  • Loading branch information
lbussy committed Mar 31, 2020
1 parent a229fd0 commit 3c27121
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 76 deletions.
83 changes: 35 additions & 48 deletions src/bubbles.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,78 +22,73 @@ SOFTWARE. */

#include "bubbles.h"

Bubbles *pBubbles; // Pointer to Counter class
Bubbles __attribute__((unused)) bubbles;

static ICACHE_RAM_ATTR void HandleInterruptsStatic(void) { // External interrupt handler
pBubbles->handleInterrupts(); // Calls class member handler
bubbles.handleInterrupts(); // Calls class member handler
}

Bubbles* Bubbles::single = NULL; // Holds pointer to class

Bubbles* Bubbles::getInstance() {
if (!single) {
single = new Bubbles();
void Bubbles::start() {
pinMode(COUNTPIN, INPUT); // Change pinmode to input
attachInterrupt(digitalPinToInterrupt(COUNTPIN), HandleInterruptsStatic, RISING); // FALLING, RISING or CHANGE
pBubbles = single; // Assign current instance to pointer
single->ulLastReport = millis();// Store the last report timer
single->ulMicroLast = millis(); // Starting point for debouce timer
single->pulse = 0; // Reset pulse counter
single->doBub = false;
bubbles.ulLastReport = millis();// Store the last report timer
bubbles.ulMicroLast = millis(); // Starting point for debouce timer
bubbles.pulse = 0; // Reset pulse counter
bubbles.doBub = false;
// Set starting values
unsigned long ulNow = millis();
single->ulStart = ulNow;
single->lastBpm = 0.0;
single->lastAmb = 0.0;
single->lastVes = 0.0;
bubbles.ulStart = ulNow;
bubbles.lastBpm = 0.0;
bubbles.lastAmb = 0.0;
bubbles.lastVes = 0.0;

// Set starting time
single->lastTime = getDTS();
}
return single;
bubbles.lastTime = getDTS();
}

void Bubbles::update() { // Regular update loop, once per minute
// Get NTP Time
single->lastTime = getDTS();
BUB_NOT("started");
bubbles.lastTime = getDTS();
return;

// Store last values
single->lastBpm = single->getRawBpm();
single->lastAmb = getTemp(AMBSENSOR);
single->lastVes = getTemp(VESSENSOR);
bubbles.lastBpm = bubbles.getRawBpm();
bubbles.lastAmb = getTemp(AMBSENSOR);
bubbles.lastVes = getTemp(VESSENSOR);

// Push values to circular buffers
tempAmbAvg.push(single->lastAmb);
tempVesAvg.push(single->lastVes);
bubAvg.push(single->lastBpm);
tempAmbAvg.push(bubbles.lastAmb);
tempVesAvg.push(bubbles.lastVes);
bubAvg.push(bubbles.lastBpm);

Log.verbose(F("Current BPM is %D. Averages (%l in sample): BPM = %D, Ambient = %D, Vessel = %D." CR),
single->lastBpm,
bubbles.lastBpm,
tempVesAvg.size(),
single->getAvgBpm(),
single->getAvgAmbient(),
single->getAvgVessel()
bubbles.getAvgBpm(),
bubbles.getAvgAmbient(),
bubbles.getAvgVessel()
);
}

void Bubbles::handleInterrupts(void) { // Bubble Interrupt handler
void Bubbles::handleInterrupts(void) { // Bubbles Interrupt handler
digitalWrite(LED, LOW);
unsigned long now = micros();
if ((now - single->ulMicroLast) > RESOLUTION) { // Filter noise/bounce
single->pulse++; // Increment pulse count
single->ulMicroLast = now;
if ((now - bubbles.ulMicroLast) > RESOLUTION) { // Filter noise/bounce
bubbles.pulse++; // Increment pulse count
bubbles.ulMicroLast = now;
}
single->doBub = true;
bubbles.doBub = true;
}

float Bubbles::getRawBpm() { // Return raw pulses per minute (resets counter)
unsigned long thisTime = millis(); // Get timer value now
unsigned long ulLapsed = thisTime - single->ulLastReport; // Millis since last run
unsigned long ulLapsed = thisTime - bubbles.ulLastReport; // Millis since last run
float fLapsed = (float) ulLapsed; // Cast to float
float secs = fLapsed / 60000.0; // Minutes since last request
float ppm = (pulse / secs); // Calculate PPM
single->pulse = 0; // Zero the pulse counter
single->ulLastReport = millis(); // Store the last report timer
bubbles.pulse = 0; // Zero the pulse counter
bubbles.ulLastReport = millis(); // Store the last report timer
return ppm; // Return pulses per minute
}

Expand Down Expand Up @@ -135,14 +130,6 @@ void Bubbles::setLast(double last) {
}

void setDoBubUpdate() {
doBubUpdate = true; // Semaphore required for Ticker + radio event
}

void bubLoop() {
Bubbles *bubble = Bubbles::getInstance();
// Do Bubble update post
if (doBubUpdate) {
doBubUpdate = false;
bubble->update();
}
BUB_NOT("running" CR);
doBubUpdate = true;
}
25 changes: 14 additions & 11 deletions src/bubbles.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,17 @@ SOFTWARE. */
#ifndef _BUBBLES_H
#define _BUBBLES_H

// #define BUB_DEBUG // Enable Debug for module

#include "config.h"
#include "sensors.h"
#include "ntp.h"
#include <ArduinoLog.h>
#include <CircularBuffer.h>
#include <Arduino.h>

class Bubbles {
struct Bubbles {
private:
// Singleton Declarations
Bubbles() {};
static Bubbles *single;

// Private Methods
float getRawBpm();

Expand All @@ -52,11 +50,8 @@ class Bubbles {
float lastVes;

public:
// Singleton Declarations
static Bubbles* getInstance();
~Bubbles() {single = NULL;}

// Public Methods
void start();
void handleInterrupts(void);
void update(); // Call every 60 seconds
float getAvgAmbient();
Expand All @@ -70,8 +65,16 @@ class Bubbles {
};

void setDoBubUpdate();
void bubLoop();

static bool __attribute__((unused)) doBubUpdate = false; // Semaphore for Bubble timer
static bool __attribute__((unused)) doBubUpdate = false; // Semaphore for Bubbles timer

#ifdef BUB_DEBUG
#include <ArduinoLog.h>
#define BUB_NOT(...) Log.notice(F("[Bub Debug] in %s(): %s." CR), __func__, __VA_ARGS__);
#define BUB_ERR(...) Log.error(F("[Bub Debug] in %s(): %s." CR), __func__, __VA_ARGS__);
#else
#define BUB_NOT(...)
#define BUB_ERR(...)
#endif // End control debug printing

#endif // _BUBBLES_H
1 change: 1 addition & 0 deletions src/main.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,6 @@ extern struct Config config;
extern bool loadConfig();
extern const char *filename;
extern struct ThatVersion thatVersion;
extern struct Bubbles bubbles;

#endif // _MAIN_H
20 changes: 13 additions & 7 deletions src/pushhelper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,14 @@ bool pushToTarget(PushTarget *target, IPAddress targetIP, int port) {
LCBUrl lcburl;
lcburl.setUrl(String(target->url) + String(target->key.name));

Bubbles *bubble = Bubbles::getInstance();
const size_t capacity = JSON_OBJECT_SIZE(8) + 210;
StaticJsonDocument<capacity> doc;

if (target->apiName.enabled) doc[target->apiName.name] = F(API_KEY);
if (target->bubName.enabled) doc[target->bubName.name] = config.bubble.name;
if (target->bpm.enabled) doc[target->bpm.name] = bubble->getAvgBpm();
if (target->ambientTemp.enabled) doc[target->ambientTemp.name] = bubble->getAvgAmbient();
if (target->vesselTemp.enabled) doc[target->vesselTemp.name] = bubble->getAvgVessel();
if (target->bpm.enabled) doc[target->bpm.name] = bubbles.getAvgBpm();
if (target->ambientTemp.enabled) doc[target->ambientTemp.name] = bubbles.getAvgAmbient();
if (target->vesselTemp.enabled) doc[target->vesselTemp.name] = bubbles.getAvgVessel();
if (target->tempFormat.enabled) {
if (config.bubble.tempinf == true) doc[target->tempFormat.name] = F("F");
else doc[target->tempFormat.name] = F("C");
Expand Down Expand Up @@ -160,11 +159,18 @@ void setDoBrewfTarget() {
}

void tickerLoop() {
Bubbles *bubble = Bubbles::getInstance();
Target *target = Target::getInstance();
BFTarget *bfTarget = BFTarget::getInstance();
BrewfTarget *brewfTarget = BrewfTarget::getInstance();

// Handle Bubble update
//
// Do URL Target post
if (doBubUpdate) {
doBubUpdate = false;
bubbles.update();
}
//
// Handle JSON posts
//
// Do URL Target post
Expand Down Expand Up @@ -194,10 +200,10 @@ void tickerLoop() {
}

// Some just for fun serial logging
if (bubble->doBub) { // Serial log for bubble detect
if (bubbles.doBub) { // Serial log for bubble detect
#ifdef LOG_LEVEL
Log.verbose(F("॰ₒ๐°৹" CR)); // Looks like a bubble, right?
#endif
bubble->doBub = false;
bubbles.doBub = false;
}
}
3 changes: 3 additions & 0 deletions src/pushhelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,13 @@ SOFTWARE. */
IPAddress resolveHost(const char hostname[129]);
bool pushToTarget(PushTarget*, IPAddress, int);
void tickerLoop();
void updateLoop();
void setDoURLTarget();
void setDoBFTarget();
void setDoBrewfTarget();

extern struct Bubbles bubbles;

static bool __attribute__((unused)) doURLTarget = false; // Semaphore for Target timer
static bool __attribute__((unused)) doBFTarget = false; // Semaphore for BF timer
static bool __attribute__((unused)) doBrewfTarget = false; // Semaphore for BRF timer
Expand Down
6 changes: 2 additions & 4 deletions src/tools.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ void reboot() {
}

void loadBpm() {
Bubbles *bubble = Bubbles::getInstance();
const size_t capacity = JSON_OBJECT_SIZE(1) + 10;
DynamicJsonDocument doc(capacity);
const char * bpmFileName = "lastBpm.json";
Expand All @@ -60,7 +59,7 @@ void loadBpm() {
Log.error(F("Failed to deserialize lastBpm." CR));
Log.error(err.c_str());
} else {
bubble->setLast(doc["lastBpm"]);
bubbles.setLast(doc["lastBpm"]);
Log.notice(F("Loaded lastBpm." CR));
}
// Delete file
Expand All @@ -69,12 +68,11 @@ void loadBpm() {
}

void saveBpm() {
Bubbles *bubble = Bubbles::getInstance();
const size_t capacity = JSON_OBJECT_SIZE(1) + 10;
DynamicJsonDocument doc(capacity);
const char * bpmFileName = "lastBpm.json";

doc["lastBpm"] = bubble->getAvgBpm();
doc["lastBpm"] = bubbles.getAvgBpm();

// Open file for writing
File file = SPIFFS.open(bpmFileName, "w");
Expand Down
2 changes: 2 additions & 0 deletions src/tools.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,6 @@ void reboot();
void loadBpm();
void saveBpm();

extern struct Bubbles bubbles;

#endif
37 changes: 31 additions & 6 deletions src/webserver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -102,22 +102,20 @@ void setJsonHandlers() {
// Used to provide the Bubbles json
Log.verbose(F("Sending /bubble/." CR));

Bubbles *bubble = Bubbles::getInstance();

const size_t capacity = JSON_OBJECT_SIZE(8) + 210;
StaticJsonDocument<capacity> doc;

doc[F("api_key")] = F(API_KEY);
doc[F("device_source")] = F(SOURCE);
doc[F("name")] = config.bubble.name;
doc[F("bpm")] = bubble->getAvgBpm();
doc[F("ambient")] = bubble->getAvgAmbient();
doc[F("temp")] = bubble->getAvgVessel();
doc[F("bpm")] = bubbles.getAvgBpm();
doc[F("ambient")] = bubbles.getAvgAmbient();
doc[F("temp")] = bubbles.getAvgVessel();
if (config.bubble.tempinf == true)
doc[F("temp_unit")] = F("F");
else
doc[F("temp_unit")] = F("C");
doc[F("datetime")] = bubble->lastTime;
doc[F("datetime")] = bubbles.lastTime;

String json;
serializeJsonPretty(doc, json);
Expand Down Expand Up @@ -454,6 +452,33 @@ void setSettingsAliases() {
request->send(500, F("text/json"), err.c_str());
}
});

server.on("/apply/", HTTP_POST, [](AsyncWebServerRequest *request) {
// Leave blank
}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
request->addInterestingHeader("Accept: application/json");
Log.verbose(F("Processing /apply/." CR));
const size_t capacity = 3*JSON_OBJECT_SIZE(2) + 4*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(8) + 690;
DynamicJsonDocument doc(capacity);

DeserializationError error = deserializeJson(doc, (const char*)data);
if (error) {
request->send(500, "text/plain", error.c_str());
} else {
//config.load(doc.as<JsonObject>());
//saveConfig();
request->send(200, "text/plain", "Ok"); // DEBUG
// if (doc.containsKey("bubname")) { // TODO: Handle individual things like hostname change
// serializeJsonPretty(doc, Serial); // DEBUG
// Serial.println(); // DEBUG
// Log.verbose(F("DEBUG: Bubble Name = %s" CR), doc["bubname"]);
// request->send(200, "text/plain", "Ok");
// } else {
// request->send(500, "text/plain", "No known data received.");
// }
}
}
);
}

void stopWebServer() {
Expand Down
1 change: 1 addition & 0 deletions src/webserver.h
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,6 @@ void stopWebServer();

extern struct Config config;
extern struct ThatVersion thatVersion;
extern struct Bubbles bubbles;

#endif // _WEBSERVER_H

0 comments on commit 3c27121

Please sign in to comment.