diff --git a/src/bms.js b/src/bms.js new file mode 100644 index 0000000..20e0cd3 --- /dev/null +++ b/src/bms.js @@ -0,0 +1,19 @@ +import i2c from 'i2c-bus'; + +async function bmsStatus(address = 0x57) { + const i2cBus = await i2c.openPromisified(1); + const data = await Promise.all([ + i2cBus.readByte(address, 0x02), + i2cBus.readByte(address, 0x04), + i2cBus.readByte(address, 0x22), + i2cBus.readByte(address, 0x23), + i2cBus.readByte(address, 0x2a), + ]); + return { + charging: !!((data[0] >> 7) & 1), + percentage: data[4] / 100, + temperature: data[1] - 40, + voltage: ((data[2] << 8) | data[3]) / 1000, + } +} +console.log(await bmsStatus()); diff --git a/src/http.js b/src/http.js index 840cbc6..ccd10b9 100644 --- a/src/http.js +++ b/src/http.js @@ -9,17 +9,20 @@ export default class Http extends Controller { constructor(apollo, port = 8000) { super(apollo); this.express = express(); + + this.express.get('/api/*', async (req, res) => { + const cmd = req.params['0']; + console.log(cmd); + res.json(await this.run(cmd)); + }); + this.express.get('*', (req, res) => { let p = req.params['0']; if(!p || p == '/') p = 'index.html'; const absolute = path.join(import.meta.url, '/../../ui/', p).replace('file:', ''); res.sendFile(absolute); }); - this.express.get('/api/*', async (req, res) => { - const cmd = req.params['0']; - console.log(cmd); - res.json(await this.run(cmd)); - }); + this.express.listen(port); } } diff --git a/src/sensor-suite.js b/src/sensor-suite.js index c4c782c..6079eda 100644 --- a/src/sensor-suite.js +++ b/src/sensor-suite.js @@ -21,23 +21,27 @@ export default class SensorSuite { set data(d) { this._data = d; } get data() { return {timestamp: new Date().getTime(), ...this._data}; } - get status() { return { sensors: 'ok' }; } + _env_sensor = false; + get status() { return { env_sensor: this._env_sensor ? 'ok' : 'failed' }; } constructor() { this.bme280 = new BME280({i2cBusNo: 1, i2cAddress: 0x76}); } - async start() { - await this.bme280.init(); - - // Poll environmental data - this.stopBme280 = poll(async () => { - const d = await this.bme280.readSensorData(); - this._data.humidity = d.humidity / 100; - this._data.temperature = d.temperature_C; - this._data.pressure = d.pressure_hPa; - this._data.altitude = BME280.calculateAltitudeMeters(this.data.pressure); - }, 1000); + start() { + return this.bme280.init().then(() => { + // Poll environmental data + this._env_sensor = true; + this.stopBme280 = poll(async () => { + const d = await this.bme280.readSensorData(); + this._data.humidity = d.humidity / 100; + this._data.temperature = d.temperature_C; + this._data.pressure = d.pressure_hPa; + this._data.altitude = BME280.calculateAltitudeMeters(this.data.pressure); + }, 1000); + }).catch(err => { + this._env_sensor = false; + }); } stop() {