forked from jncarter123/signalk-raspberry-pi-bme280
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·122 lines (105 loc) · 3.01 KB
/
index.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
* Copyright 2019 Jeremy Carter <jncarter@hotmail.com>
*
* Add the MIT license
*/
const BME280 = require('bme280-sensor')
module.exports = function (app) {
let timer = null
let plugin = {}
plugin.id = 'signalk-raspberry-pi-bme280'
plugin.name = 'Raspberry-Pi BME280'
plugin.description = 'BME280 temperature sensors on Raspberry-Pi'
plugin.schema = {
type: 'object',
properties: {
rate: {
title: "Sample Rate (in seconds)",
type: 'number',
default: 60
},
path: {
type: 'string',
title: 'SignalK Path',
description: 'This is used to build the path in Signal K. It will be appended to \'environment\'',
default: 'inside.salon'
},
i2c_bus: {
type: 'integer',
title: 'I2C bus number',
default: 1,
},
i2c_address: {
type: 'string',
title: 'I2C address',
default: '0x77',
},
}
}
plugin.start = function (options) {
function createDeltaMessage (temperature, humidity, pressure) {
return {
'context': 'vessels.' + app.selfId,
'updates': [
{
'source': {
'label': plugin.id
},
'timestamp': (new Date()).toISOString(),
'values': [
{
'path': 'environment.' + options.path + '.temperature',
'value': temperature
}, {
'path': 'environment.' + options.path + '.humidity',
'value': humidity
}, {
'path': 'environment.' + options.path + '.pressure',
'value': pressure
}
]
}
]
}
}
// The BME280 constructor options are optional.
//
const bmeoptions = {
i2cBusNo : options.i2c_bus || 1, // defaults to 1
i2cAddress : Number(options.i2c_address || '0x77'), // defaults to 0x77
};
const bme280 = new BME280(bmeoptions);
// Read BME280 sensor data
function readSensorData() {
bme280.readSensorData()
.then((data) => {
// temperature_C, pressure_hPa, and humidity are returned by default.
temperature = data.temperature_C + 273.15;
pressure = data.pressure_hPa * 100;
humidity = data.humidity;
//console.log(`data = ${JSON.stringify(data, null, 2)}`);
// create message
var delta = createDeltaMessage(temperature, humidity, pressure)
// send temperature
app.handleMessage(plugin.id, delta)
})
.catch((err) => {
console.log(`BME280 read error: ${err}`);
});
}
bme280.init()
.then(() => {
console.log('BME280 initialization succeeded');
readSensorData();
})
.catch((err) => console.error(`BME280 initialization failed: ${err} `));
timer = setInterval(readSensorData, options.rate * 1000);
}
plugin.stop = function () {
if(timer){
clearInterval(timer);
timeout = null;
}
}
return plugin
}