Skip to content

Commit

Permalink
[SD] Refactor sd header and clean it up
Browse files Browse the repository at this point in the history
  • Loading branch information
brentru committed Nov 29, 2024
1 parent 52a8bd7 commit 4d9bed8
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 74 deletions.
19 changes: 9 additions & 10 deletions src/Wippersnapper_V2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1188,7 +1188,7 @@ void Wippersnapper_V2::connectV2() {
// If we are running in offline mode, we skip the network setup
// and MQTT connection process and jump to the offline device config process
// NOTE: After this, bail out of this function and run the app loop!!!
if (WsV2._sdCardV2->mode_offline == true) {
if (WsV2._sdCardV2->isModeOffline() == true) {
WS_DEBUG_PRINTLN("[Offline] Running device configuration...");
// Wait for incoming JSON string from Serial
#ifdef OFFLINE_MODE_DEBUG
Expand All @@ -1199,14 +1199,13 @@ void Wippersnapper_V2::connectV2() {
if (!WsV2._sdCardV2->parseConfigFile())
haltErrorV2("Failed to parse incoming JSON file");
WS_DEBUG_PRINT("[Offline] Attempting to configure hardware...");
// Mock the "check in" process
// Configure GPIO classes based on checkin response message
// TODO: Add checkin pins/data to the JSON string, we are hardcoding here
WsV2.digital_io_controller->SetMaxDigitalPins(10);
WsV2.analogio_controller->SetRefVoltage(3.3);
WsV2.analogio_controller->SetTotalAnalogPins(4);
// Call the signal decoder to parse the incoming JSON string
// TODO: We need a way to repeat this call better
#ifndef OFFLINE_MODE_DEBUG
// Create a new file to store the json log
if (!WsV2._sdCardV2->CreateNewLogFile()) {
haltErrorV2("Unable to create log file");
}
#endif
// Call the TL signal decoder to parse the incoming JSON data
callDecodeB2D();
WS_DEBUG_PRINTLN(
"[Offline] Hardware configured, skipping network setup...");
Expand Down Expand Up @@ -1269,7 +1268,7 @@ void Wippersnapper_V2::connectV2() {
/**************************************************************************/
ws_status_t Wippersnapper_V2::runV2() {
WsV2.feedWDTV2();
if (!WsV2._sdCardV2->mode_offline) {
if (!WsV2._sdCardV2->isModeOffline()) {
// Handle networking functions
runNetFSMV2();
pingBrokerV2();
Expand Down
6 changes: 3 additions & 3 deletions src/components/analogIO/controller.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ bool AnalogIOController::EncodePublishPinEvent(
}

// Publish the AnalogIO message to the broker
if (!WsV2._sdCardV2->mode_offline) {
if (!WsV2._sdCardV2->isModeOffline()) {
WS_DEBUG_PRINTLN("Publishing AnalogIOEvent message to broker...");
if (!WsV2.PublishSignal(
wippersnapper_signal_DeviceToBroker_analogio_event_tag,
Expand Down Expand Up @@ -225,7 +225,7 @@ bool AnalogIOController::EncodePublishPinEvent(
/***************************************************************************/
bool AnalogIOController::EncodePublishPinValue(uint8_t pin, uint16_t value) {

if (WsV2._sdCardV2->mode_offline) {
if (WsV2._sdCardV2->isModeOffline()) {
return WsV2._sdCardV2->LogGPIOSensorEventToSD(
pin, value, wippersnapper_sensor_SensorType_SENSOR_TYPE_RAW);
} else {
Expand All @@ -246,7 +246,7 @@ bool AnalogIOController::EncodePublishPinValue(uint8_t pin, uint16_t value) {
*/
/***************************************************************************/
bool AnalogIOController::EncodePublishPinVoltage(uint8_t pin, float value) {
if (WsV2._sdCardV2->mode_offline) {
if (WsV2._sdCardV2->isModeOffline()) {
return WsV2._sdCardV2->LogGPIOSensorEventToSD(
pin, value, wippersnapper_sensor_SensorType_SENSOR_TYPE_VOLTAGE);
} else {
Expand Down
4 changes: 2 additions & 2 deletions src/components/digitalIO/controller.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ bool DigitalIOController::IsPinTimerExpired(DigitalIOPin *pin, ulong cur_time) {
*/
/***********************************************************************/
void DigitalIOController::PrintPinValue(DigitalIOPin *pin) {
if (WsV2._sdCardV2->mode_offline)
if (WsV2._sdCardV2->isModeOffline())
return;
WS_DEBUG_PRINT("[digitalio] DIO Pin D");
WS_DEBUG_PRINT(pin->pin_name);
Expand Down Expand Up @@ -308,7 +308,7 @@ bool DigitalIOController::EncodePublishPinEvent(uint8_t pin_name,
sprintf(c_pin_name, "D%d", pin_name);

// If we are in ONLINE mode, publish the event to the broker
if (!WsV2._sdCardV2->mode_offline) {
if (!WsV2._sdCardV2->isModeOffline()) {
WS_DEBUG_PRINT(
"[digitalio] Publishing DigitalIOEvent message to broker for pin: ");
WS_DEBUG_PRINTLN(c_pin_name);
Expand Down
4 changes: 2 additions & 2 deletions src/components/ds18x20/controller.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ bool DS18X20Controller::Handle_Ds18x20Add(pb_istream_t *stream) {

// If we're not in offline mode, publish a Ds18x20Added message back to the
// broker
if (!WsV2._sdCardV2->mode_offline) {
if (!WsV2._sdCardV2->isModeOffline()) {
// Encode and publish a Ds18x20Added message back to the broker
if (!_DS18X20_model->EncodeDS18x20Added(
_DS18X20_model->GetDS18x20AddMsg()->onewire_pin, is_initialized)) {
Expand Down Expand Up @@ -227,7 +227,7 @@ void DS18X20Controller::update() {
_DS18X20_model->GetDS18x20EventMsg();
pb_size_t event_count = event_msg->sensor_events_count;

if (!WsV2._sdCardV2->mode_offline) {
if (!WsV2._sdCardV2->isModeOffline()) {
// Encode the Ds18x20Event message
if (!_DS18X20_model->EncodeDs18x20Event()) {
WS_DEBUG_PRINTLN(
Expand Down
53 changes: 28 additions & 25 deletions src/provisioning/sdcard/ws_sdcard.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@
*/
/**************************************************************************/
ws_sdcard::ws_sdcard() {
mode_offline = false;
_wokwi_runner = false;
is_mode_offline = false;
_is_using_wokwi = false;
_use_test_data = false;
_sz_log_file = 0;
}

/**************************************************************************/
Expand All @@ -33,20 +34,20 @@ ws_sdcard::ws_sdcard() {
ws_sdcard::~ws_sdcard() {
// TODO: Close any open files
// Then, end the SD card (ends SPI transaction)
if (mode_offline) {
if (is_mode_offline) {
_sd.end();
mode_offline = false;
is_mode_offline = false;
}
}

bool ws_sdcard::InitSDCard() {
#ifdef SD_CS_PIN
// Attempt to initialize the SD card
if (_sd.begin(SD_CS_PIN)) {
mode_offline = true;
is_mode_offline = true;
}
#endif
return mode_offline;
return is_mode_offline;
}

/**************************************************************************/
Expand Down Expand Up @@ -346,6 +347,25 @@ bool ws_sdcard::PushSignalToSharedBuffer(
return true;
}

/**************************************************************************/
/*!
@brief Creates a new logging file on the SD card using the RTC's
timestamp and sets the current log file path to reflect this
file.
@returns True if a log file was successfully created, False otherwise.
*/
/**************************************************************************/
bool ws_sdcard::CreateNewLogFile() {
File32 file;
String logFilename = "log_" + String(GetTimestamp()) + ".json";
_log_filename = logFilename.c_str();
if (!file.open(_log_filename, FILE_WRITE))
return false;
WS_DEBUG_PRINT("[SD] Created new log file on SD card: ");
WS_DEBUG_PRINTLN(_log_filename);
return true;
}

/**************************************************************************/
/*!
@brief Searches for and parses the JSON configuration file and sets up
Expand Down Expand Up @@ -395,7 +415,7 @@ bool ws_sdcard::parseConfigFile() {
// this!
const char *exportedBy = doc["exportedBy"];
if (strcmp(exportedBy, "wokwi") == 0) {
_wokwi_runner = true;
_is_using_wokwi = true;
}

// Parse the exportedFromDevice array
Expand Down Expand Up @@ -425,23 +445,6 @@ bool ws_sdcard::parseConfigFile() {
return false;
}

// Create new logging file on device from the RTC's timestamp
#ifndef OFFLINE_MODE_DEBUG
// TODO: Refactor this out into a func
// TODO: Implement a counter within the log funcs to track # of lines in the
// file and implement a MAX_LINE cutoff
String logFilename = "log_" + String(GetTimestamp()) + ".json";
_log_filename = logFilename.c_str();
File32 file;
if (!file.open(_log_filename, FILE_WRITE)) {
WS_DEBUG_PRINTLN(
"[SD] FATAL - Failed to create initial logging file on SD card!");
return false;
}
WS_DEBUG_PRINT("[SD] Created new log file on SD card: ");
WS_DEBUG_PRINTLN(_log_filename);
#endif

// Parse the "components" array into a JsonObject
JsonArray components_ar = doc["components"].as<JsonArray>();
if (components_ar.isNull()) {
Expand Down Expand Up @@ -548,7 +551,7 @@ uint32_t ws_sdcard::GetTimestamp() {
now = _rtc_soft->now();
}

if (_wokwi_runner)
if (_is_using_wokwi)
return 0;

return now.unixtime();
Expand Down
69 changes: 37 additions & 32 deletions src/provisioning/sdcard/ws_sdcard.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include "Wippersnapper_V2.h"

#define SD_FAT_TYPE 3
#define MAX_LOG_FILE_SZ 500 ///< Maximum log file size of 500 bytes

// forward decl.
class Wippersnapper_V2;
Expand All @@ -35,13 +36,32 @@ class ws_sdcard {
ws_sdcard();
~ws_sdcard();
bool InitSDCard();
bool parseConfigFile();
#ifdef OFFLINE_MODE_DEBUG
bool waitForSerialConfig();
#endif
bool CreateNewLogFile();
bool isModeOffline() { return is_mode_offline; }

bool LogGPIOSensorEventToSD(uint8_t pin, float value,
wippersnapper_sensor_SensorType read_type);
bool LogGPIOSensorEventToSD(uint8_t pin, bool value,
wippersnapper_sensor_SensorType read_type);
bool LogGPIOSensorEventToSD(uint8_t pin, uint16_t value,
wippersnapper_sensor_SensorType read_type);
bool LogDS18xSensorEventToSD(wippersnapper_ds18x20_Ds18x20Event *event_msg);

private:
bool ConfigureRTC(const char *rtc_type);
uint32_t GetTimestamp();
bool mode_offline; // TODO: Refactor to getter/setter
bool
PushSignalToSharedBuffer(wippersnapper_signal_BrokerToDevice &msg_signal);
bool InitDS1307();
bool InitDS3231();
bool InitPCF8523();
bool InitSoftRTC();
bool validateJson(const char *input);
void CheckIn(uint8_t max_digital_pins, uint8_t max_analog_pins,
float ref_voltage);

bool parseConfigFile();
wippersnapper_sensor_SensorType ParseSensorType(const char *sensor_type);
bool ParseDigitalIOAdd(wippersnapper_digitalio_DigitalIOAdd &msg_DigitalIOAdd,
const char *pin, float period, bool value,
Expand All @@ -60,36 +80,21 @@ class ws_sdcard {
wippersnapper_sensor_SensorType read_type);
void BuildJSONDoc(JsonDocument &doc, const char *pin, bool value,
wippersnapper_sensor_SensorType read_type);
bool LogGPIOSensorEventToSD(uint8_t pin, float value,
wippersnapper_sensor_SensorType read_type);
bool LogGPIOSensorEventToSD(uint8_t pin, bool value,
wippersnapper_sensor_SensorType read_type);
bool LogGPIOSensorEventToSD(uint8_t pin, uint16_t value,
wippersnapper_sensor_SensorType read_type);
bool LogDS18xSensorEventToSD(wippersnapper_ds18x20_Ds18x20Event *event_msg);

#ifdef OFFLINE_MODE_DEBUG
bool waitForSerialConfig();
bool validateJson(const char *input);
#endif
private:
bool InitDS1307();
bool InitDS3231();
bool InitPCF8523();
bool InitSoftRTC();
void CheckIn(uint8_t max_digital_pins, uint8_t max_analog_pins,
float ref_voltage);
SdFat _sd; ///< SD object from Adafruit SDFat library
String _serialInput; ///< Serial input buffer
const char *json_test_data; ///< Json test data
bool _use_test_data; ///< True if sample data is being used to test, instead
///< of serial input, False otherwise.
bool _wokwi_runner; ///< True if `exportedBy` key is "wokwi", otherwise False
const char *_log_filename; ///< Path to the log file
RTC_DS3231 *_rtc_ds3231 = nullptr; ///< DS3231 RTC object
RTC_DS1307 *_rtc_ds1307 = nullptr; ///< DS1307 RTC object
bool
PushSignalToSharedBuffer(wippersnapper_signal_BrokerToDevice &msg_signal);
SdFat _sd; ///< SD object from Adafruit SDFat library
bool is_mode_offline; ///< True if offline mode is enabled, False otherwise
String _serialInput; ///< Serial input buffer
const char *json_test_data; ///< Json test data
const char *_log_filename; ///< Path to the log file
int _sz_log_file; ///< Size of the current log file, in Bytes
RTC_DS3231 *_rtc_ds3231 = nullptr; ///< DS3231 RTC object
RTC_DS1307 *_rtc_ds1307 = nullptr; ///< DS1307 RTC object
RTC_PCF8523 *_rtc_pcf8523 = nullptr; ///< PCF8523 RTC object
RTC_Millis *_rtc_soft = nullptr; ///< Software RTC object
// Testing
bool _use_test_data; ///< True if sample data is being used for testing
bool _is_using_wokwi; ///< True if `exportedBy` key is "wokwi"
};
extern Wippersnapper_V2 WsV2;
#endif // WS_SDCARD_H

0 comments on commit 4d9bed8

Please sign in to comment.