1
0

Hydrawise.js 18 KB

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