aboutsummaryrefslogtreecommitdiff
path: root/apps/device.js
diff options
context:
space:
mode:
Diffstat (limited to 'apps/device.js')
-rw-r--r--apps/device.js55
1 files changed, 55 insertions, 0 deletions
diff --git a/apps/device.js b/apps/device.js
new file mode 100644
index 0000000..1b8e169
--- /dev/null
+++ b/apps/device.js
@@ -0,0 +1,55 @@
+var pg, log;
+
+function init(config) {
+ pg = config.pg;
+ log = config.log;
+}
+exports.init = init;
+
+var deviceR = /^\/diller\/([0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5})\//;
+
+function onMessage(topic, message, payload) {
+ var matches = deviceR.exec(topic)
+
+ if (!matches) {
+ log.warn('no match: ', topic);
+ return;
+ }
+
+ var mac = matches[1];
+
+ pg.connect(function (err, client, done) {
+ if (err) {
+ done();
+ log.error('Could not connect to postgres', err);
+ return;
+ }
+
+ client.query('select count(*) as count from device where key=$1', [mac], function (err, result) {
+ if (err) {
+ done();
+ log.error('error running query', err);
+ return;
+ }
+
+ if (result.rows[0].count > 0) {
+ done();
+ return;
+ }
+
+ log.info('New device:', mac);
+
+ client.query('insert into device(id, key, created_timestamp) values(default, $1, current_timestamp) returning id', [mac], function (err, result) {
+ if (err) {
+ done();
+ log.error('error inserting new device', err);
+ }
+
+ log.info('New device created', result.rows[0].id);
+ done();
+ });
+ });
+ });
+}
+
+exports.onMessage = onMessage;