const Client = require("iconsole-bike-client"); const _ = require("underscore"); const EventEmitter = require("events"); class IConsoleDriver { constructor(connect) { this.connectString = connect; this.client = null; this.events = new EventEmitter(); this.maxLevel = 24; this.lastLevel = 18; this.workoutStatus = {}; this.started = false; this.state = "disconnected"; } async connect() { this.client = await Client.scan(this.connectString.toLowerCase(), 15000) await this.client.connect(); this.client.events.on("data", ({kind, workoutStatus, maxLevel}) => { switch (kind) { case "workoutStatus": { if (!_.isEqual(this.workoutStatus, workoutStatus)) { this.workoutStatus = {...workoutStatus}; this.events.emit("workoutStatus", {...workoutStatus}); } break; } case "maxLevel": { this.events.emit("maxLevel", maxLevel); break; } } }); this.state = this.client.state; } async start() { if (!this.started) { await this.client.start({level: this.lastLevel}); this.started = true; } else { await this.client.resume(); await this.client.setLevel(this.lastLevel); } this.state = "started"; } async pause() { await this.client.pause(); this.state = "connected"; } async resume() { await this.client.resume(); this.state = "started"; } async stop() { await this.client.pause(); } async setLevel(n) { if (n < 0 || n > this.maxLevel) { return Promise.reject(new Error(`Level is out of range (0 - ${this.maxLevel})`)) } this.lastLevel = n; return await this.client.setLevel(n); } destroy() { this.stop(); this.client.disconnect(); this.events.emit("destroy"); this.events.removeAllListeners(); } } module.exports = IConsoleDriver;