Using RTC registers to store fuel gauge.

Added BrowserUpload class
This commit is contained in:
Ray Jones 2019-07-18 22:25:28 +10:00
parent 77ac324d64
commit e50d93bb8c
5 changed files with 401 additions and 0 deletions

BIN
icons/Bowser.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 B

View File

@ -0,0 +1,122 @@
/*
* This file is part of the "bluetoothheater" distribution
* (https://gitlab.com/mrjones.id.au/bluetoothheater)
*
* Copyright (C) 2018 Ray Jones <ray@mrjones.id.au>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
//
// We need to identify the PCB the firmware is running upon for 2 reasons related to GPIO functions
//
// 1: Digital Inputs
// To the outside world, the digital inputs are always treated as contact closures to ground.
// V1.0 PCBs expose the bare ESP inputs for GPIO, they are normally pulled HIGH.
// V2.0+ PCBs use an input conditioning transistor that inverts the sense state.
// Inactive state for V1.0 is HIGH
// Inactive state for V2.0+ is LOW
//
// 2: Analogue input
// Unfortunately the pin originally chosen for the analogue input on the V2.0 PCB goes to
// an ADC2 channel of the ESP32.
// It turns out NONE of the 10 ADC2 channels can be used if Wifi is enabled!
// The remedy on V2.0 PCBs is to cut the traces leading from Digital input 1 and the Analogue input.
// The signals are then tranposed.
// This then presents Digital Input #1 to GPIO26, and analogue to GPIO33.
// As GPIO33 uses an ADC1 channel no issue is present reading analogue values with wifi enabled.
//
// Board Detection
// Fortunately due to the use of the digital input transistors on V2.0+ PCBs, a logical
// determination of the board configuration can be made.
// By setting the pins as digital inputs with pull ups enabled, the logic level presented
// can be read and thus the input signal paths can be determined.
// Due to the input conditioning transistors, V2.0 PCBs will hold the inputs to the ESP32
// LOW when inactive, V1.0 PCBs will pull HIGH.
// Likewise, the analogue input is left to float, so it will always be pulled HIGH.
// NOTE: a 100nF capacitor exists on the analogue input so a delay is required to ensure
// a reliable read.
//
// Input state truth table
// GPIO26 GPIO33
// ------ ------
// V1.0 HIGH HIGH
// unmodified V2.0 HIGH LOW
// modified V2.0 LOW HIGH
// V2.1 LOW HIGH
//
//
// ****************************************************************************************
// This test only needs to be performed upon the very first firmware execution.
// Once the board has been identified, the result is saved to non volatile memory
// If a valid value is detected, the test is bypassed.
// This avoids future issues should the GPIO inputs be legitimately connected to
// extension hardware that may distort the test results when the system is repowered.
// ****************************************************************************************
//
#include "FuelGauge.h"
#include "NVStorage.h"
#include "DebugPort.h"
CFuelGauge::CFuelGauge()
{
_tank_mL = 0;
_pumpCal = 0.02;
record.lastsave = millis();
record.storedval = _tank_mL;
DebugPort.println("CFuelGauge::CFuelGauge");
}
void
CFuelGauge::init()
{
_pumpCal = NVstore.getHeaterTuning().pumpCal;
float testVal;
getStoredFuelGauge(testVal); // RTC registers used to store this
if(INBOUNDS(testVal, 0, 200000)) {
DebugPort.printf("Initialising fuel gauge with %.2fmL\r\n", testVal);
_tank_mL = testVal;
record.storedval = _tank_mL;
}
}
void
CFuelGauge::Integrate(float Hz)
{
unsigned long timenow = millis();
long tSample = timenow - _lasttime;
_lasttime = timenow;
_tank_mL += Hz * tSample * 0.001 * _pumpCal; // Hz * seconds * mL / stroke
long tDiff = millis() - record.lastsave;
float fuelDelta = _tank_mL - record.storedval;
bool bStoppedSave = (Hz == 0) && (_tank_mL != record.storedval);
if(tDiff > 600000 || fuelDelta > 1 || bStoppedSave) { // record fuel usage every 10 minutes, or every 5mL used
DebugPort.printf("Storing fuel gauge: %.2fmL\r\n", _tank_mL);
storeFuelGauge(_tank_mL); // uses RTC registers to store this
record.lastsave = millis();
record.storedval = _tank_mL;
}
}
float
CFuelGauge::Used_mL()
{
return _tank_mL;
}

View File

@ -0,0 +1,43 @@
/*
* This file is part of the "bluetoothheater" distribution
* (https://gitlab.com/mrjones.id.au/bluetoothheater)
*
* Copyright (C) 2018 Ray Jones <ray@mrjones.id.au>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#ifndef BTC_FUELGAUGE_H_
#define BTC_FUELGAUGE_H_
#include <stdint.h>
class CFuelGauge {
float _tank_mL;
unsigned long _lasttime;
float _pumpCal;
struct {
unsigned long lastsave;
float storedval;
} record;
public:
CFuelGauge();
void init();
void Integrate(float Hz);
float Used_mL();
};
#endif

View File

@ -0,0 +1,176 @@
/*
* This file is part of the "bluetoothheater" distribution
* (https://gitlab.com/mrjones.id.au/bluetoothheater)
*
* Copyright (C) 2018 Ray Jones <ray@mrjones.id.au>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "BrowserUpload.h"
#include "../Utility/DebugPort.h"
#include <WiFi.h>
#include <Update.h>
#include <SPIFFS.h>
#include <WebServer.h>
#include "BTCota.h"
#include "../Utility/helpers.h"
void
sBrowserUpload::init()
{
Update
.onProgress([](unsigned int progress, unsigned int total) {
int percent = (progress / (total / 100));
DebugPort.printf("Progress: %u%%\r", percent);
DebugPort.handle(); // keep telnet spy alive
ShowOTAScreen(percent, eOTAWWW); // WWW update in place
DebugPort.print("^");
});
}
int
sBrowserUpload::begin(String& filename, int filesize)
{
bUploadActive = true;
SrcFile.name = filename;
SrcFile.size = -1; //start with max available size
if(filesize) {
SrcFile.size = filesize; // adapt to websocket supplied size
}
if(filename.endsWith(".bin")) {
// FIRMWARE UPLOAD START
DebugPort.printf("Starting firmware update: %s\r\n", SrcFile.name.c_str()); // name without leading slash
if (!Update.begin(SrcFile.size)) {
Update.printError(DebugPort);
bUploadActive = false;
return -1;
}
}
else {
// SPIFFS UPLOAD START
DebugPort.printf("Starting SPIFFS upload: %s\r\n", SrcFile.name.c_str());
if(SPIFFS.exists(SrcFile.name)) {
DebugPort.println("Removing existing file from SPIFFS");
SPIFFS.remove(SrcFile.name);
}
// calculate a *very wild* guess of max size me *may* be able to cope with
int freebytes = SPIFFS.totalBytes() - SPIFFS.usedBytes();
DebugPort.printf("SPIFFS freespace test = %d %d\r\n", freebytes, SrcFile.size); // report our space estimate
freebytes -= 8192; // at least 2 blocks must be kept free, each being 4k
// int pageestimate = (SrcFile.size / 256) + 1 + 1; // +1 for shortfall, +1 for metadata
// freebytes -= pageestimate * 256;
int pageestimate = (SrcFile.size / 4096) + 1 + 1; // +1 for shortfall, +1 for metadata
freebytes -= pageestimate * 4096;
DebugPort.printf("SPIFFS freespace test = %d\r\n", freebytes); // report our space estimate
DstFile.state = -1; // assume SPIFFS error for now...
bUploadActive = false;
if(freebytes > 0) {
// *may* have enough space, open a file
DstFile.file = SPIFFS.open(SrcFile.name, "w"); // Open the file for writing in SPIFFS (create if it doesn't exist)
if(DstFile.file) {
DstFile.state = 1; // opened OK, mark as SPIFFS upload in progress
bUploadActive = true;
}
}
// not enough space - return error to browser via web socket, javascript will report error
if(DstFile.state == -1) {
DebugPort.println("Aborting SPIFFS upload, insufficient space");
return -1;
}
}
return 0;
}
int
sBrowserUpload::fragment(HTTPUpload& upload)
{
if(isSPIFFSupload()) {
// SPIFFS update (may be error state)
if(DstFile.file) {
// file is open, add new fragment of data to file opened for writing
if(DstFile.file.write(upload.buf, upload.currentSize) != upload.currentSize) { // Write the received bytes to the file
// ERROR! write operation failed if length does not match!
DstFile.file.close(); // close the file (fsUploadFile becomes NULL)
DstFile.state = -1; // flag SPIFFS error!
bUploadActive = false;
DebugPort.printf("UPLOAD_FILE_WRITE error: removing %s\r\n", SrcFile.name.c_str());
::SPIFFS.remove(SrcFile.name.c_str()); // remove the bad file from SPIFFS
return -2;
}
}
}
else {
// Firmware update, add new fragment to OTA partition
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
// ERROR !
Update.printError(DebugPort);
return -3;
}
}
return upload.totalSize;
}
int
sBrowserUpload::end(HTTPUpload& upload)
{
int retval = upload.totalSize;
if(isSPIFFSupload()) {
// any form of SPIFFS attempt (may be error)
// Close the file if still open (did not encounter write error)
if(DstFile.file) {
DstFile.file.close();
DebugPort.printf("Final SPIFFS upload Size: %d\r\n", upload.totalSize);
}
else {
// file already closed indicates we encountered a write error
retval = -2;
}
}
else {
// completion of firmware update
// check the added CRC we genertaed matches
// - this guards against malicious, badly formatted bin file attempts.
if(!CheckFirmwareCRC(SrcFile.size)) {
Update.abort();
retval = -4;
}
if (Update.end()) {
DebugPort.printf("Update Success: %s, %d bytes\r\nRebooting...\r\n", SrcFile.name.c_str(), upload.totalSize);
} else {
Update.printError(DebugPort);
if(retval == upload.totalSize) {
retval = -3;
}
}
}
return retval;
}
bool
sBrowserUpload::isOK() const
{
if(isSPIFFSupload())
return DstFile.state == 1;
else
return !Update.hasError();
}

View File

@ -0,0 +1,60 @@
/*
* This file is part of the "bluetoothheater" distribution
* (https://gitlab.com/mrjones.id.au/bluetoothheater)
*
* Copyright (C) 2018 Ray Jones <ray@mrjones.id.au>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#ifndef BTC_BROWSERUPLOAD_H_
#define BTC_BROWSERUPLOAD_H_
#include <Arduino.h>
#include <SPIFFS.h>
#include <WebServer.h>
struct sBrowserUpload{
struct {
String name;
int size;
} SrcFile;
struct {
File file; // a File object to store the received file into SPIFFS
int state;
} DstFile;
bool bUploadActive;
//methods
sBrowserUpload() {
reset();
}
void reset() {
if(DstFile.file) {
DstFile.file.close();
}
DstFile.state = 0;
bUploadActive = false;
}
void init();
int begin(String& filename, int filesize = -1);
int fragment(HTTPUpload& upload);
int end(HTTPUpload& upload);
bool isSPIFFSupload() const { return DstFile.state != 0; };
bool isOK() const;
};
#endif