Hydrawise.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. "use strict";
  2. /**
  3. * @author Miroslav Abrahám - Further modifications and fixes
  4. * @author Martijn Dierckx - Complete rewrite to service both the cloud & local API binding
  5. * @author Paul Molluzzo (https://paulmolluzzo.com) - Initial 0.1.0 version containing the cloud binding
  6. */
  7. Object.defineProperty(exports, "__esModule", { value: true });
  8. exports.Hydrawise = void 0;
  9. var HydrawiseConnectionType_1 = require("./HydrawiseConnectionType");
  10. var HydrawiseZone_1 = require("./HydrawiseZone");
  11. var HydrawiseController_1 = require("./HydrawiseController");
  12. var HydrawiseCommandException_1 = require("./HydrawiseCommandException");
  13. var axios_1 = require("axios");
  14. /** Class representing a Hydrawise local or cloud based API binding */
  15. var Hydrawise = /** @class */ (function () {
  16. /**
  17. * Create a new instance of the Hydrawise API binding
  18. * @param {object} options - Options object containing all parameters
  19. * @param {string} options.type - The type of binding you wish to make: 'CLOUD' or 'LOCAL'
  20. * @param {string} [options.host] - The hostname or ip address of the local host you wish to connect to. Only needed for local bindings.
  21. * @param {string} [options.user = admin] - The username of the local Hydrawise controller. Only needed for local bindings (falls back to the default 'admin' user).
  22. * @param {string} [options.password] - The password of the local Hydrawise controller. Only needed for local bindings.
  23. * @param {string} [options.key] - The API key of your Hydrawise cloud account. Only needed for cloud bindings.
  24. */
  25. function Hydrawise(options) {
  26. this.cloudUrl = 'https://app.hydrawise.com/api/v1/';
  27. this.type = options.type || HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD; // CLOUD or LOCAL
  28. this.url = (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL ? 'http://' + options.host + '/' : this.cloudUrl);
  29. // Local Auth
  30. this.localAuthUsername = options.user || 'admin';
  31. this.localAuthPassword = options.password || '';
  32. // Cloud Auth
  33. this.cloudAuthAPIkey = options.key || '';
  34. }
  35. /**
  36. * Private function that makes a GET request to the local or cloud Hydrawise server
  37. * @param {string} path - The path of the API endpoint
  38. * @param {object} [params] - Parameters to be added to the URL path
  39. * @return {Promise} A Promise which will be resolved when the request has returned from the local or cloud server.
  40. */
  41. Hydrawise.prototype.request = function (path, params) {
  42. var _this = this;
  43. if (path === void 0) { path = ''; }
  44. if (params === void 0) { params = {}; }
  45. var promise = new Promise(function (resolve, reject) {
  46. // setup basic request
  47. var options = {
  48. method: 'get',
  49. url: _this.url + path,
  50. params: params,
  51. json: true
  52. };
  53. // Basic auth for local binding
  54. if (_this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL) {
  55. var authBuffer = Buffer.from(_this.localAuthUsername + ':' + _this.localAuthPassword);
  56. options.headers = {
  57. 'Authorization': 'Basic ' + authBuffer.toString('base64')
  58. };
  59. }
  60. // API key auth for cloud binding
  61. else {
  62. options.params.api_key = _this.cloudAuthAPIkey;
  63. }
  64. // Send request
  65. (0, axios_1.default)(options).then(function (response) {
  66. //Check for errors
  67. if (response.data.messageType == 'error') {
  68. reject(new HydrawiseCommandException_1.HydrawiseCommandException(response.data.message));
  69. }
  70. resolve(response.data);
  71. }).catch(function (err) {
  72. reject(err);
  73. });
  74. });
  75. // return request
  76. return promise;
  77. };
  78. /**
  79. * Sends a command to a single zone/relay
  80. * @param {string} action - The required command to be executed for the given zone/relay: run, suspend, stop
  81. * @param {(HydrawiseZone|number|number)} zoneOrRelay - The zone/relay you are targetting. Can be a zone object returned by getZones, a relay number (zone.zone) for local bindings or a relayID (zone.relayID) for cloud bindings
  82. * @param {number} [duration] - How long should the command be executed (only applicable for run & suspend)
  83. * @todo Allow using a controller id instead of HydrawiseController object.
  84. * @return {Promise} A Promise which will be resolved when the command has been executed.
  85. */
  86. Hydrawise.prototype.commandZone = function (action, zoneOrRelay, duration) {
  87. var that = this;
  88. // Get started
  89. var promise = new Promise(function (resolve, reject) {
  90. var opts = {
  91. period_id: 998,
  92. action: action,
  93. };
  94. // Set Relay number for local binding
  95. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL) {
  96. opts.relay = zoneOrRelay instanceof HydrawiseZone_1.HydrawiseZone ? zoneOrRelay.zone : zoneOrRelay; // A zone object, as returned by getZones, or just the relayID can be sent
  97. }
  98. // Set Relay ID for cloud binding
  99. else {
  100. opts.relay_id = zoneOrRelay instanceof HydrawiseZone_1.HydrawiseZone ? zoneOrRelay.relayID : zoneOrRelay; // A zone object, as returned by getZones, or just the relayID can be sent
  101. }
  102. // Custom duration?
  103. if (duration !== undefined) {
  104. opts.custom = duration;
  105. }
  106. // Set controller if one was provided (only for cloud)
  107. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD && zoneOrRelay instanceof HydrawiseZone_1.HydrawiseZone && zoneOrRelay.controller !== undefined && zoneOrRelay.controller instanceof HydrawiseController_1.HydrawiseController) {
  108. opts.controller_id = zoneOrRelay.controller.id;
  109. }
  110. // Execute command
  111. that.setZone(opts).then(function (data) {
  112. resolve(data);
  113. }).catch(function (err) {
  114. reject(err);
  115. });
  116. });
  117. return promise;
  118. };
  119. /**
  120. * Sends a command to all zones/relays
  121. * @param {string} action - The required command to be executed: runall, suspendall, stopall
  122. * @param {number} [duration] - How long should the given command be executed (only applicable for runall & suspendall)
  123. * @todo Check whether controller_id needs to sent when the account contains multiple zones
  124. * @return {Promise} A Promise which will be resolved when the command has been executed.
  125. */
  126. Hydrawise.prototype.commandAllZones = function (action, controller, duration) {
  127. var that = this;
  128. // Get started
  129. var promise = new Promise(function (resolve, reject) {
  130. var opts = {
  131. period_id: 998,
  132. action: action
  133. };
  134. // Custom duration?
  135. if (duration !== undefined) {
  136. opts.custom = duration;
  137. }
  138. // Specific controller? (only cloud)
  139. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD && controller !== undefined && controller !== null) {
  140. if (controller instanceof HydrawiseController_1.HydrawiseController) {
  141. opts.controller_id = controller.id;
  142. }
  143. else {
  144. opts.controller_id = controller;
  145. }
  146. }
  147. that.setZone(opts).then(function (data) {
  148. resolve(data);
  149. }).catch(function (err) {
  150. reject(err);
  151. });
  152. });
  153. return promise;
  154. };
  155. /**
  156. * Sends the run command to a single zone/relay
  157. * @param {(HydrawiseZone|number)} zoneOrRelay - The zone/relay you are targetting. Can be a zone object returned by getZones, a relay number (zone.zone) for local bindings or a relayID (zone.relayID) for cloud bindings
  158. * @param {number} [duration] - How long should the command be executed
  159. * @return {Promise} A Promise which will be resolved when the command has been executed.
  160. */
  161. Hydrawise.prototype.runZone = function (zoneOrRelay, duration) {
  162. return this.commandZone('run', zoneOrRelay, duration);
  163. };
  164. /**
  165. * Sends the run command to all zones/relays
  166. * @param {number} [duration] - How long should the command be executed
  167. * @return {Promise} A Promise which will be resolved when the command has been executed.
  168. */
  169. Hydrawise.prototype.runAllZones = function (controller, duration) {
  170. return this.commandAllZones('runall', controller, duration);
  171. };
  172. /**
  173. * Sends the suspend command to a single zone/relay
  174. * @param {(HydrawiseZone|number)} zoneOrRelay - The zone/relay you are targetting. Can be a zone object returned by getZones, a relay number (zone.zone) for local bindings or a relayID (zone.relayID) for cloud bindings
  175. * @param {number} [duration] - How long should the command be executed
  176. * @return {Promise} A Promise which will be resolved when the command has been executed.
  177. */
  178. Hydrawise.prototype.suspendZone = function (zoneOrRelay, duration) {
  179. return this.commandZone('suspend', zoneOrRelay, duration);
  180. };
  181. /**
  182. * Sends the suspend command to all zones/relays for a specific controller
  183. * @param {number} [duration] - How long should the command be executed
  184. * @param {HydrawiseController|number} [controller] - Return zones for a specific controller. If not specified, the zones of the deault controller are returned.
  185. * @return {Promise} A Promise which will be resolved when the command has been executed.
  186. */
  187. Hydrawise.prototype.suspendAllZones = function (controller, duration) {
  188. return this.commandAllZones('suspendall', controller, duration);
  189. };
  190. /**
  191. * Sends the stop command to a single zone/relay
  192. * @param {(HydrawiseZone|number)} zoneOrRelay - The zone/relay you are targetting. Can be a zone object returned by getZones, a relay number (zone.zone) for local bindings or a relayID (zone.relayID) for cloud bindings
  193. * @return {Promise} A Promise which will be resolved when the command has been executed.
  194. */
  195. Hydrawise.prototype.stopZone = function (zoneOrRelay) {
  196. return this.commandZone('stop', zoneOrRelay);
  197. };
  198. /**
  199. * Sends the stop command to all zones/relays
  200. * @return {Promise} A Promise which will be resolved when the command has been executed.
  201. */
  202. Hydrawise.prototype.stopAllZones = function (controller) {
  203. return this.commandAllZones('stopall', controller);
  204. };
  205. /**
  206. * Retrieves all zones/relays known to the server
  207. * @param {HydrawiseController|number} [controller] - Return zones for a specific controller. If not specified, the zones of the deault controller are returned.
  208. * @return {Promise} A Promise which will be resolved when all zones have been retrieved
  209. */
  210. Hydrawise.prototype.getZones = function (controller) {
  211. var that = this;
  212. // Get started
  213. var promise = new Promise(function (resolve, reject) {
  214. // Controller set?
  215. var controllerID;
  216. if (controller !== undefined && controller !== null) {
  217. if (controller instanceof HydrawiseController_1.HydrawiseController) {
  218. controllerID = controller.id;
  219. }
  220. else {
  221. controllerID = controller;
  222. }
  223. }
  224. // Get relays
  225. that.getStatusAndSchedule(controllerID).then(function (data) {
  226. var zones = [];
  227. // Check every returned relay
  228. data.relays.map(function (z) {
  229. // Only configured zones
  230. // Commented out because it drive the zones unusable from time to time by filtering them out
  231. // if(that.type == HydrawiseConnectionType.CLOUD || z.lastwaterepoch != 0){
  232. // Zone
  233. var zone = {
  234. apiBinding: that,
  235. relayID: z.relay_id,
  236. zone: z.relay,
  237. name: z.name,
  238. nextRunAt: new Date((data.time + z.time) * 1000),
  239. nextRunDuration: z.run || z.run_seconds,
  240. isSuspended: z.suspended !== undefined && z.suspended == 1,
  241. isRunning: false,
  242. remainingRunningTime: 0
  243. };
  244. // Link controller to the zones if it was provided when calling the method
  245. if (controller !== undefined && controller !== null && controller instanceof HydrawiseController_1.HydrawiseController) {
  246. zone.controller = controller;
  247. }
  248. // Only available data for local connections
  249. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL) {
  250. zone.defaultRunDuration = z.normalRuntime * 60;
  251. }
  252. // Running? (local connection)
  253. if (data.running !== undefined) {
  254. var runningZone = data.running.find(function (x) {
  255. return x.relay_id == z.relay_id;
  256. });
  257. if (runningZone != undefined && runningZone != null) {
  258. zone.isRunning = true;
  259. zone.remainingRunningTime = runningZone.time_left;
  260. }
  261. }
  262. // Running? (cloud connection)
  263. if (z.time == 1) {
  264. zone.isRunning = true;
  265. zone.remainingRunningTime = z.run;
  266. }
  267. zones.push(new HydrawiseZone_1.HydrawiseZone(zone));
  268. // }
  269. });
  270. resolve(zones);
  271. }).catch(function (err) {
  272. reject(err);
  273. });
  274. });
  275. return promise;
  276. };
  277. /**
  278. * Retrieves all controllers known to the Hydrawise cloud or returns a single dummy one for a local connection
  279. * @return {Promise} A Promise which will be resolved when all controllers have been retrieved
  280. */
  281. Hydrawise.prototype.getControllers = function () {
  282. var _this = this;
  283. var that = this;
  284. // Get started
  285. var promise = new Promise(function (resolve, reject) {
  286. // Cloud
  287. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD) {
  288. // Get Controllers
  289. _this.getCustomerDetails('controllers').then(function (data) {
  290. var controllers = [];
  291. // Check every returned relay
  292. data.controllers.map(function (c) {
  293. // Controller
  294. var controller = {
  295. apiBinding: that,
  296. id: c.controller_id,
  297. name: c.name,
  298. serialNumber: c.serial_number,
  299. lastContactWithCloud: new Date(c.last_contact * 1000),
  300. status: c.status
  301. };
  302. controllers.push(new HydrawiseController_1.HydrawiseController(controller));
  303. });
  304. resolve(controllers);
  305. }).catch(function (err) {
  306. reject(err);
  307. });
  308. }
  309. // Local
  310. else {
  311. // Controller
  312. var controller = {
  313. apiBinding: that,
  314. name: that.url
  315. };
  316. resolve([new HydrawiseController_1.HydrawiseController(controller)]);
  317. }
  318. });
  319. return promise;
  320. };
  321. /* -------- Raw API calls -------- */
  322. /**
  323. * Gets the customer ID & list of available controllers configured in the Hydrawise cloud. Only available in cloud binding.
  324. * @param {string} type - Defines the type of customer details to be retrieved alongside the customer ID
  325. * @return {Promise} A Promise which will be resolved when the request has returned from the cloud server.
  326. */
  327. Hydrawise.prototype.getCustomerDetails = function (type) {
  328. // Cloud only API
  329. if (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL) {
  330. return new Promise(function (resolve, reject) {
  331. reject(new HydrawiseCommandException_1.HydrawiseCommandException('Calling Cloud API function on a Local Binding'));
  332. });
  333. }
  334. return this.request('customerdetails.php', { type: type });
  335. };
  336. /**
  337. * Gets the status and schedule of the locally connected controller or all controllers in the cloud
  338. * @param {number} [controller] - Return the status and schedule for a specific controller. If not specified, the zones of the deault controller are returned.
  339. * @return {Promise} A Promise which will be resolved when the request has returned from the local or cloud server.
  340. */
  341. Hydrawise.prototype.getStatusAndSchedule = function (controller) {
  342. var uri = (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL ? 'get_sched_json.php' : 'statusschedule.php');
  343. var params = {};
  344. // Was a controller set?
  345. if (controller !== undefined && controller !== null) {
  346. params.controller_id = controller;
  347. }
  348. // If no controller was set
  349. return this.request(uri, params);
  350. };
  351. /**
  352. * Sends an action request to a specific or all zones
  353. * @param {object} params - Parameters object containing all parameters to be sent along with the request
  354. * @param {string} [params.relay_id] - The id of the relay which needs to be targetted. Not needed for runall, suspendall, stopall
  355. * @param {string} params.action - The action to be executed: run, stop, suspend, runall, suspendall, stopall
  356. * @param {number} [params.custom] - The amount of seconds the action needs to be run. Only for run, suspend, runall, suspendall
  357. * @param {number} [controller] - Needs to be specified if you have multiple controllers (cloud only)
  358. * @todo Complete params documentation
  359. * @return {Promise} A Promise which will be resolved when the request has returned from the local or cloud server.
  360. */
  361. Hydrawise.prototype.setZone = function (params, controller) {
  362. if (params === void 0) { params = {}; }
  363. var uri = (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL ? 'set_manual_data.php' : 'setzone.php');
  364. // Was a controller set?
  365. if (controller !== undefined && controller !== null) {
  366. params.controller_id = controller;
  367. }
  368. return this.request(uri, params);
  369. };
  370. return Hydrawise;
  371. }());
  372. exports.Hydrawise = Hydrawise;