-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
100 lines (89 loc) · 2.48 KB
/
app.js
File metadata and controls
100 lines (89 loc) · 2.48 KB
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
const _ = require('lodash');
const Xantrex = require("./lib/xantrex.js").Xantrex;
const schedule = require('node-schedule');
const SunCalc = require('suncalc');
const isBefore = require('date-fns/is_before');
const isAfter = require('date-fns/is_after');
const isSameDay = require('date-fns/is_same_day');
const formatDate = require('date-fns/format');
// Load the AWS SDK for Node.js
let AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: process.env.AWS_REGION});
AWS.config.loadFromPath('./config.json');
let dynamoClient = new AWS.DynamoDB.DocumentClient();
let times = {};
let lastReading = {
date: new Date()
};
function log(message) {
const now = new Date();
console.log(formatDate(now) + ': ' + message);
}
/**
* Load sunrise and sunset times
*/
function updateTimes() {
let now = new Date();
times = _.extend(SunCalc.getTimes(now, -37, 144), {timestamp: now});
}
function setLastReading(reading) {
let now = new Date();
_.extend(
lastReading,
{
date: now,
reading: reading
});
}
/**
* Read from the inverter
*/
function performReading(lastReading, times) {
let now = new Date();
if (isAfter(now, times.sunset)) {
log('Sun has set');
} else if (isBefore(now, times.sunrise)) {
log('Before sunrise');
} else {
log('Getting reading');
let xantrex = new Xantrex("/dev/ttyUSB0", 9600);
xantrex.connect().then(
function () {
xantrex.getSummary().then(
function (result) {
if (!isSameDay(now, lastReading.date) &&
parseFloat(result.kwhtoday) > 0.5) {
log('Skipping yesterday\'s reading');
} else {
let data = {
'device_id': 'XANTREX0001',
timestamp: formatDate(now),
reading: result
};
setLastReading(result);
console.log('Sending reading');
dynamoClient.put(
{
TableName: "sensors",
Item: data
},
function (err, data) {
});
}
xantrex.disconnect();
});
}).fail(function (error) {
log('Error:'.JSON.stringify(error));
xantrex.disconnect();
});
}
}
/**
* init
*/
updateTimes();
const updateTimesSchedule = schedule.scheduleJob('updateTimes', '0 * * * *', updateTimes);
const j = schedule.scheduleJob('performReading', '* * * * *', () => {
performReading(lastReading, times);
});