Update the API use Stream instead of Hardware/Software serial

This commit is contained in:
Phat Nguyen
2024-09-24 20:07:14 +07:00
parent ebb3f01dcd
commit cb511903ef
6 changed files with 38 additions and 38 deletions

View File

@ -4,32 +4,33 @@
/**
* @brief Initializes the sensor and attempts to read data.
*
* @param HardwareSerial UART stream
* @param stream UART stream
* @return true Sucecss
* @return false Failure
*/
bool PMSBase::begin(HardwareSerial &serial) {
bool PMSBase::begin(Stream *stream) {
Serial.printf("initializing PM sensor\n");
failCount = 0;
_connected = false;
// Run and check sensor data for 4sec
int bytesCleared = serial.available();
serial.flush();
if (bytesCleared) {
Serial.printf("cleared %d byte(s)\n", bytesCleared);
// empty first
int bytesCleared = 0;
while (stream->read() != -1) {
bytesCleared++;
}
Serial.printf("cleared %d byte(s)\n", bytesCleared);
// explicitly put the sensor into active mode, this seems to be be needed for
// the Cubic PM2009X
Serial.printf("Setting active mode\n");
uint8_t activeModeCommand[] = {0x42, 0x4D, 0xE1, 0x00, 0x01, 0x01, 0x71};
size_t bytesWritten =
serial.write(activeModeCommand, sizeof(activeModeCommand));
// explicitly put the sensor into active mode, this seems to be be needed for the Cubic PM2009X
Serial.printf("setting active mode\n");
uint8_t activeModeCommand[] = { 0x42, 0x4D, 0xE1, 0x00, 0x01, 0x01, 0x71 };
size_t bytesWritten = stream->write(activeModeCommand, sizeof(activeModeCommand));
Serial.printf("%d byte(s) written\n", bytesWritten);
// Run and check sensor data for 4sec
unsigned long lastInit = millis();
while (true) {
readPackage(serial);
readPackage(stream);
if (_connected) {
break;
}
@ -37,15 +38,9 @@ bool PMSBase::begin(HardwareSerial &serial) {
delay(1);
unsigned long ms = (unsigned long)(millis() - lastInit);
if (ms >= 4000) {
Serial.println("Initialize PMS sensor: Timeout");
break;
}
}
if (_connected) {
Serial.println("Initialize PMS sensor");
}
return _connected;
}
@ -54,7 +49,7 @@ bool PMSBase::begin(HardwareSerial &serial) {
*
* @param serial
*/
void PMSBase::readPackage(HardwareSerial &serial) {
void PMSBase::readPackage(Stream *serial) {
/** If readPackage has process as period larger than READ_PACKAGE_TIMEOUT,
* should be clear the lastPackage and readBufferIndex */
if (lastReadPackage) {
@ -83,9 +78,9 @@ void PMSBase::readPackage(HardwareSerial &serial) {
/** Count to call delay() to release the while loop MCU resource for avoid the
* watchdog time reset */
uint8_t delayCount = 0;
while (serial.available()) {
while (serial->available()) {
/** Get value */
uint8_t value = (uint8_t)serial.read();
uint8_t value = (uint8_t)serial->read();
/** Process receiving package... */
switch (readBufferIndex) {