i ready now. esphome with pulse_counter or pulse_meter works not good in my case.
i try different settings, all values in home assistant are to high after a while. i dont know why.
esphome read more counters as in real.
so, im back to this arduino script, and change it to:
/****************************************************************
*
* Code for GasMeter
* created: Alexander Kabza, 2017-03-15
* V2.05: 2020-02-23 Minor code optimization
* use /SetValue?Value=xx to set new value
****************************************************************/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <TimeLib.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#define LED_PIN 0
#define IN_PIN 2
String DEVICENAME = "ESP8266_ESP01_GasMeter";
String CODEVERSION = "V2.05 xml mod";
int actual = 1;
int prev = 1;
long int value = 0;
String MACStr;
unsigned long prevWIFIMillis = 0; // WIFI check trigger
unsigned long prevNTPMillis = 0; // Trigger per hour
unsigned long prevLEDMillis = 0; // Trigger for LED
unsigned long WIFIConnectCounter = 0;
unsigned long startEpochTime = 0;
unsigned long elapsedEpochTime = 0;
String formattedDateTime;
String formattedStartDateTime;
float RunTimeHours = 0;
//------------------------------------------
//WIFI
const char* ssid = "my_ssid";
const char* password = "my_password";
IPAddress ip(192,168,1,112); // Static IP
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
IPAddress nameserver(192,168,1,1);
//------------------------------------------
//HTTP
ESP8266WebServer server(80);
// NTP Servers:
static const char ntpServerName[] = "de.pool.ntp.org";
const int timeZone = 1; // Central European Time
WiFiUDP Udp;
unsigned int localPort = 8888; // local port to listen for UDP packets
time_t getNtpTime();
void digitalClockDisplay();
void printDigits(int digits);
void sendNTPpacket(IPAddress &address);
// ****************************************************************
String GetDateTime() {
char dt[19];
sprintf(dt, "%4d-%02d-%02d %02d:%02d:%02d", year(), month(), day(), hour(), minute(), second());
String strdt = String(dt);
return strdt;
} // GetDateTime()
void printDigits(int digits)
{
// utility for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}
/*-------- NTP code ----------*/
const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
time_t getNtpTime()
{
IPAddress ntpServerIP; // NTP server's ip address
while (Udp.parsePacket() > 0) ; // discard any previously received packets
Serial.println("Transmit NTP Request");
// get a random server from the pool
WiFi.hostByName(ntpServerName, ntpServerIP);
Serial.print(ntpServerName);
Serial.print(": ");
Serial.println(ntpServerIP);
sendNTPpacket(ntpServerIP);
uint32_t beginWait = millis();
while (millis() - beginWait < 1500) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
Serial.println("Receive NTP Response");
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
}
}
Serial.println("No NTP Response :-(");
return 0; // return 0 if unable to get the time
}
// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
}
// ****************************************************************
String ToHEX(unsigned char* bytearray, uint8_t arraysize){
String str = "";
for (uint8_t i = 0; i < arraysize; i++){
if (i > 0) str += ":";
if (bytearray[i] < 16) str += String(0, HEX);
str += String(bytearray[i], HEX);
}
return str;
}
// ****************************************************************
void handleRoot() { //Handler
String msg = "";
msg += "<div class='gasvalue'>" + String(float(value)/100) + "</div>" ;
// msg += "<data name=\"GasMeter\" value=\"" + String(float(value)/100) + "\" valueunit=\"m^3\"/>\n";
server.send(200, "text/plain", msg); //Response to the HTTP request
}
// ****************************************************************
void handleGenericArgs() { //Handler
String msg = DEVICENAME + ": Number of args received:";
msg += server.args(); //Get number of parameters
msg += "\n"; //Add a new line
for (int i = 0; i < server.args(); i++) {
msg += "Arg no" + (String)i + " – "; //Include the current iteration value
msg += server.argName(i) + ": "; //Get the name of the parameter
msg += server.arg(i) + "\n"; //Get the value of the parameter
}
server.send(200, "text/plain", msg); //Response to the HTTP request
}
// ****************************************************************
void handleNotFound(){
String msg = DEVICENAME + ": File Not Found\n\n";
msg += "URI: ";
msg += server.uri();
msg += "\nMethod: ";
msg += (server.method() == HTTP_GET)?"GET":"POST";
msg += "\nArguments: ";
msg += server.args();
msg += "\n";
for (uint8_t i=0; i<server.args(); i++){
msg += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", msg);
}
// ****************************************************************
void handleSetValue() {
String msg = "";
String valuestr = "";
if (server.arg("Value")== ""){ //Parameter not found
msg = DEVICENAME + ": Value Argument not found!";
} else { //Parameter found
msg = DEVICENAME + ": New Value = ";
msg += server.arg("Value"); //Gets the value of the query parameter
valuestr = server.arg("Value");
value = valuestr.toFloat() * 100;
}
server.send(200, "text/plain", msg); //Returns the HTTP response
}
// ****************************************************************
void wificonnect() {
byte MAC[6];
WiFi.setAutoConnect (true);
WiFi.setAutoReconnect (true);
WiFi.mode(WIFI_STA);
WiFi.config(ip, gateway, subnet, nameserver);
WiFi.begin(ssid, password); //Connect to the WiFi network
Serial.println();
WiFi.macAddress(MAC);
MACStr = ToHEX(MAC, sizeof(MAC));
Serial.print("MAC = ");
Serial.println(MACStr);
//Wait for WIFI connection
while (WiFi.status() != WL_CONNECTED) { //Wait for connection
digitalWrite(LED_PIN, HIGH); // LED is OFF
delay(100);
digitalWrite(LED_PIN, LOW); // LED is ON
delay(100);
Serial.print(".");
}
digitalWrite(LED_PIN, LOW); // LED is ON
delay(1000);
digitalWrite(LED_PIN, HIGH); // LED is OFF
Serial.println("");
Serial.print("WIFI connected to: ");
Serial.println(WiFi.SSID());
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
WIFIConnectCounter++;
}
// ****************************************************************
long int GetActGasMeter() {
long int ActGasMeter = 0;
HTTPClient http;
http.begin("http://192.168.X.Y/GetActualGasMeter.php");
int httpCode = http.GET();
// httpCode will be negative on error
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
//Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK) {
String StrActGasMeter = http.getString();
ActGasMeter = 100 * StrActGasMeter.toFloat();
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
return ActGasMeter;
}
// ****************************************************************
void setupOTA() {
ArduinoOTA.setHostname(DEVICENAME.c_str());
ArduinoOTA.setPasswordHash("b096734cb8ca8d95d02e8a9c7f5b2cXXXYYYZZZ42435de7f8be");
ArduinoOTA.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH) {
type = "sketch";
} else { // U_FS
type = "filesystem";
}
// NOTE: if updating FS this would be the place to unmount FS using FS.end()
Serial.println("Start updating " + type);
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) {
Serial.println("Auth Failed");
} else if (error == OTA_BEGIN_ERROR) {
Serial.println("Begin Failed");
} else if (error == OTA_CONNECT_ERROR) {
Serial.println("Connect Failed");
} else if (error == OTA_RECEIVE_ERROR) {
Serial.println("Receive Failed");
} else if (error == OTA_END_ERROR) {
Serial.println("End Failed");
}
});
ArduinoOTA.begin();
Serial.println("OTA ready");
}
// ****************************************************************
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(IN_PIN, INPUT);
Serial.begin(115200);
wificonnect();
delay(1000);
server.on("/", handleRoot);
server.on("/genericArgs", handleGenericArgs);
server.on("/SetValue", handleSetValue);
server.onNotFound( handleNotFound );
server.begin(); //Start the server
Serial.println("Server in now listening ...");
actual = digitalRead(IN_PIN);
Serial.println("Starting UDP");
Udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(Udp.localPort());
Serial.println("waiting for sync");
setSyncProvider(getNtpTime);
setSyncInterval(300);
startEpochTime = now();
formattedStartDateTime = GetDateTime();
Serial.println("Start: " + formattedStartDateTime + " " + String(startEpochTime));
setupOTA();
value = GetActGasMeter();
Serial.println("Start value for GasMeter: " + String(float(value)/100));
} // end setup
// ****************************************************************
void loop() {
unsigned long currentMillis = millis();
server.handleClient(); //Handling of incoming requests
ArduinoOTA.handle();
actual = digitalRead(IN_PIN);
if (actual == 0 && actual != prev) {
value++;
Serial.println(value);
digitalWrite(LED_PIN, HIGH);
delay(250);
digitalWrite(LED_PIN, LOW);
}
prev = actual;
if (currentMillis - prevLEDMillis >= 2000) { // blink every 2sec
digitalWrite(LED_PIN, HIGH);
delay(10);
digitalWrite(LED_PIN, LOW);
prevLEDMillis = currentMillis;
}
if (currentMillis - prevWIFIMillis >= 900000000) { // check wifi every 15min
if (WiFi.status() != WL_CONNECTED) {
wificonnect();
delay(200);
}
prevWIFIMillis = currentMillis;
}
if (currentMillis - prevNTPMillis >= 900000) { // update NTP every 15min
if (timeStatus() != timeNotSet) {
elapsedEpochTime = now() - startEpochTime;
RunTimeHours = float(elapsedEpochTime) / 3600;
}
prevNTPMillis = currentMillis;
}
delay(10);
} // end loop
// ****************************************************************
and add this to my sensor.yaml
#-------------------------------------------------------------
# esp8266 Gassensor
#-------------------------------------------------------------
- platform: scrape
resource: http://192.168.1.112
select: ".gasvalue"
name: esp8266_gasvalue
authentication: basic
now, it works perfect.
no differents between HA and my Gasmeter.
with http://ip.of.esp/SetValue?Value=xxxxxx
you can set the actually valu
Edit: Works perfect since 7 days