From fbdfd1f1e3897e948a215e25166c00dff1e36ce1 Mon Sep 17 00:00:00 2001 From: Lubos Petrovic Date: Sun, 27 Dec 2020 15:39:35 +0100 Subject: [PATCH] Serial.print now covered by LogSerial class --- Board320_240.cpp | 132 ++++++++++++++++++++++----------------------- BoardInterface.cpp | 20 +++---- CarBmwI3.cpp | 24 ++++----- CommInterface.cpp | 12 ++--- CommObd2Ble4.cpp | 96 ++++++++++++++++----------------- CommObd2Can.cpp | 108 ++++++++++++++++++------------------- LiveData.cpp | 4 +- LiveData.h | 12 ++--- LogSerial.cpp | 8 +++ LogSerial.h | 27 ++++++++++ evDash.ino | 18 +++---- 11 files changed, 246 insertions(+), 215 deletions(-) create mode 100644 LogSerial.cpp create mode 100644 LogSerial.h diff --git a/Board320_240.cpp b/Board320_240.cpp index 648c1e1..fa00710 100644 --- a/Board320_240.cpp +++ b/Board320_240.cpp @@ -30,7 +30,7 @@ void Board320_240::initBoard() { liveData->params.chargingStartTime = liveData->params.currentTime = mktime(&now); // Init display - Serial.println("Init tft display"); + syslog->println("Init tft display"); tft.begin(); tft.invertDisplay(invertDisplay); tft.setRotation(liveData->settings.displayRotation); @@ -61,24 +61,24 @@ void Board320_240::afterSetup() { // Starting Wifi after BLE prevents reboot loop if (liveData->settings.wifiEnabled == 1) { - /*Serial.print("memReport(): MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM bytes free. "); - Serial.println(heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM)); + /*syslog->print("memReport(): MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM bytes free. "); + syslog->println(heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM)); - Serial.println("WiFi init..."); + syslog->println("WiFi init..."); WiFi.enableSTA(true); WiFi.mode(WIFI_STA); WiFi.begin(liveData->settings.wifiSsid, liveData->settings.wifiPassword); - Serial.println("WiFi init completed...");*/ + syslog->println("WiFi init completed...");*/ } // Init GPS if (liveData->settings.gpsHwSerialPort <= 2) { - Serial.print("GPS initialization on hwUart: "); - Serial.println(liveData->settings.gpsHwSerialPort); + syslog->print("GPS initialization on hwUart: "); + syslog->println(liveData->settings.gpsHwSerialPort); if (liveData->settings.gpsHwSerialPort == 0) { - Serial.println("hwUart0 collision with serial console! Disabling serial console"); - Serial.flush(); - Serial.end(); + syslog->println("hwUart0 collision with serial console! Disabling serial console"); + syslog->flush(); + syslog->end(); } gpsHwUart = new HardwareSerial(liveData->settings.gpsHwSerialPort); gpsHwUart->begin(9600); @@ -87,7 +87,7 @@ void Board320_240::afterSetup() { // SD card if (liveData->settings.sdcardEnabled == 1) { if (sdcardMount() && liveData->settings.sdcardAutstartLog == 1) { - Serial.println("Toggle recording on SD card"); + syslog->println("Toggle recording on SD card"); sdcardToggleRecording(); } } @@ -98,7 +98,7 @@ void Board320_240::afterSetup() { } // Init from parent class - Serial.println("BoardInterface::afterSetup"); + syslog->println("BoardInterface::afterSetup"); BoardInterface::afterSetup(); } @@ -1006,12 +1006,12 @@ void Board320_240::menuItemClick() { // Exit menu, parent level menu, open item bool showParentMenu = false; if (liveData->menuItemSelected > 0) { - Serial.println(tmpMenuItem->id); + syslog->println(tmpMenuItem->id); // Device list if (tmpMenuItem->id > 10000 && tmpMenuItem->id < 10100) { strlcpy((char*)liveData->settings.obdMacAddress, (char*)tmpMenuItem->obdMacAddress, 20); - Serial.print("Selected adapter MAC address "); - Serial.println(liveData->settings.obdMacAddress); + syslog->print("Selected adapter MAC address "); + syslog->println(liveData->settings.obdMacAddress); saveSettings(); ESP.restart(); } @@ -1120,7 +1120,7 @@ void Board320_240::menuItemClick() { } } liveData->menuCurrent = parentMenu; - Serial.println(liveData->menuCurrent); + syslog->println(liveData->menuCurrent); showMenu(); } return; @@ -1255,7 +1255,7 @@ void Board320_240::redrawScreen() { */ void Board320_240::loadTestData() { - Serial.println("Loading test data"); + syslog->println("Loading test data"); testDataMode = true; // skip lights off message carInterface->loadTestData(); @@ -1353,18 +1353,18 @@ void Board320_240::mainLoop() { if (liveData->params.sdcardInit && liveData->params.sdcardRecording && liveData->params.sdcardCanNotify && (liveData->params.odoKm != -1 && liveData->params.socPerc != -1)) { - //Serial.println(&now, "%y%m%d%H%M"); + //syslog->println(&now, "%y%m%d%H%M"); // create filename if (liveData->params.operationTimeSec > 0 && strlen(liveData->params.sdcardFilename) == 0) { sprintf(liveData->params.sdcardFilename, "/%llu.json", uint64_t(liveData->params.operationTimeSec / 60)); - Serial.print("Log filename by opTimeSec: "); - Serial.println(liveData->params.sdcardFilename); + syslog->print("Log filename by opTimeSec: "); + syslog->println(liveData->params.sdcardFilename); } if (liveData->params.currTimeSyncWithGps && strlen(liveData->params.sdcardFilename) < 15) { strftime(liveData->params.sdcardFilename, sizeof(liveData->params.sdcardFilename), "/%y%m%d%H%M.json", &now); - Serial.print("Log filename by GPS: "); - Serial.println(liveData->params.sdcardFilename); + syslog->print("Log filename by GPS: "); + syslog->println(liveData->params.sdcardFilename); } // append buffer, clear buffer & notify state @@ -1372,14 +1372,14 @@ void Board320_240::mainLoop() { liveData->params.sdcardCanNotify = false; File file = SD.open(liveData->params.sdcardFilename, FILE_APPEND); if (!file) { - Serial.println("Failed to open file for appending"); + syslog->println("Failed to open file for appending"); File file = SD.open(liveData->params.sdcardFilename, FILE_WRITE); } if (!file) { - Serial.println("Failed to create file"); + syslog->println("Failed to create file"); } if (file) { - Serial.println("Save buffer to SD card"); + syslog->println("Save buffer to SD card"); serializeParamsToJson(file); file.print(",\n"); file.close(); @@ -1408,7 +1408,7 @@ bool Board320_240::skipAdapterScan() { bool Board320_240::sdcardMount() { if (liveData->params.sdcardInit) { - Serial.print("SD card already mounted..."); + syslog->print("SD card already mounted..."); return true; } @@ -1416,47 +1416,47 @@ bool Board320_240::sdcardMount() { bool SdState = false; while (1) { - Serial.print("Initializing SD card..."); + syslog->print("Initializing SD card..."); #ifdef BOARD_TTGO_T4 - Serial.print(" TTGO-T4 "); + syslog->print(" TTGO-T4 "); SPIClass * hspi = new SPIClass(HSPI); spiSD.begin(pinSdcardSclk, pinSdcardMiso, pinSdcardMosi, pinSdcardCs); //SCK,MISO,MOSI,ss SdState = SD.begin(pinSdcardCs, *hspi, SPI_FREQUENCY); #endif BOARD_TTGO_T4 - Serial.print(" M5STACK "); + syslog->print(" M5STACK "); SdState = SD.begin(pinSdcardCs); if (SdState) { uint8_t cardType = SD.cardType(); if (cardType == CARD_NONE) { - Serial.println("No SD card attached"); + syslog->println("No SD card attached"); return false; } - Serial.println("SD card found."); + syslog->println("SD card found."); liveData->params.sdcardInit = true; - Serial.print("SD Card Type: "); + syslog->print("SD Card Type: "); if (cardType == CARD_MMC) { - Serial.println("MMC"); + syslog->println("MMC"); } else if (cardType == CARD_SD) { - Serial.println("SDSC"); + syslog->println("SDSC"); } else if (cardType == CARD_SDHC) { - Serial.println("SDHC"); + syslog->println("SDHC"); } else { - Serial.println("UNKNOWN"); + syslog->println("UNKNOWN"); } uint64_t cardSize = SD.cardSize() / (1024 * 1024); - Serial.printf("SD Card Size: %lluMB\n", cardSize); + syslog->printf("SD Card Size: %lluMB\n", cardSize); return true; } - Serial.println("Initialization failed!"); + syslog->println("Initialization failed!"); countdown--; if (countdown <= 0) { break; @@ -1475,7 +1475,7 @@ void Board320_240::sdcardToggleRecording() { if (!liveData->params.sdcardInit) return; - Serial.println("Toggle SD card recording..."); + syslog->println("Toggle SD card recording..."); liveData->params.sdcardRecording = !liveData->params.sdcardRecording; if (liveData->params.sdcardRecording) { liveData->params.sdcardCanNotify = true; @@ -1498,8 +1498,8 @@ void Board320_240::syncGPS() { } if (gps.satellites.isValid()) { liveData->params.gpsSat = gps.satellites.value(); - //Serial.print("GPS satellites: "); - //Serial.println(liveData->params.gpsSat); + //syslog->print("GPS satellites: "); + //syslog->println(liveData->params.gpsSat); } if (!liveData->params.currTimeSyncWithGps && gps.date.isValid() && gps.time.isValid()) { liveData->params.currTimeSyncWithGps = true; @@ -1523,8 +1523,8 @@ void Board320_240::syncGPS() { SIM800L */ bool Board320_240::sim800lSetup() { - Serial.print("Setting SIM800L module. HW port: "); - Serial.println(liveData->settings.gprsHwSerialPort); + syslog->print("Setting SIM800L module. HW port: "); + syslog->println(liveData->settings.gprsHwSerialPort); gprsHwUart = new HardwareSerial(liveData->settings.gprsHwSerialPort); gprsHwUart->begin(9600); @@ -1535,31 +1535,31 @@ bool Board320_240::sim800lSetup() { bool sim800l_ready = sim800l->isReady(); for (uint8_t i = 0; i < 5 && !sim800l_ready; i++) { - Serial.println("Problem to initialize SIM800L module, retry in 1 sec"); + syslog->println("Problem to initialize SIM800L module, retry in 1 sec"); delay(1000); sim800l_ready = sim800l->isReady(); } if (!sim800l_ready) { - Serial.println("Problem to initialize SIM800L module"); + syslog->println("Problem to initialize SIM800L module"); } else { - Serial.println("SIM800L module initialized"); + syslog->println("SIM800L module initialized"); - Serial.print("Setting GPRS APN to: "); - Serial.println(liveData->settings.gprsApn); + syslog->print("Setting GPRS APN to: "); + syslog->println(liveData->settings.gprsApn); bool sim800l_gprs = sim800l->setupGPRS(liveData->settings.gprsApn); for (uint8_t i = 0; i < 5 && !sim800l_gprs; i++) { - Serial.println("Problem to set GPRS APN, retry in 1 sec"); + syslog->println("Problem to set GPRS APN, retry in 1 sec"); delay(1000); sim800l_gprs = sim800l->setupGPRS(liveData->settings.gprsApn); } if (sim800l_gprs) { liveData->params.sim800l_enabled = true; - Serial.println("GPRS APN set OK"); + syslog->println("GPRS APN set OK"); } else { - Serial.println("Problem to set GPRS APN"); + syslog->println("Problem to set GPRS APN"); } } @@ -1567,31 +1567,31 @@ bool Board320_240::sim800lSetup() { } bool Board320_240::sendDataViaGPRS() { - Serial.println("Sending data via GPRS"); + syslog->println("Sending data via GPRS"); if (liveData->params.socPerc < 0) { - Serial.println("No valid data, skipping data send"); + syslog->println("No valid data, skipping data send"); return false; } NetworkRegistration network = sim800l->getRegistrationStatus(); if (network != REGISTERED_HOME && network != REGISTERED_ROAMING) { - Serial.println("SIM800L module not connected to network, skipping data send"); + syslog->println("SIM800L module not connected to network, skipping data send"); return false; } if (!sim800l->isConnectedGPRS()) { - Serial.println("GPRS not connected... Connecting"); + syslog->println("GPRS not connected... Connecting"); bool connected = sim800l->connectGPRS(); for (uint8_t i = 0; i < 5 && !connected; i++) { - Serial.println("Problem to connect GPRS, retry in 1 sec"); + syslog->println("Problem to connect GPRS, retry in 1 sec"); delay(1000); connected = sim800l->connectGPRS(); } if (connected) { - Serial.println("GPRS connected!"); + syslog->println("GPRS connected!"); } else { - Serial.println("GPRS not connected! Reseting SIM800L module!"); + syslog->println("GPRS not connected! Reseting SIM800L module!"); sim800l->reset(); sim800lSetup(); @@ -1599,7 +1599,7 @@ bool Board320_240::sendDataViaGPRS() { } } - Serial.println("Start HTTP POST..."); + syslog->println("Start HTTP POST..."); StaticJsonDocument<512> jsonData; @@ -1624,19 +1624,19 @@ bool Board320_240::sendDataViaGPRS() { char payload[512]; serializeJson(jsonData, payload); - Serial.print("Sending payload: "); - Serial.println(payload); + syslog->print("Sending payload: "); + syslog->println(payload); - Serial.print("Remote API server: "); - Serial.println(liveData->settings.remoteApiUrl); + syslog->print("Remote API server: "); + syslog->println(liveData->settings.remoteApiUrl); uint16_t rc = sim800l->doPost(liveData->settings.remoteApiUrl, "application/json", payload, 10000, 10000); if (rc == 200) { - Serial.println("HTTP POST successful"); + syslog->println("HTTP POST successful"); } else { // Failed... - Serial.print("HTTP POST error: "); - Serial.println(rc); + syslog->print("HTTP POST error: "); + syslog->println(rc); } return true; diff --git a/BoardInterface.cpp b/BoardInterface.cpp index b058aa5..bfb2e6c 100644 --- a/BoardInterface.cpp +++ b/BoardInterface.cpp @@ -28,7 +28,7 @@ void BoardInterface::attachCar(CarInterface* pCarInterface) { */ void BoardInterface::shutdownDevice() { - Serial.println("Shutdown."); + syslog->println("Shutdown."); char msg[20]; for (int i = 3; i >= 1; i--) { @@ -65,7 +65,7 @@ void BoardInterface::shutdownDevice() { void BoardInterface::saveSettings() { // Flash to memory - Serial.println("Settings saved to eeprom."); + syslog->println("Settings saved to eeprom."); EEPROM.put(0, liveData->settings); EEPROM.commit(); } @@ -76,7 +76,7 @@ void BoardInterface::saveSettings() { void BoardInterface::resetSettings() { // Flash to memory - Serial.println("Factory reset."); + syslog->println("Factory reset."); liveData->settings.initFlag = 1; EEPROM.put(0, liveData->settings); EEPROM.commit(); @@ -143,17 +143,17 @@ void BoardInterface::loadSettings() { liveData->settings.gprsLogIntervalSec = 60; // Load settings and replace default values - Serial.println("Reading settings from eeprom."); + syslog->println("Reading settings from eeprom."); EEPROM.begin(sizeof(SETTINGS_STRUC)); EEPROM.get(0, liveData->tmpSettings); // Init flash with default settings if (liveData->tmpSettings.initFlag != 183) { - Serial.println("Settings not found. Initialization."); + syslog->println("Settings not found. Initialization."); saveSettings(); } else { - Serial.print("Loaded settings ver.: "); - Serial.println(liveData->tmpSettings.settingsVersion); + syslog->print("Loaded settings ver.: "); + syslog->println(liveData->tmpSettings.settingsVersion); // Upgrade structure if (liveData->settings.settingsVersion != liveData->tmpSettings.settingsVersion) { @@ -219,8 +219,8 @@ void BoardInterface::loadSettings() { void BoardInterface::afterSetup() { // Init Comm iterface - Serial.print("Init communication device: "); - Serial.println(liveData->settings.commType); + syslog->print("Init communication device: "); + syslog->println(liveData->settings.commType); if (liveData->settings.commType == COMM_TYPE_OBD2BLE4) { commInterface = new CommObd2Ble4(); @@ -228,7 +228,7 @@ void BoardInterface::afterSetup() { commInterface = new CommObd2Can(); } else if (liveData->settings.commType == COMM_TYPE_OBD2BT3) { //commInterface = new CommObd2Bt3(); - Serial.println("BT3 not implemented"); + syslog->println("BT3 not implemented"); } commInterface->initComm(liveData, this); diff --git a/CarBmwI3.cpp b/CarBmwI3.cpp index e0e6545..4738b90 100644 --- a/CarBmwI3.cpp +++ b/CarBmwI3.cpp @@ -69,15 +69,15 @@ void CarBmwI3::activateCommandQueue() { void CarBmwI3::parseRowMerged() { -// Serial.println("--Parsing row merged: "); -// Serial.print("--responseRowMerged: "); Serial.println(liveData->responseRowMerged); -// Serial.print("--currentAtshRequest: "); Serial.println(liveData->currentAtshRequest); -// Serial.print("--commandRequest: "); Serial.println(liveData->commandRequest); -// Serial.print("--mergedLength: "); Serial.println(liveData->responseRowMerged.length()); - Serial.print("--mergedVectorLength: "); Serial.println(liveData->vResponseRowMerged.size()); +// syslog->println("--Parsing row merged: "); +// syslog->print("--responseRowMerged: "); syslog->println(liveData->responseRowMerged); +// syslog->print("--currentAtshRequest: "); syslog->println(liveData->currentAtshRequest); +// syslog->print("--commandRequest: "); syslog->println(liveData->commandRequest); +// syslog->print("--mergedLength: "); syslog->println(liveData->responseRowMerged.length()); + syslog->print("--mergedVectorLength: "); syslog->println(liveData->vResponseRowMerged.size()); if (liveData->responseRowMerged.length() <= 6) { - Serial.println("--too short data, skiping processing"); + syslog->println("--too short data, skiping processing"); } struct Header_t @@ -98,8 +98,8 @@ void CarBmwI3::parseRowMerged() std::vector payloadReversed(pHeader->pData, pHeader->pData + payloadLength); std::reverse(payloadReversed.begin(), payloadReversed.end()); - //Serial.print("--extracted PID: "); Serial.println(pHeader->getPid()); - //Serial.print("--payload length: "); Serial.println(payloadLength); + //syslog->print("--extracted PID: "); syslog->println(pHeader->getPid()); + //syslog->print("--payload length: "); syslog->println(payloadLength); // BMS @@ -200,9 +200,9 @@ void CarBmwI3::parseRowMerged() liveData->params.batTempC = ptr->tempAvg / 100.0; liveData->params.batMaxC = ptr->tempMax / 100.0; - Serial.print("----batMinC: "); Serial.println(liveData->params.batMinC); - Serial.print("----batTemp: "); Serial.println(liveData->params.batTempC); - Serial.print("----batMaxC: "); Serial.println(liveData->params.batMaxC); + syslog->print("----batMinC: "); syslog->println(liveData->params.batMinC); + syslog->print("----batTemp: "); syslog->println(liveData->params.batTempC); + syslog->print("----batMaxC: "); syslog->println(liveData->params.batMaxC); } } break; diff --git a/CommInterface.cpp b/CommInterface.cpp index 13ac4a4..53f085f 100644 --- a/CommInterface.cpp +++ b/CommInterface.cpp @@ -19,12 +19,12 @@ void CommInterface::initComm(LiveData* pLiveData, BoardInterface* pBoard) { void CommInterface::mainLoop() { // Send command from TTY to OBD2 - if (Serial.available()) { - ch = Serial.read(); + if (syslog->available()) { + ch = syslog->read(); if (ch == '\r' || ch == '\n') { board->customConsoleCommand(response); response = response + ch; - Serial.println(response); + syslog->println(response); executeCommand(response); response = ""; } else { @@ -59,8 +59,8 @@ bool CommInterface::doNextQueueCommand() { liveData->currentAtshRequest = liveData->commandRequest; } - Serial.print(">>> "); - Serial.println(liveData->commandRequest); + syslog->print(">>> "); + syslog->println(liveData->commandRequest); liveData->responseRowMerged = ""; executeCommand(liveData->commandRequest); liveData->commandQueueIndex++; @@ -72,7 +72,7 @@ bool CommInterface::doNextQueueCommand() { bool CommInterface::parseResponse() { // 1 frame data - Serial.println(liveData->responseRow); + syslog->println(liveData->responseRow); // Merge frames 0:xxxx 1:yyyy 2:zzzz to single response xxxxyyyyzzzz string if (liveData->responseRow.length() >= 2 && liveData->responseRow.charAt(1) == ':') { diff --git a/CommObd2Ble4.cpp b/CommObd2Ble4.cpp index c680a24..dc268a7 100644 --- a/CommObd2Ble4.cpp +++ b/CommObd2Ble4.cpp @@ -14,13 +14,13 @@ class MyClientCallback : public BLEClientCallbacks { // On BLE connect void onConnect(BLEClient* pclient) { - Serial.println("onConnect"); + syslog->println("onConnect"); } // On BLE disconnect void onDisconnect(BLEClient* pclient) { liveDataObj->commConnected = false; - Serial.println("onDisconnect"); + syslog->println("onDisconnect"); boardObj->displayMessage("BLE disconnected", ""); } @@ -34,9 +34,9 @@ class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { // Called for each advertising BLE server. void onResult(BLEAdvertisedDevice advertisedDevice) { - Serial.print("BLE advertised device found: "); - Serial.println(advertisedDevice.toString().c_str()); - Serial.println(advertisedDevice.getAddress().toString().c_str()); + syslog->print("BLE advertised device found: "); + syslog->println(advertisedDevice.toString().c_str()); + syslog->println(advertisedDevice.getAddress().toString().c_str()); // Add to device list (max. 9 devices allowed yet) String tmpStr; @@ -56,17 +56,17 @@ class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { } // if (advertisedDevice.getServiceDataUUID().toString() != "") { - // Serial.print("ServiceDataUUID: "); - // Serial.println(advertisedDevice.getServiceDataUUID().toString().c_str()); + // syslog->print("ServiceDataUUID: "); + // syslog->println(advertisedDevice.getServiceDataUUID().toString().c_str()); // if (advertisedDevice.getServiceUUID().toString() != "") { - // Serial.print("ServiceUUID: "); - // Serial.println(advertisedDevice.getServiceUUID().toString().c_str()); + // syslog->print("ServiceUUID: "); + // syslog->println(advertisedDevice.getServiceUUID().toString().c_str()); // } // } if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(BLEUUID(liveDataObj->settings.serviceUUID)) && (strcmp(advertisedDevice.getAddress().toString().c_str(), liveDataObj->settings.obdMacAddress) == 0)) { - Serial.println("Stop scanning. Found my BLE device."); + syslog->println("Stop scanning. Found my BLE device."); BLEDevice::getScan()->stop(); liveDataObj->foundMyBleDevice = new BLEAdvertisedDevice(advertisedDevice); } @@ -81,29 +81,29 @@ uint32_t PIN = 1234; class MySecurity : public BLESecurityCallbacks { uint32_t onPassKeyRequest() { - Serial.printf("Pairing password: %d \r\n", PIN); + syslog->printf("Pairing password: %d \r\n", PIN); return PIN; } void onPassKeyNotify(uint32_t pass_key) { - Serial.printf("onPassKeyNotify\r\n"); + syslog->printf("onPassKeyNotify\r\n"); } bool onConfirmPIN(uint32_t pass_key) { - Serial.printf("onConfirmPIN\r\n"); + syslog->printf("onConfirmPIN\r\n"); return true; } bool onSecurityRequest() { - Serial.printf("onSecurityRequest\r\n"); + syslog->printf("onSecurityRequest\r\n"); return true; } void onAuthenticationComplete(esp_ble_auth_cmpl_t auth_cmpl) { if (auth_cmpl.success) { - Serial.printf("onAuthenticationComplete\r\n"); + syslog->printf("onAuthenticationComplete\r\n"); } else { - Serial.println("Auth failure. Incorrect PIN?"); + syslog->println("Auth failure. Incorrect PIN?"); liveDataObj->bleConnect = false; } } @@ -129,8 +129,8 @@ static void notifyCallback (BLERemoteCharacteristic * pBLERemoteCharacteristic, liveDataObj->responseRow += ch; if (liveDataObj->responseRow == ">") { if (liveDataObj->responseRowMerged != "") { - Serial.print("merged:"); - Serial.println(liveDataObj->responseRowMerged); + syslog->print("merged:"); + syslog->println(liveDataObj->responseRowMerged); boardObj->parseRowMerged(); } liveDataObj->responseRowMerged = ""; @@ -149,7 +149,7 @@ void CommObd2Ble4::connectDevice() { liveDataObj = liveData; boardObj = board; - Serial.println("BLE4 connectDevice"); + syslog->println("BLE4 connectDevice"); // Start BLE connection ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT)); @@ -157,7 +157,7 @@ void CommObd2Ble4::connectDevice() { // Retrieve a Scanner and set the callback we want to use to be informed when we have detected a new device. // Specify that we want active scanning and start the scan to run for 10 seconds. - Serial.println("Setup BLE scan"); + syslog->println("Setup BLE scan"); liveData->pBLEScan = BLEDevice::getScan(); liveData->pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); liveData->pBLEScan->setInterval(1349); @@ -166,7 +166,7 @@ void CommObd2Ble4::connectDevice() { // Skip BLE scan if middle button pressed if (strcmp(liveData->settings.obdMacAddress, "00:00:00:00:00:00") != 0 && !board->skipAdapterScan()) { - Serial.println(liveData->settings.obdMacAddress); + syslog->println(liveData->settings.obdMacAddress); startBleScan(); } } @@ -176,7 +176,7 @@ void CommObd2Ble4::connectDevice() { */ void CommObd2Ble4::disconnectDevice() { - Serial.println("COMM disconnectDevice"); + syslog->println("COMM disconnectDevice"); btStop(); } @@ -185,7 +185,7 @@ void CommObd2Ble4::disconnectDevice() { */ void CommObd2Ble4::scanDevices() { - Serial.println("COMM scanDevices"); + syslog->println("COMM scanDevices"); startBleScan(); } @@ -201,13 +201,13 @@ void CommObd2Ble4::startBleScan() { board->displayMessage(" > Scanning BLE4 devices", "40sec.or hold middle&RST"); // Start scanning - Serial.println("Scanning BLE devices..."); - Serial.print("Looking for "); - Serial.println(liveData->settings.obdMacAddress); + syslog->println("Scanning BLE devices..."); + syslog->print("Looking for "); + syslog->println(liveData->settings.obdMacAddress); BLEScanResults foundDevices = liveData->pBLEScan->start(40, false); - Serial.print("Devices found: "); - Serial.println(foundDevices.getCount()); - Serial.println("Scan done!"); + syslog->print("Devices found: "); + syslog->println(foundDevices.getCount()); + syslog->println("Scan done!"); liveData->pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory char tmpStr1[20]; @@ -216,7 +216,7 @@ void CommObd2Ble4::startBleScan() { // Scan devices from menu, show list of devices if (liveData->menuCurrent == 9999) { - Serial.println("Display menu with devices"); + syslog->println("Display menu with devices"); liveData->menuVisible = true; //liveData->menuCurrent = 9999; liveData->menuItemSelected = 0; @@ -238,8 +238,8 @@ bool CommObd2Ble4::connectToServer(BLEAddress pAddress) { board->displayMessage(" > Connecting device", ""); - Serial.print("liveData->bleConnect "); - Serial.println(pAddress.toString().c_str()); + syslog->print("liveData->bleConnect "); + syslog->println(pAddress.toString().c_str()); board->displayMessage(" > Connecting device - init", pAddress.toString().c_str()); BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT); @@ -253,49 +253,49 @@ bool CommObd2Ble4::connectToServer(BLEAddress pAddress) { board->displayMessage(" > Connecting device", pAddress.toString().c_str()); liveData->pClient = BLEDevice::createClient(); liveData->pClient->setClientCallbacks(new MyClientCallback()); - if (liveData->pClient->connect(pAddress, BLE_ADDR_TYPE_RANDOM) ) Serial.println("liveData->bleConnected"); - Serial.println(" - liveData->bleConnected to server"); + if (liveData->pClient->connect(pAddress, BLE_ADDR_TYPE_RANDOM) ) syslog->println("liveData->bleConnected"); + syslog->println(" - liveData->bleConnected to server"); // Remote service board->displayMessage(" > Connecting device", "Connecting service..."); BLERemoteService* pRemoteService = liveData->pClient->getService(BLEUUID(liveData->settings.serviceUUID)); if (pRemoteService == nullptr) { - Serial.print("Failed to find our service UUID: "); - Serial.println(liveData->settings.serviceUUID); + syslog->print("Failed to find our service UUID: "); + syslog->println(liveData->settings.serviceUUID); board->displayMessage(" > Connecting device", "Unable to find service"); return false; } - Serial.println(" - Found our service"); + syslog->println(" - Found our service"); // Get characteristics board->displayMessage(" > Connecting device", "Connecting TxUUID..."); liveData->pRemoteCharacteristic = pRemoteService->getCharacteristic(BLEUUID(liveData->settings.charTxUUID)); if (liveData->pRemoteCharacteristic == nullptr) { - Serial.print("Failed to find our characteristic UUID: "); - Serial.println(liveData->settings.charTxUUID);//.toString().c_str()); + syslog->print("Failed to find our characteristic UUID: "); + syslog->println(liveData->settings.charTxUUID);//.toString().c_str()); board->displayMessage(" > Connecting device", "Unable to find TxUUID"); return false; } - Serial.println(" - Found our characteristic"); + syslog->println(" - Found our characteristic"); // Get characteristics board->displayMessage(" > Connecting device", "Connecting RxUUID..."); liveData->pRemoteCharacteristicWrite = pRemoteService->getCharacteristic(BLEUUID(liveData->settings.charRxUUID)); if (liveData->pRemoteCharacteristicWrite == nullptr) { - Serial.print("Failed to find our characteristic UUID: "); - Serial.println(liveData->settings.charRxUUID);//.toString().c_str()); + syslog->print("Failed to find our characteristic UUID: "); + syslog->println(liveData->settings.charRxUUID);//.toString().c_str()); board->displayMessage(" > Connecting device", "Unable to find RxUUID"); return false; } - Serial.println(" - Found our characteristic write"); + syslog->println(" - Found our characteristic write"); board->displayMessage(" > Connecting device", "Register callbacks..."); // Read the value of the characteristic. if (liveData->pRemoteCharacteristic->canNotify()) { - Serial.println(" - canNotify"); + syslog->println(" - canNotify"); if (liveData->pRemoteCharacteristic->canIndicate()) { - Serial.println(" - canIndicate"); + syslog->println(" - canIndicate"); const uint8_t indicationOn[] = {0x2, 0x0}; //const uint8_t indicationOff[] = {0x0,0x0}; liveData->pRemoteCharacteristic->getDescriptor(BLEUUID((uint16_t)0x2902))->writeValue((uint8_t*)indicationOn, 2, true); @@ -307,7 +307,7 @@ bool CommObd2Ble4::connectToServer(BLEAddress pAddress) { board->displayMessage(" > Connecting device", "Done..."); if (liveData->pRemoteCharacteristicWrite->canWrite()) { - Serial.println(" - canWrite"); + syslog->println(" - canWrite"); } return true; @@ -326,7 +326,7 @@ void CommObd2Ble4::mainLoop() { liveData->commConnected = true; liveData->bleConnect = false; - Serial.println("We are now connected to the BLE device."); + syslog->println("We are now connected to the BLE device."); // Print message board->displayMessage(" > Processing init AT cmds", ""); @@ -335,7 +335,7 @@ void CommObd2Ble4::mainLoop() { doNextQueueCommand(); } else { - Serial.println("We have failed to connect to the server; there is nothing more we will do."); + syslog->println("We have failed to connect to the server; there is nothing more we will do."); } } diff --git a/CommObd2Can.cpp b/CommObd2Can.cpp index 6cd1767..7d5ac4a 100644 --- a/CommObd2Can.cpp +++ b/CommObd2Can.cpp @@ -10,22 +10,22 @@ */ void CommObd2Can::connectDevice() { - Serial.println("CAN connectDevice"); + syslog->println("CAN connectDevice"); //CAN = new MCP_CAN(pinCanCs); // todo: remove if smart pointer is ok CAN.reset(new MCP_CAN(pinCanCs)); // smart pointer so it's automatically cleaned when out of context and also free to re-init if (CAN == nullptr) { - Serial.println("Error: Not enough memory to instantiate CAN class"); - Serial.println("init_can() failed"); + syslog->println("Error: Not enough memory to instantiate CAN class"); + syslog->println("init_can() failed"); return; } // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled. if (CAN->begin(MCP_STDEXT, CAN_500KBPS, MCP_8MHZ) == CAN_OK) { - Serial.println("MCP2515 Initialized Successfully!"); + syslog->println("MCP2515 Initialized Successfully!"); board->displayMessage(" > CAN init OK", ""); } else { - Serial.println("Error Initializing MCP2515..."); + syslog->println("Error Initializing MCP2515..."); board->displayMessage(" > CAN init failed", ""); return; } @@ -40,7 +40,7 @@ void CommObd2Can::connectDevice() { } if (MCP2515_OK != CAN->setMode(MCP_NORMAL)) { // Set operation mode to normal so the MCP2515 sends acks to received data. - Serial.println("Error: CAN->setMode(MCP_NORMAL) failed"); + syslog->println("Error: CAN->setMode(MCP_NORMAL) failed"); board->displayMessage(" > CAN init failed", ""); return; } @@ -51,7 +51,7 @@ void CommObd2Can::connectDevice() { liveData->commConnected = true; doNextQueueCommand(); - Serial.println("init_can() done"); + syslog->println("init_can() done"); } /** @@ -60,7 +60,7 @@ void CommObd2Can::connectDevice() { void CommObd2Can::disconnectDevice() { liveData->commConnected = false; - Serial.println("COMM disconnectDevice"); + syslog->println("COMM disconnectDevice"); } /** @@ -68,7 +68,7 @@ void CommObd2Can::disconnectDevice() { */ void CommObd2Can::scanDevices() { - Serial.println("COMM scanDevices"); + syslog->println("COMM scanDevices"); } /** @@ -90,7 +90,7 @@ void CommObd2Can::mainLoop() { delay(1); // apply timeout for next frames loop too if (lastDataSent != 0 && (unsigned long)(millis() - lastDataSent) > 100) { - Serial.print("CAN execution timeout (multiframe message).\n"); + syslog->print("CAN execution timeout (multiframe message).\n"); break; } } @@ -101,7 +101,7 @@ void CommObd2Can::mainLoop() { } } if (lastDataSent != 0 && (unsigned long)(millis() - lastDataSent) > 100) { - Serial.print("CAN execution timeout. Continue with next command.\n"); + syslog->print("CAN execution timeout. Continue with next command.\n"); liveData->canSendNextAtCommand = true; return; } @@ -112,8 +112,8 @@ void CommObd2Can::mainLoop() { */ void CommObd2Can::executeCommand(String cmd) { - Serial.print("executeCommand "); - Serial.println(cmd); + syslog->print("executeCommand "); + syslog->println(cmd); if (cmd.equals("") || cmd.startsWith("AT")) { // skip AT commands as not used by direct CAN connection lastDataSent = 0; @@ -184,17 +184,17 @@ void CommObd2Can::sendPID(const uint16_t pid, const String& cmd) { const uint8_t sndStat = CAN->sendMsgBuf(pid, 0, 8, txBuf); // 11 bit // uint8_t sndStat = CAN->sendMsgBuf(0x7e4, 1, 8, tmp); // 29 bit extended frame if (sndStat == CAN_OK) { - Serial.print("SENT "); + syslog->print("SENT "); lastDataSent = millis(); } else { - Serial.print("Error sending PID "); + syslog->print("Error sending PID "); } - Serial.print(pid); + syslog->print(pid); for (uint8_t i = 0; i < 8; i++) { sprintf(msgString, " 0x%.2X", txBuf[i]); - Serial.print(msgString); + syslog->print(msgString); } - Serial.println(""); + syslog->println(""); } /** @@ -212,16 +212,16 @@ void CommObd2Can::sendFlowControlFrame() { const uint8_t sndStat = CAN->sendMsgBuf(lastPid, 0, 8, txBuf); // 11 bit if (sndStat == CAN_OK) { - Serial.print("Flow control frame sent "); + syslog->print("Flow control frame sent "); } else { - Serial.print("Error sending flow control frame "); + syslog->print("Error sending flow control frame "); } - Serial.print(lastPid); + syslog->print(lastPid); for (auto txByte : txBuf) { sprintf(msgString, " 0x%.2X", txByte); - Serial.print(msgString); + syslog->print(msgString); } - Serial.println(""); + syslog->println(""); } /** @@ -232,7 +232,7 @@ uint8_t CommObd2Can::receivePID() { if (!digitalRead(pinCanInt)) // If CAN0_INT pin is low, read receive buffer { lastDataSent = millis(); - Serial.print(" CAN READ "); + syslog->print(" CAN READ "); CAN->readMsgBuf(&rxId, &rxLen, rxBuf); // Read data: len = data length, buf = data byte(s) // mockupReceiveCanBuf(&rxId, &rxLen, rxBuf); @@ -241,22 +241,22 @@ uint8_t CommObd2Can::receivePID() { else sprintf(msgString, "Standard ID: 0x%.3lX DLC: %1d Data:", rxId, rxLen); - Serial.print(msgString); + syslog->print(msgString); if ((rxId & 0x40000000) == 0x40000000) { // Determine if message is a remote request frame. sprintf(msgString, " REMOTE REQUEST FRAME"); - Serial.print(msgString); + syslog->print(msgString); } else { for (uint8_t i = 0; i < rxLen; i++) { sprintf(msgString, " 0x%.2X", rxBuf[i]); - Serial.print(msgString); + syslog->print(msgString); } } // Check if this packet shall be discarded due to its length. // If liveData->expectedPacketLength is set to 0, accept any length. if(liveData->expectedMinimalPacketLength != 0 && rxLen < liveData->expectedMinimalPacketLength) { - Serial.println(" [Ignored packet]"); + syslog->println(" [Ignored packet]"); return 0xff; } @@ -265,16 +265,16 @@ uint8_t CommObd2Can::receivePID() { long unsigned int atsh_response = liveData->hexToDec(liveData->currentAtshRequest.substring(4), 2, false) + 8; if(rxId != atsh_response) { - Serial.println(" [Filtered packet]"); + syslog->println(" [Filtered packet]"); return 0xff; } } - Serial.println(); + syslog->println(); processFrameBytes(); //processFrame(); } else { - //Serial.println(" CAN NOT READ "); + //syslog->println(" CAN NOT READ "); return 0xff; } @@ -287,11 +287,11 @@ static void printHexBuffer(uint8_t* pData, const uint16_t length, const bool bAd for (uint8_t i = 0; i < length; i++) { sprintf(str, " 0x%.2X", pData[i]); - Serial.print(str); + syslog->print(str); } if (bAddNewLine) { - Serial.println(); + syslog->println(); } } @@ -348,7 +348,7 @@ bool CommObd2Can::processFrameBytes() { rxRemaining = 0; - //Serial.print("----Processing SingleFrame payload: "); printHexBuffer(pSingleFrame->pData, pSingleFrame->size, true); + //syslog->print("----Processing SingleFrame payload: "); printHexBuffer(pSingleFrame->pData, pSingleFrame->size, true); // single frame - process directly buffer2string(liveData->responseRowMerged, mergedData.data(), mergedData.size()); @@ -381,7 +381,7 @@ bool CommObd2Can::processFrameBytes() { dataRows[0].assign(pFirstFrame->pData, pFirstFrame->pData + framePayloadSize); rxRemaining -= framePayloadSize; - //Serial.print("----Processing FirstFrame payload: "); printHexBuffer(pFirstFrame->pData, framePayloadSize, true); + //syslog->print("----Processing FirstFrame payload: "); printHexBuffer(pFirstFrame->pData, framePayloadSize, true); } break; @@ -395,19 +395,19 @@ bool CommObd2Can::processFrameBytes() { }; const uint8_t structSize = sizeof(ConsecutiveFrame_t); - //Serial.print("[debug] sizeof(ConsecutiveFrame_t) is expected to be 1 and it's "); Serial.println(structSize); + //syslog->print("[debug] sizeof(ConsecutiveFrame_t) is expected to be 1 and it's "); syslog->println(structSize); ConsecutiveFrame_t* pConseqFrame = (ConsecutiveFrame_t*)pDataStart; const uint8_t framePayloadSize = frameLenght - sizeof(ConsecutiveFrame_t); // remove one byte of header dataRows[pConseqFrame->index].assign(pConseqFrame->pData, pConseqFrame->pData + framePayloadSize); rxRemaining -= framePayloadSize; - //Serial.print("----Processing ConsecFrame payload: "); printHexBuffer(pConseqFrame->pData, framePayloadSize, true); + //syslog->print("----Processing ConsecFrame payload: "); printHexBuffer(pConseqFrame->pData, framePayloadSize, true); } break; default: - Serial.print("Unknown frame type within CommObd2Can::processFrameBytes(): "); Serial.println((uint8_t)frameType); + syslog->print("Unknown frame type within CommObd2Can::processFrameBytes(): "); syslog->println((uint8_t)frameType); return false; break; } // \switch (frameType) @@ -416,10 +416,10 @@ bool CommObd2Can::processFrameBytes() { if (rxRemaining <= 0) { // multiple frames and no data remaining - merge everything to single packet for (int i = 0; i < dataRows.size(); i++) { - //Serial.print("------merging packet index "); - //Serial.print(i); - //Serial.print(" with length "); - //Serial.println(dataRows[i].size()); + //syslog->print("------merging packet index "); + //syslog->print(i); + //syslog->print(" with length "); + //syslog->println(dataRows[i].size()); mergedData.insert(mergedData.end(), dataRows[i].begin(), dataRows[i].end()); } @@ -467,11 +467,11 @@ bool CommObd2Can::processFrame() { break; } - Serial.print("> frametype:"); - Serial.print(frameType); - Serial.print(", r: "); - Serial.print(rxRemaining); - Serial.print(" "); + syslog->print("> frametype:"); + syslog->print(frameType); + syslog->print(", r: "); + syslog->print(rxRemaining); + syslog->print(" "); for (uint8_t i = start; i < rxLen; i++) { sprintf(msgString, "%.2X", rxBuf[i]); @@ -479,14 +479,14 @@ bool CommObd2Can::processFrame() { rxRemaining--; } - Serial.print(", r: "); - Serial.print(rxRemaining); - Serial.println(" "); + syslog->print(", r: "); + syslog->print(rxRemaining); + syslog->println(" "); //parseResponse(); // We need to sort frames // 1 frame data - Serial.println(liveData->responseRow); + syslog->println(liveData->responseRow); // Merge frames 0:xxxx 1:yyyy 2:zzzz to single response xxxxyyyyzzzz string if (liveData->responseRow.length() >= 2 && liveData->responseRow.charAt(1) == ':') { //liveData->responseRowMerged += liveData->responseRow.substring(2); @@ -494,7 +494,7 @@ bool CommObd2Can::processFrame() { uint16_t startPos = (rowNo * 14) - ((rowNo > 0) ? 2 : 0); uint16_t endPos = ((rowNo + 1) * 14) - ((rowNo > 0) ? 2 : 0); liveData->responseRowMerged = liveData->responseRowMerged.substring(0, startPos) + liveData->responseRow.substring(2) + liveData->responseRowMerged.substring(endPos); - Serial.println(liveData->responseRowMerged); + syslog->println(liveData->responseRowMerged); } // Send response to board module @@ -510,8 +510,8 @@ bool CommObd2Can::processFrame() { processMergedResponse */ void CommObd2Can::processMergedResponse() { - Serial.print("merged:"); - Serial.println(liveData->responseRowMerged); + syslog->print("merged:"); + syslog->println(liveData->responseRowMerged); board->parseRowMerged(); liveData->responseRowMerged = ""; liveData->canSendNextAtCommand = true; diff --git a/LiveData.cpp b/LiveData.cpp index ca13483..87e1a7e 100644 --- a/LiveData.cpp +++ b/LiveData.cpp @@ -1,11 +1,13 @@ #include "LiveData.h" #include "menu.h" +LogSerial* syslog; + /** * Debug level */ void debug(String msg, uint8_t debugLevel) { - Serial.println(msg); + syslog->println(msg); } /** diff --git a/LiveData.h b/LiveData.h index 1f57de0..c0efadf 100644 --- a/LiveData.h +++ b/LiveData.h @@ -7,6 +7,7 @@ #include #include #include "config.h" +#include "LogSerial.h" #include // SUPPORTED CARS @@ -34,15 +35,11 @@ #define SCREEN_CHARGING 5 #define SCREEN_SOC10 6 -// DEBUG LEVEL -#define DEBUG_INFO 0 -#define DEBUG_COMM 1 -#define DEBUG_GPS 2 -#define DEBUG_SDCARD 3 - // #define MONTH_SEC 2678400 +extern LogSerial* syslog; + // Structure with realtime values typedef struct { // System @@ -215,9 +212,6 @@ typedef struct { // } SETTINGS_STRUC; -// Debug functions -void debug(String msg, uint8_t debugLevel = DEBUG_INFO); - // LiveData class class LiveData { protected: diff --git a/LogSerial.cpp b/LogSerial.cpp new file mode 100644 index 0000000..8a92ad8 --- /dev/null +++ b/LogSerial.cpp @@ -0,0 +1,8 @@ +#include "LogSerial.h" + +/** + * Constructor + */ +LogSerial::LogSerial() : HardwareSerial(0) { + HardwareSerial::begin(115200); +} diff --git a/LogSerial.h b/LogSerial.h new file mode 100644 index 0000000..ffe9d0a --- /dev/null +++ b/LogSerial.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +// DEBUG LEVEL +#define DEBUG_NONE 0 +#define DEBUG_COMM 1 // filter comm +#define DEBUG_GPS 2 // filter gps messages +#define DEBUG_SDCARD 3 // filter sdcard + +// +class LogSerial: public HardwareSerial { + protected: + + public: + LogSerial(); + /*virtual void infoNolfType(String msg, uint8_t debugLevel = TYPE_NONE); + virtual void infoType(String msg, uint8_t debugLevel = TYPE_NONE); + /* + template void infoNolf(String msg, uint8_t debugLevel = TYPE_NONE); + template void info(String msg, uint8_t debugLevel = DEBUG_ALL); + template void warnNolf(String msg, uint8_t debugLevel = DEBUG_ALL); + template void warn(String msg, uint8_t debugLevel = DEBUG_ALL); + template void errNolf(String msg, uint8_t debugLevel = DEBUG_ALL); + template void err(String msg, uint8_t debugLevel = DEBUG_ALL);*/ + +}; diff --git a/evDash.ino b/evDash.ino index e2cdabf..34ac43c 100644 --- a/evDash.ino +++ b/evDash.ino @@ -63,19 +63,19 @@ LiveData* liveData; */ void setup(void) { - // Serial console, init structures - Serial.begin(115200); - debug("\nBooting device..."); - + // Serial console + syslog = new LogSerial(); + syslog->println("\nBooting device..."); + // Init settings/params liveData = new LiveData(); liveData->initParams(); // Turn off serial console - if (liveData->settings.serialConsolePort = 255) { - debug("Serial console disabled..."); - Serial.flush(); - Serial.end(); + if (liveData->settings.serialConsolePort == 255) { + syslog->println("Serial console disabled..."); + syslog->flush(); + syslog->end(); } // Init board @@ -124,7 +124,7 @@ void setup(void) { board->afterSetup(); // End - Serial.println("Device setup completed"); + syslog->println("Device setup completed"); } /**