You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
1.8 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. const Client = require("iconsole-bike-client");
  2. const _ = require("underscore");
  3. const EventEmitter = require("events");
  4. class IConsoleDriver {
  5. constructor(connect) {
  6. this.connectString = connect;
  7. this.client = null;
  8. this.events = new EventEmitter();
  9. this.maxLevel = 24;
  10. this.lastLevel = 18;
  11. this.workoutStatus = {};
  12. this.started = false;
  13. this.state = "disconnected";
  14. }
  15. async connect() {
  16. this.client = await Client.scan(this.connectString.toLowerCase(), 15000)
  17. await this.client.connect();
  18. this.client.events.on("data", ({kind, workoutStatus, maxLevel}) => {
  19. switch (kind) {
  20. case "workoutStatus": {
  21. if (!_.isEqual(this.workoutStatus, workoutStatus)) {
  22. this.workoutStatus = {...workoutStatus};
  23. this.events.emit("workoutStatus", {...workoutStatus});
  24. }
  25. break;
  26. }
  27. case "maxLevel": {
  28. this.events.emit("maxLevel", maxLevel);
  29. break;
  30. }
  31. }
  32. });
  33. this.state = this.client.state;
  34. }
  35. async start() {
  36. if (!this.started) {
  37. await this.client.start({level: this.lastLevel});
  38. this.started = true;
  39. } else {
  40. await this.client.resume();
  41. }
  42. this.state = "started";
  43. }
  44. async pause() {
  45. await this.client.pause();
  46. this.state = "connected";
  47. }
  48. async resume() {
  49. await this.client.resume();
  50. this.state = "started";
  51. }
  52. async stop() {
  53. await this.client.pause();
  54. }
  55. async setLevel(n) {
  56. if (n < 0 || n > this.maxLevel) {
  57. return Promise.reject(new Error(`Level is out of range (0 - ${this.maxLevel})`))
  58. }
  59. this.lastLevel = n;
  60. return await this.client.setLevel(n);
  61. }
  62. destroy() {
  63. this.stop();
  64. this.client.disconnect();
  65. this.events.emit("destroy");
  66. this.events.removeAllListeners();
  67. }
  68. }
  69. module.exports = IConsoleDriver;