I’m trying to replace a sensor I had. It takes some data from an I2C chip and sends it to a postgres table as well as Home Assistant. It was all custom Arduino code, but I want to migrate it over to ESPHome to make it easier to maintain (over the air updates, etc). I figured I could use the custom output to send the sensor value to postgres. I think I have it setup correctly (squashed all my errors in the compilation), but now I’m getting messages like
undefined reference to `_ZN12PGconnection5closeEv’
Any idea what I’m doing wrong? Code is as follows:
YAML File:
esphome:
name: test
includes:
- postgresql.h
esp8266:
board: esp01_1m
# Enable logging
logger:
# Enable Home Assistant API
api:
ota:
password: "497eb82db5ba18c292c6b7e7b98f483d"
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Test Fallback Hotspot"
password: "D2OSUL8Av3He"
captive_portal:
external_components:
- source: SimplePgSQL
output:
- platform: custom
type: float
lambda: |-
auto ph_to_postgres = new Save_To_Postgres(IPAddress(X,X,X,X), "username", "password", "db", "schema", "table", "PH");
App.register_component(ph_to_postgres);
return {ph_to_postgres};
outputs:
id: ph_to_postgres
postgresql.h:
#include <SimplePgSQL.h>
#include "esphome.h"
using namespace esphome;
class Save_To_Postgres : public Component, public FloatOutput {
public:
Save_To_Postgres(IPAddress,std::string, std::string, std::string, std::string, std::string, std::string);
IPAddress host;
std::string user;
std::string password;
std::string dbname;
std::string schema;
std::string table;
std::string sensor;
void setup() override {
// This will be called by App.setup()
}
void write_state(float state) override {
WiFiClient client;
char buffer[10240];
PGconnection conn(&client, 0, 10240, buffer);
int ignore;
ignore = conn.setDbLogin(host, user.c_str(), password.c_str(), dbname.c_str(), "utf8");
while (conn.status() != CONNECTION_OK) {
delay(1000);
}
std::string sql;
sql = "insert into " + schema + "." + table + " (sensor, value) values ('" + sensor + "', ";
sql += state;
sql += ");";
int returned_value;
returned_value = conn.execute(sql.c_str());
conn.close();
}
};
Save_To_Postgres::Save_To_Postgres(IPAddress ip, std::string username, std::string pass, std::string db, std::string schemaname, std::string tablename, std::string sensorname) {
host = ip;
user = username;
password = pass;
dbname = db;
schema = schemaname;
table = tablename;
sensor = sensorname;
};
The SimplePgSQL directory in the config directory is a clone of this git repo:
https://github.com/ethanak/SimplePgSQL