From c56840f03cf139d60c6d90b55cf16e70f6ae2bc2 Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Sun, 21 Jun 2015 00:15:04 +0200 Subject: o Going all header file based and single-executable to launch all apps. o Ading CMake magic to generate the launcher --- apps/sm-db-insert.h | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 apps/sm-db-insert.h (limited to 'apps/sm-db-insert.h') diff --git a/apps/sm-db-insert.h b/apps/sm-db-insert.h new file mode 100644 index 0000000..b786e41 --- /dev/null +++ b/apps/sm-db-insert.h @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include "json.hpp" +#include + +namespace trygvis { +namespace apps { + +template +using o = boost::optional; +using namespace std; +using json = nlohmann::json; + +class sm_db_insert : public app { + +public: + sm_db_insert() : app("sm-db-insert") { + } + + ~sm_db_insert() = default; + + void add_options(po::options_description_easy_init &options) override { + options + ("file", po::value()->required(), "The file to read"); + } + + int main(app_execution &execution) override { + auto file = execution.vm["file"].as(); + cout << "reading from " << file << endl; + + fstream f(file); + + json j; + + j << f; + + pqxx::connection c("host=localhost dbname=soil-moisture"); + + pqxx::work work(c); + + string mac = j["mac"]; // "aa:bb:cc:dd:ee:ff"; + + auto rs = work.parameterized("select id from soil_moisture_device where mac=$1")(mac).exec(); + + if (!rs.size()) { + cout << "New device: " << mac << endl; + + rs = work.parameterized("insert into soil_moisture_device(mac) values($1) returning id")(mac).exec(); + } + + auto deviceId = rs.begin()["id"].as(); + + int sensor = j["sensor"]; + + rs = work.parameterized("select id from soil_moisture_sensor where device=$1 and sensor=$2")(deviceId)(sensor).exec(); + + if (!rs.size()) { + cout << "New sensor: " << sensor << endl; + + rs = work.parameterized("insert into soil_moisture_sensor(device, sensor) values($1, $2) returning id")(deviceId)(sensor).exec(); + } + auto sensorId = rs.begin()["id"].as(); + + unsigned long timestamp = get(j, "timestamp"); + unsigned int value = get(j, "value"); + + work.parameterized("insert into soil_moisture_sample(sensor, timestamp, value) values($1, $2, $3)")(sensorId)(timestamp)(value).exec(); + + cout << "Sample inserted" << endl; + + work.commit(); + + return EXIT_SUCCESS; + } +}; + +} +} -- cgit v1.2.3