Hydrawise.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. var __importDefault = (this && this.__importDefault) || function (mod) {
  8. return (mod && mod.__esModule) ? mod : { "default": mod };
  9. };
  10. Object.defineProperty(exports, "__esModule", { value: true });
  11. exports.Hydrawise = void 0;
  12. const HydrawiseConnectionType_1 = require("./HydrawiseConnectionType");
  13. const HydrawiseZone_1 = require("./HydrawiseZone");
  14. const HydrawiseController_1 = require("./HydrawiseController");
  15. const HydrawiseCommandException_1 = require("./HydrawiseCommandException");
  16. const axios_1 = __importDefault(require("axios"));
  17. /** Class representing a Hydrawise local or cloud based API binding */
  18. class Hydrawise {
  19. /**
  20. * Create a new instance of the Hydrawise API binding
  21. * @param {object} options - Options object containing all parameters
  22. * @param {string} options.type - The type of binding you wish to make: 'CLOUD' or 'LOCAL'
  23. * @param {string} [options.host] - The hostname or ip address of the local host you wish to connect to. Only needed for local bindings.
  24. * @param {string} [options.user = admin] - The username of the local Hydrawise controller. Only needed for local bindings (falls back to the default 'admin' user).
  25. * @param {string} [options.password] - The password of the local Hydrawise controller. Only needed for local bindings.
  26. * @param {string} [options.key] - The API key of your Hydrawise cloud account. Only needed for cloud bindings.
  27. */
  28. constructor(options) {
  29. this.cloudUrl = 'https://app.hydrawise.com/api/v1/';
  30. this.type = options.type || HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD; // CLOUD or LOCAL
  31. this.url = (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL ? 'http://' + options.host + '/' : this.cloudUrl);
  32. // Local Auth
  33. this.localAuthUsername = options.user || 'admin';
  34. this.localAuthPassword = options.password || '';
  35. // Cloud Auth
  36. this.cloudAuthAPIkey = options.key || '';
  37. }
  38. /**
  39. * Private function that makes a GET request to the local or cloud Hydrawise server
  40. * @param {string} path - The path of the API endpoint
  41. * @param {object} [params] - Parameters to be added to the URL path
  42. * @return {Promise} A Promise which will be resolved when the request has returned from the local or cloud server.
  43. */
  44. request(path = '', params = {}) {
  45. let promise = new Promise((resolve, reject) => {
  46. // setup basic request
  47. let 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. let 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((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((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. commandZone(action, zoneOrRelay, duration) {
  87. let that = this;
  88. // Get started
  89. let promise = new Promise((resolve, reject) => {
  90. let 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((data) => {
  112. resolve(data);
  113. }).catch((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. commandAllZones(action, controller, duration) {
  127. let that = this;
  128. // Get started
  129. let promise = new Promise((resolve, reject) => {
  130. let 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(data => {
  148. resolve(data);
  149. }).catch((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. runZone(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. runAllZones(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. suspendZone(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. suspendAllZones(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. stopZone(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. stopAllZones(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. getZones(controller) {
  211. let that = this;
  212. // Get started
  213. let promise = new Promise((resolve, reject) => {
  214. // Controller set?
  215. let 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((data) => {
  226. let zones = [];
  227. // Check every returned relay
  228. data.relays.map((z) => {
  229. // Only configured zones
  230. // Commented out because it may drive some zones unusable from time to time by filtering them out
  231. // if(that.type == HydrawiseConnectionType.CLOUD || z.lastwaterepoch != 0){
  232. // Zone
  233. let 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. remainingRunTime: 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. let runningZone = data.running.find((x) => {
  255. return x.relay_id == z.relay_id;
  256. });
  257. if (runningZone != undefined && runningZone != null) {
  258. zone.isRunning = true;
  259. zone.remainingRunTime = runningZone.time_left;
  260. }
  261. }
  262. // Running? (cloud connection)
  263. if (z.time == 1) {
  264. zone.isRunning = true;
  265. zone.remainingRunTime = z.run;
  266. }
  267. zones.push(new HydrawiseZone_1.HydrawiseZone(zone));
  268. // }
  269. });
  270. resolve(zones);
  271. }).catch((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. getControllers() {
  282. let that = this;
  283. // Get started
  284. let promise = new Promise((resolve, reject) => {
  285. // Cloud
  286. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD) {
  287. // Get Controllers
  288. this.getCustomerDetails('controllers').then(data => {
  289. let controllers = [];
  290. // Check every returned relay
  291. data.controllers.map((c) => {
  292. // Controller
  293. let controller = {
  294. apiBinding: that,
  295. id: c.controller_id,
  296. name: c.name,
  297. serialNumber: c.serial_number,
  298. lastContactWithCloud: new Date(c.last_contact * 1000),
  299. status: c.status
  300. };
  301. controllers.push(new HydrawiseController_1.HydrawiseController(controller));
  302. });
  303. resolve(controllers);
  304. }).catch((err) => {
  305. reject(err);
  306. });
  307. }
  308. // Local
  309. else {
  310. // Controller
  311. let controller = {
  312. apiBinding: that,
  313. name: that.url
  314. };
  315. resolve([new HydrawiseController_1.HydrawiseController(controller)]);
  316. }
  317. });
  318. return promise;
  319. }
  320. /* -------- Raw API calls -------- */
  321. /**
  322. * Gets the customer ID & list of available controllers configured in the Hydrawise cloud. Only available in cloud binding.
  323. * @param {string} type - Defines the type of customer details to be retrieved alongside the customer ID
  324. * @return {Promise} A Promise which will be resolved when the request has returned from the cloud server.
  325. */
  326. getCustomerDetails(type) {
  327. // Cloud only API
  328. if (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL) {
  329. return new Promise((resolve, reject) => {
  330. reject(new HydrawiseCommandException_1.HydrawiseCommandException('Calling Cloud API function on a Local Binding'));
  331. });
  332. }
  333. return this.request('customerdetails.php', { type: type });
  334. }
  335. /**
  336. * Gets the status and schedule of the locally connected controller or all controllers in the cloud
  337. * @param {number} [controller] - Return the status and schedule for a specific controller. If not specified, the zones of the deault controller are returned.
  338. * @return {Promise} A Promise which will be resolved when the request has returned from the local or cloud server.
  339. */
  340. getStatusAndSchedule(controller) {
  341. let uri = (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL ? 'get_sched_json.php' : 'statusschedule.php');
  342. let params = {};
  343. // Was a controller set?
  344. if (controller !== undefined && controller !== null) {
  345. params.controller_id = controller;
  346. }
  347. // If no controller was set
  348. return this.request(uri, params);
  349. }
  350. /**
  351. * Sends an action request to a specific or all zones
  352. * @param {object} params - Parameters object containing all parameters to be sent along with the request
  353. * @param {string} [params.relay_id] - The id of the relay which needs to be targetted. Not needed for runall, suspendall, stopall
  354. * @param {string} params.action - The action to be executed: run, stop, suspend, runall, suspendall, stopall
  355. * @param {number} [params.custom] - The amount of seconds the action needs to be run. Only for run, suspend, runall, suspendall
  356. * @param {number} [controller] - Needs to be specified if you have multiple controllers (cloud only)
  357. * @todo Complete params documentation
  358. * @return {Promise} A Promise which will be resolved when the request has returned from the local or cloud server.
  359. */
  360. setZone(params = {}, controller) {
  361. let uri = (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL ? 'set_manual_data.php' : 'setzone.php');
  362. // Was a controller set?
  363. if (controller !== undefined && controller !== null) {
  364. params.controller_id = controller;
  365. }
  366. return this.request(uri, params);
  367. }
  368. }
  369. exports.Hydrawise = Hydrawise;
  370. //# sourceMappingURL=Hydrawise.js.map