-
Notifications
You must be signed in to change notification settings - Fork 9
/
app.js
105 lines (85 loc) · 2.3 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// mongolab-motion: An Arduino motion sensor example that logs to
// MongoLab's REST API and to an email address.
//
//
// by Ben Wen
// with thanks to the Arduino community, esp. Rick Waldon for Johnny Five,
// SendGrid for the Uno board, esp. @swiftalphaone for the Waza tutorial.
//
//
// Copyright 2013 Benson Wen.
//
//
// MIT licensed
//
// March 2013
var five = require('johnny-five'),
board = new five.Board(),
https = require('https'),
mailer = require('mailer'),
config = require('./config').config,
detected = 0,
ceased = 0;
// Set up event handlers to process motion events.
board.on('ready', function() {
var button = new five.Button(config.sensorpin)
board.repl.inject({
button: button
})
button.on('down', function() {
noteEvent ('Motion detected.')
detected = detected + 1
})
button.on('up', function() {
noteEvent('Motion detection ceased.')
ceased = ceased + 1
})
})
function noteEvent(msg) {
var time = new Date ()
console.log(time.toString() + ': ' + msg)
logMsg({
'_id' : time.getTime(),
'sensorid' : config.id,
'time' : time.toString(),
'event' : msg
})
// FIXME using message string matching is distasteful
if ((/.*detected.*/.test(msg) && config.detectTest(time, detected)) ||
(/.*ceased.*/.test(msg) && config.ceasedTest(time, ceased)))
mailMsg(msg)
}
var email = config.mailer
email.subject = 'mongolab_motion event!'
// TODO: make mailMsg and logMsg use the same msg semantics.
function mailMsg(msg) {
email.subject = config.id +": " + msg;
email.body = 'Hello! from mongolab_motion sensor:' + config.id + '.\nMessage: ' + msg
mailer.send(email, function (err, result) {
if (err) console.log (err)
console.log ('mail sent')
})
}
function logMsg(msg) {
var options = {
host: 'api.mongolab.com',
port: '443',
path: '/api/1/databases/' + config.database + '/collections/' + config.collection
+ '?apiKey=' + config.apiKey,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk) {
if (! /.*_id.*/.test(chunk))
console.log('Unexpected server response: ' + chunk)
})
})
// post the data
req.write(JSON.stringify(msg))
req.end()
}