scrypted-rachio3-plugin
Version:
A Scrypted plugin that controls Rachio 3 Smart Sprinkler Controller via the Rachio Cloud API.
576 lines (567 loc) • 35.1 kB
JavaScript
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 176:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = {
enumerable: true,
get: function get() {
return m[k];
}
};
}
Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function (o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.RachioPlugin = exports.RachioZoneDevice = void 0;
var sdk_1 = __importStar(__webpack_require__(469));
var deviceManager = sdk_1["default"].deviceManager;
///////////////////////////////////////////////////////////////////////////
// RachioZoneDevice
///////////////////////////////////////////////////////////////////////////
var RachioZoneDevice = /*#__PURE__*/function (_sdk_1$ScryptedDevice) {
function RachioZoneDevice(plugin, nativeId, zoneName, durationSeconds) {
var _this;
_classCallCheck(this, RachioZoneDevice);
_this = _callSuper(this, RachioZoneDevice, [nativeId]);
_this.running = false;
_this.plugin = plugin;
_this.zoneId = nativeId;
_this.durationSeconds = durationSeconds;
_this.console.log("RachioZoneDevice created: ".concat(zoneName, " (zoneId=").concat(_this.zoneId, "), default watering duration=").concat(durationSeconds, "s"));
return _this;
}
// StartStop interface property from Scrypted is "running"
// We won't redefine get/set 'running' to avoid conflicts.
// Instead, we simply set this.binaryState = true/false as needed.
_inherits(RachioZoneDevice, _sdk_1$ScryptedDevice);
return _createClass(RachioZoneDevice, [{
key: "start",
value: function () {
var _start = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var url, body;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
this.console.log("Starting zone ".concat(this.zoneId, " for ").concat(this.durationSeconds, " seconds."));
url = "https://api.rach.io/1/public/zone/start";
body = {
id: this.zoneId,
duration: this.durationSeconds
};
_context.next = 6;
return fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer ".concat(this.plugin.rachioAuthToken)
},
body: JSON.stringify(body)
});
case 6:
// Mark the zone as running
this.running = true;
this.console.log("Zone ".concat(this.zoneId, " started."));
_context.next = 13;
break;
case 10:
_context.prev = 10;
_context.t0 = _context["catch"](0);
this.console.error("Error starting zone ".concat(this.zoneId, ": ").concat(_context.t0));
case 13:
case "end":
return _context.stop();
}
}, _callee, this, [[0, 10]]);
}));
function start() {
return _start.apply(this, arguments);
}
return start;
}()
}, {
key: "stop",
value: function () {
var _stop = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var url;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
this.console.log("Stopping watering for all zones (including ".concat(this.zoneId, ")."));
url = "https://api.rach.io/1/public/device/stop_water";
_context2.next = 5;
return fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer ".concat(this.plugin.rachioAuthToken)
}
});
case 5:
// Mark the zone as no longer running
this.running = false;
this.console.log("Zone ".concat(this.zoneId, " stopped."));
_context2.next = 12;
break;
case 9:
_context2.prev = 9;
_context2.t0 = _context2["catch"](0);
this.console.error("Error stopping zone ".concat(this.zoneId, ": ").concat(_context2.t0));
case 12:
case "end":
return _context2.stop();
}
}, _callee2, this, [[0, 9]]);
}));
function stop() {
return _stop.apply(this, arguments);
}
return stop;
}()
}]);
}(sdk_1.ScryptedDeviceBase);
exports.RachioZoneDevice = RachioZoneDevice;
///////////////////////////////////////////////////////////////////////////
// RachioPlugin - main plugin
///////////////////////////////////////////////////////////////////////////
var RachioPlugin = /*#__PURE__*/function (_sdk_1$ScryptedDevice2) {
function RachioPlugin(nativeId) {
var _this2;
_classCallCheck(this, RachioPlugin);
_this2 = _callSuper(this, RachioPlugin, [nativeId]);
// Keep a local map of discovered zones
_this2.devices = new Map();
// If there's already a token, try discovering on startup
if (_this2.rachioAuthToken) {
// "scan" parameter is optional, so pass 'false' or 'true' or nothing
_this2.discoverDevices(false);
}
return _this2;
}
_inherits(RachioPlugin, _sdk_1$ScryptedDevice2);
return _createClass(RachioPlugin, [{
key: "rachioAuthToken",
get:
// Rachio Auth Token stored in plugin settings
function get() {
return this.storage.getItem("rachioAuthToken") || "";
},
set: function set(token) {
this.storage.setItem("rachioAuthToken", token);
}
}, {
key: "adoptDevice",
value: function () {
var _adoptDevice = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(device) {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
this.console.log('adoptDevice not implemented.');
// Return a valid nativeId string.
return _context3.abrupt("return", device.nativeId || '');
case 2:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function adoptDevice(_x) {
return _adoptDevice.apply(this, arguments);
}
return adoptDevice;
}()
}, {
key: "releaseDevice",
value: function () {
var _releaseDevice = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(id) {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
this.console.log('releaseDevice not implemented.');
case 1:
case "end":
return _context4.stop();
}
}, _callee4, this);
}));
function releaseDevice(_x2) {
return _releaseDevice.apply(this, arguments);
}
return releaseDevice;
}()
/************************************************************************
* Scrypted Settings
************************************************************************/
}, {
key: "getSettings",
value: (function () {
var _getSettings = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
return _context5.abrupt("return", [{
key: "rachioAuthToken",
title: "Rachio API Token",
description: "Enter your Rachio Personal Access Token here",
value: this.rachioAuthToken || ""
}]);
case 1:
case "end":
return _context5.stop();
}
}, _callee5, this);
}));
function getSettings() {
return _getSettings.apply(this, arguments);
}
return getSettings;
}())
}, {
key: "putSetting",
value: function () {
var _putSetting = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(key, value) {
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
if (!(key === "rachioAuthToken")) {
_context6.next = 5;
break;
}
this.rachioAuthToken = value.trim();
this.console.log("Rachio API token updated. Discovering devices...");
// re-discover after token changes
_context6.next = 5;
return this.discoverDevices(false);
case 5:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
function putSetting(_x3, _x4) {
return _putSetting.apply(this, arguments);
}
return putSetting;
}()
/************************************************************************
* DeviceProvider
************************************************************************/
// Must be async and return a Promise
}, {
key: "getDevice",
value: (function () {
var _getDevice = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(nativeId) {
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
return _context7.abrupt("return", nativeId ? this.devices.get(nativeId) : undefined);
case 1:
case "end":
return _context7.stop();
}
}, _callee7, this);
}));
function getDevice(_x5) {
return _getDevice.apply(this, arguments);
}
return getDevice;
}()
/************************************************************************
* DeviceDiscovery
************************************************************************/
// Must return a Promise of DiscoveredDevice[] and accept an optional boolean
)
}, {
key: "discoverDevices",
value: (function () {
var _discoverDevices = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(scan) {
var _a, discoveredDevices, url, resp, infoData, personId, personDetail, _iterator, _step, device, deviceName, deviceId, zones, _iterator2, _step2, zone, zoneId, zoneName, discoveredDevice, _i, _discoveredDevices, d, sid, existing;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
this.console.log("Discovering Rachio devices. scan=".concat(scan !== null && scan !== void 0 ? scan : false));
discoveredDevices = [];
if (this.rachioAuthToken) {
_context8.next = 5;
break;
}
this.console.warn("No Rachio auth token set, cannot discover devices.");
return _context8.abrupt("return", discoveredDevices);
case 5:
_context8.prev = 5;
// Step 1: Get Person info to retrieve userId
url = "https://api.rach.io/1/public/person/info";
_context8.next = 9;
return fetch(url, {
method: "GET",
headers: {
Authorization: "Bearer ".concat(this.rachioAuthToken)
}
});
case 9:
resp = _context8.sent;
if (resp.ok) {
_context8.next = 12;
break;
}
throw new Error("Failed fetching /person/info: ".concat(resp.statusText));
case 12:
_context8.next = 14;
return resp.json();
case 14:
infoData = _context8.sent;
personId = infoData.id; // Step 2: With personId, fetch /person/:id to get devices
url = "https://api.rach.io/1/public/person/".concat(personId);
_context8.next = 19;
return fetch(url, {
method: "GET",
headers: {
Authorization: "Bearer ".concat(this.rachioAuthToken)
}
});
case 19:
resp = _context8.sent;
if (resp.ok) {
_context8.next = 22;
break;
}
throw new Error("Failed fetching /person/".concat(personId, ": ").concat(resp.statusText));
case 22:
_context8.next = 24;
return resp.json();
case 24:
personDetail = _context8.sent;
if (!(!personDetail.devices || !Array.isArray(personDetail.devices))) {
_context8.next = 28;
break;
}
this.console.warn("No Rachio devices found in this account.");
return _context8.abrupt("return", discoveredDevices);
case 28:
// Each device can have multiple "zones"
_iterator = _createForOfIteratorHelper(personDetail.devices);
_context8.prev = 29;
_iterator.s();
case 31:
if ((_step = _iterator.n()).done) {
_context8.next = 61;
break;
}
device = _step.value;
deviceName = device.name;
deviceId = device.id;
this.console.log("Found Rachio controller: ".concat(deviceName, ", id=").concat(deviceId));
zones = device.zones || [];
_iterator2 = _createForOfIteratorHelper(zones);
_context8.prev = 38;
_iterator2.s();
case 40:
if ((_step2 = _iterator2.n()).done) {
_context8.next = 51;
break;
}
zone = _step2.value;
if (zone.enabled) {
_context8.next = 45;
break;
}
this.console.log("Skipping disabled zone: ".concat(zone.name, " (id=").concat(zone.id, ")"));
return _context8.abrupt("continue", 49);
case 45:
zoneId = zone.id;
zoneName = zone.name; // Build a discovered device descriptor
discoveredDevice = {
name: zoneName,
nativeId: zoneId,
description: "Rachio Zone: ".concat(zoneName),
type: sdk_1.ScryptedDeviceType.Valve,
interfaces: [sdk_1.ScryptedInterface.StartStop],
info: {
manufacturer: "Rachio",
model: "Rachio 3",
firmware: device.firmwareVersion || "",
serialNumber: zoneId
}
};
discoveredDevices.push(discoveredDevice);
case 49:
_context8.next = 40;
break;
case 51:
_context8.next = 56;
break;
case 53:
_context8.prev = 53;
_context8.t0 = _context8["catch"](38);
_iterator2.e(_context8.t0);
case 56:
_context8.prev = 56;
_iterator2.f();
return _context8.finish(56);
case 59:
_context8.next = 31;
break;
case 61:
_context8.next = 66;
break;
case 63:
_context8.prev = 63;
_context8.t1 = _context8["catch"](29);
_iterator.e(_context8.t1);
case 66:
_context8.prev = 66;
_iterator.f();
return _context8.finish(66);
case 69:
// Inform Scrypted about the discovered devices
deviceManager.onDevicesChanged({
devices: discoveredDevices.map(function (d) {
return {
nativeId: d.nativeId,
name: d.name,
description: d.description,
type: d.type,
interfaces: d.interfaces || [],
info: d.info
};
})
});
// Create or update local device wrappers
_i = 0, _discoveredDevices = discoveredDevices;
case 71:
if (!(_i < _discoveredDevices.length)) {
_context8.next = 82;
break;
}
d = _discoveredDevices[_i];
if (d.nativeId) {
_context8.next = 76;
break;
}
this.console.error("Discovered device has no nativeId, skipping: ".concat(d.name));
return _context8.abrupt("continue", 79);
case 76:
sid = d.nativeId; // safe string
existing = this.devices.get(sid);
if (!existing) {
existing = new RachioZoneDevice(this, sid, (_a = d.name) !== null && _a !== void 0 ? _a : 'Unknown Zone', 60);
this.devices.set(sid, existing);
}
case 79:
_i++;
_context8.next = 71;
break;
case 82:
this.console.log("Rachio device discovery complete.");
_context8.next = 88;
break;
case 85:
_context8.prev = 85;
_context8.t2 = _context8["catch"](5);
this.console.error("Rachio discovery error: ".concat(_context8.t2));
case 88:
return _context8.abrupt("return", discoveredDevices);
case 89:
case "end":
return _context8.stop();
}
}, _callee8, this, [[5, 85], [29, 63, 66, 69], [38, 53, 56, 59]]);
}));
function discoverDevices(_x6) {
return _discoverDevices.apply(this, arguments);
}
return discoverDevices;
}())
}]);
}(sdk_1.ScryptedDeviceBase);
exports.RachioPlugin = RachioPlugin;
// Default export for Scrypted
exports["default"] = RachioPlugin;
/***/ }),
/***/ 469:
/***/ ((module) => {
module.exports = require("@scrypted/sdk");
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module is referenced by other modules so it can't be inlined
/******/ var __webpack_exports__ = __webpack_require__(176);
/******/ var __webpack_export_target__ = exports;
/******/ for(var __webpack_i__ in __webpack_exports__) __webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
/******/ if(__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });
/******/
/******/ })()
;