init.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. var __generator = (this && this.__generator) || function (thisArg, body) {
  12. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  13. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  14. function verb(n) { return function (v) { return step([n, v]); }; }
  15. function step(op) {
  16. if (f) throw new TypeError("Generator is already executing.");
  17. while (g && (g = 0, op[0] && (_ = 0)), _) try {
  18. 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;
  19. if (y = 0, t) op = [op[0] & 2, t.value];
  20. switch (op[0]) {
  21. case 0: case 1: t = op; break;
  22. case 4: _.label++; return { value: op[1], done: false };
  23. case 5: _.label++; y = op[1]; op = [0]; continue;
  24. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  25. default:
  26. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  27. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  28. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  29. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  30. if (t[2]) _.ops.pop();
  31. _.trys.pop(); continue;
  32. }
  33. op = body.call(thisArg, _);
  34. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  35. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  36. }
  37. };
  38. var __values = (this && this.__values) || function(o) {
  39. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  40. if (m) return m.call(o);
  41. if (o && typeof o.length === "number") return {
  42. next: function () {
  43. if (o && i >= o.length) o = void 0;
  44. return { value: o && o[i++], done: !o };
  45. }
  46. };
  47. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  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. exports.setCkDeviceOnlineState = exports.initWs2Ck = exports.ws2ckRes = exports.curUserGwData = exports.ws2ha = exports.init = exports.closeWs2Ck = void 0;
  54. var WebSocket2Ha_1 = require("./WebSocket2Ha");
  55. var dataUtil_1 = require("../utils/dataUtil");
  56. var coolkit_api_1 = __importDefault(require("coolkit-api"));
  57. var coolkit_api_device_1 = __importDefault(require("coolkit-api-device"));
  58. var lodash_1 = __importDefault(require("lodash"));
  59. var app_1 = require("../config/app");
  60. var coolkit_ws_device_1 = __importDefault(require("coolkit-ws-device"));
  61. var protocols_1 = require("./protocols");
  62. var eventBus_1 = __importDefault(require("../utils/eventBus"));
  63. var process_1 = __importDefault(require("process"));
  64. var logger_1 = require("../utils/logger");
  65. var api_1 = require("./api");
  66. var uuid4 = require('uuid').v4;
  67. var WS_ONLINE = 2;
  68. var WS_OFFLINE = 3;
  69. var ws2ha;
  70. exports.ws2ha = ws2ha;
  71. var curUserGwData = null;
  72. exports.curUserGwData = curUserGwData;
  73. var ws2ckRes;
  74. exports.ws2ckRes = ws2ckRes;
  75. function setCkDeviceOnlineState(_a) {
  76. var subDevId = _a.subDevId, uiid = _a.uiid, deviceid = _a.deviceid, online = _a.online;
  77. return __awaiter(this, void 0, void 0, function () {
  78. return __generator(this, function (_b) {
  79. coolkit_ws_device_1.default.sendMessage({
  80. action: 'subDevice',
  81. apikey: curUserGwData.userApiKey,
  82. deviceid: curUserGwData.gwDeviceid,
  83. userAgent: 'device',
  84. params: {
  85. cmds: [
  86. {
  87. uiid: uiid,
  88. type: online ? WS_ONLINE : WS_OFFLINE,
  89. subDevId: subDevId,
  90. deviceid: deviceid
  91. }
  92. ]
  93. }
  94. });
  95. return [2];
  96. });
  97. });
  98. }
  99. exports.setCkDeviceOnlineState = setCkDeviceOnlineState;
  100. function handleDeleteGateway() {
  101. return __awaiter(this, void 0, void 0, function () {
  102. return __generator(this, function (_a) {
  103. switch (_a.label) {
  104. case 0:
  105. exports.curUserGwData = curUserGwData = [];
  106. return [4, (0, dataUtil_1.setGwData)([])];
  107. case 1:
  108. _a.sent();
  109. closeWs2Ck();
  110. init();
  111. setTimeout(function () {
  112. eventBus_1.default.emit('sse-update-ha-device');
  113. }, 1000);
  114. return [2];
  115. }
  116. });
  117. });
  118. }
  119. function initWs2Ck(_a) {
  120. var apikey = _a.apikey, region = _a.region, deviceid = _a.deviceid;
  121. return __awaiter(this, void 0, void 0, function () {
  122. return __generator(this, function (_b) {
  123. switch (_b.label) {
  124. case 0:
  125. logger_1.logger.info('Init websocket to CK...');
  126. logger_1.logger.verbose("apikey: ".concat(apikey));
  127. return [4, coolkit_ws_device_1.default.init({
  128. userAgent: 'device',
  129. apikey: apikey,
  130. region: region,
  131. deviceid: deviceid,
  132. useTestEnv: process_1.default.env.CK_API_ENV === 'test',
  133. debug: true
  134. })];
  135. case 1:
  136. exports.ws2ckRes = ws2ckRes = _b.sent();
  137. coolkit_ws_device_1.default.on('message', function (e) {
  138. try {
  139. var msg = JSON.parse(e.data);
  140. if (msg.action === 'update') {
  141. (0, protocols_1.handleCkWsUpdateMessage)(msg);
  142. }
  143. else if (msg.action === 'notify' && msg.cmd === 'deleteNotify') {
  144. handleDeleteGateway();
  145. }
  146. }
  147. catch (err) {
  148. }
  149. });
  150. return [2];
  151. }
  152. });
  153. });
  154. }
  155. exports.initWs2Ck = initWs2Ck;
  156. function closeWs2Ck() {
  157. if (coolkit_ws_device_1.default.isWsExist()) {
  158. coolkit_ws_device_1.default.close();
  159. ws2ckRes.error = -1;
  160. }
  161. }
  162. exports.closeWs2Ck = closeWs2Ck;
  163. function init() {
  164. return __awaiter(this, void 0, void 0, function () {
  165. var userData, userApiKey, gwData, gwuuid, found, data, deviceListRes, deviceList, newGwData, index, i, userGwuuid, apikey, deviceid, region, devList, devList_1, devList_1_1, dev, entities, online, params;
  166. var e_1, _a;
  167. return __generator(this, function (_b) {
  168. switch (_b.label) {
  169. case 0:
  170. logger_1.logger.info('Start init lib-ha...');
  171. if (!lodash_1.default.get(ws2ha, 'connected')) {
  172. exports.ws2ha = ws2ha = new WebSocket2Ha_1.WebSocket2Ha();
  173. }
  174. return [4, (0, dataUtil_1.initLibHaFiles)()];
  175. case 1:
  176. _b.sent();
  177. userData = (0, dataUtil_1.getDataSync)('user.json', ['user']);
  178. if (!userData) {
  179. return [2];
  180. }
  181. userApiKey = userData.apikey;
  182. return [4, (0, dataUtil_1.getGwData)()];
  183. case 2:
  184. gwData = _b.sent();
  185. gwuuid = uuid4();
  186. if (!!(found = lodash_1.default.find(gwData, { userApiKey: userApiKey }))) return [3, 4];
  187. data = {
  188. userApiKey: userData.apikey,
  189. gwuuid: gwuuid,
  190. gwInList: false,
  191. };
  192. gwData.push(data);
  193. exports.curUserGwData = curUserGwData = data;
  194. return [4, (0, dataUtil_1.setGwData)(gwData)];
  195. case 3:
  196. _b.sent();
  197. return [3, 5];
  198. case 4:
  199. exports.curUserGwData = curUserGwData = found;
  200. _b.label = 5;
  201. case 5: return [4, coolkit_api_1.default.device.getThingList()];
  202. case 6:
  203. deviceListRes = _b.sent();
  204. if (deviceListRes.error !== 0) {
  205. return [2];
  206. }
  207. deviceList = deviceListRes.data.thingList;
  208. return [4, (0, dataUtil_1.getGwData)()];
  209. case 7:
  210. newGwData = _b.sent();
  211. index = lodash_1.default.findIndex(newGwData, { userApiKey: userApiKey });
  212. for (i = 0; i < deviceList.length; i++) {
  213. userGwuuid = lodash_1.default.get(deviceList[i].itemData, 'params.partnerDevice.ezVedioSerial');
  214. if (userGwuuid === newGwData[index].gwuuid) {
  215. apikey = lodash_1.default.get(deviceList[i], 'itemData.devicekey');
  216. deviceid = lodash_1.default.get(deviceList[i], 'itemData.deviceid');
  217. region = (0, dataUtil_1.getDataSync)('user.json', ['region']);
  218. coolkit_api_device_1.default.init({
  219. apikey: apikey,
  220. appSecret: app_1.appSecret,
  221. deviceid: deviceid,
  222. region: region,
  223. useTestEnv: process_1.default.env.CK_API_ENV === 'test'
  224. });
  225. newGwData[index].gwInList = true;
  226. break;
  227. }
  228. else {
  229. newGwData[index].gwInList = false;
  230. continue;
  231. }
  232. }
  233. exports.curUserGwData = curUserGwData = newGwData[index];
  234. return [4, (0, dataUtil_1.setGwData)(newGwData)];
  235. case 8:
  236. _b.sent();
  237. if (!(curUserGwData.gwInList && lodash_1.default.get(ws2ckRes, 'error') !== 0)) return [3, 11];
  238. return [4, initWs2Ck({
  239. apikey: curUserGwData.gwApikey,
  240. region: (0, dataUtil_1.getDataSync)('user.json', ['region']),
  241. deviceid: curUserGwData.gwDeviceid
  242. })];
  243. case 9:
  244. _b.sent();
  245. return [4, (0, api_1.getHaDeviceList)()];
  246. case 10:
  247. devList = _b.sent();
  248. if (devList !== -1) {
  249. try {
  250. for (devList_1 = __values(devList), devList_1_1 = devList_1.next(); !devList_1_1.done; devList_1_1 = devList_1.next()) {
  251. dev = devList_1_1.value;
  252. if (dev.ckDeviceData) {
  253. entities = dev.haDeviceData.entities;
  254. online = true;
  255. if (entities.some(function (entity) { return entity.entityState.state === 'unavailable'; })) {
  256. online = false;
  257. }
  258. setCkDeviceOnlineState({
  259. subDevId: dev.haDeviceData.deviceId,
  260. uiid: dev.deviceUiid,
  261. deviceid: dev.ckDeviceData.deviceid,
  262. online: online
  263. });
  264. params = (0, protocols_1.initDeviceParams)(dev);
  265. coolkit_ws_device_1.default.sendMessage(JSON.stringify({
  266. action: 'update',
  267. apikey: curUserGwData.userApiKey,
  268. deviceid: dev.ckDeviceData.deviceid,
  269. userAgent: 'device',
  270. params: params
  271. }));
  272. }
  273. }
  274. }
  275. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  276. finally {
  277. try {
  278. if (devList_1_1 && !devList_1_1.done && (_a = devList_1.return)) _a.call(devList_1);
  279. }
  280. finally { if (e_1) throw e_1.error; }
  281. }
  282. }
  283. _b.label = 11;
  284. case 11: return [2];
  285. }
  286. });
  287. });
  288. }
  289. exports.init = init;