use json from mqtt and store it in postgresql
authorDobrica Pavlinusic <dpavlin@rot13.org>
Thu, 29 Jun 2023 21:33:52 +0000 (23:33 +0200)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Thu, 29 Jun 2023 21:33:52 +0000 (23:33 +0200)
create.sql [new file with mode: 0644]
mqtt-pgsql.sh [new file with mode: 0755]

diff --git a/create.sql b/create.sql
new file mode 100644 (file)
index 0000000..094a297
--- /dev/null
@@ -0,0 +1,24 @@
+drop table eg5120;
+create table eg5120 (
+       time timestamp without time zone default now(),
+       mac text,
+       addr text,
+       "nodeId" int,
+       json jsonb,
+       _id serial
+);
+
+CREATE OR REPLACE FUNCTION json_fn()
+  RETURNS TRIGGER AS
+$func$
+BEGIN
+   NEW := jsonb_populate_record(NEW, NEW.json); -- or hstore alternative
+   RETURN NEW;
+END
+$func$ LANGUAGE plpgsql;
+
+CREATE TRIGGER json_trigger
+BEFORE INSERT OR UPDATE ON eg5120 FOR EACH ROW
+EXECUTE PROCEDURE json_fn();
+
+
diff --git a/mqtt-pgsql.sh b/mqtt-pgsql.sh
new file mode 100755 (executable)
index 0000000..e25d39f
--- /dev/null
@@ -0,0 +1,8 @@
+#!/bin/sh -e
+
+mosquitto_sub -h localhost -t eg5120 | while read json ; do
+       date=$( date +%Y-%m-%dT%H:%M:%S )
+       ecno -n $date ' '
+       echo $json | tee data/$date.json | tee /dev/shm/last-eg5120.json
+       psql --quiet -c "copy eg5120 (json) from '/dev/shm/last-eg5120.json'" eg5120
+done