Skip to content

Commit

Permalink
Best Firmware update settings yet
Browse files Browse the repository at this point in the history
  • Loading branch information
doudar committed Mar 6, 2024
1 parent ed7283e commit 9157a78
Show file tree
Hide file tree
Showing 9 changed files with 63 additions and 39 deletions.
1 change: 1 addition & 0 deletions include/Main.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class SS2K {
int txCheck;
bool rebootFlag = false;
bool saveFlag = false;
bool isUpdating = false;

bool IRAM_ATTR deBounce();
static void IRAM_ATTR moveStepper(void *pvParameters);
Expand Down
2 changes: 1 addition & 1 deletion platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ build_flags =
!python build_date_macro.py
-D CONFIG_BT_NIMBLE_MAX_CONNECTIONS=6
-D CONFIG_MDNS_STRICT_MODE=1
-D CORE_DEBUG_LEVEL=3
-D CORE_DEBUG_LEVEL=1
-D ARDUINO_SERIAL_EVENT_TASK_STACK_SIZE=3500
lib_deps =
https://github.com/h2zero/NimBLE-Arduino/archive/refs/tags/1.4.1.zip
Expand Down
4 changes: 4 additions & 0 deletions src/BLE_Client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ static void onNotify(BLERemoteCharacteristic *pBLERemoteCharacteristic, uint8_t
void bleClientTask(void *pvParameters) {
long int scanDelay = millis();
for (;;) {
//be quiet while updating BLE
while (ss2k->isUpdating) {
vTaskDelay(100);
}
vTaskDelay(BLE_CLIENT_DELAY / portTICK_PERIOD_MS); // Delay a second between loops.
if ((millis() - scanDelay) * 2 > (BLE_RECONNECT_SCAN_DURATION * 1000)) {
spinBLEClient.checkBLEReconnect();
Expand Down
10 changes: 7 additions & 3 deletions src/BLE_Common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ TaskHandle_t BLECommunicationTask;

void BLECommunications(void *pvParameters) {
for (;;) {
// if (!spinBLEClient.dontBlockScan) {
// NimBLEDevice::getScan()->stop(); // stop routine scans
// }
//be quiet while updating
while (ss2k->isUpdating) {
vTaskDelay(100);
}
// if (!spinBLEClient.dontBlockScan) {
// NimBLEDevice::getScan()->stop(); // stop routine scans
// }
// **********************************Client***************************************
for (size_t x = 0; x < NUM_BLE_DEVICES; x++) { // loop through discovered devices
if (spinBLEClient.myBLEDevices[x].connectedClientID != BLE_HS_CONN_HANDLE_NONE) {
Expand Down
62 changes: 35 additions & 27 deletions src/BLE_Firmware_Update.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,69 +41,77 @@ bool downloadFlag = false;
----------------------------------------------------------------------------*/

class otaCallback : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
void onWrite(BLECharacteristic *pCharacteristic, ble_gap_conn_desc *connDesc) {
std::string rxData = pCharacteristic->getValue();
bufferCount++;

if (!downloadFlag) {
ss2k->isUpdating = true;
//-----------------------------------------------
// First BLE bytes have arrived
//-----------------------------------------------
// update the connection interval so that it provides enough time for the long writes

SS2K_LOG(BLE_SERVER_LOG_TAG, "1. BeginOTA");
Serial.printf("1. BeginOTA");
BLEDevice::getServer()->updateConnParams(connDesc->conn_handle, 12, 12, 0, 1000);
const esp_partition_t *configured = esp_ota_get_boot_partition();
const esp_partition_t *running = esp_ota_get_running_partition();

if (configured != running) {
SS2K_LOG(BLE_SERVER_LOG_TAG, "ERROR: Configured OTA boot partition at offset 0x%08x, but running from offset 0x%08x", configured->address, running->address);
SS2K_LOG(BLE_SERVER_LOG_TAG, "(This can happen if either the OTA boot data or preferred boot image become corrupted somehow.)");
Serial.printf("ERROR: Configured OTA boot partition at offset 0x%08x, but running from offset 0x%08x", configured->address, running->address);
Serial.printf("(This can happen if either the OTA boot data or preferred boot image become corrupted somehow.)");
downloadFlag = false;
esp_ota_end(otaHandler);
} else {
SS2K_LOG(BLE_SERVER_LOG_TAG, "2. Running partition type %d subtype %d (offset 0x%08x) \n", running->type, running->subtype, running->address);
Serial.printf("2. Running partition type %d subtype %d (offset 0x%08x) \n", running->type, running->subtype, running->address);
}

update_partition = esp_ota_get_next_update_partition(NULL);
assert(update_partition != NULL);

SS2K_LOG(BLE_SERVER_LOG_TAG, "3. Writing to partition subtype %d at offset 0x%x \n", update_partition->subtype, update_partition->address);
Serial.printf("3. Writing to partition subtype %d at offset 0x%x \n", update_partition->subtype, update_partition->address);

//------------------------------------------------------------------------------------------
// esp_ota_begin can take a while to complete as it erase the flash partition (3-5 seconds)
// so make sure there's no timeout on the client side (iOS) that triggers before that.
//------------------------------------------------------------------------------------------
esp_task_wdt_init(10, false);

if (BLECommunicationTask != NULL) {
SS2K_LOG(MAIN_LOG_TAG, "Stop BLE Tasks");
vTaskDelete(BLECommunicationTask);
BLECommunicationTask = NULL;
}
if (BLEClientTask != NULL) {
vTaskDelete(BLEClientTask);
BLEClientTask = NULL;
}

// if (BLECommunicationTask != NULL) {
// SS2K_LOG(MAIN_LOG_TAG, "Stop BLE Tasks");
// if (NimBLEDevice::getScan()->isScanning()) {
// NimBLEDevice::getScan()->stop();
// }
// vTaskDelete(BLECommunicationTask);
// BLECommunicationTask = NULL;
// }
// if (BLEClientTask != NULL) {
// vTaskDelete(BLEClientTask);
// BLEClientTask = NULL;
// }

// vTaskDelay(5);

if (esp_ota_begin(update_partition, OTA_SIZE_UNKNOWN, &otaHandler) != ESP_OK) {
downloadFlag = false;
ss2k->isUpdating = false;
return;
}
downloadFlag = true;
}

if (bufferCount >= 1 || rxData.length() > 0) {
if (esp_ota_write(otaHandler, (uint8_t *)rxData.c_str(), rxData.length()) != ESP_OK) {
SS2K_LOG(BLE_SERVER_LOG_TAG, "Error: write to flash failed");
Serial.printf("Error: write to flash failed");
downloadFlag = false;
pTxCharacteristic->setValue(&txValue, 4);
pTxCharacteristic->notify();
return;
} else {
bufferCount = 1;
SS2K_LOG(BLE_SERVER_LOG_TAG, "%d bytes", rxData.length());
// Notify the iOS app so next batch can be sent
// Serial.printf("%d bytes", rxData.length());
// Notify the iOS app so next batch can be sent
Serial.printf(".");
pTxCharacteristic->setValue(&txValue, 2);
// pTxCharacteristic->notify();
}
Expand All @@ -113,39 +121,38 @@ class otaCallback : public BLECharacteristicCallbacks {
// smaller than the maximum MTU size). For improvement: let iOS app send byte
// length instead of hardcoding "510"
//-------------------------------------------------------------------
if (rxData.length() < 500) // TODO Asumes at least 511 data bytes (@BLE 4.2).
if (rxData.length() < 512) // TODO Asumes at least 511 data bytes (@BLE 4.2).
{
SS2K_LOG(BLE_SERVER_LOG_TAG, "4. Final byte arrived");
Serial.printf("4. Final byte arrived");
//-----------------------------------------------------------------
// Final chunk arrived. Now check that
// the length of total file is correct
//-----------------------------------------------------------------
if (esp_ota_end(otaHandler) != ESP_OK) {
SS2K_LOG(BLE_SERVER_LOG_TAG, "OTA end failed ");
Serial.printf("OTA end failed ");
downloadFlag = false;
pTxCharacteristic->setValue(&txValue, 4);
pTxCharacteristic->notify();
return;
}
pTxCharacteristic->setValue(&txValue, 5);
pTxCharacteristic->notify();
vTaskDelay(1000);
//-----------------------------------------------------------------
// Clear download flag and restart the ESP32 if the firmware
// update was successful
//-----------------------------------------------------------------
SS2K_LOG(BLE_SERVER_LOG_TAG, "Set Boot partion");
Serial.printf("Set Boot partion");
if (ESP_OK == esp_ota_set_boot_partition(update_partition)) {
esp_ota_end(otaHandler);
downloadFlag = false;
SS2K_LOG(BLE_SERVER_LOG_TAG, "Restarting...");
esp_restart();
Serial.printf("Restarting...");
ss2k->rebootFlag = true;
return;
} else {
//------------------------------------------------------------
// Something went wrong, the upload was not successful
//------------------------------------------------------------
SS2K_LOG(BLE_SERVER_LOG_TAG, "Upload Error");
Serial.printf("Upload Error");
pTxCharacteristic->setValue(&txValue, 4);
pTxCharacteristic->notify();
downloadFlag = false;
Expand All @@ -154,6 +161,7 @@ class otaCallback : public BLECharacteristicCallbacks {
}
}
} else {
ss2k->isUpdating = false;
downloadFlag = false;
}
}
Expand Down
8 changes: 3 additions & 5 deletions src/BLE_Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ void startBLEServer() {
smartSpin2kCharacteristic =
pSmartSpin2kService->createCharacteristic(SMARTSPIN2K_CHARACTERISTIC_UUID, NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::INDICATE | NIMBLE_PROPERTY::NOTIFY);

spinBLEServer.pServer->setCallbacks(new MyServerCallbacks());
spinBLEServer.pServer->setCallbacks(new MyServerCallbacks());

// Creating Characteristics
heartRateMeasurementCharacteristic->setValue(heartRateMeasurement, 2);
Expand Down Expand Up @@ -326,8 +326,7 @@ void MyServerCallbacks::onDisconnect(BLEServer *pServer) {
}

bool MyServerCallbacks::onConnParamsUpdateRequest(NimBLEClient *pClient, const ble_gap_upd_params *params) {
// Failing to accept parameters may result in the remote device
// disconnecting.
SS2K_LOG(BLE_SERVER_LOG_TAG, "Updated Server Connection Parameters for %s", pClient->getPeerAddress().toString().c_str());
return true;
};

Expand Down Expand Up @@ -387,7 +386,6 @@ void processFTMSWrite() {
uint8_t returnValue[3] = {FitnessMachineControlPointProcedure::ResponseCode, (uint8_t)rxValue[0], FitnessMachineControlPointResultCode::OpCodeNotSupported};

ftmsStatus = {FitnessMachineStatus::ReservedForFutureUse};


switch ((uint8_t)rxValue[0]) {
case FitnessMachineControlPointProcedure::RequestControl:
Expand Down Expand Up @@ -498,7 +496,7 @@ void processFTMSWrite() {

case FitnessMachineControlPointProcedure::SetIndoorBikeSimulationParameters: { // sim mode
rtConfig->setFTMSMode((uint8_t)rxValue[0]);
returnValue[2] = FitnessMachineControlPointResultCode::Success; // 0x01;
returnValue[2] = FitnessMachineControlPointResultCode::Success; // 0x01;
pCharacteristic->setValue(returnValue, 3);

signed char buf[2];
Expand Down
10 changes: 7 additions & 3 deletions src/ERG_Mode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ 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*/
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 */
Expand All @@ -40,6 +40,10 @@ void ergTaskLoop(void* pvParameters) {
int loopCounter = 0;

while (true) {
// be quiet while updating via BLE
while (ss2k->isUpdating) {
vTaskDelay(100);
}
vTaskDelay(ERG_MODE_DELAY / portTICK_PERIOD_MS);

hasConnectedPowerMeter = spinBLEClient.connectedPM;
Expand Down Expand Up @@ -256,7 +260,7 @@ int32_t TorqueTable::lookup(int watts, int cad) {
float torque = _wattsToTorque(watts, cad);

int i = round(torque / TORQUETABLE_INCREMENT); // find the closest entry
//Cap i to max table size.
// Cap i to max table size.
if (i > TORQUETABLE_SIZE) {
i = TORQUETABLE_SIZE - 1;
}
Expand Down Expand Up @@ -624,7 +628,7 @@ void ErgMode::_updateValues(int newCadence, Measurement& newWatts, float newIncl

bool ErgMode::_userIsSpinning(int cadence, float incline) {
if (cadence <= MIN_ERG_CADENCE) {
if (!this->engineStopped) { // Test so motor stop command only happens once.
if (!this->engineStopped) { // Test so motor stop command only happens once.
ss2k->motorStop(); // release tension
rtConfig->setTargetIncline(incline - WATTS_PER_SHIFT); // release incline
this->engineStopped = true;
Expand Down
4 changes: 4 additions & 0 deletions src/HTTP_Server_Basic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,10 @@ void HTTP_Server::start() {
void HTTP_Server::webClientUpdate(void *pvParameters) {
static unsigned long mDnsTimer = millis(); // NOLINT: There is no overload in String for uint64_t
for (;;) {
// be quiet while updating via BLE
while (ss2k->isUpdating) {
vTaskDelay(100);
}
server.handleClient();
vTaskDelay(WEBSERVER_DELAY / portTICK_RATE_MS);
if (WiFi.getMode() != WIFI_MODE_STA) {
Expand Down
1 change: 1 addition & 0 deletions src/Main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ void SS2K::maintenanceLoop(void *pvParameters) {
if (NimBLEDevice::getServer()) {
if (!(NimBLEDevice::getServer()->getConnectedCount())) {
SS2K_LOGW(MAIN_LOG_TAG, "Rebooting due to inactivity");

ss2k->rebootFlag = true;
} else {
rebootTimer = millis();
Expand Down

0 comments on commit 9157a78

Please sign in to comment.