Hydrawise.js 17 KB

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