58 String BinarySensor_VERSION =
"0.1.0";
67 unsigned long basePollRate = 500000L;
68 uint32_t pollRateMs = 2000;
69 uint32_t lastPollMs = 0;
71 bool initialPublish =
false;
74 BinarySensor(String name, uint8_t digitalPort,
bool inverseLogic =
false, String topicName =
"state")
75 : name(name), digitalPort(digitalPort), inverseLogic(inverseLogic), topicName(topicName) {
95 physicalState = digitalRead(digitalPort);
107 physicalState = digitalRead(digitalPort);
109 logicalState = !physicalState;
111 logicalState = physicalState;
116 void begin(Scheduler *_pSched, uint32_t _pollRateMs = 2000) {
123 pollRateMs = _pollRateMs;
125 auto ft = [=]() { this->loop(); };
126 tID = pSched->add(ft, name, basePollRate);
128 pinMode(digitalPort, INPUT_PULLUP);
130 initialPublish =
false;
132 auto fnall = [=](String topic, String msg, String originator) {
133 this->subsMsg(topic, msg, originator);
135 pSched->subscribe(tID, name +
"/sensor/#", fnall);
136 pSched->subscribe(tID, name +
"/binary_sensor/#", fnall);
137 pSched->subscribe(tID, name +
"/mqtt/state", fnall);
142 void publishPhysicalState() {
149 pSched->publish(name +
"/sensor/physical/" + topicName, buf);
150 pSched->publish(name +
"/binary_sensor/physical/" + topicName, buf);
153 void publishBinarySensor() {
160 pSched->publish(name +
"/sensor/" + topicName, buf);
161 pSched->publish(name +
"/binary_sensor/" + topicName, buf);
166 if (timeDiff(lastPollMs, millis()) >= pollRateMs || !initialPublish) {
167 bool hasChanged =
false;
168 lastPollMs = millis();
169 bool oldLogicalState = logicalState;
171 if (st != oldLogicalState || !initialPublish) {
175 publishBinarySensor();
176 initialPublish =
true;
182 void subsMsg(String topic, String msg, String originator) {
183 if (topic == name +
"/sensor/" + topicName +
"/get" || topic == name +
"/binary_sensor/" + topicName +
"/get") {
184 publishBinarySensor();
185 }
else if (topic == name +
"/sensor/physical/" + topicName +
"/get" || topic == name +
"/binary_sensor/physical/" + topicName +
"/get") {
186 publishBinarySensor();
187 }
else if (topic == name +
"mqtt/state") {
188 if (msg ==
"connected") {
189 initialPublish =
false;
mupplet-sensor, binary sensor
Definition: mup_binary_sensor.h:56
bool getBinarySensorLogicalState()
Definition: mup_binary_sensor.h:99
BinarySensor(String name, uint8_t digitalPort, bool inverseLogic=false, String topicName="state")
Definition: mup_binary_sensor.h:74
void begin(Scheduler *_pSched, uint32_t _pollRateMs=2000)
Definition: mup_binary_sensor.h:116
bool getPhysicalState()
Definition: mup_binary_sensor.h:87