HASocketClass.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. "use strict";
  2. var __assign = (this && this.__assign) || function () {
  3. __assign = Object.assign || function(t) {
  4. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5. s = arguments[i];
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  7. t[p] = s[p];
  8. }
  9. return t;
  10. };
  11. return __assign.apply(this, arguments);
  12. };
  13. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  14. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  15. return new (P || (P = Promise))(function (resolve, reject) {
  16. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  17. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  18. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  19. step((generator = generator.apply(thisArg, _arguments || [])).next());
  20. });
  21. };
  22. var __generator = (this && this.__generator) || function (thisArg, body) {
  23. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  24. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  25. function verb(n) { return function (v) { return step([n, v]); }; }
  26. function step(op) {
  27. if (f) throw new TypeError("Generator is already executing.");
  28. while (g && (g = 0, op[0] && (_ = 0)), _) try {
  29. 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;
  30. if (y = 0, t) op = [op[0] & 2, t.value];
  31. switch (op[0]) {
  32. case 0: case 1: t = op; break;
  33. case 4: _.label++; return { value: op[1], done: false };
  34. case 5: _.label++; y = op[1]; op = [0]; continue;
  35. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  36. default:
  37. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  38. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  39. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  40. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  41. if (t[2]) _.ops.pop();
  42. _.trys.pop(); continue;
  43. }
  44. op = body.call(thisArg, _);
  45. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  46. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  47. }
  48. };
  49. var __importDefault = (this && this.__importDefault) || function (mod) {
  50. return (mod && mod.__esModule) ? mod : { "default": mod };
  51. };
  52. Object.defineProperty(exports, "__esModule", { value: true });
  53. var ws_1 = __importDefault(require("ws"));
  54. var url_1 = require("../config/url");
  55. var AuthClass_1 = __importDefault(require("./AuthClass"));
  56. var initHaSocket_1 = __importDefault(require("../utils/initHaSocket"));
  57. var syncDevice2Ha_1 = __importDefault(require("../utils/syncDevice2Ha"));
  58. var logger_1 = require("../utils/logger");
  59. var HaSocket = (function () {
  60. function HaSocket() {
  61. this.count = 1;
  62. this.connect();
  63. this.heartBeat();
  64. }
  65. HaSocket.prototype.connect = function () {
  66. try {
  67. this.client = new ws_1.default(url_1.HaSocketURL);
  68. this.client.on('error', function () {
  69. logger_1.logger.warn('Please check HA running state');
  70. });
  71. }
  72. catch (error) {
  73. logger_1.logger.warn("init HA-WS error: ".concat(error));
  74. }
  75. };
  76. HaSocket.createInstance = function () {
  77. if (!HaSocket.instance) {
  78. HaSocket.instance = new HaSocket();
  79. }
  80. return HaSocket.instance;
  81. };
  82. HaSocket.prototype.init = function (reconnect) {
  83. if (reconnect === void 0) { reconnect = false; }
  84. return __awaiter(this, void 0, void 0, function () {
  85. var handler;
  86. var _this = this;
  87. return __generator(this, function (_a) {
  88. if (reconnect) {
  89. this.connect();
  90. }
  91. return [2, new Promise(function (resolve, reject) {
  92. _this.client.on('open', function () {
  93. if (_this.client.readyState !== 1) {
  94. resolve(-1);
  95. }
  96. _this.client.send(JSON.stringify({
  97. type: 'auth',
  98. access_token: AuthClass_1.default.curAuth,
  99. }));
  100. });
  101. _this.client.on('message', (handler = function (res) {
  102. try {
  103. var data = JSON.parse(res);
  104. if (data.type === 'auth_ok') {
  105. resolve(0);
  106. if (reconnect) {
  107. (0, syncDevice2Ha_1.default)({
  108. syncLovelace: false,
  109. sleepTime: 2000,
  110. });
  111. }
  112. _this.client.removeEventListener('message', handler);
  113. }
  114. }
  115. catch (error) {
  116. logger_1.logger.warn("HaSocket init error: ".concat(error));
  117. resolve(-1);
  118. }
  119. }));
  120. })];
  121. });
  122. });
  123. };
  124. HaSocket.prototype.heartBeat = function () {
  125. var _this = this;
  126. setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
  127. var res;
  128. return __generator(this, function (_a) {
  129. switch (_a.label) {
  130. case 0: return [4, this.query({
  131. type: 'ping',
  132. })];
  133. case 1:
  134. res = _a.sent();
  135. logger_1.logger.info("HA-WS heart beat result: ".concat(JSON.stringify(res)));
  136. if (res === -1) {
  137. (0, initHaSocket_1.default)(true);
  138. }
  139. this.heartBeat();
  140. return [2];
  141. }
  142. });
  143. }); }, 120000);
  144. };
  145. HaSocket.prototype.subscribeEvents = function (eventType) {
  146. this.client.send(JSON.stringify({
  147. id: this.count++,
  148. type: 'subscribe_events',
  149. event_type: eventType,
  150. }));
  151. };
  152. HaSocket.prototype.handleEvent = function (eventType, handler) {
  153. this.client.on('message', function (res) {
  154. try {
  155. var data = JSON.parse(res);
  156. if (data.type === 'event' && data.event.event_type === eventType) {
  157. handler(data.event.data);
  158. }
  159. }
  160. catch (err) {
  161. logger_1.logger.warn("HaSocket handleEvent error: ".concat(err));
  162. }
  163. });
  164. };
  165. HaSocket.prototype.query = function (data) {
  166. return __awaiter(this, void 0, void 0, function () {
  167. var cur, handler;
  168. var _this = this;
  169. return __generator(this, function (_a) {
  170. if (this.client.readyState !== 1) {
  171. logger_1.logger.warn('Could not connect to HA-WS, please restart addon');
  172. return [2, -1];
  173. }
  174. cur = this.count++;
  175. return [2, new Promise(function (resolve) {
  176. _this.client.send(JSON.stringify(__assign({ id: cur }, data)));
  177. setTimeout(function () {
  178. _this.client.removeEventListener('message', handler);
  179. resolve(-1);
  180. }, 5000);
  181. _this.client.on('message', (handler = function (res) {
  182. try {
  183. var data_1 = JSON.parse(res);
  184. if (data_1.id === cur) {
  185. if (!data_1.result && data_1.type) {
  186. resolve(data_1.type);
  187. }
  188. resolve(data_1.result);
  189. _this.client.removeEventListener('message', handler);
  190. }
  191. }
  192. catch (error) {
  193. logger_1.logger.warn("HaSocket query error: ".concat(error));
  194. resolve(-1);
  195. _this.client.removeEventListener('message', handler);
  196. }
  197. }));
  198. })];
  199. });
  200. });
  201. };
  202. HaSocket.prototype.getStates = function () {
  203. this.client.send(JSON.stringify({
  204. id: this.count++,
  205. type: 'get_states',
  206. }));
  207. };
  208. HaSocket.prototype.getConfig = function () {
  209. this.client.send(JSON.stringify({
  210. id: this.count++,
  211. type: 'get_config',
  212. }));
  213. };
  214. HaSocket.prototype.getLovelace = function () {
  215. return __awaiter(this, void 0, void 0, function () {
  216. var res;
  217. return __generator(this, function (_a) {
  218. switch (_a.label) {
  219. case 0: return [4, this.query({
  220. type: 'lovelace/config',
  221. })];
  222. case 1:
  223. res = _a.sent();
  224. return [2, res];
  225. }
  226. });
  227. });
  228. };
  229. HaSocket.prototype.getLongLivedToken = function () {
  230. return __awaiter(this, void 0, void 0, function () {
  231. var res;
  232. return __generator(this, function (_a) {
  233. switch (_a.label) {
  234. case 0:
  235. if (this.client.readyState !== 1) {
  236. return [2, null];
  237. }
  238. return [4, this.query({
  239. type: 'auth/long_lived_access_token',
  240. client_name: 'eWeLink Smart Home',
  241. lifespan: 3650,
  242. })];
  243. case 1:
  244. res = _a.sent();
  245. return [2, res];
  246. }
  247. });
  248. });
  249. };
  250. return HaSocket;
  251. }());
  252. var instance = HaSocket.createInstance();
  253. exports.default = instance;