Skip to content

Commit

Permalink
Merge pull request #405 from doudar/auto_reconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
doudar authored Dec 7, 2022
2 parents 20f45e6 + be3de91 commit 1b77d6c
Show file tree
Hide file tree
Showing 12 changed files with 94 additions and 39 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added blocking for shifts above or below min/max set points.
- Added power scaler for new board.
- Added Main Index link to develop.html.
- Added feature to automatically reconnect BLE devices if both are specified.

### Changed
- PowerTable values are now adjusted to 90 RPM cad on input.
Expand Down
32 changes: 19 additions & 13 deletions data/bluetoothscanner.html
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ <h2>
var t_obj = JSON.parse(data.foundDevices)
{
for (var key in t_obj) {
if (t_obj[key].UUID == '0x1818' || t_obj[key].UUID == '0x1826') {
if (t_obj[key].UUID == '0x1818' || t_obj[key].UUID == '0x1826' || t_obj[key].UUID == '6e400001-b5a3-f393-e0a9-e50e24dcca9e' || t_obj[key].UUID == '0bf669f0-45f2-11e7-9598-0800200c9a66') {
optionPM = document.createElement('option');
if (t_obj[key].name) {
optionPM.text = t_obj[key].name;
Expand Down Expand Up @@ -152,18 +152,24 @@ <h2>
}
}

optionPM = document.createElement('option');
optionPM.text = 'none';
PMDropdown.add(optionPM);
optionHR = document.createElement('option');
optionHR.text = 'none';
HRDropdown.add(optionHR);
let defaultOptionPM = document.createElement('option');
defaultOptionPM.text = 'any';
let defaultOptionHR = document.createElement('option');
defaultOptionHR.text = 'any';
PMDropdown.add(defaultOptionPM);
HRDropdown.add(defaultOptionHR);
let connectedOptionPM = document.createElement('option');
connectedOptionPM.text = data.connectedPowerMeter;
let connectedOptionHR = document.createElement('option');
connectedOptionHR.text = data.connectedHeartMonitor;
PMDropdown.add(connectedOptionPM);
HRDropdown.add(connectedOptionHR);
let anyOptionPM = document.createElement('option');
anyOptionPM.text = 'any';
let anyOptionHR = document.createElement('option');
anyOptionHR.text = 'any';
PMDropdown.add(anyOptionPM);
HRDropdown.add(anyOptionHR);
let noneOptionPM = document.createElement('option');
noneOptionPM.text = 'none';
let noneOptionHR = document.createElement('option');
noneOptionHR.text = 'none';
PMDropdown.add(noneOptionPM);
HRDropdown.add(noneOptionHR);
document.getElementById("connectedPowerMeter").innerHTML = data.connectedPowerMeter;
document.getElementById("connectedHeartMonitor").innerHTML = data.connectedHeartMonitor;
document.getElementById("powerCorrectionFactorValue").innerHTML = data.powerCorrectionFactor;
Expand Down
2 changes: 1 addition & 1 deletion include/BLE_Common.h
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ class SpinBLEClient {
void start();
void serverScan(bool connectRequest);
bool connectToServer();
void scanProcess();
void scanProcess(int duration = DEFAULT_SCAN_DURATION);
void disconnect();
// Check for duplicate services of BLEClient and remove the previously
// connected one.
Expand Down
1 change: 1 addition & 0 deletions include/Main.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class SS2K {
void checkDriverTemperature();
void motorStop(bool releaseTension = false);
void checkSerial();
void checkBLEReconnect();

SS2K() {
targetPosition = 0;
Expand Down
4 changes: 2 additions & 2 deletions include/SmartSpin_parameters.h
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ class userParameters {
bool getAutoUpdate() { return autoUpdate; }
const char* getSsid() { return ssid.c_str(); }
const char* getPassword() { return password.c_str(); }
const char* getconnectedPowerMeter() { return connectedPowerMeter.c_str(); }
const char* getconnectedHeartMonitor() { return connectedHeartMonitor.c_str(); }
const char* getConnectedPowerMeter() { return connectedPowerMeter.c_str(); }
const char* getConnectedHeartMonitor() { return connectedHeartMonitor.c_str(); }
int getStepperPower() { return stepperPower; }
int getMaxWatts() { return maxWatts; }
int getMinWatts() { return minWatts; }
Expand Down
16 changes: 14 additions & 2 deletions include/settings.h
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,15 @@
// If not receiving Peleton Messages, how long to wait before next TX attempt is
#define TX_CHECK_INTERVAL 20

// If ble devices are both setup, how often to attempt a reconnect.
#define BLE_RECONNECT_INTERVAL 40

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

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

// Uncomment to enable sending Telegram debug messages back to the chat
// specified in telegram_token.h
// #define USE_TELEGRAM
Expand All @@ -253,8 +262,11 @@
//#define DEBUG_STACK

// Uncomment to enable HR->PWR debugging info. Always displays HR->PWR
// Calculation. Never sets userConfig.setSimulatedPower(); #define
// DEBUG_HR_TO_PWR
// Calculation. Never sets userConfig.setSimulatedPower();
// #define DEBUG_HR_TO_PWR

// Uncomment to enable HR->PWR enhanced powertable debugging.
// #define DEBUG_POWERTABLE

#ifdef USE_TELEGRAM
// Max number of telegram messages to send per session
Expand Down
26 changes: 13 additions & 13 deletions src/BLE_Client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ static void onNotify(BLERemoteCharacteristic *pBLERemoteCharacteristic, uint8_t
// BLE Client loop task
void bleClientTask(void *pvParameters) {
for (;;) {
if (spinBLEClient.doScan && (spinBLEClient.scanRetries > 0)) {
if (spinBLEClient.doScan && (spinBLEClient.scanRetries > 0) && !NimBLEDevice::getScan()->isScanning()) {
spinBLEClient.scanRetries--;
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Initiating Scan from Client Task:");
spinBLEClient.scanProcess();
Expand Down Expand Up @@ -347,24 +347,24 @@ void MyAdvertisedDeviceCallback::onResult(BLEAdvertisedDevice *advertisedDevice)
// not specified.
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Matching Device Name: %s", aDevName.c_str());
if (advertisedDevice->getServiceUUID() == HEARTSERVICE_UUID) {
if (String(userConfig.getconnectedHeartMonitor()) == "any") {
if (String(userConfig.getConnectedHeartMonitor()) == "any") {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "HR String Matched Any");
// continue
} else if (aDevName != String(userConfig.getconnectedHeartMonitor()) || (String(userConfig.getconnectedHeartMonitor()) == "none")) {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Skipping non-selected HRM |%s|%s", aDevName.c_str(), userConfig.getconnectedHeartMonitor());
} else if (aDevName != String(userConfig.getConnectedHeartMonitor()) || (String(userConfig.getConnectedHeartMonitor()) == "none")) {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Skipping non-selected HRM |%s|%s", aDevName.c_str(), userConfig.getConnectedHeartMonitor());
return;
} else if (aDevName == String(userConfig.getconnectedHeartMonitor())) {
} else if (aDevName == String(userConfig.getConnectedHeartMonitor())) {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "HR String Matched %s", aDevName.c_str());
}
} else { // Already tested -->((advertisedDevice->getServiceUUID()(CYCLINGPOWERSERVICE_UUID) || advertisedDevice->getServiceUUID()(FLYWHEEL_UART_SERVICE_UUID) ||
// advertisedDevice->getServiceUUID()(FITNESSMACHINESERVICE_UUID)))
if (String(userConfig.getconnectedPowerMeter()) == "any") {
if (String(userConfig.getConnectedPowerMeter()) == "any") {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "PM String Matched Any");
// continue
} else if (aDevName != String(userConfig.getconnectedPowerMeter()) || (String(userConfig.getconnectedPowerMeter()) == "none")) {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Skipping non-selected PM |%s|%s", aDevName.c_str(), userConfig.getconnectedPowerMeter());
} else if (aDevName != String(userConfig.getConnectedPowerMeter()) || (String(userConfig.getConnectedPowerMeter()) == "none")) {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Skipping non-selected PM |%s|%s", aDevName.c_str(), userConfig.getConnectedPowerMeter());
return;
} else if (aDevName == String(userConfig.getconnectedPowerMeter())) {
} else if (aDevName == String(userConfig.getConnectedPowerMeter())) {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "PM String Matched %s", aDevName.c_str());
}
}
Expand All @@ -384,7 +384,7 @@ void MyAdvertisedDeviceCallback::onResult(BLEAdvertisedDevice *advertisedDevice)
}
}

void SpinBLEClient::scanProcess() {
void SpinBLEClient::scanProcess(int duration) {
this->doScan = false; // Confirming we did the scan
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Scanning for BLE servers and putting them into a list...");

Expand All @@ -394,7 +394,7 @@ void SpinBLEClient::scanProcess() {
pBLEScan->setWindow(67);
pBLEScan->setDuplicateFilter(true);
pBLEScan->setActiveScan(true);
BLEScanResults foundDevices = pBLEScan->start(10, true);
BLEScanResults foundDevices = pBLEScan->start(duration, true);
// Load the scan into a Json String
int count = foundDevices.getCount();

Expand Down Expand Up @@ -507,13 +507,13 @@ void SpinBLEClient::postConnect(NimBLEClient *pClient) {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Activated Echelon callbacks.");
}
// spinBLEClient.removeDuplicates(pclient);
BLEDevice::getServer()->updateConnParams(pClient->getConnId(), 400, 400, 0, 250);
BLEDevice::getServer()->updateConnParams(pClient->getConnId(), 400, 400, 2, 1000);
return;
}
if ((this->myBLEDevices[i].charUUID == HEARTCHARACTERISTIC_UUID)) {
this->connectedHR = true;
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Registered HRM on Connect");
BLEDevice::getServer()->updateConnParams(pClient->getConnId(), 400, 400, 0, 250);
BLEDevice::getServer()->updateConnParams(pClient->getConnId(), 400, 400, 2, 1000);
return;
} else {
SS2K_LOG(BLE_CLIENT_LOG_TAG, "These did not match|%s|%s|", pClient->getPeerAddress().toString().c_str(), this->myBLEDevices[i].peerAddress.toString().c_str());
Expand Down
2 changes: 1 addition & 1 deletion src/BLE_Common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ void BLECommunications(void *pvParameters) {
} else {
digitalWrite(LED_PIN, HIGH);
}
if (spinBLEClient.doScan && (spinBLEClient.scanRetries > 0)) {
if (spinBLEClient.doScan && (spinBLEClient.scanRetries > 0) && !NimBLEDevice::getScan()->isScanning()) {
spinBLEClient.scanRetries--;
SS2K_LOG(BLE_CLIENT_LOG_TAG, "Initiating Scan from Client Task:");
spinBLEClient.scanProcess();
Expand Down
4 changes: 2 additions & 2 deletions src/BLE_Setup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ void setupBLE() { // Common BLE setup for both client and server

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) {
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", userConfig.getconnectedPowerMeter(), userConfig.getconnectedHeartMonitor());
SS2K_LOG(BLE_SETUP_LOG_TAG, "%s %s", userConfig.getConnectedPowerMeter(), userConfig.getConnectedHeartMonitor());
SS2K_LOG(BLE_SETUP_LOG_TAG, "End BLE Setup");
}
4 changes: 4 additions & 0 deletions src/ERG_Mode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -163,13 +163,17 @@ void PowerTable::newEntry(PowerBuffer& powerBuffer) {
cad = powerBuffer.powerEntry[i].cad;
continue;
}
#ifdef DEBUG_POWERTABLE
SS2K_LOGW(POWERTABLE_LOG_TAG, "Buf[%d](%dw)(%dpos)(%dcad)", i, powerBuffer.powerEntry[i].watts, powerBuffer.powerEntry[i].targetPosition, powerBuffer.powerEntry[i].cad);
#endif
// calculate average
watts = (watts + powerBuffer.powerEntry[i].watts) / 2;
targetPosition = (targetPosition + powerBuffer.powerEntry[i].targetPosition) / 2;
cad = (cad + powerBuffer.powerEntry[i].cad) / 2;
}
#ifdef DEBUG_POWERTABLE
SS2K_LOG(POWERTABLE_LOG_TAG, "Avg:(%dw)(%dpos)(%dcad)", (int)watts, targetPosition, cad);
#endif
// Done with powerBuffer
// To start working on the PowerTable, we need to calculate position in the table for the new entry
int i = round(watts / POWERTABLE_INCREMENT);
Expand Down
18 changes: 14 additions & 4 deletions src/HTTP_Server_Basic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,7 @@ void HTTP_Server::settingsProcessor() {
String tString;
bool wasBTUpdate = false;
bool wasSettingsUpdate = false;
bool reboot = false;
if (!server.arg("ssid").isEmpty()) {
tString = server.arg("ssid");
tString.trim();
Expand Down Expand Up @@ -528,21 +529,26 @@ void HTTP_Server::settingsProcessor() {
wasBTUpdate = true;
if (server.arg("blePMDropdown")) {
tString = server.arg("blePMDropdown");
userConfig.setConnectedPowerMeter(server.arg("blePMDropdown"));
if (tString != userConfig.getConnectedPowerMeter()) {
reboot = true;
}
} else {
userConfig.setConnectedPowerMeter("any");
}
}
if (!server.arg("bleHRDropdown").isEmpty()) {
wasBTUpdate = true;
if (server.arg("bleHRDropdown")) {
tString = server.arg("bleHRDropdown");
bool reset = false;
tString = server.arg("bleHRDropdown");
if (tString != userConfig.getConnectedHeartMonitor()) {
reboot = true;
}
userConfig.setConnectedHeartMonitor(server.arg("bleHRDropdown"));
} else {
userConfig.setConnectedHeartMonitor("any");
}
}

if (!server.arg("session1HR").isEmpty()) { // Needs checking for unrealistic numbers.
userPWC.session1HR = server.arg("session1HR").toInt();
}
Expand Down Expand Up @@ -579,7 +585,7 @@ void HTTP_Server::settingsProcessor() {
} else { // Normal response
response +=
"Network settings will be applied at next reboot. <br> Everything "
"else is availiable immediately.</h2></body><script> "
"else is available immediately.</h2></body><script> "
"setTimeout(\"location.href = 'http://" +
myIP.toString() + "/index.html';\",1000);</script></html>";
}
Expand All @@ -589,6 +595,10 @@ void HTTP_Server::settingsProcessor() {
userConfig.printFile();
userPWC.saveToLittleFS();
userPWC.printFile();
if (reboot) {
vTaskDelay(100 / portTICK_PERIOD_MS);
ESP.restart();
}
}

void HTTP_Server::stop() {
Expand Down
23 changes: 22 additions & 1 deletion src/Main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ void setup() {

xTaskCreatePinnedToCore(SS2K::maintenanceLoop, /* Task function. */
"maintenanceLoopFunction", /* name of task. */
3500, /* Stack size of task */
4000, /* Stack size of task */
NULL, /* parameter of the task */
1, /* priority of the task */
&maintenanceLoopTask, /* Task handle to keep track of created task */
Expand Down Expand Up @@ -228,6 +228,7 @@ void SS2K::maintenanceLoop(void *pvParameters) {
if (loopCounter > 4) {
ss2k.scanIfShiftersHeld();
ss2k.checkDriverTemperature();
ss2k.checkBLEReconnect();

#ifdef DEBUG_STACK
Serial.printf("Step Task: %d \n", uxTaskGetStackHighWaterMark(moveStepperTask));
Expand Down Expand Up @@ -498,3 +499,23 @@ void SS2K::checkSerial() {
txCheck++;
}
}

void SS2K::checkBLEReconnect() {
static int bleCheck = 0;
if (((userConfig.getConnectedHeartMonitor() != "any" && !spinBLEClient.connectedHR) || (userConfig.getConnectedPowerMeter() != "any" && !spinBLEClient.connectedPM)) && (bleCheck >= BLE_RECONNECT_INTERVAL)) {
bleCheck = 0;
if (((userConfig.getConnectedPowerMeter() == "none") && (userConfig.getConnectedHeartMonitor() == "none"))){
return;
}
if (!NimBLEDevice::getScan()->isScanning()) {
SS2K_LOG(MAIN_LOG_TAG, "Scanning from Check BLE Reconnect %d", bleCheck);
spinBLEClient.resetDevices();
spinBLEClient.scanProcess(BLE_RECONNECT_SCAN_DURATION);
}
}
if (NimBLEDevice::getScan()->isScanning()) {
bleCheck = 0;
} else {
bleCheck++;
}
}

0 comments on commit 1b77d6c

Please sign in to comment.