Hydrawise.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 Allow using a controller id instead of HydrawiseController object.
  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 = zoneOrRelay instanceof HydrawiseZone_1.HydrawiseZone ? 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 = zoneOrRelay instanceof HydrawiseZone_1.HydrawiseZone ? 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. // Set controller if one was provided (only for cloud)
  105. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD && zoneOrRelay instanceof HydrawiseZone_1.HydrawiseZone && zoneOrRelay.controller !== undefined && zoneOrRelay.controller instanceof HydrawiseController_1.HydrawiseController) {
  106. opts.controller_id = zoneOrRelay.controller.id;
  107. }
  108. // Execute command
  109. that.setZone(opts).then((data) => {
  110. resolve(data);
  111. }).catch((err) => {
  112. reject(err);
  113. });
  114. });
  115. return promise;
  116. }
  117. /**
  118. * Sends a command to all zones/relays
  119. * @param {string} action - The required command to be executed: runall, suspendall, stopall
  120. * @param {number} [duration] - How long should the given command be executed (only applicable for runall & suspendall)
  121. * @todo Check whether controller_id needs to sent when the account contains multiple zones
  122. * @return {Promise} A Promise which will be resolved when the command has been executed.
  123. */
  124. commandAllZones(action, controller, duration) {
  125. let that = this;
  126. // Get started
  127. let promise = new Promise((resolve, reject) => {
  128. let opts = {
  129. period_id: 998,
  130. action: action
  131. };
  132. // Custom duration?
  133. if (duration !== undefined) {
  134. opts.custom = duration;
  135. }
  136. // Specific controller? (only cloud)
  137. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD && controller !== undefined && controller !== null) {
  138. if (controller instanceof HydrawiseController_1.HydrawiseController) {
  139. opts.controller_id = controller.id;
  140. }
  141. else {
  142. opts.controller_id = controller;
  143. }
  144. }
  145. that.setZone(opts).then(data => {
  146. resolve(data);
  147. }).catch((err) => {
  148. reject(err);
  149. });
  150. });
  151. return promise;
  152. }
  153. /**
  154. * Sends the run command to a single zone/relay
  155. * @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
  156. * @param {number} [duration] - How long should the command be executed
  157. * @return {Promise} A Promise which will be resolved when the command has been executed.
  158. */
  159. runZone(zoneOrRelay, duration) {
  160. return this.commandZone('run', zoneOrRelay, duration);
  161. }
  162. /**
  163. * Sends the run command to all zones/relays
  164. * @param {number} [duration] - How long should the command be executed
  165. * @return {Promise} A Promise which will be resolved when the command has been executed.
  166. */
  167. runAllZones(controller, duration) {
  168. return this.commandAllZones('runall', controller, duration);
  169. }
  170. /**
  171. * Sends the suspend command to a single zone/relay
  172. * @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
  173. * @param {number} [duration] - How long should the command be executed
  174. * @return {Promise} A Promise which will be resolved when the command has been executed.
  175. */
  176. suspendZone(zoneOrRelay, duration) {
  177. return this.commandZone('suspend', zoneOrRelay, duration);
  178. }
  179. /**
  180. * Sends the suspend command to all zones/relays for a specific controller
  181. * @param {number} [duration] - How long should the command be executed
  182. * @param {HydrawiseController|number} [controller] - Return zones for a specific controller. If not specified, the zones of the deault controller are returned.
  183. * @return {Promise} A Promise which will be resolved when the command has been executed.
  184. */
  185. suspendAllZones(controller, duration) {
  186. return this.commandAllZones('suspendall', controller, duration);
  187. }
  188. /**
  189. * Sends the stop command to a single zone/relay
  190. * @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
  191. * @return {Promise} A Promise which will be resolved when the command has been executed.
  192. */
  193. stopZone(zoneOrRelay) {
  194. return this.commandZone('stop', zoneOrRelay);
  195. }
  196. /**
  197. * Sends the stop command to all zones/relays
  198. * @return {Promise} A Promise which will be resolved when the command has been executed.
  199. */
  200. stopAllZones(controller) {
  201. return this.commandAllZones('stopall', controller);
  202. }
  203. /**
  204. * Retrieves all zones/relays known to the server
  205. * @param {HydrawiseController|number} [controller] - Return zones for a specific controller. If not specified, the zones of the deault controller are returned.
  206. * @return {Promise} A Promise which will be resolved when all zones have been retrieved
  207. */
  208. getZones(controller) {
  209. let that = this;
  210. // Get started
  211. let promise = new Promise((resolve, reject) => {
  212. // Controller set?
  213. let controllerID;
  214. if (controller !== undefined && controller !== null) {
  215. if (controller instanceof HydrawiseController_1.HydrawiseController) {
  216. controllerID = controller.id;
  217. }
  218. else {
  219. controllerID = controller;
  220. }
  221. }
  222. // Get relays
  223. that.getStatusAndSchedule(controllerID).then((data) => {
  224. let zones = [];
  225. // Check every returned relay
  226. data.relays.map((z) => {
  227. // Only configured zones
  228. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD || z.lastwaterepoch != 0) {
  229. // Zone
  230. let zone = {
  231. apiBinding: that,
  232. relayID: z.relay_id,
  233. zone: z.relay,
  234. name: z.name,
  235. nextRunAt: new Date((data.time + z.time) * 1000),
  236. nextRunDuration: z.run || z.run_seconds,
  237. isSuspended: z.suspended !== undefined && z.suspended == 1,
  238. isRunning: false,
  239. remainingRunningTime: 0
  240. };
  241. // Link controller to the zones if it was provided when calling the method
  242. if (controller !== undefined && controller !== null && controller instanceof HydrawiseController_1.HydrawiseController) {
  243. zone.controller = controller;
  244. }
  245. // Only available data for local connections
  246. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL) {
  247. zone.defaultRunDuration = z.normalRuntime * 60;
  248. }
  249. // Running?
  250. if (data.running !== undefined) {
  251. let runningZone = data.running.find((x) => {
  252. return x.relay_id == z.relay_id;
  253. });
  254. if (runningZone != undefined && runningZone != null) {
  255. zone.isRunning = true;
  256. zone.remainingRunningTime = runningZone.time_left;
  257. }
  258. }
  259. zones.push(new HydrawiseZone_1.HydrawiseZone(zone));
  260. }
  261. });
  262. resolve(zones);
  263. }).catch((err) => {
  264. reject(err);
  265. });
  266. });
  267. return promise;
  268. }
  269. /**
  270. * Retrieves all controllers known to the Hydrawise cloud or returns a single dummy one for a local connection
  271. * @return {Promise} A Promise which will be resolved when all controllers have been retrieved
  272. */
  273. getControllers() {
  274. let that = this;
  275. // Get started
  276. let promise = new Promise((resolve, reject) => {
  277. // Cloud
  278. if (that.type == HydrawiseConnectionType_1.HydrawiseConnectionType.CLOUD) {
  279. // Get Controllers
  280. this.getCustomerDetails('controllers').then(data => {
  281. let controllers = [];
  282. // Check every returned relay
  283. data.controllers.map((c) => {
  284. // Controller
  285. let controller = {
  286. apiBinding: that,
  287. id: c.controller_id,
  288. name: c.name,
  289. serialNumber: c.serial_number,
  290. lastContactWithCloud: new Date(c.last_contact * 1000),
  291. status: c.status
  292. };
  293. controllers.push(new HydrawiseController_1.HydrawiseController(controller));
  294. });
  295. resolve(controllers);
  296. }).catch((err) => {
  297. reject(err);
  298. });
  299. }
  300. // Local
  301. else {
  302. // Controller
  303. let controller = {
  304. apiBinding: that,
  305. name: that.url
  306. };
  307. resolve([new HydrawiseController_1.HydrawiseController(controller)]);
  308. }
  309. });
  310. return promise;
  311. }
  312. /* -------- Raw API calls -------- */
  313. /**
  314. * Gets the customer ID & list of available controllers configured in the Hydrawise cloud. Only available in cloud binding.
  315. * @param {string} type - Defines the type of customer details to be retrieved alongside the customer ID
  316. * @return {Promise} A Promise which will be resolved when the request has returned from the cloud server.
  317. */
  318. getCustomerDetails(type) {
  319. // Cloud only API
  320. if (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL) {
  321. return new Promise((resolve, reject) => {
  322. reject(new HydrawiseCommandException_1.HydrawiseCommandException('Calling Cloud API function on a Local Binding'));
  323. });
  324. }
  325. return this.request('customerdetails.php', { type: type });
  326. }
  327. /**
  328. * Gets the status and schedule of the locally connected controller or all controllers in the cloud
  329. * @param {number} [controller] - Return the status and schedule for a specific controller. If not specified, the zones of the deault controller are returned.
  330. * @return {Promise} A Promise which will be resolved when the request has returned from the local or cloud server.
  331. */
  332. getStatusAndSchedule(controller) {
  333. let uri = (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL ? 'get_sched_json.php' : 'statusschedule.php');
  334. let params = {};
  335. // Was a controller set?
  336. if (controller !== undefined && controller !== null) {
  337. params.controller_id = controller;
  338. }
  339. // If no controller was set
  340. return this.request(uri, params);
  341. }
  342. /**
  343. * Sends an action request to a specific or all zones
  344. * @param {object} params - Parameters object containing all parameters to be sent along with the request
  345. * @param {string} [params.relay_id] - The id of the relay which needs to be targetted. Not needed for runall, suspendall, stopall
  346. * @param {string} params.action - The action to be executed: run, stop, suspend, runall, suspendall, stopall
  347. * @param {number} [params.custom] - The amount of seconds the action needs to be run. Only for run, suspend, runall, suspendall
  348. * @param {number} [controller] - Needs to be specified if you have multiple controllers (cloud only)
  349. * @todo Complete params documentation
  350. * @return {Promise} A Promise which will be resolved when the request has returned from the local or cloud server.
  351. */
  352. setZone(params = {}, controller) {
  353. let uri = (this.type == HydrawiseConnectionType_1.HydrawiseConnectionType.LOCAL ? 'set_manual_data.php' : 'setzone.php');
  354. // Was a controller set?
  355. if (controller !== undefined && controller !== null) {
  356. params.controller_id = controller;
  357. }
  358. return this.request(uri, params);
  359. }
  360. }
  361. exports.Hydrawise = Hydrawise;
  362. //# sourceMappingURL=Hydrawise.js.map