Skip to content

Commit

Permalink
Merge pull request #572 from doudar/Consolidate_Tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
doudar authored Sep 3, 2024
2 parents 0044afd + ae0f80d commit 04fd746
Show file tree
Hide file tree
Showing 12 changed files with 126 additions and 222 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Removed driver temp checking. It's not accurate on the ESP32.
- Peloton resistance limit enhancements.
- Continue updating power metrics to other clients if one client disconnects.

- Freed 19k of ram by consolidating tasks and using timers instead of delays.

### Hardware
- added Yesoul S3.
Expand Down
4 changes: 1 addition & 3 deletions include/BLE_Common.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,9 @@

// Setup
void setupBLE();
extern TaskHandle_t BLECommunicationTask;
extern TaskHandle_t BLEClientTask;
// ***********************Common**********************************
void BLECommunications(void *pvParameters);

void BLECommunications();
// *****************************Server****************************
class MyServerCallbacks : public NimBLEServerCallbacks {
public:
Expand Down
7 changes: 3 additions & 4 deletions include/ERG_Mode.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@
#define ERG_MODE_DELAY 700
#define RETURN_ERROR INT32_MIN

extern TaskHandle_t ErgTask;
void setupERG();
void ergTaskLoop(void* pvParameters);

class PowerEntry {
public:
int watts;
Expand Down Expand Up @@ -95,6 +91,9 @@ class PowerTable {
public:
TableRow tableRow[POWERTABLE_CAD_SIZE];

// What used to be in the ERGTaskLoop(). This is the main control function for ERG Mode and the powertable operations.
void runERG();

// Pick up new power value and put them into the power table
void processPowerValue(PowerBuffer& powerBuffer, int cadence, Measurement power);

Expand Down
2 changes: 1 addition & 1 deletion include/HTTP_Server_Basic.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class HTTP_Server {
static void handleHrSlider();
static void FirmwareUpdate();

static void webClientUpdate(void *pvParameters);
static void webClientUpdate();

HTTP_Server() { internetConnection = false; }
};
Expand Down
2 changes: 1 addition & 1 deletion include/Main.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ class SS2K {
bool isUpdating = false;

bool IRAM_ATTR deBounce();
static void IRAM_ATTR moveStepper(void *pvParameters);
static void IRAM_ATTR maintenanceLoop(void *pvParameters);
static void IRAM_ATTR shiftUp();
static void IRAM_ATTR shiftDown();
static void moveStepper();
void resetIfShiftersHeld();
void startTasks();
void stopTasks();
Expand Down
28 changes: 12 additions & 16 deletions include/settings.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
#define AUTO_FIRMWARE_UPDATE true

// Default Bluetooth WiFi and MDNS Name
const char * const DEVICE_NAME = "SmartSpin2k";
const char* const DEVICE_NAME = "SmartSpin2k";

// Default WiFi Password
const char * const DEFAULT_PASSWORD = "password";
const char* const DEFAULT_PASSWORD = "password";

// default URL To get Updates From.
// If changed you'll also need to get a root certificate from the new server
Expand All @@ -38,7 +38,7 @@ const char * const DEFAULT_PASSWORD = "password";
// name of local file to save Physical Working Capacity in LittleFS
#define userPWCFILENAME "/userPWC.txt"

// name of the local file to save the torque table.
// name of the local file to save the torque table.
#define POWER_TABLE_FILENAME "/PowerTable.txt"

// Default Incline Multiplier.
Expand Down Expand Up @@ -80,13 +80,13 @@ const char * const DEFAULT_PASSWORD = "password";
// Amount to change watt target per shift in ERG mode.
#define ERG_PER_SHIFT 10

//Pass all of the FTMS commands sent to SS2k down to a connected FTMS device.
// Pass all of the FTMS commands sent to SS2k down to a connected FTMS device.
#define FTMS_PASSTHROUGH false

// Use internal ERG control on external FTMS Trainer.
//#define INTERNAL_ERG_4EXT_FTMS
// #define INTERNAL_ERG_4EXT_FTMS

//Minimum cadence where ERG mode stops.
// Minimum cadence where ERG mode stops.
#define MIN_ERG_CADENCE 30

// Default Min Watts to stop stepper.
Expand Down Expand Up @@ -268,7 +268,7 @@ const char * const DEFAULT_PASSWORD = "password";
// Size of increments (in watts) for the ERG Lookup Table. This needs to be a decimal for proper calculation.
#define POWERTABLE_WATT_INCREMENT 30

// Size of increments (in CAD) for the ERG Lookup Table. This needs to be a decimal for proper calculation.
// Size of increments (in CAD) for the ERG Lookup Table. This needs to be a decimal for proper calculation.
#define POWERTABLE_CAD_INCREMENT 5

// Number of similar power samples to take before writing to the Power Table
Expand All @@ -283,8 +283,8 @@ const char * const DEFAULT_PASSWORD = "password";
// Where does the CAD portion of the table start?
#define MINIMUM_TABLE_CAD 60

//Minimum positions recorded in the active table before attempting to load the saved table.
//Increase this value if the offset for the loaded table is inaccurate.
// Minimum positions recorded in the active table before attempting to load the saved table.
// Increase this value if the offset for the loaded table is inaccurate.
#define MINIMUM_RELIABLE_POSITIONS 3

// Temperature of the ESP32 at which to start reducing the power output of the stepper motor driver.
Expand All @@ -303,21 +303,17 @@ const char * const DEFAULT_PASSWORD = "password";
#define BLE_RECONNECT_INTERVAL 1

// Interval for polling ble battery updates
#define BATTERY_UPDATE_INTERVAL_MILLIS 300000
#define BATTERY_UPDATE_INTERVAL_MILLIS 300000

// Initial and web scan duration.
#define DEFAULT_SCAN_DURATION 5

// BLE automatic reconnect duration. Set this low to avoid interruption.
#define BLE_RECONNECT_SCAN_DURATION 5

//Task Stack Sizes
#define MAIN_STACK 4500
#define ERG_STACK 6000
#define HTTP_STACK 6000
#define BLE_COMM_STACK 6000
// Task Stack Sizes
#define MAIN_STACK 6000
#define BLE_CLIENT_STACK 5500
#define STEPPER_STACK 2000

// Uncomment to enable stack size debugging info
// #define DEBUG_STACK
Expand Down
3 changes: 2 additions & 1 deletion src/BLE_Client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ static void onNotify(BLERemoteCharacteristic *pBLERemoteCharacteristic, uint8_t
}
}

// BLE Client loop task
// BLE Client loop task.
// Manages device connections and scanning.
void bleClientTask(void *pvParameters) {
long int scanDelay = millis();
for (;;) {
Expand Down
20 changes: 5 additions & 15 deletions src/BLE_Common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,10 @@

bool hr2p = false;

TaskHandle_t BLECommunicationTask;

void BLECommunications(void *pvParameters) {
for (;;) {
// if (!spinBLEClient.dontBlockScan) {
// NimBLEDevice::getScan()->stop(); // stop routine scans
// }
void BLECommunications() {
static unsigned long int bleCommTimer = millis();
if (((millis() - bleCommTimer) > BLE_NOTIFY_DELAY) && !ss2k->isUpdating) {
bleCommTimer = millis();
// **********************************Client***************************************
for (auto &_BLEd : spinBLEClient.myBLEDevices) { // loop through discovered devices
if (_BLEd.connectedClientID != BLE_HS_CONN_HANDLE_NONE) {
Expand Down Expand Up @@ -63,10 +60,7 @@ void BLECommunications(void *pvParameters) {
spinBLEClient.handleBattInfo(pClient, false);

} else if (!pClient->isConnected()) { // This shouldn't ever be
// called...
// if (pClient->disconnect() == 0) { // 0 is a successful disconnect
// BLEDevice::deleteClient(pClient);
// vTaskDelay(100 / portTICK_PERIOD_MS);
// called...
SS2K_LOG(BLE_COMMON_LOG_TAG, "Workaround connect");
_BLEd.doConnect = true;
//}
Expand Down Expand Up @@ -129,9 +123,5 @@ void BLECommunications(void *pvParameters) {
} else {
digitalWrite(LED_PIN, HIGH);
}
vTaskDelay((BLE_NOTIFY_DELAY) / portTICK_PERIOD_MS);
#ifdef DEBUG_STACK
Serial.printf("BLEComm: %d \n", uxTaskGetStackHighWaterMark(BLECommunicationTask));
#endif // DEBUG_STACK
}
}
17 changes: 1 addition & 16 deletions src/BLE_Setup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,9 @@
void setupBLE() { // Common BLE setup for both client and server
SS2K_LOG(BLE_SETUP_LOG_TAG, "Starting Arduino BLE Client application...");
BLEDevice::init(userConfig->getDeviceName());
BLEDevice::setMTU(515); //-- enabling this is very important for BLE firmware updates.
BLEDevice::setMTU(515); //-- enabling this is very important for BLE firmware updates.
spinBLEClient.start();
startBLEServer();

xTaskCreatePinnedToCore(BLECommunications, /* Task function. */
"BLECommunicationTask", /* name of task. */
BLE_COMM_STACK, /* Stack size of task*/
NULL, /* parameter of the task */
3, /* priority of the task*/
&BLECommunicationTask, /* Task handle to keep track of created task */
1); /* pin task to core */

SS2K_LOG(BLE_SETUP_LOG_TAG, "BLE Notify Task Started");
/*vTaskDelay(100 / portTICK_PERIOD_MS);
if (strcmp(userConfig->getConnectedPowerMeter(), "none") != 0 || strcmp(userConfig->getConnectedHeartMonitor(), "none") != 0) {
spinBLEClient.serverScan(true);
SS2K_LOG(BLE_SETUP_LOG_TAG, "Scanning");
}*/
SS2K_LOG(BLE_SETUP_LOG_TAG, "%s %s %s", userConfig->getConnectedPowerMeter(), userConfig->getConnectedHeartMonitor(), userConfig->getConnectedRemote());
SS2K_LOG(BLE_SETUP_LOG_TAG, "End BLE Setup");
}
63 changes: 21 additions & 42 deletions src/ERG_Mode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,42 +16,28 @@
#include <limits>
#include <numeric>

TaskHandle_t ErgTask;
PowerTable* powerTable = new PowerTable;

// Create a torque table representing 0w-1000w in 50w increments.
// i.e. powerTable[1] corresponds to the incline required for 50w. powerTable[2] is the incline required for 100w and so on.

void setupERG() {
SS2K_LOG(ERG_MODE_LOG_TAG, "Starting ERG Mode task...");
xTaskCreatePinnedToCore(ergTaskLoop, /* Task function. */
"FTMSModeTask", /* name of task. */
ERG_STACK, /* Stack size of task*/
NULL, /* parameter of the task */
1, /* priority of the task*/
&ErgTask, /* Task handle to keep track of created task */
0); /* pin task to core 0 */

SS2K_LOG(ERG_MODE_LOG_TAG, "ERG Mode task started");
}

void ergTaskLoop(void* pvParameters) {
ErgMode ergMode;
PowerBuffer powerBuffer;
static unsigned long int ergTimer = millis();

ergMode._writeLogHeader();
bool hasConnectedPowerMeter = false;
bool simulationRunning = false;
int loopCounter = 0;
void PowerTable::runERG() {
static ErgMode ergMode;
static PowerBuffer powerBuffer;
static bool hasConnectedPowerMeter = false;
static bool simulationRunning = false;
static int loopCounter = 0;

while (true) {
if ((millis() - ergTimer) > ERG_MODE_DELAY) {
// reset the timer.
ergTimer = millis();
// be quiet while updating via BLE
while (ss2k->isUpdating) {
vTaskDelay(ERG_MODE_DELAY / portTICK_PERIOD_MS);
if (ss2k->isUpdating) {
return;
}

vTaskDelay(ERG_MODE_DELAY / portTICK_PERIOD_MS);

if (rtConfig->cad.getValue() > 0 && rtConfig->watts.getValue() > 0) {
hasConnectedPowerMeter = spinBLEClient.connectedPM;
simulationRunning = rtConfig->watts.getTarget();
Expand Down Expand Up @@ -82,12 +68,7 @@ void ergTaskLoop(void* pvParameters) {
if (ss2k->resetPowerTableFlag) {
powerTable->reset();
}

loopCounter++;

#ifdef DEBUG_STACK
Serial.printf("ERG Task: %d \n", uxTaskGetStackHighWaterMark(ErgTask));
#endif // DEBUG_STACK
}
}

Expand Down Expand Up @@ -932,8 +913,8 @@ bool PowerTable::_manageSaveState() {
}
this->tableRow[i].tableEntry[j].targetPosition = savedTargetPosition;
this->tableRow[i].tableEntry[j].readings = savedReadings;
//SS2K_LOG(POWERTABLE_LOG_TAG, "Position %d, %d, Target %d, Readings %d, loaded", i, j, this->tableRow[i].tableEntry[j].targetPosition,
// this->tableRow[i].tableEntry[j].readings);
// SS2K_LOG(POWERTABLE_LOG_TAG, "Position %d, %d, Target %d, Readings %d, loaded", i, j, this->tableRow[i].tableEntry[j].targetPosition,
// this->tableRow[i].tableEntry[j].readings);
}
}

Expand Down Expand Up @@ -1146,17 +1127,15 @@ void ErgMode::_setPointChangeState(int newCadence, Measurement& newWatts) {
SS2K_LOG(ERG_MODE_LOG_TAG, "SetPoint changed:%dw PowerTable Result: %d", newWatts.getTarget(), tableResult);
_updateValues(newCadence, newWatts, tableResult);

int i = 0;
while (rtConfig->getTargetIncline() != rtConfig->getCurrentIncline()) { // wait while the knob moves to target position.
vTaskDelay(100 / portTICK_PERIOD_MS);
if (i > 50) { // failsafe for infinite loop
SS2K_LOG(ERG_MODE_LOG_TAG, "Stepper didn't reach target position");
break;
if (rtConfig->getTargetIncline() != rtConfig->getCurrentIncline()) { // add some time to wait while the knob moves to target position.
int timeToAdd = abs(rtConfig->getCurrentIncline() - rtConfig->getTargetIncline());
if (timeToAdd > 5000) { // 5 seconds
SS2K_LOG(ERG_MODE_LOG_TAG, "Capping ERG seek time to 5 seconds");
timeToAdd = 5000;
}
i++;
ergTimer += timeToAdd;
}

vTaskDelay((ERG_MODE_DELAY * 2) / portTICK_PERIOD_MS); // Wait for power meter to register new watts
ergTimer += (ERG_MODE_DELAY * 2); // Wait for power meter to register new watts
}

void ErgMode::_inSetpointState(int newCadence, Measurement& newWatts) {
Expand Down
Loading

0 comments on commit 04fd746

Please sign in to comment.