vastra-radiator-valve
Version:
Node.js library to query and configure Vastra's smart radiator valves.
592 lines (591 loc) • 30.1 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var constants_1 = require("./constants");
var protocol_1 = require("./protocol");
var utils_1 = require("./utils");
var valve_state_1 = require("./valve-state");
var RadiatorValve = /** @class */ (function () {
function RadiatorValve(peripheral, options) {
this.peripheral = peripheral;
this.options = options;
this.lastSentWakeUpTime = 0;
this.logger = this.options.logger;
}
/**
* Attempts to establish a connection with the device.
*
* @param attempt Counts how many attempts have been made so far. For internal use only.
*/
RadiatorValve.prototype.connect = function (attempt) {
var _a, _b, _c, _d, _e, _f;
if (attempt === void 0) { attempt = 0; }
return __awaiter(this, void 0, void 0, function () {
var timeoutToken, services, characteristics, descriptors;
var _g;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
if (!(this.peripheral.state === "connected")) return [3 /*break*/, 2];
return [4 /*yield*/, this.peripheral.disconnectAsync()];
case 1:
_h.sent();
return [3 /*break*/, 3];
case 2:
if (this.peripheral.state === "connecting") {
throw new Error("Already connecting to ".concat(this.peripheral.address));
}
_h.label = 3;
case 3:
if (attempt >= this.options.maxConnectionAttempts) {
throw new Error("Too many attempts trying to connect to ".concat(this.peripheral.address));
}
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug("Connecting to ".concat(this.peripheral.address, " (timeout=").concat(this.options.connectionTimeout, ", attempt=").concat(attempt, ")"));
timeoutToken = new utils_1.TimeoutToken(this.options.connectionTimeout);
if (!(this.peripheral.state !== "connected")) return [3 /*break*/, 5];
return [4 /*yield*/, (0, utils_1.withTimeout)(this.peripheral.connectAsync(), timeoutToken)];
case 4:
_h.sent();
if (timeoutToken.timedOut) {
(_b = this.logger) === null || _b === void 0 ? void 0 : _b.warn("Timed out connecting to ".concat(this.peripheral.address));
return [2 /*return*/, this.connect(attempt + 1)];
}
_h.label = 5;
case 5: return [4 /*yield*/, (0, utils_1.withTimeout)(this.peripheral.discoverServicesAsync([constants_1.VALVE_SERVICE_UUID]), timeoutToken)];
case 6:
services = _h.sent();
if (timeoutToken.timedOut) {
(_c = this.logger) === null || _c === void 0 ? void 0 : _c.warn("Timed out discovering services of ".concat(this.peripheral.address));
return [2 /*return*/, this.connect(attempt + 1)];
}
if (services.length === 0) {
throw new Error("".concat(this.peripheral.address, " did not report a communication service"));
}
return [4 /*yield*/, (0, utils_1.withTimeout)(services[0].discoverCharacteristicsAsync([constants_1.VALVE_RX_UUID, constants_1.VALVE_TX_UUID]), timeoutToken)];
case 7:
characteristics = _h.sent();
if (timeoutToken.timedOut) {
(_d = this.logger) === null || _d === void 0 ? void 0 : _d.warn("Timed out discovering characteristics of ".concat(this.peripheral.address));
return [2 /*return*/, this.connect(attempt + 1)];
}
if (characteristics.length != 2) {
throw new Error("".concat(this.peripheral.address, " did not report read/write characteristics"));
}
_g = __read(characteristics, 2), this.rx = _g[0], this.tx = _g[1];
return [4 /*yield*/, (0, utils_1.withTimeout)(this.rx.discoverDescriptorsAsync(), timeoutToken)];
case 8:
descriptors = _h.sent();
if (timeoutToken.timedOut) {
(_e = this.logger) === null || _e === void 0 ? void 0 : _e.warn("Timed out discovering descriptors of ".concat(this.peripheral.address));
return [2 /*return*/, this.connect(attempt + 1)];
}
if (this.options.raspberryFix) {
descriptors[0].writeValueAsync(Buffer.from([0x01, 0x00]));
}
(_f = this.logger) === null || _f === void 0 ? void 0 : _f.debug("Connected to ".concat(this.peripheral.address));
return [2 /*return*/];
}
});
});
};
/**
* Closes connection with the peripheral.
*/
RadiatorValve.prototype.disconnect = function () {
var _a;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(this.peripheral.state !== "disconnected")) return [3 /*break*/, 2];
return [4 /*yield*/, this.peripheral.disconnectAsync()];
case 1:
_b.sent();
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug("Closed connection to ".concat(this.peripheral.address));
_b.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
/**
* Writes data contained in given buffer to the device.
* Make sure to wait for the message to be fully sent by `await`-ing this
* method before writing more data.
*
* @param data Data to write.
*/
RadiatorValve.prototype.write = function (data) {
var _a, _b;
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.verbose("[Host -> ".concat(this.peripheral.address, "]"), data);
return (_b = this.tx) === null || _b === void 0 ? void 0 : _b.writeAsync(data, false);
};
/**
* Writes a request to the device and waits for the response.
*
* @param request Request to send.
* @returns Response.
*/
RadiatorValve.prototype.sendRequest = function (request) {
var _this = this;
var work = function (resolve, reject, attempt) { return __awaiter(_this, void 0, void 0, function () {
var responseChunks, timeoutId;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.tx || !this.rx) {
throw new Error("Connection must be open before sending requests.");
}
if (attempt >= this.options.maxReadAttempts) {
// TODO: Probably we should re-connect, because it's difficult to say how
// the peripheral will act in case of a small congestion.
throw new Error("Timed out reading response from ".concat(this.peripheral.address));
}
responseChunks = [];
this.rx.notify(true);
this.rx.on("data", function (data) {
var _a, _b, _c;
(_a = _this.logger) === null || _a === void 0 ? void 0 : _a.verbose("[".concat(_this.peripheral.address, " -> Host]"), data);
responseChunks.push(data);
if (data.length >= 2 && data.readUInt16LE(data.length - 2) === 0x0a0d) {
(_b = _this.rx) === null || _b === void 0 ? void 0 : _b.removeAllListeners("data");
(_c = _this.rx) === null || _c === void 0 ? void 0 : _c.notify(false);
clearTimeout(timeoutId);
resolve(Buffer.concat(responseChunks));
}
});
if (this.options.readTimeout > 0) {
timeoutId = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
var error_1;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (this.rx) {
this.rx.removeAllListeners("data");
this.rx.notify(false);
}
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn("Timed out reading response from ".concat(this.peripheral.address, " (attempt ").concat(attempt, ")"));
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, work(resolve, reject, attempt + 1)];
case 2:
_b.sent();
return [3 /*break*/, 4];
case 3:
error_1 = _b.sent();
reject(error_1);
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); }, this.options.readTimeout);
}
return [4 /*yield*/, this.write(request)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); };
return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, work(resolve, reject, 0)];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
error_2 = _a.sent();
reject(error_2);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
};
/**
* Sends Wake Up command to the peripheral and waits for a response.
*/
RadiatorValve.prototype.requestWakeUp = function () {
return __awaiter(this, void 0, void 0, function () {
var timeSinceLastWakeUp;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
timeSinceLastWakeUp = new Date().getTime() - this.lastSentWakeUpTime;
if (timeSinceLastWakeUp < this.options.wakeUpInterval) {
return [2 /*return*/];
}
return [4 /*yield*/, this.sendRequest((0, protocol_1.createWakeUpPacket)())];
case 1:
_a.sent();
this.lastSentWakeUpTime = new Date().getTime();
return [2 /*return*/];
}
});
});
};
/**
* Requests value of a single field from peripheral's state buffer.
* @returns Buffer containing the value.
*/
RadiatorValve.prototype.requestReadField = function (field) {
return __awaiter(this, void 0, void 0, function () {
var _a, position, encoding, packet, response, encodedValue;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = __read(field, 2), position = _a[0], encoding = _a[1];
packet = (0, protocol_1.createStateReadPacket)(position[0], position[1]);
return [4 /*yield*/, this.sendRequest(packet)];
case 1:
response = _b.sent();
encodedValue = response.subarray(protocol_1.PACKET_HEADER_LENGTH, response.length - protocol_1.RESPONSE_FOOTER_LENGTH);
return [2 /*return*/, (0, protocol_1.decodeStateField)(encodedValue, encoding)];
}
});
});
};
/**
* Updates the value of a field.
*
* @param field Field to update.
* @param value New value.
*/
RadiatorValve.prototype.requestWriteField = function (field, value) {
return __awaiter(this, void 0, void 0, function () {
var _a, _b, offset, length, encoding, encodedValue, paddedValue, packets, work;
var _this = this;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = __read(field, 2), _b = __read(_a[0], 2), offset = _b[0], length = _b[1], encoding = _a[1];
encodedValue = (0, protocol_1.encodeStateField)(value, encoding);
if (encodedValue.length > length) {
throw new Error("Overflow when writing field value. Expected at most ".concat(length, " bytes, got ").concat(encodedValue.length));
}
paddedValue = Buffer.concat([encodedValue], length);
packets = (0, protocol_1.createStateWritePackets)(paddedValue, offset);
work = function (attempt) {
if (attempt === void 0) { attempt = 0; }
return __awaiter(_this, void 0, void 0, function () {
var failed, packetIndex, packet, response;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (attempt >= this.options.maxWriteAttempts) {
throw new Error("Too many failed attempts at updating configuration of ".concat(this.peripheral.address));
}
failed = false;
packetIndex = 0;
_b.label = 1;
case 1:
if (!(packetIndex < packets.length)) return [3 /*break*/, 4];
packet = packets[packetIndex];
return [4 /*yield*/, this.sendRequest(packet)];
case 2:
response = _b.sent();
if (response[2] !== protocol_1.PacketId.SaveSuccess) {
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn("Unable to update configuration of ".concat(this.peripheral.address, " (offset=").concat(offset, ", packet=").concat(packet, ", packetIndex=").concat(packetIndex, ", attempt=").concat(attempt, ")"));
failed = true;
return [3 /*break*/, 4];
}
_b.label = 3;
case 3:
packetIndex++;
return [3 /*break*/, 1];
case 4:
if (!failed) return [3 /*break*/, 6];
return [4 /*yield*/, work(attempt + 1)];
case 5:
_b.sent();
_b.label = 6;
case 6: return [2 /*return*/];
}
});
});
};
return [4 /*yield*/, work(0)];
case 1:
_c.sent();
return [2 /*return*/];
}
});
});
};
/**
* Requests a snapshot of the entire state buffer from the peripheral.
* @returns Buffer containing the state.
*/
RadiatorValve.prototype.requestStateSnapshot = function () {
return __awaiter(this, void 0, void 0, function () {
var buffer, offset, packet, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
buffer = Buffer.alloc(0);
offset = 0;
_a.label = 1;
case 1:
if (!(offset < constants_1.VALVE_STATE_LENGTH)) return [3 /*break*/, 4];
packet = (0, protocol_1.createStateReadPacket)(offset, constants_1.MAX_STATE_READ_CHUNK);
return [4 /*yield*/, this.sendRequest(packet)];
case 2:
response = _a.sent();
// Skip header and checksum.
response = response.subarray(protocol_1.PACKET_HEADER_LENGTH, response.length - protocol_1.RESPONSE_FOOTER_LENGTH);
buffer = Buffer.concat([buffer, response]);
_a.label = 3;
case 3:
offset += constants_1.MAX_STATE_READ_CHUNK;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, buffer];
}
});
});
};
RadiatorValve.prototype.setName = function (name) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (name.length > 64) {
throw new Error("Name can not be longer than 64 characters");
}
return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [4 /*yield*/, this.requestWriteField(valve_state_1.FIELD_NAME, name)];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
RadiatorValve.prototype.getName = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [2 /*return*/, this.requestReadField(valve_state_1.FIELD_NAME)];
}
});
});
};
RadiatorValve.prototype.getSerialNumber = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [2 /*return*/, this.requestReadField(valve_state_1.FIELD_SERIAL_NUMBER)];
}
});
});
};
RadiatorValve.prototype.setLocked = function (locked) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [4 /*yield*/, this.requestWriteField(valve_state_1.FIELD_LOCKED, locked ? 1 : 0)];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
RadiatorValve.prototype.getLocked = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [2 /*return*/, this.requestReadField(valve_state_1.FIELD_LOCKED)];
}
});
});
};
RadiatorValve.prototype.getBatteryVoltage = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [2 /*return*/, this.requestReadField(valve_state_1.FIELD_BATTERY_VOLTAGE)];
}
});
});
};
RadiatorValve.prototype.getTemperatureDeviation = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [2 /*return*/, this.requestReadField(valve_state_1.FIELD_TEMPERATURE_DEVIATION)];
}
});
});
};
RadiatorValve.prototype.getCurrentTemperature = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [2 /*return*/, this.requestReadField(valve_state_1.FIELD_CURRENT_TEMPERATURE)];
}
});
});
};
/**
* Sets the target temperature.
* It takes up to 9 minutes for the valve to actually apply
* the update in case of this field.
*
* @param value New target temperature.
*/
RadiatorValve.prototype.setTargetTemperature = function (value) {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (value < 0.5 || value > 29.5) {
throw new Error("Target temperature must be in [0.5-29.5] range");
}
return [4 /*yield*/, this.requestWakeUp()];
case 1:
_b.sent();
_a = this.requestWriteField;
return [4 /*yield*/, this.getTargetTemperatureField()];
case 2: return [4 /*yield*/, _a.apply(this, [_b.sent(), value])];
case 3:
_b.sent();
return [2 /*return*/];
}
});
});
};
RadiatorValve.prototype.getTargetTemperatureField = function () {
return __awaiter(this, void 0, void 0, function () {
var mode;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getMode()];
case 1:
mode = _a.sent();
if (mode === 0) {
return [2 /*return*/, valve_state_1.FIELD_TARGET_TEMPERATURE_AUTO];
}
else if (mode === 1) {
return [2 /*return*/, valve_state_1.FIELD_TARGET_TEMPERATURE_MANUAL];
}
else if (mode === 2) {
return [2 /*return*/, valve_state_1.FIELD_TARGET_TEMPERATURE_SAVING];
}
throw new Error("Unknown mode: ".concat(mode));
}
});
});
};
RadiatorValve.prototype.getTargetTemperature = function () {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_b.sent();
_a = this.requestReadField;
return [4 /*yield*/, this.getTargetTemperatureField()];
case 2: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
RadiatorValve.prototype.getMode = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.requestWakeUp()];
case 1:
_a.sent();
return [2 /*return*/, this.requestReadField(valve_state_1.FIELD_MODE)];
}
});
});
};
return RadiatorValve;
}());
exports.default = RadiatorValve;