const log = require('./lib/logger')(__filename.slice(__dirname.length + 1));
const ver = 'v1';
+const notify = require('./lib/notify');
const indexRouter = require('./routes/index');
// api-docs
app.use('/' + ver + '/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
+// subscribe notification after 2s
+setTimeout(subscribeNotification, 2000);
+
+function subscribeNotification() {
+ notify.subscribe('prod', null);
+}
+
module.exports = app;
+++ /dev/null
-
-
-function generateVAPIDKeys() {
- var curve = crypto.createECDH('prime256v1');
- curve.generateKeys();
-
- return {
- publicKey: curve.getPublicKey(),
- privateKey: curve.getPrivateKey(),
- };
-}
-
--- /dev/null
+{
+ "publicKey": "<enter_your_public_vapid_key_here>",
+ "privateKey": "<enter_your_private_vapid_key_here>",
+ "fcmApiKey": "<enter_your_public_fcm_api_key_here>",
+ "prodApiKey": "<enter_your_production_api_key_here>",
+ "testApiKey": "2TTqCD4mNNny"
+}
+++ /dev/null
-{"publicKey":"BLDSdGasI5sLks30brbIWvlLMFqzoxxkOs7aW_E9PDBzIO_mDs6-tvtb2U0-BVFDafNd58DJgoXxdK5711FF29c","privateKey":"_AFTIegzYV_l_5RYwzOCc22cpYcMUmpkA8bLbrlNq9I"}
return reject(msg.dbError);
}
if (res.key !== data.key) {
- log.info('API key doesn\'t match');
- return reject(msg.keyMismatch);
+ // notification request on start?
+ if (data.key !== null) {
+ log.info('API key doesn\'t match');
+ return reject(msg.keyMismatch);
+ }
}
log.debug('API key is valid');
resolve(msg.ok);
var reedState;
var controlCallback = null;
var notificationCallback = null;
-var apiKey = null;
var timer = null;
function init() {
rpio.msleep(500);
rpio.write(RELAIS, rpio.LOW);
- log.debug('relais triggered');
+ log.debug('Relais triggered');
}
function readDebounced(pin) {
rpio.msleep(1000);
if (state != rpio.read(pin)) {
- log.debug('state unknown');
+ log.debug('State unknown');
return UNKNOWN;
} else {
return state;
if (state != UNKNOWN && reedState != UNKNOWN) {
if (state != reedState) {
- log.debug('reed state changed, now:', state);
+ log.debug('Reed state changed, now:', state);
if (controlCallback != null) {
// handle callbacks
}
}
-function subscribe(callback, key) {
+function subscribe(callback) {
notificationCallback = callback;
- apiKey = key;
}
function evaluation(state) {
if (notificationCallback != null) {
if (state == rpio.HIGH) {
- timer = setTimeout(notificationCallback, DELAY * 1000, apiKey);
+ timer = setTimeout(notificationCallback, DELAY * 1000);
log.debug('Open door evaluation started');
} else {
clearTimeout(timer);
--- /dev/null
+const log = require('./logger')(__filename.slice(__dirname.length + 1));
+const db = require('./db');
+const gpio = require('./gpio');
+const settings = require('./../init/settings.json');
+const fs = require('fs');
+const webpush = require('web-push');
+
+var data = {
+ area: null,
+ key: null
+};
+
+function subscribe(area, key) {
+ data.area = area;
+ data.key = key;
+
+ // subscribe notification
+ gpio.subscribe(onDoorOpen);
+ log.info('Open door event subscribed');
+}
+
+function onDoorOpen() {
+ // get settings
+ db.getNotification({
+ area: data.area,
+ key: data.key
+ }, (err, data) => {
+ if (err) {
+ switch (err) {
+ case db.msg.dbError:
+ log.info('Server error response');
+ break;
+ case db.msg.keyMismatch:
+ log.info('Unauthorized access');
+ break;
+ default:
+ log.error('Error result unexpected');
+ break;
+ }
+ } else {
+ executeNotification(data);
+ }
+ });
+}
+
+function executeNotification(notification) {
+ const pushSubscription = {
+ endpoint: notification.endpoint,
+ keys: {
+ auth: notification.keys.auth,
+ p256dh: notification.keys.p256dh
+ }
+ };
+
+ const options = {
+ gcmAPIKey: settings.fcmApiKey,
+ vapidDetails: {
+ subject: 'mailto:ebelcrom@gmail.com',
+ publicKey: settings.publicKey,
+ privateKey: settings.privateKey
+ },
+ headers: {
+ 'Urgency': 'high'
+ },
+ contentEncoding: 'aes128gcm'
+ };
+
+ const icon = 'data:image/png;base64,' +
+ fs.readFileSync(__dirname + '/../public/images/icon.png', 'base64');
+ const payload = {
+ message: 'The garage door is open!',
+ icon: icon
+ };
+ log.debug('Paylod length:', JSON.stringify(payload).length);
+/*
+ const details = webpush.generateRequestDetails(pushSubscription, JSON.stringify(payload), options);
+ log.debug('Request details:', JSON.stringify(details));
+*/
+ webpush.sendNotification(pushSubscription, JSON.stringify(payload), options)
+ .then(data => {
+ if (data) {
+ log.debug('Notification sent, data:', JSON.stringify(data));
+ }
+ })
+ .catch(err => {
+ log.error('Notification sending failed:', JSON.stringify(err));
+ });
+}
+
+module.exports = {
+ subscribe,
+ executeNotification
+}
const options = {
host: '192.168.3.2',
path: '/snapshot.cgi',
- mthod: 'GET',
+ method: 'GET',
headers: {
'Authorization': 'Basic ' + new Buffer(username + ':').toString('base64')
}
const router = express.Router();
const db = require('./../../lib/db');
const EventEmitter = require('events');
+const webcam = require('./../../lib/webcam');
const events = new EventEmitter();
var response = null;
};
if (image) {
webcam.getImage()
- .then(image => {
- content['image'] = new Buffer(image).toString('base64');
- res.json(content);
+ .then(img => {
+ content['image'] = new Buffer(img).toString('base64');
+ response.json(content);
+ response = null;
})
.catch(err => {
log.error('Error on getting webcam image', JSON.stringify(err));
- res.status(500).send();
+ response.status(500).send();
+ response = null;
});
} else {
- res.json(content);
+ response.json(content);
+ response = null;
}
- response = null;
}
});
const router = express.Router();
const db = require('./../../lib/db');
const gpio = require('./../../lib/gpio');
+const notify = require('./../../lib/notify');
const fs = require('fs');
-const webpush = require('web-push');
/* Disables caching in client */
function nocache(req, res, next) {
}
} else {
// subscribe notification
- gpio.subscribe(onDoorOpen, req.header('X-API-Key'));
- log.debug('Open door event subscribed');
+ notify.subscribe('prod', req.header('X-API-Key'));
+ log.debug('Notification subscribed');
res.status(200).send();
}
});
}
});
-function onDoorOpen(key) {
- // get settings
- db.getNotification({
- area: 'prod',
- key: key
- }, (err, data) => {
- if (err) {
- switch (err) {
- case db.msg.dbError:
- log.info('Server error response');
- res.status(500).send();
- break;
- case db.msg.keyMismatch:
- log.info('Unauthorized access');
- res.status(401).send();
- break;
- default:
- log.error('Error result unexpected');
- res.status(500).send();
- break;
- }
- } else {
- executeNotification(data);
- }
- });
-}
-
-function executeNotification(notification) {
- const pushSubscription = {
- endpoint: notification.endpoint,
- keys: {
- auth: notification.keys.auth,
- p256dh: notification.keys.p256dh
- }
- };
-
- const options = {
- gcmAPIKey: 'AAAAUtHuYco:APA91bEBTxCRGaez9_glljXAlit3PY5HMwhLSqWYMC1j-jFSp6'
- + 'nvnNqjI42jAVFApQbM0oyAOQjCUilIovB76cwTFxyZTP96wm9n09XwiMRXJjhwiJX1hO3'
- + '2mBB2zwK6X-w7epE1V67K',
- vapidDetails: {
- subject: 'mailto:ebelcrom@gmail.com',
- publicKey: 'BLDSdGasI5sLks30brbIWvlLMFqzoxxkOs7aW_E9PDBzIO_mDs6-tvtb2U0-'
- + 'BVFDafNd58DJgoXxdK5711FF29c',
- privateKey: '_AFTIegzYV_l_5RYwzOCc22cpYcMUmpkA8bLbrlNq9I'
- },
- headers: {
- 'Urgency': 'high'
- },
- contentEncoding: 'aes128gcm'
- };
-
- const icon = 'data:image/png;base64,' +
- fs.readFileSync(__dirname + '/../../public/images/icon.png', 'base64');
- const payload = {
- message: 'The garage door is open!',
- icon: icon
- };
- log.debug('Paylod length:', JSON.stringify(payload).length);
-
- const details = webpush.generateRequestDetails(pushSubscription, JSON.stringify(payload), options);
- log.debug('Request details:', JSON.stringify(details));
-
- webpush.sendNotification(pushSubscription, JSON.stringify(payload), options)
- .then(data => {
- if (data) {
- log.info('sent, data:', JSON.stringify(data));
- }
- })
- .catch(err => {
- log.info('sent, err:', JSON.stringify(err));
- });
-}
-
module.exports = router;
const qStr = require('query-string');
const router = express.Router();
const db = require('./../../../lib/db');
+const notify = require('./../../../lib/notify');
+const fs = require('fs');
/* Disables caching in client */
function nocache(req, res, next) {
const router = express.Router();
const db = require('./../../../lib/db');
const fs = require('fs');
+const notify = require('./../../../lib/notify');
const webpush = require('web-push');
const delayMin = -1;
if (typeof req.body.notification == 'object' ) {
if (typeof req.body.notification.delay == 'number' &&
req.body.notification.delay !== delayMin) {
- notify(req, res, next, settings.notification.delay);
+ subscribe(req, res, next, settings.notification.delay);
} else {
res.status(200).send();
}
}
});
-function notify(req, res, next, delay) {
+function subscribe(req, res, next, delay) {
// get settings
db.getNotification({
area: 'test',
clearTimeout(timer);
timer = null;
- const pushSubscription = {
- endpoint: notification.endpoint,
- keys: {
- auth: notification.keys.auth,
- p256dh: notification.keys.p256dh
- }
- };
-
- const options = {
- gcmAPIKey: 'AAAAUtHuYco:APA91bEBTxCRGaez9_glljXAlit3PY5HMwhLSqWYMC1j-jFSp6'
- + 'nvnNqjI42jAVFApQbM0oyAOQjCUilIovB76cwTFxyZTP96wm9n09XwiMRXJjhwiJX1hO3'
- + '2mBB2zwK6X-w7epE1V67K',
- vapidDetails: {
- subject: 'mailto:ebelcrom@gmail.com',
- publicKey: 'BLDSdGasI5sLks30brbIWvlLMFqzoxxkOs7aW_E9PDBzIO_mDs6-tvtb2U0-'
- + 'BVFDafNd58DJgoXxdK5711FF29c',
- privateKey: '_AFTIegzYV_l_5RYwzOCc22cpYcMUmpkA8bLbrlNq9I'
- },
- headers: {
- 'Urgency': 'high'
- },
- contentEncoding: 'aes128gcm'
- };
-
- const icon = 'data:image/png;base64,' +
- fs.readFileSync(__dirname + '/../../../public/images/icon.png', 'base64');
- const payload = {
- message: 'The garage door is open!',
- icon: icon
- };
- log.debug('Paylod length:', JSON.stringify(payload).length);
-
- const details = webpush.generateRequestDetails(pushSubscription, JSON.stringify(payload), options);
- log.debug('Request details:', JSON.stringify(details));
-
- webpush.sendNotification(pushSubscription, JSON.stringify(payload), options)
- .then(data => {
- if (data) {
- log.info('sent, data:', JSON.stringify(data));
- }
- })
- .catch(err => {
- log.info('sent, err:', JSON.stringify(err));
- });
+ notify.executeNotification(notification);
}
module.exports = router;