69 lines
1.7 KiB
C++
69 lines
1.7 KiB
C++
|
#include "geiger_counter_sensor.h"
|
||
|
#include "esphome/core/log.h"
|
||
|
#include "esphome.h"
|
||
|
|
||
|
namespace esphome {
|
||
|
namespace geiger_counter_sensor {
|
||
|
|
||
|
static const char *TAG = "geiger_counter_sensor.sensor";
|
||
|
|
||
|
|
||
|
void GeigerCounterSensor::setup() {
|
||
|
ESP_LOGCONFIG(TAG, "Setting up Geiger Counter Sensor...");
|
||
|
}
|
||
|
|
||
|
void GeigerCounterSensor::loop() {
|
||
|
const int max_line_length = 80;
|
||
|
static char buffer[max_line_length];
|
||
|
while (available()) {
|
||
|
if(readline(read(), buffer, max_line_length) > 0) {
|
||
|
int cpm = atof(buffer);
|
||
|
float usv = cpm * 0.0057;
|
||
|
ESP_LOGCONFIG(TAG, "Received radiation level: %d cpm, %.2f μSv", cpm, usv);
|
||
|
this->publish_state(usv);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
void GeigerCounterSensor::dump_config() {
|
||
|
LOG_SENSOR("", "Geiger Counter Sensor", this);
|
||
|
}
|
||
|
|
||
|
void GeigerCounterSensor::update() {
|
||
|
|
||
|
}
|
||
|
|
||
|
} // namespace geiger_counter_sensor
|
||
|
} // namespace esphome
|
||
|
|
||
|
int readline(int readch, char *buffer, int len) {
|
||
|
static int pos = 0;
|
||
|
int rpos;
|
||
|
|
||
|
if (readch > 0) {
|
||
|
switch (readch) {
|
||
|
case '\n':
|
||
|
case '\r': // Return on CR or newline
|
||
|
buffer[pos] = 0; // Just to be sure, set last character 0
|
||
|
rpos = pos;
|
||
|
pos = 0; // Reset position index ready for next time
|
||
|
return rpos;
|
||
|
default:
|
||
|
if ((pos < len-1) && ( readch < 127 )) { // Filter on <127 to make sure it is a character
|
||
|
buffer[pos++] = readch;
|
||
|
buffer[pos] = 0;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
buffer[pos] = 0; // Just to be sure, set last character 0
|
||
|
rpos = pos;
|
||
|
pos = 0; // Reset position index ready for next time
|
||
|
return rpos;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
// No end of line has been found, so return -1.
|
||
|
return -1;
|
||
|
}
|