bring repo up-to-date

This commit is contained in:
2022-05-21 17:57:38 +02:00
parent cd7de5dc64
commit ff41037806
96 changed files with 224981 additions and 1 deletions
@@ -0,0 +1,43 @@
#include <HX711_ADC.h>
//HX711 constructor (dout pin, sck pin)
HX711_ADC LoadCell_1(A3, A2); //HX711 1
HX711_ADC LoadCell_2(A1, A0); //HX711 2
long t;
void setup() {
Serial.begin(9600); delay(10);
Serial.println();
Serial.println("Starting...");
LoadCell_1.begin();
LoadCell_2.begin();
long stabilisingtime = 2000; // tare preciscion can be improved by adding a few seconds of stabilising time
byte loadcell_1_rdy = 0;
byte loadcell_2_rdy = 0;
while ((loadcell_1_rdy + loadcell_2_rdy) < 2) { //run startup, stabilization and tare, both modules simultaniously
if (!loadcell_1_rdy) loadcell_1_rdy = LoadCell_1.startMultiple(stabilisingtime);
if (!loadcell_2_rdy) loadcell_2_rdy = LoadCell_2.startMultiple(stabilisingtime);
}
LoadCell_1.setCalFactor(100); // user set calibration value (float)
LoadCell_2.setCalFactor(100); // user set calibration value (float)
Serial.println("Startup + tare is complete");
}
void loop() {
//update() should be called at least as often as HX711 sample rate; >10Hz@10SPS, >80Hz@80SPS
//longer delay in scetch will reduce effective sample rate (be carefull with use of delay() in the loop)
LoadCell_1.update();
LoadCell_2.update();
//get smoothed value from data set + current calibration factor
if (millis() > t + 250) {
long a = LoadCell_1.getSingleConversionRaw();
long b = LoadCell_2.getSingleConversionRaw();
Serial.print("Load_cell 1 output val: ");
Serial.print(a);
Serial.print(" Load_cell 2 output val: ");
Serial.println(b);
t = millis();
}
}
@@ -0,0 +1,43 @@
#include <HX711_ADC.h>
//HX711 constructor (dout pin, sck pin)
HX711_ADC LoadCell_1(A3, A2); //HX711 1
HX711_ADC LoadCell_2(A1, A0); //HX711 2
long t;
void setup() {
Serial.begin(9600); delay(10);
Serial.println();
Serial.println("Starting...");
LoadCell_1.begin();
LoadCell_2.begin();
long stabilisingtime = 2000; // tare preciscion can be improved by adding a few seconds of stabilising time
byte loadcell_1_rdy = 0;
byte loadcell_2_rdy = 0;
while ((loadcell_1_rdy + loadcell_2_rdy) < 2) { //run startup, stabilization and tare, both modules simultaniously
if (!loadcell_1_rdy) loadcell_1_rdy = LoadCell_1.startMultiple(stabilisingtime);
if (!loadcell_2_rdy) loadcell_2_rdy = LoadCell_2.startMultiple(stabilisingtime);
}
LoadCell_1.setCalFactor(100); // user set calibration value (float)
LoadCell_2.setCalFactor(100); // user set calibration value (float)
Serial.println("Startup + tare is complete");
}
void loop() {
//update() should be called at least as often as HX711 sample rate; >10Hz@10SPS, >80Hz@80SPS
//longer delay in scetch will reduce effective sample rate (be carefull with use of delay() in the loop)
LoadCell_1.update();
LoadCell_2.update();
//get smoothed value from data set + current calibration factor
if (millis() > t + 250) {
long a = LoadCell_1.getSingleConversionRaw();
long b = LoadCell_2.getSingleConversionRaw();
Serial.print("Load_cell 1 output val: ");
Serial.print(a);
Serial.print(" Load_cell 2 output val: ");
Serial.println(b);
t = millis();
}
}
@@ -2,7 +2,7 @@
#include <hal/hal.h>
#include <SPI.h>
#include "HX711.h"
#include "Adafruit_Si7021.h"
//#include "Adafruit_Si7021.h"
#include "Adafruit_FRAM_SPI.h"
// Defines
@@ -0,0 +1,672 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_TxBuffer.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD
;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t *pSendJob);
static void warmupDoneCb(osjob_t *pSendJob);
static void txFailedDoneCb(osjob_t *pSendJob);
static void sleepDoneCb(osjob_t *pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 4;
static const uint8_t LORA_DATA_VERSION = 1;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
typedef struct {
uint8_t version; // Versionierung des Paketformats
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Zehntels-Prozent
uint8_t pressure; // Luftdruck in XXXX
uint8_t reading_offset[MAX_VALUES_TO_SEND]; // Zeit der Messung in Sekunden, erster Wert ist 0
int16_t weight_raw1[MAX_VALUES_TO_SEND]; // Reading (raw) der ersten Waegzelle
int16_t weight_raw2[MAX_VALUES_TO_SEND]; // Reading (raw) der zweiten Waegzelle
int16_t temperature[MAX_VALUES_TO_SEND]; // Temperatur in 1/10 Grad Celsius
} LORA_data;
// Global Variables
LORA_data lora_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed (Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK
);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t *pJob);
void setup(void)
{
gCatena.begin();
lora_data.version = LORA_DATA_VERSION;
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (! (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)))
{
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion))
);
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring)
);
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena))
{
gCatena.SafePrintf("failed\n");
}
else
{
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t *pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM * const pPlatform = gCatena.GetPlatform();
if (pPlatform)
{
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i)
{
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags
);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags()
);
}
else
{
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep))
{
fBme = true;
}
else
{
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
LoadCell_1.begin(A3, A2);
LoadCell_2.begin(A1, A0);
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS))
{
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else
{
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest)))
{
if (! gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else
{
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
startSendingUplink();
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
/* for mfg test, don't tx, just fill -- this causes output to Serial */
if (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))
{
TxBuffer_t b;
fillBuffer(b);
delay(1000);
}
}
void ReadSensors()
{
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int) (vBat * 1000.0f));
lora_data.vbat = (vBat * 1000 / 20);
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int) (vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
if (fBme)
{
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int) m.Temperature,
(int) m.Pressure,
(int) m.Humidity
);
lora_data.temperature[0] = m.Temperature;
lora_data.humidity = m.Temperature;
lora_data.pressure = m.Pressure;
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.wait_ready_timeout(1000))
{
long w1 = LoadCell_1.read_average(5);
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not found.");
}
if (LoadCell_2.wait_ready_timeout(1000))
{
long w2 = LoadCell_2.read_average(5);
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not found.");
}
gCatena.SafePrintf("After Read Scales\n");
}
void fillBuffer(TxBuffer_t &b)
{
b.begin();
FlagsSensor2 flag;
flag = FlagsSensor2(0);
b.put(FormatSensor2); /* the flag for this record format */
uint8_t * const pFlag = b.getp();
b.put(0x00); /* will be set to the flags */
// vBat is sent as 5000 * v
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int) (vBat * 1000.0f));
b.putV(vBat);
flag |= FlagsSensor2::FlagVbat;
// vBus is sent as 5000 * v
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int) (vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
uint32_t bootCount;
if (gCatena.getBootCount(bootCount))
{
b.putBootCountLsb(bootCount);
flag |= FlagsSensor2::FlagBoot;
}
if (fBme)
{
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int) m.Temperature,
(int) m.Pressure,
(int) m.Humidity
);
b.putT(m.Temperature);
b.putP(m.Pressure);
b.putRH(m.Humidity);
flag |= FlagsSensor2::FlagTPH;
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.wait_ready_timeout(1000))
{
long w1 = LoadCell_1.read_average(5);
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not found.");
}
if (LoadCell_2.wait_ready_timeout(1000))
{
long w2 = LoadCell_2.read_average(5);
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not found.");
}
gCatena.SafePrintf("After Read Scales\n");
*pFlag = uint8_t(flag);
}
void startSendingUplink(void)
{
TxBuffer_t b;
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
fillBuffer(b);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16))
{
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
//gLoRaWAN.SendBuffer(b.getbase(), b.getn(), sendBufferDoneCb, NULL, fConfirmed);
gLoRaWAN.SendBuffer((uint8_t*) &lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
static void sendBufferDoneCb(
void *pContext,
bool fStatus
)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (! fStatus)
{
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else
{
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime()+sec2osticks(CATCFG_T_SETTLE),
pFn
);
}
static void txFailedDoneCb(
osjob_t *pSendJob
)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t *pSendJob
)
{
const bool fDeepSleep = checkDeepSleep();
if (! g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest)
{
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr())
{
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17))
{
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0)
{
fDeepSleep = true;
}
else
{
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay
);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n)
{
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000)
{
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100)
{
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t *pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t *pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb
);
}
static void sleepDoneCb(
osjob_t *pJob
)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb
);
}
static void warmupDoneCb(
osjob_t *pJob
)
{
startSendingUplink();
}
@@ -0,0 +1,978 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
CATCFG_T_CYCLE_INITIAL = 30, // every 30 seconds initially
CATCFG_INTERVAL_COUNT_INITIAL = 30, // repeat for 15 minutes
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
CATCFG_T_MIN = CATCFG_T_OVERHEAD,
CATCFG_T_MAX = CATCFG_T_CYCLE < 60 * 60 ? 60 * 60 : CATCFG_T_CYCLE, // normally one hour max.
CATCFG_INTERVAL_COUNT = 30,
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// the cycle time to use
unsigned gTxCycle;
// remaining before we reset to default
unsigned gTxCycleCount;
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
static Arduino_LoRaWAN::ReceivePortBufferCbFn receiveMessage;
void setTxCycleTime(unsigned txCycle, unsigned txCount);
// Additional Commands
// forward reference to the command function
cCommandStream::CommandFn cmdHello;
cCommandStream::CommandFn cmdGetCalibrationSettings;
cCommandStream::CommandFn cmdGetSensorReadings;
cCommandStream::CommandFn cmdGetScale1;
cCommandStream::CommandFn cmdGetScale2;
cCommandStream::CommandFn cmdCalibrateZeroScale1;
cCommandStream::CommandFn cmdCalibrateZeroScale2;
cCommandStream::CommandFn cmdCalibrateScale1;
cCommandStream::CommandFn cmdCalibrateScale2;
// the individual commmands are put in this table
static const cCommandStream::cEntry sMyExtraCommmands[] =
{
{ "hello", cmdHello },
{ "get_calibration_settings", cmdGetCalibrationSettings },
{ "get_sensor_readings", cmdGetSensorReadings },
{ "calibrate_zero_scale1", cmdCalibrateZeroScale1 },
{ "calibrate_zero_scale2", cmdCalibrateZeroScale2 },
{ "calibrate_scale1", cmdCalibrateScale1 },
{ "calibrate_scale2", cmdCalibrateScale2 },
// other commands go here....
};
/* a top-level structure wraps the above and connects to the system table */
/* it optionally includes a "first word" so you can for sure avoid name clashes */
static cCommandStream::cDispatch
sMyExtraCommands_top(
sMyExtraCommmands, /* this is the pointer to the table */
sizeof(sMyExtraCommmands), /* this is the size of the table */
"application" /* this is the "first word" for all the commands in this table*/
);
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 8;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
// must be 65 bytes long...
typedef struct {
long cal_w1_0; // 4 Bytes, Wert Waegezelle 1 ohne Gewicht
long cal_w2_0; // 4 Bytes, Wert Waegezelle 2 ohne Gewicht
float cal_w1_factor; // 4 Bytes,
float cal_w2_factor;
byte fill[49];
} __attribute__((packed)) CONFIG_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (0: <= 2510mV, 70: 3000mV, 170: 3700mV, 255: >= 4295mV [1 Einheit => 7mV])
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur (Startwert) in 1/10 Grad Celsius
int8_t temperature_change[MAX_VALUES_TO_SEND - 1]; // Unterschied Temperatur seit letztem Messwert in 1/10 Grad Celsius
uint8_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
uint16_t weight[MAX_VALUES_TO_SEND]; // Waegezelle Gesamtgewicht, in 5g
uint8_t offset_last_reading; // Zeitunterschied letzte zu erste Messung (in Minuten)
} __attribute__((packed)) LORA_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (0: <= 2510mV, 70: 3000mV, 170: 3700mV, 255: >= 4295mV [1 Einheit => 7mV])
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur in 1/10 Grad Celsius
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} __attribute__((packed)) LORA_data_first;
typedef struct {
uint8_t vbat; // Batteriespannung (0: <= 2510mV, 70: 3000mV, 170: 3700mV, 255: >= 4295mV [1 Einheit => 7mV])
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur in 1/10 Grad Celsius
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} SENSOR_data;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
LORA_data_first lora_data_first;
CONFIG_data config_data;
SENSOR_data last_sensor_reading;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
// Use D10 to regulate power
pinMode(D10, OUTPUT);
setup_platform();
setup_bme280();
//setup_scales();
/* for 4451, we need wider tolerances, it seems */
#if defined(ARDUINO_ARCH_STM32)
LMIC_setClockError(10 * 65536 / 100);
#endif
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
/* add our application-specific commands */
gCatena.addCommands(
sMyExtraCommands_top,
nullptr
);
// read config_data from fram...
gCatena.SafePrintf("Reading Calibration Config from FRAM...\n");
gCatena.getFram()->getField(cFramStorage::kBme680Cal, (uint8_t *)&config_data, sizeof(config_data));
gCatena.SafePrintf("cal_w1_0: %d\n", config_data.cal_w1_0);
gCatena.SafePrintf("cal_w2_0: %d\n", config_data.cal_w2_0);
gCatena.SafePrintf("cal_w1_factor: %d.%03d\n", (int)config_data.cal_w1_factor, (int)(config_data.cal_w1_factor * 1000) % 1000);
gCatena.SafePrintf("cal_w2_factor: %d.%03d\n", (int)config_data.cal_w2_factor, (int)(config_data.cal_w2_factor * 1000) % 1000);
gCatena.SafePrintf("Size of config_data: %d\n", sizeof(config_data));
// im Moment statisch...
//config_data.cal_w1_0 = 20000;
//config_data.cal_w2_0 = 20000;
//config_data.cal_w1_factor = 2.5;
//config_data.cal_w2_factor = 2.5;
// config_data speichern...
//gCatena.SafePrintf("Writing Calibration Config to FRAM...\n");
//gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gLoRaWAN.SetReceiveBufferBufferCb(receiveMessage);
setTxCycleTime(CATCFG_T_CYCLE_INITIAL, CATCFG_INTERVAL_COUNT_INITIAL);
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Enable Power
digitalWrite(D10, HIGH);
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A1, A0);
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
//LoadCell_1.power_down();
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(D12, A2);
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
//LoadCell_2.power_down();
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true, false);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
lora_data.temperature = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight[i] = 0;
if (i < (MAX_VALUES_TO_SEND - 1)) {
lora_data.temperature_change[i] = 0;
}
}
lora_data_first.version = LORA_DATA_VERSION_FIRST_PACKAGE;
lora_data_first.vbat = 0;
lora_data_first.humidity = 0;
lora_data_first.pressure = 0;
lora_data_first.weight1 = 0;
lora_data_first.weight2 = 0;
lora_data_first.weight = 0;
lora_data_first.temperature = 0;
my_position = 0;
}
void ShowLORAData(bool firstTime)
{
if (firstTime) {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n", lora_data_first.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n", lora_data_first.vbat);
gCatena.SafePrintf(" \"humidity\": \"%u\",\n", lora_data_first.humidity);
gCatena.SafePrintf(" \"pressure\": \"%u\",\n", lora_data_first.pressure);
gCatena.SafePrintf(" \"weight1\": \"%ld\",\n", lora_data_first.weight1);
gCatena.SafePrintf(" \"weight2\": \"%ld\",\n", lora_data_first.weight2);
gCatena.SafePrintf(" \"weight\": \"%u\",\n", lora_data_first.weight);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n", lora_data_first.temperature);
gCatena.SafePrintf("}\n");
} else {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n", lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n", lora_data.vbat);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n", lora_data.temperature);
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d", lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d", lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld", lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature_change\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND - 1; i++) {
gCatena.SafePrintf("%d", lora_data.temperature_change[i]);
if (i < (MAX_VALUES_TO_SEND - 2)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
}
uint8_t GetVBatValue(int millivolts)
{
uint8_t res;
if (millivolts <= 2510) {
res = 0;
} else if (millivolts >= 4295) {
res = 255;
} else {
res = (millivolts - 2510) / 7;
}
return res;
}
void ReadSensors(bool firstTime, bool readOnly)
{
int16_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
int16_t temp_last;
int16_t temp_change;
int32_t weight_current32;
uint16_t weight_current;
uint16_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (int16_t)((m.Temperature) * 10);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n", pressure_current);
}
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
// Setup Scales
setup_scales();
// Read Scales
gCatena.SafePrintf("Before Read Scales\n");
// Power-Up HX711
LoadCell_1.power_up();
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
// Power-Down HX711
//LoadCell_1.power_down();
// Power-Up HX711
LoadCell_2.power_up();
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
// Power-Down HX711
//LoadCell_2.power_down();
// Disable Power
digitalWrite(D10, LOW);
gCatena.SafePrintf("After Read Scales\n");
// Gewicht berechnen
weight_current32 = ((weight1_current - config_data.cal_w1_0) / config_data.cal_w1_factor) + ((weight2_current - config_data.cal_w2_0) / config_data.cal_w2_factor);
if (weight_current32 < 0) {
weight_current32 = 0;
} else if (weight_current32 > UINT16_MAX) {
weight_current32 = UINT16_MAX;
}
weight_current = (uint16_t)weight_current32;
if (not(readOnly)) {
// calculate last value
weight_last = 0;
temp_last = lora_data.temperature;
for (int i = 0; i < my_position; i++) {
temp_last = temp_last + lora_data.temperature_change[i];
}
if (my_position > 0) {
weight_last = lora_data.weight[my_position - 1];
}
if (firstTime) {
lora_data_first.vbat = GetVBatValue((int)(vBat * 1000.0f));
lora_data_first.weight1 = weight1_current;
lora_data_first.weight2 = weight2_current;
lora_data_first.weight = weight_current;
lora_data_first.temperature = temp_current;
lora_data_first.humidity = humidity_current;
lora_data_first.pressure = pressure_current;
} else {
lora_data.vbat = GetVBatValue((int)(vBat * 1000.0f));
lora_data.weight[my_position] = weight_current;
if (my_position == 0) {
lora_data.temperature = temp_current;
} else {
temp_change = temp_current - temp_last;
if (temp_change > 127) {
temp_change = 127;
}
if (temp_change < -128) {
temp_change = -128;
}
lora_data.temperature_change[my_position - 1] = (uint8_t)temp_change;
}
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
}
if (my_position == 0) {
timer_pos0 = millis();
}
ShowLORAData(firstTime);
my_position++;
// Should we send the Data?
// we send data the first time the system is started, when the array is full
// or when the weight has fallen more than 100g or the first measurement is
// more than one hour old (which should not happen :-) )
if (firstTime || (my_position >= MAX_VALUES_TO_SEND) || ((weight_last - weight_current) > 20) || ((millis() - timer_pos0) > 3600000)) {
lora_data.offset_last_reading = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink(firstTime);
} else {
gCatena.SafePrintf("now going to sleep for 6 minutes...\n");
Serial.flush();
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
gCatena.Sleep(CATCFG_T_INTERVAL - 5);
}
}
last_sensor_reading.vbat = GetVBatValue((int)(vBat * 1000.0f));
last_sensor_reading.weight1 = weight1_current;
last_sensor_reading.weight2 = weight2_current;
last_sensor_reading.weight = weight_current;
last_sensor_reading.temperature = temp_current;
last_sensor_reading.humidity = humidity_current;
last_sensor_reading.pressure = pressure_current;
}
void startSendingUplink(bool firstTime)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (firstTime) {
gCatena.SafePrintf("SendBuffer firstTime\n");
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed);
} else {
gCatena.SafePrintf("SendBuffer not firstTime\n");
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
gCatena.SafePrintf("sendBufferDoneCB before TimedCallback\n");
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
gCatena.SafePrintf("sendBufferDoneCB after TimedCallback\n");
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("settleDoneCb\n");
sleepDoneCb(pSendJob);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false, false);
}
static void receiveMessage(void *pContext, uint8_t port, const uint8_t *pMessage, size_t nMessage)
{
unsigned txCycle;
unsigned txCount;
gCatena.SafePrintf("receiveMessage was called!!!\n");
if (! (port == 1 && 2 <= nMessage && nMessage <= 3))
{
gCatena.SafePrintf("invalid message port(%02x)/length(%zx)\n",
port, nMessage
);
return;
}
txCycle = (pMessage[0] << 8) | pMessage[1];
if (txCycle < CATCFG_T_MIN || txCycle > CATCFG_T_MAX)
{
gCatena.SafePrintf("tx cycle time out of range: %u\n", txCycle);
return;
}
// byte [2], if present, is the repeat count.
// explicitly sending zero causes it to stick.
txCount = CATCFG_INTERVAL_COUNT;
if (nMessage >= 3)
{
txCount = pMessage[2];
}
// we print out the received message...
gCatena.SafePrintf("Received Data (Payload): \n");
for (byte i = 0; i < nMessage; i++) {
gCatena.SafePrintf("%c", pMessage[i]);
}
gCatena.SafePrintf("\n");
setTxCycleTime(txCycle, txCount);
}
void setTxCycleTime(unsigned txCycle, unsigned txCount)
{
if (txCount > 0)
gCatena.SafePrintf(
"message cycle time %u seconds for %u messages\n",
txCycle, txCount
);
else
gCatena.SafePrintf(
"message cycle time %u seconds indefinitely\n",
txCycle
);
gTxCycle = txCycle;
gTxCycleCount = txCount;
}
/* process "application hello" -- args are ignored */
// argv[0] is "hello"
// argv[1..argc-1] are the (ignored) arguments
cCommandStream::CommandStatus cmdHello(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
pThis->printf("Hello, world!\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetCalibrationSettings(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
pThis->printf("{\n");
pThis->printf(" \"cal_w1_0\": \"%d\",\n", config_data.cal_w1_0);
pThis->printf(" \"cal_w2_0\": \"%d\",\n", config_data.cal_w2_0);
pThis->printf(" \"cal_w1_factor\": \"%d.%03d\n", (int)config_data.cal_w1_factor, (int)abs(config_data.cal_w1_factor * 1000) % 1000);
pThis->printf(" \"cal_w2_factor\": \"%d.%03d\n", (int)config_data.cal_w2_factor, (int)abs(config_data.cal_w2_factor * 1000) % 1000);
pThis->printf("}\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetSensorReadings(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
pThis->printf("{\n");
pThis->printf(" \"weight\": \"%d\",\n", last_sensor_reading.weight);
pThis->printf(" \"weight1_raw\": \"%d\",\n", last_sensor_reading.weight1);
pThis->printf(" \"weight2_raw\": \"%d\",\n", last_sensor_reading.weight2);
pThis->printf(" \"temperature\": \"%d\",\n", last_sensor_reading.temperature);
pThis->printf(" \"humidity\": \"%d\",\n", last_sensor_reading.humidity);
pThis->printf(" \"pressure\": \"%d\",\n", last_sensor_reading.pressure);
pThis->printf(" \"batt\": \"%d\",\n", last_sensor_reading.vbat);
pThis->printf("}\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetScale1(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
pThis->printf("getscale1\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetScale2(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
pThis->printf("getscale2\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateZeroScale1(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
config_data.cal_w1_0 = last_sensor_reading.weight1;
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_zero_scale1 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateZeroScale2(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
config_data.cal_w2_0 = last_sensor_reading.weight2;
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_zero_scale2 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateScale1(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
String w1_gramm(argv[1]);
config_data.cal_w1_factor = (((float)last_sensor_reading.weight1 - config_data.cal_w1_0) / w1_gramm.toFloat());
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_scale1 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateScale2(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
String w2_gramm(argv[1]);
config_data.cal_w2_factor = (((float)last_sensor_reading.weight2 - config_data.cal_w2_0) / w2_gramm.toFloat());
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_scale2 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
@@ -0,0 +1,988 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
CATCFG_T_CYCLE_INITIAL = 30, // every 30 seconds initially
CATCFG_INTERVAL_COUNT_INITIAL = 30, // repeat for 15 minutes
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
CATCFG_T_MIN = CATCFG_T_OVERHEAD,
CATCFG_T_MAX = CATCFG_T_CYCLE < 60 * 60 ? 60 * 60 : CATCFG_T_CYCLE, // normally one hour max.
CATCFG_INTERVAL_COUNT = 30,
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// the cycle time to use
unsigned gTxCycle;
// remaining before we reset to default
unsigned gTxCycleCount;
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
static Arduino_LoRaWAN::ReceivePortBufferCbFn receiveMessage;
void setTxCycleTime(unsigned txCycle, unsigned txCount);
// Additional Commands
// forward reference to the command function
cCommandStream::CommandFn cmdHello;
cCommandStream::CommandFn cmdGetCalibrationSettings;
cCommandStream::CommandFn cmdGetSensorReadings;
cCommandStream::CommandFn cmdGetScale1;
cCommandStream::CommandFn cmdGetScale2;
cCommandStream::CommandFn cmdCalibrateZeroScale1;
cCommandStream::CommandFn cmdCalibrateZeroScale2;
cCommandStream::CommandFn cmdCalibrateScale1;
cCommandStream::CommandFn cmdCalibrateScale2;
// the individual commmands are put in this table
static const cCommandStream::cEntry sMyExtraCommmands[] =
{
{ "hello", cmdHello },
{ "get_calibration_settings", cmdGetCalibrationSettings },
{ "get_sensor_readings", cmdGetSensorReadings },
{ "calibrate_zero_scale1", cmdCalibrateZeroScale1 },
{ "calibrate_zero_scale2", cmdCalibrateZeroScale2 },
{ "calibrate_scale1", cmdCalibrateScale1 },
{ "calibrate_scale2", cmdCalibrateScale2 },
// other commands go here....
};
/* a top-level structure wraps the above and connects to the system table */
/* it optionally includes a "first word" so you can for sure avoid name clashes */
static cCommandStream::cDispatch
sMyExtraCommands_top(
sMyExtraCommmands, /* this is the pointer to the table */
sizeof(sMyExtraCommmands), /* this is the size of the table */
"application" /* this is the "first word" for all the commands in this table*/
);
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 8;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
// must be 65 bytes long...
typedef struct {
long cal_w1_0; // 4 Bytes, Wert Waegezelle 1 ohne Gewicht
long cal_w2_0; // 4 Bytes, Wert Waegezelle 2 ohne Gewicht
float cal_w1_factor; // 4 Bytes,
float cal_w2_factor;
byte fill[123];
} __attribute__((packed)) CONFIG_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (0: <= 2510mV, 70: 3000mV, 170: 3700mV, 255: >= 4295mV [1 Einheit => 7mV])
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur (Startwert) in 1/10 Grad Celsius
int8_t temperature_change[MAX_VALUES_TO_SEND - 1]; // Unterschied Temperatur seit letztem Messwert in 1/10 Grad Celsius
uint8_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
uint16_t weight[MAX_VALUES_TO_SEND]; // Waegezelle Gesamtgewicht, in 5g
uint8_t offset_last_reading; // Zeitunterschied letzte zu erste Messung (in Minuten)
} __attribute__((packed)) LORA_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (0: <= 2510mV, 70: 3000mV, 170: 3700mV, 255: >= 4295mV [1 Einheit => 7mV])
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur in 1/10 Grad Celsius
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} __attribute__((packed)) LORA_data_first;
typedef struct {
uint8_t vbat; // Batteriespannung (0: <= 2510mV, 70: 3000mV, 170: 3700mV, 255: >= 4295mV [1 Einheit => 7mV])
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur in 1/10 Grad Celsius
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} SENSOR_data;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
LORA_data_first lora_data_first;
CONFIG_data config_data;
SENSOR_data last_sensor_reading;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
// Use D10 to regulate power
pinMode(D10, OUTPUT);
setup_platform();
setup_bme280();
//setup_scales();
/* for 4451, we need wider tolerances, it seems */
#if defined(ARDUINO_ARCH_STM32)
LMIC_setClockError(10 * 65536 / 100);
#endif
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
/* add our application-specific commands */
gCatena.addCommands(
sMyExtraCommands_top,
nullptr
);
// read config_data from fram...
gCatena.SafePrintf("Reading Calibration Config from FRAM...\n");
gCatena.getFram()->getField(cFramStorage::kBme680Cal, (uint8_t *)&config_data, sizeof(config_data));
gCatena.SafePrintf("cal_w1_0: %d\n", config_data.cal_w1_0);
gCatena.SafePrintf("cal_w2_0: %d\n", config_data.cal_w2_0);
gCatena.SafePrintf("cal_w1_factor: %d.%03d\n", (int)config_data.cal_w1_factor, (int)(config_data.cal_w1_factor * 1000) % 1000);
gCatena.SafePrintf("cal_w2_factor: %d.%03d\n", (int)config_data.cal_w2_factor, (int)(config_data.cal_w2_factor * 1000) % 1000);
gCatena.SafePrintf("Size of config_data: %d\n", sizeof(config_data));
// im Moment statisch...
//config_data.cal_w1_0 = 20000;
//config_data.cal_w2_0 = 20000;
//config_data.cal_w1_factor = 2.5;
//config_data.cal_w2_factor = 2.5;
// config_data speichern...
//gCatena.SafePrintf("Writing Calibration Config to FRAM...\n");
//gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gLoRaWAN.SetReceiveBufferBufferCb(receiveMessage);
setTxCycleTime(CATCFG_T_CYCLE_INITIAL, CATCFG_INTERVAL_COUNT_INITIAL);
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Enable Power
digitalWrite(D10, HIGH);
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A1, A0);
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
//LoadCell_1.power_down();
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(D12, A2);
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
//LoadCell_2.power_down();
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true, false);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
lora_data.temperature = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight[i] = 0;
if (i < (MAX_VALUES_TO_SEND - 1)) {
lora_data.temperature_change[i] = 0;
}
}
lora_data_first.version = LORA_DATA_VERSION_FIRST_PACKAGE;
lora_data_first.vbat = 0;
lora_data_first.humidity = 0;
lora_data_first.pressure = 0;
lora_data_first.weight1 = 0;
lora_data_first.weight2 = 0;
lora_data_first.weight = 0;
lora_data_first.temperature = 0;
my_position = 0;
}
void ShowLORAData(bool firstTime)
{
if (firstTime) {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n", lora_data_first.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n", lora_data_first.vbat);
gCatena.SafePrintf(" \"humidity\": \"%u\",\n", lora_data_first.humidity);
gCatena.SafePrintf(" \"pressure\": \"%u\",\n", lora_data_first.pressure);
gCatena.SafePrintf(" \"weight1\": \"%ld\",\n", lora_data_first.weight1);
gCatena.SafePrintf(" \"weight2\": \"%ld\",\n", lora_data_first.weight2);
gCatena.SafePrintf(" \"weight\": \"%u\",\n", lora_data_first.weight);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n", lora_data_first.temperature);
gCatena.SafePrintf("}\n");
} else {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n", lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n", lora_data.vbat);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n", lora_data.temperature);
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d", lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d", lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld", lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature_change\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND - 1; i++) {
gCatena.SafePrintf("%d", lora_data.temperature_change[i]);
if (i < (MAX_VALUES_TO_SEND - 2)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
}
uint8_t GetVBatValue(int millivolts)
{
uint8_t res;
if (millivolts <= 2510) {
res = 0;
} else if (millivolts >= 4295) {
res = 255;
} else {
res = (millivolts - 2510) / 7;
}
return res;
}
void ReadSensors(bool firstTime, bool readOnly)
{
int16_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
int16_t temp_last;
int16_t temp_change;
int32_t weight_current32;
uint16_t weight_current;
uint16_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (int16_t)((m.Temperature) * 10);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n", pressure_current);
}
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
// Setup Scales
setup_scales();
// Read Scales
gCatena.SafePrintf("Before Read Scales\n");
// Power-Up HX711
LoadCell_1.power_up();
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
gCatena.SafePrintf("Load_cell 1 weight1_current: %ld\n", weight1_current);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
// Power-Down HX711
//LoadCell_1.power_down();
// Power-Up HX711
LoadCell_2.power_up();
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
gCatena.SafePrintf("Load_cell 2 weight2_current: %ld\n", weight2_current);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
// Power-Down HX711
//LoadCell_2.power_down();
// Disable Power
digitalWrite(D10, LOW);
gCatena.SafePrintf("After Read Scales\n");
// Gewicht berechnen
weight_current32 = (int32_t)((((weight1_current - config_data.cal_w1_0) / config_data.cal_w1_factor) + ((weight2_current - config_data.cal_w2_0) / config_data.cal_w2_factor)) / 5.0);
if (weight_current32 < 0) {
weight_current32 = 0;
} else if (weight_current32 > UINT16_MAX) {
weight_current32 = UINT16_MAX;
}
weight_current = (uint16_t)weight_current32;
if (not(readOnly)) {
// calculate last value
weight_last = 0;
temp_last = lora_data.temperature;
for (int i = 0; i < my_position; i++) {
temp_last = temp_last + lora_data.temperature_change[i];
}
if (my_position > 0) {
weight_last = lora_data.weight[my_position - 1];
}
if (firstTime) {
lora_data_first.vbat = GetVBatValue((int)(vBat * 1000.0f));
lora_data_first.weight1 = weight1_current;
lora_data_first.weight2 = weight2_current;
lora_data_first.weight = weight_current;
lora_data_first.temperature = temp_current;
lora_data_first.humidity = humidity_current;
lora_data_first.pressure = pressure_current;
} else {
lora_data.vbat = GetVBatValue((int)(vBat * 1000.0f));
lora_data.weight[my_position] = weight_current;
if (my_position == 0) {
lora_data.temperature = temp_current;
} else {
temp_change = temp_current - temp_last;
if (temp_change > 127) {
temp_change = 127;
}
if (temp_change < -128) {
temp_change = -128;
}
lora_data.temperature_change[my_position - 1] = (uint8_t)temp_change;
}
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
}
if (my_position == 0) {
timer_pos0 = millis();
}
ShowLORAData(firstTime);
my_position++;
// Should we send the Data?
// we send data the first time the system is started, when the array is full
// or when the weight has fallen more than 100g or the first measurement is
// more than one hour old (which should not happen :-) )
if (firstTime || (my_position >= MAX_VALUES_TO_SEND) || ((weight_last - weight_current) > 20) || ((millis() - timer_pos0) > 3600000)) {
lora_data.offset_last_reading = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink(firstTime);
} else {
gCatena.SafePrintf("now going to sleep for 6 minutes...\n");
Serial.flush();
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
if (!fUsbPower) {
gCatena.Sleep(CATCFG_T_INTERVAL - 5);
}
}
}
last_sensor_reading.vbat = GetVBatValue((int)(vBat * 1000.0f));
last_sensor_reading.weight1 = weight1_current;
last_sensor_reading.weight2 = weight2_current;
last_sensor_reading.weight = weight_current;
last_sensor_reading.temperature = temp_current;
last_sensor_reading.humidity = humidity_current;
last_sensor_reading.pressure = pressure_current;
}
void startSendingUplink(bool firstTime)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (firstTime) {
gCatena.SafePrintf("SendBuffer firstTime\n");
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed);
} else {
gCatena.SafePrintf("SendBuffer not firstTime\n");
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
gCatena.SafePrintf("sendBufferDoneCB before TimedCallback\n");
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
gCatena.SafePrintf("sendBufferDoneCB after TimedCallback\n");
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("settleDoneCb\n");
sleepDoneCb(pSendJob);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false, false);
}
static void receiveMessage(void *pContext, uint8_t port, const uint8_t *pMessage, size_t nMessage)
{
unsigned txCycle;
unsigned txCount;
gCatena.SafePrintf("receiveMessage was called!!!\n");
if (! (port == 1 && 2 <= nMessage && nMessage <= 3))
{
gCatena.SafePrintf("invalid message port(%02x)/length(%zx)\n",
port, nMessage
);
return;
}
txCycle = (pMessage[0] << 8) | pMessage[1];
if (txCycle < CATCFG_T_MIN || txCycle > CATCFG_T_MAX)
{
gCatena.SafePrintf("tx cycle time out of range: %u\n", txCycle);
return;
}
// byte [2], if present, is the repeat count.
// explicitly sending zero causes it to stick.
txCount = CATCFG_INTERVAL_COUNT;
if (nMessage >= 3)
{
txCount = pMessage[2];
}
// we print out the received message...
gCatena.SafePrintf("Received Data (Payload): \n");
for (byte i = 0; i < nMessage; i++) {
gCatena.SafePrintf("%c", pMessage[i]);
}
gCatena.SafePrintf("\n");
setTxCycleTime(txCycle, txCount);
}
void setTxCycleTime(unsigned txCycle, unsigned txCount)
{
if (txCount > 0)
gCatena.SafePrintf(
"message cycle time %u seconds for %u messages\n",
txCycle, txCount
);
else
gCatena.SafePrintf(
"message cycle time %u seconds indefinitely\n",
txCycle
);
gTxCycle = txCycle;
gTxCycleCount = txCount;
}
/* process "application hello" -- args are ignored */
// argv[0] is "hello"
// argv[1..argc-1] are the (ignored) arguments
cCommandStream::CommandStatus cmdHello(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
pThis->printf("Hello, world!\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetCalibrationSettings(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
pThis->printf("{\n");
pThis->printf(" \"cal_w1_0\": \"%d\",\n", config_data.cal_w1_0);
pThis->printf(" \"cal_w2_0\": \"%d\",\n", config_data.cal_w2_0);
pThis->printf(" \"cal_w1_factor\": \"%d.%03d\n", (int)config_data.cal_w1_factor, (int)abs(config_data.cal_w1_factor * 1000) % 1000);
pThis->printf(" \"cal_w2_factor\": \"%d.%03d\n", (int)config_data.cal_w2_factor, (int)abs(config_data.cal_w2_factor * 1000) % 1000);
pThis->printf("}\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetSensorReadings(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
pThis->printf("{\n");
pThis->printf(" \"weight\": \"%d\",\n", last_sensor_reading.weight);
pThis->printf(" \"weight1_raw\": \"%d\",\n", last_sensor_reading.weight1);
pThis->printf(" \"weight2_raw\": \"%d\",\n", last_sensor_reading.weight2);
pThis->printf(" \"temperature\": \"%d\",\n", last_sensor_reading.temperature);
pThis->printf(" \"humidity\": \"%d\",\n", last_sensor_reading.humidity);
pThis->printf(" \"pressure\": \"%d\",\n", last_sensor_reading.pressure);
pThis->printf(" \"batt\": \"%d\",\n", last_sensor_reading.vbat);
pThis->printf("}\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetScale1(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
pThis->printf("getscale1\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetScale2(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
pThis->printf("getscale2\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateZeroScale1(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
config_data.cal_w1_0 = last_sensor_reading.weight1;
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_zero_scale1 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateZeroScale2(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
config_data.cal_w2_0 = last_sensor_reading.weight2;
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_zero_scale2 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateScale1(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
String w1_gramm(argv[1]);
config_data.cal_w1_factor = (((float)last_sensor_reading.weight1 - config_data.cal_w1_0) / w1_gramm.toFloat());
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
gCatena.SafePrintf("last_sensor_reading.weight1: %ld\n", last_sensor_reading.weight1);
gCatena.SafePrintf("config_data.cal_w1_0: %ld\n", config_data.cal_w1_0);
gCatena.SafePrintf("w1_gramm: %s\n", w1_gramm);
gCatena.SafePrintf("w1_gramm (float): %d\n", (int)w1_gramm.toFloat());
gCatena.SafePrintf("config_data.cal_w1_factor: %d\n", (int)config_data.cal_w1_factor);
pThis->printf("{ \"msg\": \"calibrate_scale1 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateScale2(cCommandStream *pThis, void *pContext, int argc, char **argv)
{
ReadSensors(false, true);
String w2_gramm(argv[1]);
config_data.cal_w2_factor = (((float)last_sensor_reading.weight2 - config_data.cal_w2_0) / w2_gramm.toFloat());
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_scale2 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
@@ -0,0 +1,850 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
CATCFG_T_CYCLE_INITIAL = 30, // every 30 seconds initially
CATCFG_INTERVAL_COUNT_INITIAL = 30, // repeat for 15 minutes
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
CATCFG_T_MIN = CATCFG_T_OVERHEAD,
CATCFG_T_MAX = CATCFG_T_CYCLE < 60 * 60 ? 60 * 60 : CATCFG_T_CYCLE, // normally one hour max.
CATCFG_INTERVAL_COUNT = 30,
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// the cycle time to use
unsigned gTxCycle;
// remaining before we reset to default
unsigned gTxCycleCount;
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
static Arduino_LoRaWAN::ReceivePortBufferCbFn receiveMessage;
void setTxCycleTime(unsigned txCycle, unsigned txCount);
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 8;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
// must be 65 bytes long...
typedef struct {
long cal_w1_0; // 4 Bytes, Wert Waegezelle 1 ohne Gewicht
long cal_w2_0; // 4 Bytes, Wert Waegezelle 1 ohne Gewicht
float cal_w1_factor; // 4 Bytes,
float cal_w2_factor;
byte fill[49];
} __attribute__((packed)) CONFIG_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur (Startwert) in 1/10 Grad Celsius
int8_t temperature_change[MAX_VALUES_TO_SEND - 1]; // Unterschied Temperatur seit letztem Messwert in 1/10 Grad Celsius
uint8_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
uint16_t weight[MAX_VALUES_TO_SEND]; // Waegezelle Gesamtgewicht, in 5g
uint8_t offset_last_reading; // Zeitunterschied letzte zu erste Messung (in Minuten)
} __attribute__((packed)) LORA_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur in 1/10 Grad Celsius
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} __attribute__((packed)) LORA_data_first;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
LORA_data_first lora_data_first;
CONFIG_data config_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
/* for 4451, we need wider tolerances, it seems */
#if defined(ARDUINO_ARCH_STM32)
LMIC_setClockError(10 * 65536 / 100);
#endif
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
// read config_data from fram...
gCatena.SafePrintf("Reading Calibration Config from FRAM...\n");
gCatena.getFram()->getField(cFramStorage::kBme680Cal, (uint8_t *)&config_data, sizeof(config_data));
gCatena.SafePrintf("cal_w1_0: %d\n",config_data.cal_w1_0);
gCatena.SafePrintf("cal_w2_0: %d\n",config_data.cal_w2_0);
gCatena.SafePrintf("cal_w1_factor: %d.%03d\n",(int)config_data.cal_w1_factor,(int)(config_data.cal_w1_factor*1000)%1000);
gCatena.SafePrintf("cal_w2_factor: %d.%03d\n",(int)config_data.cal_w2_factor,(int)(config_data.cal_w2_factor*1000)%1000);
gCatena.SafePrintf("Size of config_data: %d\n",sizeof(config_data));
// im Moment statisch...
//config_data.cal_w1_0 = 20000;
//config_data.cal_w2_0 = 20000;
//config_data.cal_w1_factor = 2.5;
//config_data.cal_w2_factor = 2.5;
// config_data speichern...
gCatena.SafePrintf("Writing Calibration Config to FRAM...\n");
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gLoRaWAN.SetReceiveBufferBufferCb(receiveMessage);
setTxCycleTime(CATCFG_T_CYCLE_INITIAL, CATCFG_INTERVAL_COUNT_INITIAL);
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
//LoadCell_1.begin(A3, A2);
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
gCatena.SafePrintf("Setup Scale 2...\n");
//LoadCell_2.begin(A1, A0);
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
lora_data.temperature = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight[i] = 0;
if (i < (MAX_VALUES_TO_SEND -1)) {
lora_data.temperature_change[i] = 0;
}
}
lora_data_first.version = LORA_DATA_VERSION_FIRST_PACKAGE;
lora_data_first.vbat = 0;
lora_data_first.humidity = 0;
lora_data_first.pressure = 0;
lora_data_first.weight1 = 0;
lora_data_first.weight2 = 0;
lora_data_first.weight = 0;
lora_data_first.temperature = 0;
my_position = 0;
}
void ShowLORAData(bool firstTime)
{
if (firstTime) {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data_first.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data_first.vbat);
gCatena.SafePrintf(" \"humidity\": \"%u\",\n",lora_data_first.humidity);
gCatena.SafePrintf(" \"pressure\": \"%u\",\n",lora_data_first.pressure);
gCatena.SafePrintf(" \"weight1\": \"%ld\",\n",lora_data_first.weight1);
gCatena.SafePrintf(" \"weight2\": \"%ld\",\n",lora_data_first.weight2);
gCatena.SafePrintf(" \"weight\": \"%u\",\n",lora_data_first.weight);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data_first.temperature);
gCatena.SafePrintf("}\n");
} else {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data.temperature);
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature_change\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND - 1; i++) {
gCatena.SafePrintf("%d",lora_data.temperature_change[i]);
if (i < (MAX_VALUES_TO_SEND - 2)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
}
void ReadSensors(bool firstTime)
{
// Power-Up HX711
LoadCell_1.power_up();
LoadCell_1.power_up();
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
int16_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
int16_t temp_last;
int16_t temp_change;
uint16_t weight_current;
uint16_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (int16_t)((m.Temperature) * 10);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
// Power-Down HX711
LoadCell_1.power_down();
LoadCell_1.power_down();
// Gewicht berechnen
weight_current = ((weight1_current - config_data.cal_w1_0) / config_data.cal_w1_factor) + ((weight2_current - config_data.cal_w2_0) / config_data.cal_w2_factor);
// calculate last value
weight_last = 0;
temp_last = lora_data.temperature;
for (int i = 0; i < my_position; i++) {
temp_last = temp_last + lora_data.temperature_change[i];
}
if (my_position > 0) {
weight_last = lora_data.weight[my_position - 1];
}
if (firstTime) {
lora_data_first.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data_first.weight1 = weight1_current;
lora_data_first.weight2 = weight2_current;
lora_data_first.weight = weight_current;
lora_data_first.temperature = temp_current;
lora_data_first.humidity = humidity_current;
lora_data_first.pressure = pressure_current;
} else {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight[my_position] = weight_current;
if (my_position == 0) {
lora_data.temperature = temp_current;
} else {
temp_change = temp_current - temp_last;
if (temp_change > 127) {
temp_change = 127;
}
if (temp_change < -128) {
temp_change = -128;
}
lora_data.temperature_change[my_position - 1] = (uint8_t)temp_change;
}
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
}
if (my_position == 0) {
timer_pos0 = millis();
}
ShowLORAData(firstTime);
my_position++;
// Should we send the Data?
// we send data the first time the system is started, when the array is full
// or when the weight has fallen more than 100g or the first measurement is
// more than one hour old (which should not happen :-) )
if (firstTime || (my_position >= MAX_VALUES_TO_SEND) || ((weight_last - weight_current) > 20) || ((millis() - timer_pos0) > 3600000)) {
lora_data.offset_last_reading = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink(firstTime);
} else {
doLightSleep(&sensorJob);
}
}
void startSendingUplink(bool firstTime)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (firstTime) {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed);
} else {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}
static void receiveMessage(void *pContext, uint8_t port, const uint8_t *pMessage, size_t nMessage)
{
unsigned txCycle;
unsigned txCount;
gCatena.SafePrintf("receiveMessage was called!!!\n");
if (! (port == 1 && 2 <= nMessage && nMessage <= 3))
{
gCatena.SafePrintf("invalid message port(%02x)/length(%zx)\n",
port, nMessage
);
return;
}
txCycle = (pMessage[0] << 8) | pMessage[1];
if (txCycle < CATCFG_T_MIN || txCycle > CATCFG_T_MAX)
{
gCatena.SafePrintf("tx cycle time out of range: %u\n", txCycle);
return;
}
// byte [2], if present, is the repeat count.
// explicitly sending zero causes it to stick.
txCount = CATCFG_INTERVAL_COUNT;
if (nMessage >= 3)
{
txCount = pMessage[2];
}
// we print out the received message...
gCatena.SafePrintf("Received Data (Payload): \n");
for (byte i = 0; i < nMessage; i++) {
gCatena.SafePrintf("%c", pMessage[i]);
}
gCatena.SafePrintf("\n");
setTxCycleTime(txCycle, txCount);
}
void setTxCycleTime(unsigned txCycle, unsigned txCount)
{
if (txCount > 0)
gCatena.SafePrintf(
"message cycle time %u seconds for %u messages\n",
txCycle, txCount
);
else
gCatena.SafePrintf(
"message cycle time %u seconds indefinitely\n",
txCycle
);
gTxCycle = txCycle;
gTxCycleCount = txCount;
}
@@ -0,0 +1,718 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 8;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
typedef struct {
long cal_w1_0;
long cal_w2_0;
float cal_w1_factor;
float cal_w2_factor;
} CONFIG_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
uint8_t temperature[MAX_VALUES_TO_SEND]; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
uint8_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
uint16_t weight[MAX_VALUES_TO_SEND]; // Waegezelle Gesamtgewicht, in 5g
uint8_t offset_last_reading;
} __attribute__((packed)) LORA_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Prozent
uint8_t temperature; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} __attribute__((packed)) LORA_data_first;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
LORA_data_first lora_data_first;
CONFIG_data config_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
// im Moment statisch...
config_data.cal_w1_0 = 20000;
config_data.cal_w2_0 = 20000;
config_data.cal_w1_factor = 2.5;
config_data.cal_w2_factor = 2.5;
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A3, A2);
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(A1, A0);
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight[i] = 0;
lora_data.temperature[i] = 0;
}
lora_data_first.version = LORA_DATA_VERSION_FIRST_PACKAGE;
lora_data_first.vbat = 0;
lora_data_first.humidity = 0;
lora_data_first.pressure = 0;
lora_data_first.weight1 = 0;
lora_data_first.weight2 = 0;
lora_data_first.weight = 0;
lora_data_first.temperature = 0;
my_position = 0;
}
void ShowLORAData(bool firstTime)
{
if (firstTime) {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data_first.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data_first.vbat);
gCatena.SafePrintf(" \"humidity\": \"%u\",\n",lora_data_first.humidity);
gCatena.SafePrintf(" \"pressure\": \"%u\",\n",lora_data_first.pressure);
gCatena.SafePrintf(" \"weight1\": \"%ld\",\n",lora_data_first.weight1);
gCatena.SafePrintf(" \"weight2\": \"%ld\",\n",lora_data_first.weight2);
gCatena.SafePrintf(" \"weight\": \"%u\",\n",lora_data_first.weight);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data_first.temperature);
gCatena.SafePrintf("}\n");
} else {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.temperature[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
}
void ReadSensors(bool firstTime)
{
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
uint8_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
uint8_t temp_last;
uint16_t weight_current;
uint16_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (uint8_t)((m.Temperature + 40) * 2);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
// Gewicht berechnen
weight_current = ((weight1_current - config_data.cal_w1_0) / config_data.cal_w1_factor) + ((weight2_current - config_data.cal_w2_0) / config_data.cal_w2_factor);
// calculate last value
weight_last = 0;
if (my_position > 0) {
temp_last =lora_data.temperature[my_position -1];
weight_last = lora_data.weight[my_position - 1];
}
if (firstTime) {
lora_data_first.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data_first.weight1 = weight1_current;
lora_data_first.weight2 = weight2_current;
lora_data_first.weight = weight_current;
lora_data_first.temperature = temp_current;
lora_data_first.humidity = humidity_current;
lora_data_first.pressure = pressure_current;
} else {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight[my_position] = weight_current;
lora_data.temperature[my_position] = temp_current;
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
}
if (my_position == 0) {
timer_pos0 = millis();
}
ShowLORAData(firstTime);
my_position++;
// Should we send the Data?
// we send data the first time the system is started, when the array is full
// or when the weight has fallen more than 100g or the first measurement is
// more than one hour old (which should not happen :-) )
if (firstTime || (my_position >= MAX_VALUES_TO_SEND) || ((weight_last - weight_current) > 20) || ((millis() - timer_pos0) > 3600000)) {
lora_data.offset_last_reading = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink(firstTime);
} else {
doLightSleep(&sensorJob);
}
}
void startSendingUplink(bool firstTime)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (firstTime) {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed);
} else {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}
@@ -0,0 +1,649 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 4;
static const uint8_t LORA_DATA_VERSION = 1;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
typedef struct {
uint8_t version; // Versionierung des Paketformats
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Zehntels-Prozent
uint8_t pressure; // Luftdruck in XXXX
uint8_t reading_offset[MAX_VALUES_TO_SEND]; // Zeit der Messung in Sekunden, erster Wert ist 0
int16_t weight_raw1[MAX_VALUES_TO_SEND]; // Reading (raw) der ersten Waegzelle
int16_t weight_raw2[MAX_VALUES_TO_SEND]; // Reading (raw) der zweiten Waegzelle
int16_t temperature[MAX_VALUES_TO_SEND]; // Temperatur in 1/10 Grad Celsius
} LORA_data;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A3, A2);
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(A1, A0);
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
bool ShouldDataBeSent(void)
{
bool res = (my_position >= MAX_VALUES_TO_SEND) ||
((millis() - timer_pos0) > 3600000);
return res;
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
lora_data.humidity = 0;
lora_data.pressure = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.reading_offset[i] = 0;
lora_data.weight_raw1[i] = 0;
lora_data.weight_raw2[i] = 0;
lora_data.temperature[i] = 0;
}
}
void ShowLORAData(void)
{
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%i\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%i\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"humidity\": \"%i\",\n",lora_data.humidity);
gCatena.SafePrintf(" \"pressure\": \"%i\",\n",lora_data.pressure);
gCatena.SafePrintf(" \"reading_offset\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%i",lora_data.reading_offset[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight_raw1\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%i",lora_data.weight_raw1[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight_raw2\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%i",lora_data.weight_raw2[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%i",lora_data.temperature[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf("}\n");
}
void ReadSensors(bool firstTime)
{
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
int16_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int16_t w1_current;
int16_t w2_current;
int16_t temp_last;
uint8_t humidity_last;
uint8_t pressure_last;
int16_t w1_last;
int16_t w2_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = m.Temperature;
humidity_current = m.Humidity;
pressure_current = m.Pressure;
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
w1_current = w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
w2_current = w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
if (my_position > 0) {
temp_last = lora_data.temperature[my_position - 1];
w1_last = lora_data.weight_raw1[my_position - 1];
w2_last = lora_data.weight_raw2[my_position - 1];
}
// Wir registrieren die Werte nur, falls die Abweichung zur letzen Messung gross genug ist
if (my_position == 0 || abs(temp_current - temp_last) > 10 || abs(w1_current - w1_last) > 50 || abs(w2_current - w2_last) > 50) {
lora_data.vbat = (vBat * 1000 / 20);
if (my_position > 0) {
lora_data.reading_offset[my_position] = int((millis() - timer_pos0) / 1000);
} else {
timer_pos0 = millis();
}
lora_data.weight_raw1[my_position] = w1_current;
lora_data.weight_raw2[my_position] = w2_current;
lora_data.temperature[my_position] = temp_current;
lora_data.humidity = humidity_current;
lora_data.pressure = humidity_current;
ShowLORAData();
my_position++;
}
else {
gCatena.SafePrintf("Too little difference, measurements are not stored...\n");
}
// Should we send the Data?
if (firstTime || ShouldDataBeSent()) {
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink();
}
}
void startSendingUplink(void)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}
@@ -0,0 +1,656 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 6;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint32_t PRESSURE_OFFSET = 80000;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
typedef struct {
long cal_w1_0;
long cal_w2_0;
float cal_w1_factor;
float cal_w2_factor;
} FRAM_data;
typedef struct {
uint8_t version; // Versionierung des Paketformats
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t pressure; // Luftdruck in Pascal (0 entspricht 80000 Pa)
uint8_t reading_offset[MAX_VALUES_TO_SEND]; // Zeit der weiteren Messung in Sekunden seit Start
int16_t weight[MAX_VALUES_TO_SEND]; // Gewicht in 10-Gramm, Addition beider Waegzellen
uint8_t temperature[MAX_VALUES_TO_SEND]; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
} LORA_data;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
FRAM_data fram_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
// aktuell noch als Konstanten...
fram_data.cal_w1_0 = -10000;
fram_data.cal_w2_0 = -10000;
fram_data.cal_w1_factor = 1;
fram_data.cal_w2_factor = 1;
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A3, A2);
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(A1, A0);
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
bool ShouldDataBeSent(void)
{
bool res = (my_position > MAX_VALUES_TO_SEND) ||
((millis() - timer_pos0) > 3600000);
return res;
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
lora_data.humidity = 0;
lora_data.pressure = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.reading_offset[i] = 0;
lora_data.weight[i] = 0;
lora_data.temperature[i] = 0;
}
my_position = 0;
}
void ShowLORAData(void)
{
char str[10];
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"humidity\": \"%d\",\n",lora_data.humidity);
gCatena.SafePrintf(" \"pressure\": \"%d\",\n",lora_data.pressure);
gCatena.SafePrintf(" \"reading_offset\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%u",lora_data.reading_offset[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.temperature[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
void ReadSensors(bool firstTime)
{
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
int8_t temp_current;
uint8_t humidity_current;
int16_t pressure_current;
int32_t weight_current;
int32_t w1_current;
int32_t w2_current;
int8_t temp_last;
int32_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (int8_t)((m.Temperature + 40) * 2);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint16_t)(m.Pressure - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
w1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
w2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
// Calculate Weight
weight_current = (((w1_current - fram_data.cal_w1_0) / fram_data.cal_w1_factor) + ((w2_current - fram_data.cal_w2_0) / fram_data.cal_w2_factor));
// calculate last value
if (my_position > 0) {
temp_last =lora_data.temperature[my_position -1];
weight_last = lora_data.weight[my_position - 1];
}
// Wir registrieren die Werte nur, falls die Abweichung zur letzen Messung gross genug ist, oder es die erste Messung ist
if (my_position == 0 || abs(temp_current - temp_last) > 3 || abs(weight_current - weight_last) > 50) {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight[my_position] = weight_current;
lora_data.temperature[my_position] = temp_current;
if (my_position > 0) {
lora_data.reading_offset[my_position] = (uint8_t)((millis() - timer_pos0) / 1000);
} else {
timer_pos0 = millis();
lora_data.humidity = humidity_current;
lora_data.pressure = pressure_current;
}
ShowLORAData();
my_position++;
}
else {
gCatena.SafePrintf("Too little difference, measurements are not stored...\n");
}
// Should we send the Data?
if (firstTime || ShouldDataBeSent()) {
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink();
}
}
void startSendingUplink(void)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}
@@ -0,0 +1,668 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 3;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint32_t PRESSURE_OFFSET = 80000;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
typedef struct {
uint8_t version; // Versionierung des Paketformats
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
uint8_t temperature[MAX_VALUES_TO_SEND]; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
int16_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Pascal (0 entspricht 80000 Pa)
int32_t weight1[MAX_VALUES_TO_SEND]; // Waegezelle 1, Raw Value
int32_t weight2[MAX_VALUES_TO_SEND]; // Waegezelle 2, Raw Value
uint16_t reading_offset[MAX_VALUES_TO_SEND - 1]; // Zeit der weiteren Messungen in Sekunden seit Start
} __attribute__((packed)) LORA_data;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A3, A2);
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(A1, A0);
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
bool ShouldDataBeSent(void)
{
bool res = (my_position >= MAX_VALUES_TO_SEND) ||
((millis() - timer_pos0) > 3600000);
return res;
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
if (i < (MAX_VALUES_TO_SEND - 1)) {
lora_data.reading_offset[i] = 0;
}
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight1[i] = 0;
lora_data.weight2[i] = 0;
lora_data.temperature[i] = 0;
}
my_position = 0;
}
void ShowLORAData(void)
{
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"reading_offset\": [");
for (int i = 0; i < (MAX_VALUES_TO_SEND - 1); i++) {
gCatena.SafePrintf("%u",lora_data.reading_offset[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight1\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight1[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight2\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight2[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.temperature[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
void ReadSensors(bool firstTime)
{
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
int8_t temp_current;
uint8_t humidity_current;
int16_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
int8_t temp_last;
int32_t weight1_last;
int32_t weight2_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (int8_t)((m.Temperature + 40) * 2);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (int16_t)(m.Pressure - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
// calculate last value
if (my_position > 0) {
temp_last =lora_data.temperature[my_position -1];
weight1_last = lora_data.weight1[my_position - 1];
weight2_last = lora_data.weight2[my_position - 1];
}
// Wir registrieren die Werte nur, falls die Abweichung zur letzen Messung gross genug ist, oder es die erste Messung ist
if (my_position == 0 || abs(temp_current - temp_last) > 3 || abs(weight1_current - weight1_last) > 500 || abs(weight2_current - weight2_last) > 500) {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight1[my_position] = weight1_current;
lora_data.weight2[my_position] = weight2_current;
lora_data.temperature[my_position] = temp_current;
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
if (my_position > 0) {
lora_data.reading_offset[my_position - 1] = (uint16_t)((millis() - timer_pos0) / 1000);
} else {
timer_pos0 = millis();
}
ShowLORAData();
my_position++;
}
else {
gCatena.SafePrintf("Too little difference, measurements are not stored...\n");
}
// Should we send the Data?
if (firstTime || ShouldDataBeSent()) {
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink();
} else {
doLightSleep(&sensorJob);
}
}
void startSendingUplink(void)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,667 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 3;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint32_t PRESSURE_OFFSET = 80000;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
typedef struct {
uint8_t version; // Versionierung des Paketformats
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
uint8_t temperature[MAX_VALUES_TO_SEND]; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
int16_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Pascal (0 entspricht 80000 Pa)
int32_t weight1[MAX_VALUES_TO_SEND]; // Waegezelle 1, Raw Value
int32_t weight2[MAX_VALUES_TO_SEND]; // Waegezelle 2, Raw Value
uint8_t reading_offset[MAX_VALUES_TO_SEND]; // Zeit der weiteren Messungen in Minuten seit Start, letzter Wert: Offset beim Senden des Pakets
} __attribute__((packed)) LORA_data;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A3, A2);
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(A1, A0);
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
bool ShouldDataBeSent(void)
{
bool res = (my_position >= MAX_VALUES_TO_SEND) ||
((millis() - timer_pos0) > 3600000);
return res;
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.reading_offset[i] = 0;
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight1[i] = 0;
lora_data.weight2[i] = 0;
lora_data.temperature[i] = 0;
}
my_position = 0;
}
void ShowLORAData(void)
{
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"reading_offset\": [");
for (int i = 0; i < (MAX_VALUES_TO_SEND); i++) {
gCatena.SafePrintf("%d",lora_data.reading_offset[i]);
if (i < (MAX_VALUES_TO_SEND - 2)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight1\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight1[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight2\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight2[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.temperature[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
void ReadSensors(bool firstTime)
{
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
int8_t temp_current;
uint8_t humidity_current;
int16_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
int8_t temp_last;
int32_t weight1_last;
int32_t weight2_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (int8_t)((m.Temperature + 40) * 2);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (int16_t)(m.Pressure - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
// calculate last value
if (my_position > 0) {
temp_last =lora_data.temperature[my_position -1];
weight1_last = lora_data.weight1[my_position - 1];
weight2_last = lora_data.weight2[my_position - 1];
}
// Wir registrieren die Werte nur, falls die Abweichung zur letzen Messung gross genug ist, oder es die erste Messung ist
if (my_position == 0 || abs(temp_current - temp_last) > 3 || abs(weight1_current - weight1_last) > 500 || abs(weight2_current - weight2_last) > 500) {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight1[my_position] = weight1_current;
lora_data.weight2[my_position] = weight2_current;
lora_data.temperature[my_position] = temp_current;
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
if (my_position > 0) {
lora_data.reading_offset[my_position - 1] = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
} else {
timer_pos0 = millis();
}
ShowLORAData();
my_position++;
}
else {
gCatena.SafePrintf("Too little difference, measurements are not stored...\n");
}
// Should we send the Data?
if (firstTime || ShouldDataBeSent()) {
lora_data.reading_offset[my_position] = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink();
} else {
doLightSleep(&sensorJob);
}
}
void startSendingUplink(void)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,923 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
//CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE = 10, // every 10 seconds
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
CATCFG_T_CYCLE_INITIAL = 30, // every 30 seconds initially
CATCFG_INTERVAL_COUNT_INITIAL = 30, // repeat for 15 minutes
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
CATCFG_T_MIN = CATCFG_T_OVERHEAD,
CATCFG_T_MAX = CATCFG_T_CYCLE < 60 * 60 ? 60 * 60 : CATCFG_T_CYCLE, // normally one hour max.
CATCFG_INTERVAL_COUNT = 30,
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// the cycle time to use
unsigned gTxCycle;
// remaining before we reset to default
unsigned gTxCycleCount;
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
// Additional Commands
// forward reference to the command function
cCommandStream::CommandFn cmdHello;
cCommandStream::CommandFn cmdGetCalibrationSettings;
cCommandStream::CommandFn cmdGetSensorReadings;
cCommandStream::CommandFn cmdGetScale1;
cCommandStream::CommandFn cmdGetScale2;
cCommandStream::CommandFn cmdCalibrateZeroScale1;
cCommandStream::CommandFn cmdCalibrateZeroScale2;
cCommandStream::CommandFn cmdCalibrateScale1;
cCommandStream::CommandFn cmdCalibrateScale2;
// the individual commmands are put in this table
static const cCommandStream::cEntry sMyExtraCommmands[] =
{
{ "hello", cmdHello },
{ "get_calibration_settings", cmdGetCalibrationSettings },
{ "get_sensor_readings", cmdGetSensorReadings },
{ "calibrate_zero_scale1", cmdCalibrateZeroScale1 },
{ "calibrate_zero_scale2", cmdCalibrateZeroScale2 },
{ "calibrate_scale1", cmdCalibrateScale1 },
{ "calibrate_scale2", cmdCalibrateScale2 },
// other commands go here....
};
/* a top-level structure wraps the above and connects to the system table */
/* it optionally includes a "first word" so you can for sure avoid name clashes */
static cCommandStream::cDispatch
sMyExtraCommands_top(
sMyExtraCommmands, /* this is the pointer to the table */
sizeof(sMyExtraCommmands), /* this is the size of the table */
"application" /* this is the "first word" for all the commands in this table*/
);
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 8;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
// must be 65 bytes long...
typedef struct {
long cal_w1_0; // 4 Bytes, Wert Waegezelle 1 ohne Gewicht
long cal_w2_0; // 4 Bytes, Wert Waegezelle 2 ohne Gewicht
float cal_w1_factor; // 4 Bytes,
float cal_w2_factor;
byte fill[49];
} __attribute__((packed)) CONFIG_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur (Startwert) in 1/10 Grad Celsius
int8_t temperature_change[MAX_VALUES_TO_SEND - 1]; // Unterschied Temperatur seit letztem Messwert in 1/10 Grad Celsius
uint8_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
uint16_t weight[MAX_VALUES_TO_SEND]; // Waegezelle Gesamtgewicht, in 5g
uint8_t offset_last_reading; // Zeitunterschied letzte zu erste Messung (in Minuten)
} __attribute__((packed)) LORA_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur in 1/10 Grad Celsius
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} __attribute__((packed)) LORA_data_first;
typedef struct {
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur in 1/10 Grad Celsius
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} SENSOR_data;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
LORA_data_first lora_data_first;
CONFIG_data config_data;
SENSOR_data last_sensor_reading;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
/* for 4451, we need wider tolerances, it seems */
#if defined(ARDUINO_ARCH_STM32)
LMIC_setClockError(10 * 65536 / 100);
#endif
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
// prepare external Power
pinMode(D10, OUTPUT);
digitalWrite(D10, HIGH);
/* add our application-specific commands */
gCatena.addCommands(
sMyExtraCommands_top,
nullptr
);
// read config_data from fram...
//gCatena.SafePrintf("Reading Calibration Config from FRAM...\n");
gCatena.getFram()->getField(cFramStorage::kBme680Cal, (uint8_t *)&config_data, sizeof(config_data));
//gCatena.SafePrintf("cal_w1_0: %d\n",config_data.cal_w1_0);
//gCatena.SafePrintf("cal_w2_0: %d\n",config_data.cal_w2_0);
//gCatena.SafePrintf("cal_w1_factor: %d.%03d\n",(int)config_data.cal_w1_factor,(int)(config_data.cal_w1_factor*1000)%1000);
//gCatena.SafePrintf("cal_w2_factor: %d.%03d\n",(int)config_data.cal_w2_factor,(int)(config_data.cal_w2_factor*1000)%1000);
//gCatena.SafePrintf("Size of config_data: %d\n",sizeof(config_data));
// im Moment statisch...
//config_data.cal_w1_0 = 20000;
//config_data.cal_w2_0 = 20000;
//config_data.cal_w1_factor = 2.5;
//config_data.cal_w2_factor = 2.5;
// config_data speichern...
//gCatena.SafePrintf("Writing Calibration Config to FRAM...\n");
//gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
//gCatena.SafePrintf("\n");
//gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
//gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
//gCatena.SafePrintf("Target network: %s / %s\n",
// gLoRaWAN.GetNetworkName(),
// gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
//gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
//gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
//gCatena.SafePrintf("USB enabled\n");
#else
//gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
//gCatena.SafePrintf(
// "CPU Unique ID: %s\n",
// gCatena.GetUniqueIDstring(&CpuIDstring));
//gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
//gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::On);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
//gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
// we only read vBus once, as there was a read error after deep sleep...
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
//gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A1, A0);
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(D12, A2);
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true,false);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
lora_data.temperature = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight[i] = 0;
if (i < (MAX_VALUES_TO_SEND -1)) {
lora_data.temperature_change[i] = 0;
}
}
lora_data_first.version = LORA_DATA_VERSION_FIRST_PACKAGE;
lora_data_first.vbat = 0;
lora_data_first.humidity = 0;
lora_data_first.pressure = 0;
lora_data_first.weight1 = 0;
lora_data_first.weight2 = 0;
lora_data_first.weight = 0;
lora_data_first.temperature = 0;
my_position = 0;
}
void ShowLORAData(bool firstTime)
{
if (firstTime) {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data_first.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data_first.vbat);
gCatena.SafePrintf(" \"humidity\": \"%u\",\n",lora_data_first.humidity);
gCatena.SafePrintf(" \"pressure\": \"%u\",\n",lora_data_first.pressure);
gCatena.SafePrintf(" \"weight1\": \"%ld\",\n",lora_data_first.weight1);
gCatena.SafePrintf(" \"weight2\": \"%ld\",\n",lora_data_first.weight2);
gCatena.SafePrintf(" \"weight\": \"%u\",\n",lora_data_first.weight);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data_first.temperature);
gCatena.SafePrintf("}\n");
} else {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data.temperature);
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature_change\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND - 1; i++) {
gCatena.SafePrintf("%d",lora_data.temperature_change[i]);
if (i < (MAX_VALUES_TO_SEND - 2)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
}
void ReadSensors(bool firstTime, bool readOnly)
{
gCatena.SafePrintf("start ReadSensors\n");
int16_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
int16_t temp_last;
int16_t temp_change;
int32_t weight_current32;
uint16_t weight_current;
uint16_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (int16_t)((m.Temperature) * 10);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
//float vBus = gCatena.ReadVbus();
//gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
//fUsbPower = (vBus > 3.0) ? true : false;
// Read Scales
gCatena.SafePrintf("Before Read Scales\n");
// Power-Up HX711
LoadCell_1.power_up();
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
// Power-Down HX711
LoadCell_1.power_down();
// Power-Up HX711
LoadCell_2.power_up();
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
// Power-Down HX711
LoadCell_2.power_down();
gCatena.SafePrintf("After Read Scales\n");
// Gewicht berechnen
weight_current32 = ((weight1_current - config_data.cal_w1_0) / config_data.cal_w1_factor) + ((weight2_current - config_data.cal_w2_0) / config_data.cal_w2_factor);
if (weight_current32 < 0) {
weight_current32 = 0;
} else if (weight_current32 > UINT16_MAX) {
weight_current32 = UINT16_MAX;
}
weight_current = (uint16_t)weight_current32;
if (not(readOnly)) {
// calculate last value
weight_last = 0;
temp_last = lora_data.temperature;
for (int i = 0; i < my_position; i++) {
temp_last = temp_last + lora_data.temperature_change[i];
}
if (my_position > 0) {
weight_last = lora_data.weight[my_position - 1];
}
if (firstTime) {
lora_data_first.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data_first.weight1 = weight1_current;
lora_data_first.weight2 = weight2_current;
lora_data_first.weight = weight_current;
lora_data_first.temperature = temp_current;
lora_data_first.humidity = humidity_current;
lora_data_first.pressure = pressure_current;
} else {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight[my_position] = weight_current;
if (my_position == 0) {
lora_data.temperature = temp_current;
} else {
temp_change = temp_current - temp_last;
if (temp_change > 127) {
temp_change = 127;
}
if (temp_change < -128) {
temp_change = -128;
}
lora_data.temperature_change[my_position - 1] = (uint8_t)temp_change;
}
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
}
if (my_position == 0) {
timer_pos0 = millis();
}
ShowLORAData(firstTime);
my_position++;
// Should we send the Data?
// we send data the first time the system is started, when the array is full
// or when the weight has fallen more than 100g or the first measurement is
// more than one hour old (which should not happen :-) )
if (firstTime || (my_position >= MAX_VALUES_TO_SEND) || ((weight_last - weight_current) > 20) || ((millis() - timer_pos0) > 3600000)) {
lora_data.offset_last_reading = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink(firstTime);
} else {
Serial.flush();
LoadCell_1.power_down();
LoadCell_2.power_down();
gCatena.Sleep(CATCFG_T_INTERVAL);
}
}
//gCatena.SafePrintf("set last_sensor_reading fields...\n");
last_sensor_reading.vbat = (uint8_t)(vBat * 1000.0f / 20);
last_sensor_reading.weight1 = weight1_current;
last_sensor_reading.weight2 = weight2_current;
last_sensor_reading.weight = weight_current;
last_sensor_reading.temperature = temp_current;
last_sensor_reading.humidity = humidity_current;
last_sensor_reading.pressure = pressure_current;
gCatena.SafePrintf("completed ReadSensors\n");
}
void startSendingUplink(bool firstTime)
{
//gCatena.SafePrintf("start startSendingUplink\n");
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (firstTime) {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed);
} else {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
ClearLoraData();
//gCatena.SafePrintf("completed startSendingUplink\n");
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
//gCatena.SafePrintf("start sendBufferDoneCb\n");
osjobcb_t pFn;
pFn = settleDoneCb;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
//gCatena.SafePrintf("completed sendBufferDoneCb\n");
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
//gCatena.SafePrintf("start txFailedDoneCb\n");
//gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
//gCatena.SafePrintf("completed txFailedDoneCb\n");
}
static void settleDoneCb(
osjob_t* pSendJob)
{
//gCatena.SafePrintf("start settleDoneCb\n");
if (fUsbPower) {
//gCatena.SafePrintf("we are running on USB power, so we do not go to deep sleep...\n");
//gCatena.SafePrintf("calling os_setTimedCallback in settleDoneCb...Interval=%d\n",CATCFG_T_INTERVAL);
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
&sensorJob,
os_getTime()+sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb
);
gCatena.SafePrintf("returning from settleDoneCb\n");
return;
}
/* ok..., now it's time for a deep sleep */
Serial.flush();
LoadCell_1.power_down();
LoadCell_2.power_down();
gCatena.Sleep(CATCFG_T_INTERVAL);
sleepDoneCb(pSendJob);
gCatena.SafePrintf("completed settleDoneCb\n");
}
static void sleepDoneCb(osjob_t* pJob)
{
//gCatena.SafePrintf("start sleepDoneCb\n");
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
//gCatena.SafePrintf("completed sleepDoneCb\n");
}
static void warmupDoneCb(osjob_t* pJob)
{
//gCatena.SafePrintf("start warmupDoneCb\n");
gLed.Set(LedPattern::WarmingUp);
ReadSensors(false,false);
//gCatena.SafePrintf("completed warmupDoneCb\n");
}
/* process "application hello" -- args are ignored */
// argv[0] is "hello"
// argv[1..argc-1] are the (ignored) arguments
cCommandStream::CommandStatus cmdHello(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
pThis->printf("Hello, world!\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetCalibrationSettings(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
pThis->printf("{\n");
pThis->printf(" \"cal_w1_0\": \"%d\",\n",config_data.cal_w1_0);
pThis->printf(" \"cal_w2_0\": \"%d\",\n",config_data.cal_w2_0);
pThis->printf(" \"cal_w1_factor\": \"%d.%03d\n",(int)config_data.cal_w1_factor,(int)abs(config_data.cal_w1_factor*1000)%1000);
pThis->printf(" \"cal_w2_factor\": \"%d.%03d\n",(int)config_data.cal_w2_factor,(int)abs(config_data.cal_w2_factor*1000)%1000);
pThis->printf("}\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetSensorReadings(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
ReadSensors(false,true);
pThis->printf("{\n");
pThis->printf(" \"weight\": \"%d\",\n",last_sensor_reading.weight);
pThis->printf(" \"weight1_raw\": \"%d\",\n",last_sensor_reading.weight1);
pThis->printf(" \"weight2_raw\": \"%d\",\n",last_sensor_reading.weight2);
pThis->printf(" \"temperature\": \"%d\",\n",last_sensor_reading.temperature);
pThis->printf(" \"humidity\": \"%d\",\n",last_sensor_reading.humidity);
pThis->printf(" \"pressure\": \"%d\",\n",last_sensor_reading.pressure);
pThis->printf(" \"batt\": \"%d\",\n", last_sensor_reading.vbat);
pThis->printf("}\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetScale1(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
pThis->printf("getscale1\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdGetScale2(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
pThis->printf("getscale2\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateZeroScale1(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
ReadSensors(false,true);
config_data.cal_w1_0 = last_sensor_reading.weight1;
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_zero_scale1 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateZeroScale2(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
ReadSensors(false,true);
config_data.cal_w2_0 = last_sensor_reading.weight2;
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_zero_scale2 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateScale1(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
ReadSensors(false,true);
String w1_gramm(argv[1]);
config_data.cal_w1_factor = (((float)last_sensor_reading.weight1 - config_data.cal_w1_0)/ w1_gramm.toFloat());
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_scale1 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
cCommandStream::CommandStatus cmdCalibrateScale2(cCommandStream *pThis,void *pContext,int argc,char **argv)
{
ReadSensors(false,true);
String w2_gramm(argv[1]);
config_data.cal_w2_factor = (((float)last_sensor_reading.weight2 - config_data.cal_w2_0)/ w2_gramm.toFloat());
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
pThis->printf("{ \"msg\": \"calibrate_scale2 was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess;
}
@@ -0,0 +1,727 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 6;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
typedef struct {
long cal_w1_0;
long cal_w2_0;
float cal_w1_factor;
float cal_w2_factor;
} CONFIG_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
uint8_t temperature[MAX_VALUES_TO_SEND]; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
uint8_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
uint16_t weight[MAX_VALUES_TO_SEND]; // Waegezelle Gesamtgewicht, in 5g
uint8_t reading_offset[MAX_VALUES_TO_SEND]; // Zeit der weiteren Messungen in Minuten seit Start, letzter Wert: Offset beim Senden des Pakets
} __attribute__((packed)) LORA_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Prozent
uint8_t temperature; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} __attribute__((packed)) LORA_data_first;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
LORA_data_first lora_data_first;
CONFIG_data config_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
// im Moment statisch...
config_data.cal_w1_0 = 20000;
config_data.cal_w2_0 = 20000;
config_data.cal_w1_factor = 2.5;
config_data.cal_w2_factor = 2.5;
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A3, A2);
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(A1, A0);
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
bool ShouldDataBeSent(void)
{
bool res = (my_position >= MAX_VALUES_TO_SEND) ||
((millis() - timer_pos0) > 3600000);
return res;
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.reading_offset[i] = 0;
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight[i] = 0;
lora_data.temperature[i] = 0;
}
lora_data_first.version = LORA_DATA_VERSION_FIRST_PACKAGE;
lora_data_first.vbat = 0;
lora_data_first.humidity = 0;
lora_data_first.pressure = 0;
lora_data_first.weight1 = 0;
lora_data_first.weight2 = 0;
lora_data_first.weight = 0;
lora_data_first.temperature = 0;
my_position = 0;
}
void ShowLORAData(bool firstTime)
{
if (firstTime) {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data_first.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data_first.vbat);
gCatena.SafePrintf(" \"humidity\": \"%u\",\n",lora_data_first.humidity);
gCatena.SafePrintf(" \"pressure\": \"%u\",\n",lora_data_first.pressure);
gCatena.SafePrintf(" \"weight1\": \"%ld\",\n",lora_data_first.weight1);
gCatena.SafePrintf(" \"weight2\": \"%ld\",\n",lora_data_first.weight2);
gCatena.SafePrintf(" \"weight\": \"%u\",\n",lora_data_first.weight);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data_first.temperature);
gCatena.SafePrintf("}\n");
} else {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"reading_offset\": [");
for (int i = 0; i < (MAX_VALUES_TO_SEND); i++) {
gCatena.SafePrintf("%d",lora_data.reading_offset[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.temperature[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
}
void ReadSensors(bool firstTime)
{
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
uint8_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
uint8_t temp_last;
uint16_t weight_current;
uint16_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (uint8_t)((m.Temperature + 40) * 2);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
// Gewicht berechnen
weight_current = ((weight1_current - config_data.cal_w1_0) / config_data.cal_w1_factor) + ((weight2_current - config_data.cal_w2_0) / config_data.cal_w2_factor);
// calculate last value
if (my_position > 0) {
temp_last =lora_data.temperature[my_position -1];
weight_last = lora_data.weight[my_position - 1];
}
// Wir registrieren die Werte nur, falls die Abweichung zur letzen Messung gross genug ist, oder es die erste Messung ist
if (my_position == 0 || abs(temp_current - temp_last) > 3 || abs(weight_current - weight_last) > 10) {
if (firstTime) {
lora_data_first.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data_first.weight1 = weight1_current;
lora_data_first.weight2 = weight2_current;
lora_data_first.weight = weight_current;
lora_data_first.temperature = temp_current;
lora_data_first.humidity = humidity_current;
lora_data_first.pressure = pressure_current;
} else {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight[my_position] = weight_current;
lora_data.temperature[my_position] = temp_current;
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
}
if (my_position > 0) {
lora_data.reading_offset[my_position - 1] = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
} else {
timer_pos0 = millis();
}
ShowLORAData(firstTime);
my_position++;
}
else {
gCatena.SafePrintf("Too little difference, measurements are not stored...\n");
}
// Should we send the Data?
if (firstTime || ShouldDataBeSent()) {
lora_data.reading_offset[my_position] = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink(firstTime);
} else {
doLightSleep(&sensorJob);
}
}
void startSendingUplink(bool firstTime)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (firstTime) {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed);
} else {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}
@@ -0,0 +1,727 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 6;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
typedef struct {
long cal_w1_0;
long cal_w2_0;
float cal_w1_factor;
float cal_w2_factor;
} CONFIG_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
uint8_t temperature[MAX_VALUES_TO_SEND]; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
uint8_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
uint16_t weight[MAX_VALUES_TO_SEND]; // Waegezelle Gesamtgewicht, in 5g
uint8_t reading_offset[MAX_VALUES_TO_SEND]; // Zeit der weiteren Messungen in Minuten seit Start, letzter Wert: Offset beim Senden des Pakets
} __attribute__((packed)) LORA_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Prozent
uint8_t temperature; // Temperatur in 1/2 Grad Celsius (0 => -40 C, 255 => 87.5 C)
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} __attribute__((packed)) LORA_data_first;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
LORA_data_first lora_data_first;
CONFIG_data config_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
// im Moment statisch...
config_data.cal_w1_0 = 20000;
config_data.cal_w2_0 = 20000;
config_data.cal_w1_factor = 2.5;
config_data.cal_w2_factor = 2.5;
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
LoadCell_1.begin(A3, A2);
gCatena.SafePrintf("Setup Scale 2...\n");
LoadCell_2.begin(A1, A0);
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
bool ShouldDataBeSent(void)
{
bool res = (my_position >= MAX_VALUES_TO_SEND) ||
((millis() - timer_pos0) > 3600000);
return res;
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.reading_offset[i] = 0;
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight[i] = 0;
lora_data.temperature[i] = 0;
}
lora_data_first.version = LORA_DATA_VERSION_FIRST_PACKAGE;
lora_data_first.vbat = 0;
lora_data_first.humidity = 0;
lora_data_first.pressure = 0;
lora_data_first.weight1 = 0;
lora_data_first.weight2 = 0;
lora_data_first.weight = 0;
lora_data_first.temperature = 0;
my_position = 0;
}
void ShowLORAData(bool firstTime)
{
if (firstTime) {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data_first.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data_first.vbat);
gCatena.SafePrintf(" \"humidity\": \"%u\",\n",lora_data_first.humidity);
gCatena.SafePrintf(" \"pressure\": \"%u\",\n",lora_data_first.pressure);
gCatena.SafePrintf(" \"weight1\": \"%ld\",\n",lora_data_first.weight1);
gCatena.SafePrintf(" \"weight2\": \"%ld\",\n",lora_data_first.weight2);
gCatena.SafePrintf(" \"weight\": \"%u\",\n",lora_data_first.weight);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data_first.temperature);
gCatena.SafePrintf("}\n");
} else {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"reading_offset\": [");
for (int i = 0; i < (MAX_VALUES_TO_SEND); i++) {
gCatena.SafePrintf("%d",lora_data.reading_offset[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.temperature[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
}
void ReadSensors(bool firstTime)
{
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
uint8_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
uint8_t temp_last;
uint16_t weight_current;
uint16_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (uint8_t)((m.Temperature + 40) * 2);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
// Gewicht berechnen
weight_current = ((weight1_current - config_data.cal_w1_0) / config_data.cal_w1_factor) + ((weight2_current - config_data.cal_w2_0) / config_data.cal_w2_factor);
// calculate last value
if (my_position > 0) {
temp_last =lora_data.temperature[my_position -1];
weight_last = lora_data.weight[my_position - 1];
}
// Wir registrieren die Werte nur, falls die Abweichung zur letzen Messung gross genug ist, oder es die erste Messung ist
if (my_position == 0 || abs(temp_current - temp_last) > 3 || abs(weight_current - weight_last) > 10) {
if (firstTime) {
lora_data_first.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data_first.weight1 = weight1_current;
lora_data_first.weight2 = weight2_current;
lora_data_first.weight = weight_current;
lora_data_first.temperature = temp_current;
lora_data_first.humidity = humidity_current;
lora_data_first.pressure = pressure_current;
} else {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight[my_position] = weight_current;
lora_data.temperature[my_position] = temp_current;
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
}
if (my_position > 0) {
lora_data.reading_offset[my_position - 1] = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
} else {
timer_pos0 = millis();
}
ShowLORAData(firstTime);
my_position++;
}
else {
gCatena.SafePrintf("Too little difference, measurements are not stored...\n");
}
// Should we send the Data?
if (firstTime || ShouldDataBeSent()) {
lora_data.reading_offset[MAX_VALUES_TO_SEND - 1] = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink(firstTime);
} else {
doLightSleep(&sensorJob);
}
}
void startSendingUplink(bool firstTime)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (firstTime) {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed);
} else {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}
@@ -0,0 +1,768 @@
/*
beescale_lora_mcci.ino
BeieliScale, see https://mini-beieli.ch
Joerg Lehmann, nbit Informatik GmbH
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <cmath>
#include <type_traits>
#include <HX711.h>
using namespace McciCatena;
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
/* how long do we wait between transmissions? (in seconds) */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
//CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE),
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD)
? CATCFG_T_OVERHEAD
: tCycle - CATCFG_T_OVERHEAD;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
enum {
PIN_ONE_WIRE = A2, // XSDA1 == A2
PIN_SHT10_CLK = 8, // XSCL0 == D8
PIN_SHT10_DATA = 12, // XSDA0 == D12
};
// forwards
static void settleDoneCb(osjob_t* pSendJob);
static void warmupDoneCb(osjob_t* pSendJob);
static void txFailedDoneCb(osjob_t* pSendJob);
static void sleepDoneCb(osjob_t* pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.1";
static const byte MAX_VALUES_TO_SEND = 8;
static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825;
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
// must be 65 bytes long...
typedef struct {
long cal_w1_0; // 4 Bytes, Wert Waegezelle 1 ohne Gewicht
long cal_w2_0; // 4 Bytes, Wert Waegezelle 1 ohne Gewicht
float cal_w1_factor; // 4 Bytes,
float cal_w2_factor;
byte fill[49];
} __attribute__((packed)) CONFIG_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity[MAX_VALUES_TO_SEND]; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur (Startwert) in 1/10 Grad Celsius
int8_t temperature_change[MAX_VALUES_TO_SEND - 1]; // Unterschied Temperatur seit letztem Messwert in 1/10 Grad Celsius
uint8_t pressure[MAX_VALUES_TO_SEND]; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
uint16_t weight[MAX_VALUES_TO_SEND]; // Waegezelle Gesamtgewicht, in 5g
uint8_t offset_last_reading; // Zeitunterschied letzte zu erste Messung (in Minuten)
} __attribute__((packed)) LORA_data;
typedef struct {
uint8_t version; // Version
uint8_t vbat; // Batteriespannung (1 Einheit => 20 mV)
uint8_t humidity; // Luftfeuchtigkeit in Prozent
int16_t temperature; // Temperatur in 1/10 Grad Celsius
uint8_t pressure; // Luftdruck in Hekto-Pascal (0 entspricht 825 hPa)
int32_t weight1; // Waegezelle 1, Raw Value
int32_t weight2; // Waegezelle 2, Raw Value
uint16_t weight; // Waegezelle Gesamtgewicht, in 5g
} __attribute__((packed)) LORA_data_first;
byte my_position = 0; // what is our actual measurement, starts with 0
long timer_pos0;
// Global Variables
LORA_data lora_data;
LORA_data_first lora_data_first;
CONFIG_data config_data;
// generic timer
long t_cur;
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed(Catena::PIN_STATUS_LED);
// The temperature/humidity sensor
Adafruit_BME280 gBME280; // The default initalizer creates an I2C connection
bool fBme;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// Scales
HX711 LoadCell_1;
HX711 LoadCell_2;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t* pJob);
void setup(void)
{
gCatena.begin();
ClearLoraData();
setup_platform();
setup_bme280();
setup_scales();
setup_flash();
setup_uplink();
}
void setup_platform(void)
{
// read config_data from fram...
gCatena.SafePrintf("Reading Calibration Config from FRAM...\n");
gCatena.getFram()->getField(cFramStorage::kBme680Cal, (uint8_t *)&config_data, sizeof(config_data));
gCatena.SafePrintf("cal_w1_0: %d\n",config_data.cal_w1_0);
gCatena.SafePrintf("cal_w2_0: %d\n",config_data.cal_w2_0);
gCatena.SafePrintf("cal_w1_factor: %d.%03d\n",(int)config_data.cal_w1_factor,(int)(config_data.cal_w1_factor*1000)%1000);
gCatena.SafePrintf("cal_w2_factor: %d.%03d\n",(int)config_data.cal_w2_factor,(int)(config_data.cal_w2_factor*1000)%1000);
gCatena.SafePrintf("Size of config_data: %d\n",sizeof(config_data));
// im Moment statisch...
//config_data.cal_w1_0 = 20000;
//config_data.cal_w2_0 = 20000;
//config_data.cal_w1_factor = 2.5;
//config_data.cal_w2_factor = 2.5;
// config_data speichern...
gCatena.SafePrintf("Writing Calibration Config to FRAM...\n");
gCatena.getFram()->saveField(cFramStorage::kBme680Cal, (const uint8_t *)&config_data, sizeof(config_data));
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended))) {
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("BeieliScale Version %s.\n", sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion)));
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
#ifdef CATENA_CFG_SYSCLK
gCatena.SafePrintf("SYSCLK: %d MHz\n", CATENA_CFG_SYSCLK);
#endif
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring));
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena)) {
gCatena.SafePrintf("failed\n");
}
else {
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t* pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM* const pPlatform = gCatena.GetPlatform();
if (pPlatform) {
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i) {
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags());
}
else {
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_bme280(void)
{
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
fBme = true;
}
else {
fBme = false;
gCatena.SafePrintf("No BME280 found: check wiring\n");
}
}
void setup_scales(void)
{
gCatena.SafePrintf("Setup Scales...\n");
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// By omitting the gain factor parameter, the library
// default "128" (Channel A) is used here.
gCatena.SafePrintf("Setup Scale 1...\n");
//LoadCell_1.begin(A3, A2);
if (!(LoadCell_1.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 1 not ready.\n");
}
gCatena.SafePrintf("Setup Scale 2...\n");
//LoadCell_2.begin(A1, A0);
if (!(LoadCell_2.wait_ready_timeout(1000))) {
gCatena.SafePrintf("Scale 2 not ready.\n");
}
gCatena.SafePrintf("Setup Scales is complete\n");
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else {
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_uplink(void)
{
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else {
gLed.Set(LedPattern::Joining);
/* warm up the BME280 by discarding a measurement */
if (fBme)
(void)gBME280.readTemperature();
/* trigger a join by sending the first packet */
ReadSensors(true);
}
}
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void loop()
{
gCatena.poll();
}
void ClearLoraData(void)
{
lora_data.version = LORA_DATA_VERSION;
lora_data.vbat = 0;
lora_data.temperature = 0;
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
lora_data.humidity[i] = 0;
lora_data.pressure[i] = 0;
lora_data.weight[i] = 0;
if (i < (MAX_VALUES_TO_SEND -1)) {
lora_data.temperature_change[i] = 0;
}
}
lora_data_first.version = LORA_DATA_VERSION_FIRST_PACKAGE;
lora_data_first.vbat = 0;
lora_data_first.humidity = 0;
lora_data_first.pressure = 0;
lora_data_first.weight1 = 0;
lora_data_first.weight2 = 0;
lora_data_first.weight = 0;
lora_data_first.temperature = 0;
my_position = 0;
}
void ShowLORAData(bool firstTime)
{
if (firstTime) {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data_first.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data_first.vbat);
gCatena.SafePrintf(" \"humidity\": \"%u\",\n",lora_data_first.humidity);
gCatena.SafePrintf(" \"pressure\": \"%u\",\n",lora_data_first.pressure);
gCatena.SafePrintf(" \"weight1\": \"%ld\",\n",lora_data_first.weight1);
gCatena.SafePrintf(" \"weight2\": \"%ld\",\n",lora_data_first.weight2);
gCatena.SafePrintf(" \"weight\": \"%u\",\n",lora_data_first.weight);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data_first.temperature);
gCatena.SafePrintf("}\n");
} else {
gCatena.SafePrintf("{\n");
gCatena.SafePrintf(" \"version\": \"%u\",\n",lora_data.version);
gCatena.SafePrintf(" \"vbat\": \"%u\",\n",lora_data.vbat);
gCatena.SafePrintf(" \"temperature\": \"%u\",\n",lora_data.temperature);
gCatena.SafePrintf(" \"humidity\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.humidity[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"pressure\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%d",lora_data.pressure[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"weight\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND; i++) {
gCatena.SafePrintf("%ld",lora_data.weight[i]);
if (i < (MAX_VALUES_TO_SEND - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("],\n");
gCatena.SafePrintf(" \"temperature_change\": [");
for (int i = 0; i < MAX_VALUES_TO_SEND - 1; i++) {
gCatena.SafePrintf("%d",lora_data.temperature_change[i]);
if (i < (MAX_VALUES_TO_SEND - 2)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("}\n");
}
}
void ReadSensors(bool firstTime)
{
// Power-Up HX711
LoadCell_1.power_up();
LoadCell_1.power_up();
// vBat
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int)(vBat * 1000.0f));
// vBus
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
int16_t temp_current;
uint8_t humidity_current;
uint8_t pressure_current;
int32_t weight1_current;
int32_t weight2_current;
int16_t temp_last;
int16_t temp_change;
uint16_t weight_current;
uint16_t weight_last;
if (fBme) {
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int)m.Temperature,
(int)m.Pressure,
(int)m.Humidity);
temp_current = (int16_t)((m.Temperature) * 10);
humidity_current = (uint8_t)m.Humidity;
pressure_current = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
gCatena.SafePrintf("pressure_current: %d\n",pressure_current);
}
gCatena.SafePrintf("Before Read Scales\n");
if (LoadCell_1.is_ready()) {
Serial.println("HX711 LoadCell_1 is ready.");
long w1 = LoadCell_1.read_average(5);
weight1_current = (int32_t)w1;
gCatena.SafePrintf("Load_cell 1 output val: %ld\n", w1);
}
else {
Serial.println("HX711 LoadCell_1 not ready.");
}
if (LoadCell_2.is_ready()) {
Serial.println("HX711 LoadCell_2 is ready.");
long w2 = LoadCell_2.read_average(5);
weight2_current = (int32_t)w2;
gCatena.SafePrintf("Load_cell 2 output val: %ld\n", w2);
}
else {
Serial.println("HX711 LoadCell_2 not ready.");
}
gCatena.SafePrintf("After Read Scales\n");
// Power-Down HX711
LoadCell_1.power_down();
LoadCell_1.power_down();
// Gewicht berechnen
weight_current = ((weight1_current - config_data.cal_w1_0) / config_data.cal_w1_factor) + ((weight2_current - config_data.cal_w2_0) / config_data.cal_w2_factor);
// calculate last value
weight_last = 0;
temp_last = lora_data.temperature;
for (int i = 0; i < my_position; i++) {
temp_last = temp_last + lora_data.temperature_change[i];
}
if (my_position > 0) {
weight_last = lora_data.weight[my_position - 1];
}
if (firstTime) {
lora_data_first.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data_first.weight1 = weight1_current;
lora_data_first.weight2 = weight2_current;
lora_data_first.weight = weight_current;
lora_data_first.temperature = temp_current;
lora_data_first.humidity = humidity_current;
lora_data_first.pressure = pressure_current;
} else {
lora_data.vbat = (uint8_t)(vBat * 1000.0f / 20);
lora_data.weight[my_position] = weight_current;
if (my_position == 0) {
lora_data.temperature = temp_current;
} else {
temp_change = temp_current - temp_last;
if (temp_change > 127) {
temp_change = 127;
}
if (temp_change < -128) {
temp_change = -128;
}
lora_data.temperature_change[my_position - 1] = (uint8_t)temp_change;
}
lora_data.humidity[my_position] = humidity_current;
lora_data.pressure[my_position] = pressure_current;
}
if (my_position == 0) {
timer_pos0 = millis();
}
ShowLORAData(firstTime);
my_position++;
// Should we send the Data?
// we send data the first time the system is started, when the array is full
// or when the weight has fallen more than 100g or the first measurement is
// more than one hour old (which should not happen :-) )
if (firstTime || (my_position >= MAX_VALUES_TO_SEND) || ((weight_last - weight_current) > 20) || ((millis() - timer_pos0) > 3600000)) {
lora_data.offset_last_reading = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
gCatena.SafePrintf("startSendingUplink()\n");
startSendingUplink(firstTime);
} else {
doLightSleep(&sensorJob);
}
}
void startSendingUplink(bool firstTime)
{
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
if (gCatena.GetOperatingFlags() & (1 << 16)) {
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (firstTime) {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed);
} else {
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed);
}
ClearLoraData();
}
static void sendBufferDoneCb(
void* pContext,
bool fStatus)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
if (!fStatus) {
gCatena.SafePrintf("send buffer failed\n");
pFn = txFailedDoneCb;
}
else {
pFn = settleDoneCb;
}
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_SETTLE),
pFn);
}
static void txFailedDoneCb(
osjob_t* pSendJob)
{
gCatena.SafePrintf("not provisioned, idling\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (!g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
bool fDeepSleep;
if (fDeepSleepTest) {
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr()) {
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() & (1 << 17)) {
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0) {
fDeepSleep = true;
}
else {
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep) {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & (1 << 19);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n) {
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000) {
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100) {
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void doDeepSleep(osjob_t* pJob)
{
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
gCatena.Sleep(CATCFG_T_INTERVAL);
/* and now... we're awake again. trigger another measurement */
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
sleepDoneCb(pJob);
}
void doLightSleep(osjob_t* pJob)
{
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_INTERVAL),
sleepDoneCb);
}
static void sleepDoneCb(osjob_t* pJob)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
ReadSensors(false);
}