From 003a9701639cf8d0f8d2a6c510bc54ff2fefa9ce Mon Sep 17 00:00:00 2001 From: Matias Vallejos Date: Tue, 23 Apr 2024 04:14:57 -0300 Subject: [PATCH] Completed code like original --- package-lock.json | 238 +++++++++- package.json | 8 +- pages/Home/index.html | 125 ++++++ {src => pages/Home}/script.ts | 134 +++--- pages/Scenes/index.html | 230 ++++++++++ src/bulbHelper.ts | 193 ++++++-- src/components/App.tsx | 29 ++ src/components/BulbContext.tsx | 34 ++ src/components/Custom.tsx | 76 ++++ src/components/Devices.tsx | 41 ++ src/components/Dynamic.tsx | 372 +++++++++++++++ src/components/Home.tsx | 124 +++++ src/components/IpModal.tsx | 65 +++ src/components/ModalCreateColor.tsx | 101 +++++ src/components/ModalEditColor.tsx | 116 +++++ src/components/Scenes.tsx | 65 +++ src/components/Sidebar.tsx | 110 +++++ src/components/Static.tsx | 55 +++ src/constants.ts | 3 +- src/index.html | 125 +----- src/index.ts | 71 ++- src/interface.d.ts | 12 +- src/preload.ts | 17 +- src/react-app-env.d.ts | 4 + src/renderer.ts | 9 +- src/types.ts | 4 +- tsconfig.json | 3 +- wikari/.gitignore | 2 - wikari/.prettierrc | 10 - wikari/LICENSE | 674 ---------------------------- wikari/README.md | 85 ---- wikari/package-lock.json | 45 -- wikari/package.json | 27 -- wikari/pnpm-lock.yaml | 21 - wikari/src/bulb.ts | 597 ------------------------ wikari/src/constants.ts | 56 --- wikari/src/discover.ts | 58 --- wikari/src/mod.ts | 5 - wikari/src/type-checker.ts | 100 ----- wikari/src/types.ts | 150 ------- wikari/src/utils.ts | 48 -- wikari/src/wikari-error.ts | 66 --- wikari/tsconfig.json | 15 - 43 files changed, 2111 insertions(+), 2212 deletions(-) create mode 100644 pages/Home/index.html rename {src => pages/Home}/script.ts (68%) create mode 100644 pages/Scenes/index.html create mode 100644 src/components/App.tsx create mode 100644 src/components/BulbContext.tsx create mode 100644 src/components/Custom.tsx create mode 100644 src/components/Devices.tsx create mode 100644 src/components/Dynamic.tsx create mode 100644 src/components/Home.tsx create mode 100644 src/components/IpModal.tsx create mode 100644 src/components/ModalCreateColor.tsx create mode 100644 src/components/ModalEditColor.tsx create mode 100644 src/components/Scenes.tsx create mode 100644 src/components/Sidebar.tsx create mode 100644 src/components/Static.tsx create mode 100644 src/react-app-env.d.ts delete mode 100644 wikari/.gitignore delete mode 100644 wikari/.prettierrc delete mode 100644 wikari/LICENSE delete mode 100644 wikari/README.md delete mode 100644 wikari/package-lock.json delete mode 100644 wikari/package.json delete mode 100644 wikari/pnpm-lock.yaml delete mode 100644 wikari/src/bulb.ts delete mode 100644 wikari/src/constants.ts delete mode 100644 wikari/src/discover.ts delete mode 100644 wikari/src/mod.ts delete mode 100644 wikari/src/type-checker.ts delete mode 100644 wikari/src/types.ts delete mode 100644 wikari/src/utils.ts delete mode 100644 wikari/src/wikari-error.ts delete mode 100644 wikari/tsconfig.json diff --git a/package-lock.json b/package-lock.json index 5e243e3..63ea932 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,10 @@ "dependencies": { "@fortawesome/fontawesome-free": "^6.5.2", "bootstrap": "^5.3.3", - "electron-squirrel-startup": "^1.0.0" + "electron-squirrel-startup": "^1.0.0", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-router-dom": "^6.22.3" }, "devDependencies": { "@electron-forge/cli": "^7.4.0", @@ -23,11 +26,14 @@ "@electron-forge/plugin-fuses": "^7.4.0", "@electron-forge/plugin-webpack": "^7.4.0", "@electron/fuses": "^1.8.0", + "@types/react": "^18.2.79", + "@types/react-dom": "^18.2.25", "@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/parser": "^5.62.0", "@vercel/webpack-asset-relocator-loader": "^1.7.3", "css-loader": "^6.11.0", "electron": "30.0.1", + "electron-devtools-installer": "^3.2.0", "eslint": "^8.57.0", "eslint-plugin-import": "^2.29.1", "fork-ts-checker-webpack-plugin": "^7.3.0", @@ -1156,6 +1162,14 @@ "url": "https://opencollective.com/popperjs" } }, + "node_modules/@remix-run/router": { + "version": "1.15.3", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.15.3.tgz", + "integrity": "sha512-Oy8rmScVrVxWZVOpEF57ovlnhpZ8CCPlnIIumVcV9nFdiSIrus99+Lw78ekXyGvVDlIsFJbSfmSovJUhCWYV3w==", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/@sindresorhus/is": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", @@ -1419,6 +1433,12 @@ "integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==", "dev": true }, + "node_modules/@types/prop-types": { + "version": "15.7.12", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.12.tgz", + "integrity": "sha512-5zvhXYtRNRluoE/jAp4GVsSduVUzNWKkOZrCDBWYtE7biZywwdC2AcEzg+cSMLFRfVgeAFqpfNabiPjxFddV1Q==", + "dev": true + }, "node_modules/@types/qs": { "version": "6.9.15", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.15.tgz", @@ -1431,6 +1451,25 @@ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", "dev": true }, + "node_modules/@types/react": { + "version": "18.2.79", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.2.79.tgz", + "integrity": "sha512-RwGAGXPl9kSXwdNTafkOEuFrTBD5SA2B3iEB96xi8+xu5ddUa/cpvyVCSNn+asgLCTHkb5ZxN8gbuibYJi4s1w==", + "dev": true, + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.2.25", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.2.25.tgz", + "integrity": "sha512-o/V48vf4MQh7juIKZU2QGDfli6p1+OOi5oXx36Hffpc9adsHeXjVp8rHuPkjd8VT8sOJ2Zp05HR7CdpGTIUFUA==", + "dev": true, + "dependencies": { + "@types/react": "*" + } + }, "node_modules/@types/responselike": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz", @@ -3287,6 +3326,12 @@ "node": ">=4" } }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "dev": true + }, "node_modules/data-view-buffer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz", @@ -3672,6 +3717,18 @@ "node": ">= 12.20.55" } }, + "node_modules/electron-devtools-installer": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/electron-devtools-installer/-/electron-devtools-installer-3.2.0.tgz", + "integrity": "sha512-t3UczsYugm4OAbqvdImMCImIMVdFzJAHgbwHpkl5jmfu1izVgUcP/mnrPqJIpEeCK1uZGpt+yHgWEN+9EwoYhQ==", + "dev": true, + "dependencies": { + "rimraf": "^3.0.2", + "semver": "^7.2.1", + "tslib": "^2.1.0", + "unzip-crx-3": "^0.2.0" + } + }, "node_modules/electron-installer-common": { "version": "0.10.3", "resolved": "https://registry.npmjs.org/electron-installer-common/-/electron-installer-common-0.10.3.tgz", @@ -6149,6 +6206,12 @@ "node": ">= 4" } }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "dev": true + }, "node_modules/import-fresh": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", @@ -6702,8 +6765,7 @@ "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "node_modules/js-yaml": { "version": "4.1.0", @@ -6778,6 +6840,54 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/jszip": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", + "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "dev": true, + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, + "node_modules/jszip/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true + }, + "node_modules/jszip/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/jszip/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "node_modules/jszip/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/junk": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/junk/-/junk-3.1.0.tgz", @@ -6828,6 +6938,15 @@ "node": ">= 0.8.0" } }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "dev": true, + "dependencies": { + "immediate": "~3.0.5" + } + }, "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", @@ -7024,6 +7143,17 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, "node_modules/lower-case": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-2.0.2.tgz", @@ -7979,6 +8109,12 @@ "node": ">=6" } }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true + }, "node_modules/param-case": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/param-case/-/param-case-3.0.4.tgz", @@ -8536,6 +8672,59 @@ "node": ">= 0.8" } }, + "node_modules/react": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz", + "integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz", + "integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.0" + }, + "peerDependencies": { + "react": "^18.2.0" + } + }, + "node_modules/react-router": { + "version": "6.22.3", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.22.3.tgz", + "integrity": "sha512-dr2eb3Mj5zK2YISHK++foM9w4eBnO23eKnZEDs7c880P6oKbrjz/Svg9+nxqtHQK+oMW4OtjZca0RqPglXxguQ==", + "dependencies": { + "@remix-run/router": "1.15.3" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8" + } + }, + "node_modules/react-router-dom": { + "version": "6.22.3", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.22.3.tgz", + "integrity": "sha512-7ZILI7HjcE+p31oQvwbokjk6OA/bnFxrhJ19n82Ex9Ph8fNAq+Hm/7KchpMGlTgWhUxRHMMCut+vEtNpWpowKw==", + "dependencies": { + "@remix-run/router": "1.15.3", + "react-router": "6.22.3" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, "node_modules/read-binary-file-arch": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz", @@ -9001,6 +9190,14 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, + "node_modules/scheduler": { + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz", + "integrity": "sha512-CtuThmgHNg7zIZWAXi3AsyIzA3n4xx7aNyjwC2VJldO2LMVDhFK+63xGqq6CsJH4rTAt6/M+N4GhZiDYPx9eUw==", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, "node_modules/schema-utils": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz", @@ -9286,6 +9483,12 @@ "node": ">= 0.4" } }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "dev": true + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -10322,6 +10525,29 @@ "node": ">= 0.8" } }, + "node_modules/unzip-crx-3": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/unzip-crx-3/-/unzip-crx-3-0.2.0.tgz", + "integrity": "sha512-0+JiUq/z7faJ6oifVB5nSwt589v1KCduqIJupNVDoWSXZtWDmjDGO3RAEOvwJ07w90aoXoP4enKsR7ecMrJtWQ==", + "dev": true, + "dependencies": { + "jszip": "^3.1.0", + "mkdirp": "^0.5.1", + "yaku": "^0.16.6" + } + }, + "node_modules/unzip-crx-3/node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, "node_modules/update-browserslist-db": { "version": "1.0.13", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", @@ -11137,6 +11363,12 @@ "node": ">=10" } }, + "node_modules/yaku": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/yaku/-/yaku-0.16.7.tgz", + "integrity": "sha512-Syu3IB3rZvKvYk7yTiyl1bo/jiEFaaStrgv1V2TIJTqYPStSMQVO8EQjg/z+DRzLq/4LIIharNT3iH1hylEIRw==", + "dev": true + }, "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", diff --git a/package.json b/package.json index 29fcf39..b01e480 100644 --- a/package.json +++ b/package.json @@ -21,11 +21,14 @@ "@electron-forge/plugin-fuses": "^7.4.0", "@electron-forge/plugin-webpack": "^7.4.0", "@electron/fuses": "^1.8.0", + "@types/react": "^18.2.79", + "@types/react-dom": "^18.2.25", "@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/parser": "^5.62.0", "@vercel/webpack-asset-relocator-loader": "^1.7.3", "css-loader": "^6.11.0", "electron": "30.0.1", + "electron-devtools-installer": "^3.2.0", "eslint": "^8.57.0", "eslint-plugin-import": "^2.29.1", "fork-ts-checker-webpack-plugin": "^7.3.0", @@ -44,6 +47,9 @@ "dependencies": { "@fortawesome/fontawesome-free": "^6.5.2", "bootstrap": "^5.3.3", - "electron-squirrel-startup": "^1.0.0" + "electron-squirrel-startup": "^1.0.0", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-router-dom": "^6.22.3" } } diff --git a/pages/Home/index.html b/pages/Home/index.html new file mode 100644 index 0000000..bdd2333 --- /dev/null +++ b/pages/Home/index.html @@ -0,0 +1,125 @@ + + + + + + WiZ APP + + +
+ + + +
+
+
+
+ Lights +
+
+
+ + +
+
+ + +
+ + diff --git a/src/script.ts b/pages/Home/script.ts similarity index 68% rename from src/script.ts rename to pages/Home/script.ts index fd65a52..60ed823 100644 --- a/src/script.ts +++ b/pages/Home/script.ts @@ -1,21 +1,19 @@ -import { BulbState } from './types'; +import { BulbState } from '../../src/types'; -function toggleSwitch() { +function switchToggleHandler() { const switchBtn = document.getElementById('lightSwitch') as HTMLInputElement; const switchBtnMain = document.getElementById('lightSwitch-main') as HTMLInputElement; switchBtn.addEventListener('change', () => { - //window.electronAPI.toggleBulb(); + window.electronAPI.toggleBulb(); switchBtnMain.checked = !switchBtnMain.checked; }); switchBtnMain.addEventListener('change', () => { - //window.electronAPI.toggleBulb(); + window.electronAPI.toggleBulb(); switchBtn.checked = !switchBtn.checked; }); } -let shortcutCreated = false; function addSwitchToggleToSidebar(res: BulbState) { - if (shortcutCreated) return; const shortcut = document.querySelector('.shortcut'); const div = document.createElement('div'); @@ -45,19 +43,18 @@ function addSwitchToggleToSidebar(res: BulbState) { const slider = document.querySelector('.form-range') as HTMLInputElement; slider.disabled = false; slider.value = String(res.dimming); - shortcutCreated = true; slider.addEventListener('change', (e) => { - //window.electronAPI.setBrightness(e.target.value); + const target = e.target as HTMLInputElement; + window.electronAPI.setBrightness(parseInt(target.value, 10)); }); + + switchToggleHandler(); } -function getLight() { - window.electronAPI.bulbStateRequest(); - window.electronAPI.bulbStateResponse((event, res) => { - if (res) { - document.querySelector('.edit').classList.remove('visually-hidden'); - document.querySelector('.lights').innerHTML = ` +function createBulbDiv(res: BulbState) { + document.querySelector('.edit').classList.remove('visually-hidden'); + document.querySelector('.lights').innerHTML = `
@@ -76,11 +73,9 @@ function getLight() {
`; - addSwitchToggleToSidebar(res); - } - toggleSwitch(); - }); +} +function createManualIpDiv() { document.querySelector('.lights').innerHTML = `
@@ -102,14 +97,24 @@ function getLight() {
`; } -let editActive = false; +function setUpLight() { + window.electronAPI.bulbStateRequest(); + window.electronAPI.bulbStateResponse((res) => { + if (res) { + createBulbDiv(res); + addSwitchToggleToSidebar(res); + } else { + createManualIpDiv(); + } + }); +} function disableEdit(editLabel: HTMLLabelElement) { const input = document.querySelector('.inputEdit') as HTMLInputElement; const bulb = document.querySelector('.bulb'); const newName = input.value; - //window.electronAPI.setBulbName(newName); + window.electronAPI.setBulbName(newName); const sidebarName = document.querySelector('.sidebar-nombre') as HTMLSpanElement; sidebarName.innerText = newName; @@ -119,40 +124,46 @@ function disableEdit(editLabel: HTMLLabelElement) { const span = document.createElement('span'); span.innerText = newName; bulb.replaceChild(span, bulb.childNodes[1]); - editActive = false; } function editName() { - const editBtn = document.querySelector('.edit i'); - const editLabel = document.querySelector('.edit span') as HTMLLabelElement; - editBtn.classList.toggle('fa-pencil'); - editBtn.classList.toggle('fa-floppy-disk'); - editLabel.innerText = 'Save Name'; - - if (!editActive) { - const input = document.createElement('input') as HTMLInputElement; - input.type = 'text'; - input.classList.add('inputEdit'); - input.maxLength = 15; - - input.addEventListener('keyup', (e) => { - if (e.key === 'Enter') { - editBtn.classList.toggle('fa-pencil'); - editBtn.classList.toggle('fa-floppy-disk'); - disableEdit(editLabel); - } - }); - - const bulb = document.querySelector('.bulb') as HTMLDivElement; - input.value = (bulb.childNodes[1] as HTMLElement).innerText; - bulb.replaceChild(input, bulb.childNodes[1]); - editActive = true; - } else { - disableEdit(editLabel); - } + let isEditActive = false; + + return function () { + const editBtn = document.querySelector('.edit i'); + const editLabel = document.querySelector('.edit span') as HTMLLabelElement; + editBtn.classList.toggle('fa-pencil'); + editBtn.classList.toggle('fa-floppy-disk'); + editLabel.innerText = 'Save Name'; + + if (!isEditActive) { + console.log('edit active'); + const input = document.createElement('input') as HTMLInputElement; + input.type = 'text'; + input.classList.add('inputEdit'); + input.maxLength = 15; + + input.addEventListener('keyup', (e) => { + if (e.key === 'Enter') { + editBtn.classList.toggle('fa-pencil'); + editBtn.classList.toggle('fa-floppy-disk'); + disableEdit(editLabel); + isEditActive = false; + } + }); + + const bulb = document.querySelector('.bulb') as HTMLDivElement; + input.value = (bulb.childNodes[1] as HTMLElement).innerText; + bulb.replaceChild(input, bulb.childNodes[1]); + isEditActive = true; + } else { + disableEdit(editLabel); + isEditActive = false; + } + }; } -function addIp() { +function setIpHandler() { const form = document.querySelector('.needs-validation'); const ipInput = document.querySelector('.ipInput') as HTMLInputElement; document.getElementById('addModal').addEventListener('shown.bs.modal', () => { @@ -164,7 +175,7 @@ function addIp() { ipInput.classList.remove('is-invalid'); ipInput.classList.add('is-valid'); form.classList.add('was-validated'); - //window.electronAPI.setIp(ipInput.value); + window.electronAPI.setIp(ipInput.value); } else { event.preventDefault(); event.stopPropagation(); @@ -174,14 +185,23 @@ function addIp() { }); } -window.addEventListener('DOMContentLoaded', () => { - getLight(); - console.log('HELLO FROM SCRIPT!'); - /* addIp(); +function visitAuthorHandler() { document.querySelector('.redirect').addEventListener('click', () => { window.electronAPI.visitAuthor(); }); - document.querySelector('.edit').addEventListener('click', () => { - editName(); - }); */ +} + +function editNameHandler() { + const editBtn = document.querySelector('.edit'); + const handleEdit = editName(); + editBtn.addEventListener('click', () => { + handleEdit(); + }); +} + +window.addEventListener('DOMContentLoaded', () => { + setUpLight(); + setIpHandler(); + visitAuthorHandler(); + editNameHandler(); }); diff --git a/pages/Scenes/index.html b/pages/Scenes/index.html new file mode 100644 index 0000000..234e437 --- /dev/null +++ b/pages/Scenes/index.html @@ -0,0 +1,230 @@ + + + + + + WiZ APP + + + + + +
+ + + +
+
+
+ Scenes +
+ +
+
+
+

Whites

+ +
+
+

Functional

+ +
+
+
+
+ + + + diff --git a/src/bulbHelper.ts b/src/bulbHelper.ts index b386652..f2cd7cc 100644 --- a/src/bulbHelper.ts +++ b/src/bulbHelper.ts @@ -1,11 +1,11 @@ import fs from 'fs'; import { CONFIG } from './constants'; import { AppData, BulbState } from './types'; -import { discover, Bulb } from '../lib/mod'; +import { discover, Bulb } from './lib/wikari/src/mod'; type systemConfig = { method: string; - params: Record; + params: Record; result: { homeId: number; roomId: number; @@ -17,49 +17,162 @@ type systemConfig = { }; }; -export const setUpBulb = async (): Promise => { - let data: AppData; - try { - data = JSON.parse(fs.readFileSync(CONFIG, 'utf-8')); - console.log('CONFIG DATA FOUND:', data); - } catch (e) { - console.warn('CONFIG DATA NOT FOUND'); +class BulbHelper { + private bulb: Bulb; + private bulbState: BulbState; + private bulbStateReady: Promise; + private appData: AppData; + private resolveBulbStateReady: () => void; + + constructor() { + this.bulbStateReady = new Promise((resolve) => { + this.resolveBulbStateReady = resolve; + }); + this.init(); + } + + private async init() { + await this.setUpBulb(); } - let bulb: Bulb; - let bulbFound = false; + private async setUpBulb() { + let data: AppData; + try { + data = JSON.parse(fs.readFileSync(CONFIG, 'utf-8')); + console.log('CONFIG DATA FOUND:', data); + } catch (e) { + console.warn('CONFIG DATA NOT FOUND'); + } + + let bulb: Bulb; + let bulbFound = false; - while (!bulbFound) { - if (data && data.bulbIp) { - console.log('STORED BULB IP FOUND:', data.bulbIp); - let res = await discover({ addr: data.bulbIp, waitMs: 2500 }); - if (res && res.length > 0) { - bulb = res[0]; - bulbFound = true; + while (!bulbFound) { + if (data && data.bulbIp) { + console.log('STORED BULB IP FOUND:', data.bulbIp); + const res = await discover({ addr: data.bulbIp, waitMs: 2500 }); + if (res && res.length > 0) { + bulb = res[0]; + bulbFound = true; + } + } else { + console.log('NO STORED BULB IP FOUND'); + const res = await discover({}); + if (res && res.length > 0) { + bulb = res[0]; + bulbFound = true; + } } - } else { - console.log('NO STORED BULB IP FOUND'); - let res = await discover({}); - if (res && res.length > 0) { - bulb = res[0]; - bulbFound = true; + + if (!bulbFound) { + console.warn('NO BULB FOUND, RETRYING...'); + this.appData.bulbIp = undefined; } } + + const pilot = (await bulb.getPilot()).result; + const config = (await bulb.sendRaw({ + method: 'getSystemConfig', + env: '', + params: { mac: '', rssi: 0 }, + })) as systemConfig; + const configResult = config.result; + this.bulbState = { + ...pilot, + ...configResult, + ip: bulb.address, + port: bulb.bulbPort, + name: data.bulbName, + customColors: data.customColors, + }; + + this.bulb = bulb; + this.appData = data; + this.resolveBulbStateReady(); } - const pilot = (await bulb.getPilot()).result; - const config = (await bulb.sendRaw({ - method: 'getSystemConfig', - env: '', - params: { mac: '', rssi: 0 }, - })) as systemConfig; - const configResult = config.result; - return { - ...pilot, - ...configResult, - ip: bulb.address, - port: bulb.bulbPort, - name: data.bulbName, - customColors: data.customColors, - }; -}; + public async toggleBulb() { + await this.bulbStateReady; + this.bulbState.state = !this.bulbState.state; + await this.bulb.toggle(); + } + + public async getBulbState() { + await this.bulbStateReady; + return this.bulbState; + } + + public async setBrightness(brightness: number) { + await this.bulbStateReady; + this.bulbState.dimming = brightness; + await this.bulb.brightness(brightness); + } + + private saveConfig() { + fs.writeFileSync(CONFIG, JSON.stringify(this.appData)); + } + + public async setBulbName(name: string) { + await this.bulbStateReady; + this.bulbState.name = name; + this.appData.bulbName = name; + this.saveConfig(); + } + + public setIp(ip: string) { + this.appData.bulbIp = ip; + this.saveConfig(); + this.setUpBulb(); + } + + public async setScene(sceneId: number) { + await this.bulbStateReady; + this.bulbState.state = true; + this.bulbState.sceneId = sceneId; + await this.bulb.scene(sceneId); + } + + private getCustomColorNewId() { + if (this.bulbState.customColors.length === 0) return 33; + + const ids = this.bulbState.customColors.map((color) => color.id); + return Math.max(...ids) + 1; + } + + public async addCustomColor(colorName: string, colorHex: string) { + await this.bulbStateReady; + const newId = this.getCustomColorNewId(); + this.bulbState.customColors.push({ id: newId, name: colorName, hex: colorHex }); + this.appData.customColors = this.bulbState.customColors; + this.saveConfig(); + } + + public async setCustomColor(colorId: number) { + console.log(colorId); + await this.bulbStateReady; + const color = this.bulbState.customColors.find((c) => c.id === colorId); + if (!color) return; + this.bulbState.state = true; + this.bulbState.sceneId = colorId; + await this.bulb.color(color.hex as `#${string}`); + } + + public async editCustomColor(colorId: number, colorName: string, colorHex: string) { + await this.bulbStateReady; + const color = this.bulbState.customColors.find((c) => c.id === colorId); + if (!color) return; + color.name = colorName; + color.hex = colorHex; + this.appData.customColors = this.bulbState.customColors; + this.saveConfig(); + } + + public async removeCustomColor(colorId: number) { + await this.bulbStateReady; + this.bulbState.customColors = this.bulbState.customColors.filter((c) => c.id !== colorId); + this.appData.customColors = this.bulbState.customColors; + this.saveConfig(); + } +} + +export default BulbHelper; diff --git a/src/components/App.tsx b/src/components/App.tsx new file mode 100644 index 0000000..e2f4073 --- /dev/null +++ b/src/components/App.tsx @@ -0,0 +1,29 @@ +import { createRoot } from 'react-dom/client'; +import Home from './Home'; +import { RouterProvider, createHashRouter } from 'react-router-dom'; +import Scenes from './Scenes'; +import { BulbProvider } from './BulbContext'; +import Devices from './Devices'; + +const router = createHashRouter([ + { + path: '/', + element: , + }, + { + path: '/scenes', + element: , + }, + { + path: '/devices', + element: , + }, +]); + +const domNode = document.getElementById('root'); +const root = createRoot(domNode); +root.render( + + + +); diff --git a/src/components/BulbContext.tsx b/src/components/BulbContext.tsx new file mode 100644 index 0000000..25d5ed5 --- /dev/null +++ b/src/components/BulbContext.tsx @@ -0,0 +1,34 @@ +import { createContext, useContext, useEffect, useState } from 'react'; +import { BulbState } from '../types'; + +interface BulbContextProps { + bulb: BulbState; + setBulb: React.Dispatch>; +} + +interface BulbProviderProps { + children: React.ReactNode; +} + +export const BulbContext = createContext(undefined); + +export const BulbProvider: React.FC = ({ children }) => { + const [bulb, setBulb] = useState(); + + useEffect(() => { + window.electronAPI.bulbStateRequest(); + window.electronAPI.bulbStateResponse((bulb) => { + setBulb(bulb); + }); + }, []); + + return {children}; +}; + +export const useBulb = (): BulbContextProps => { + const context = useContext(BulbContext); + if (context === undefined) { + throw new Error('useBulb must be used within a BulbProvider'); + } + return context; +}; diff --git a/src/components/Custom.tsx b/src/components/Custom.tsx new file mode 100644 index 0000000..7fc511c --- /dev/null +++ b/src/components/Custom.tsx @@ -0,0 +1,76 @@ +import { useState } from 'react'; +import { BulbState } from '../types'; +import { useBulb } from './BulbContext'; +import ModalCreateColor from './ModalCreateColor'; +import ModalEditColor from './ModalEditColor'; + +export default function Custom() { + const { bulb, setBulb } = useBulb(); + + const [currentEditColor, setCurrentEditColor] = useState(); + + const setCustomColorHandler = (id: number) => { + setBulb((prev) => { + return { ...prev, sceneId: id, state: true }; + }); + window.electronAPI.setCustomColor(id); + }; + + const renderCustomColor = (color: BulbState['customColors'][0]) => ( +
+ + +
+ ); + + return ( + <> + + +
+
+
+

Custom Colors

+ +
+
+ {bulb && + bulb.customColors && + bulb.customColors.map((color) => renderCustomColor(color))} +
+
+
+ + ); +} diff --git a/src/components/Devices.tsx b/src/components/Devices.tsx new file mode 100644 index 0000000..4e4c387 --- /dev/null +++ b/src/components/Devices.tsx @@ -0,0 +1,41 @@ +import { useBulb } from './BulbContext'; +import Sidebar from './Sidebar'; + +export default function Devices() { + const { bulb } = useBulb(); + + return ( +
+ +
+
+
+
+ Device Info +
+
+
+
+
+ {bulb ? ( +
+ + Module Name: {bulb.moduleName} + IP Address: {bulb.ip} + Port: {bulb.port} + Mac Address: {bulb.mac} + Status: {bulb.state ? 'ON' : 'OFF'} + Scene Id: {bulb.sceneId} + {bulb.dimming ? `Brightness: ${bulb.dimming}%` : ''} + Firmware Version: {bulb.fwVersion} + Home ID: {bulb.homeId} + Room ID: {bulb.roomId} +
+ ) : ( + '' + )} +
+
+
+ ); +} diff --git a/src/components/Dynamic.tsx b/src/components/Dynamic.tsx new file mode 100644 index 0000000..12e52c6 --- /dev/null +++ b/src/components/Dynamic.tsx @@ -0,0 +1,372 @@ +import { JSX } from 'react/jsx-runtime'; +import { useBulb } from './BulbContext'; + +export default function Dynamic() { + const { bulb, setBulb } = useBulb(); + + const changeSceneHandler = (id: number) => { + setBulb((prev) => { + return { ...prev, sceneId: id, state: true }; + }); + window.electronAPI.setScene(id); + }; + + const renderItem = (name: string, sceneId: number, icon: string, svgIcon: JSX.Element | '') => ( +
+ +
+ ); + + return ( +
+
+

Whites

+
+ {renderItem( + 'Candle Light', + 29, + '', + + + + + + )} + {renderItem('Pulse', 31, 'fa-wave-square', '')} + {renderItem( + 'Golden White', + 30, + '', + + + + + + + + + + + + + )} + {renderItem( + 'Steampunk', + 32, + '', + + + + + + + + + + + + )} +
+
+
+

Color

+
+ {renderItem( + 'Fireplace', + 5, + '', + + + + + + + )} + {renderItem('Fall', 22, 'fa-leaf', '')} + {renderItem('Club', 26, 'fa-guitar', '')} + {renderItem( + 'Sunset', + 3, + '', + + + + + + + )} + {renderItem('Romance', 2, 'fa-heart', '')} + {renderItem( + 'Party', + 4, + '', + + + + + + + + + + + + + + )} + {renderItem('Pastel Colors', 8, 'fa-swatchbook', '')} + {renderItem( + 'Rainbow', + 20, + '', + + + + + + )} + {renderItem('Summer', 21, 'fa-umbrella-beach', '')} + {renderItem('Forest', 7, 'fa-tree', '')} + {renderItem( + 'Jungle', + 24, + '', + + + + + + + + + + )} + {renderItem('Mojito', 25, 'fa-martini-glass', '')} + {renderItem('Ocean', 1, 'fa-water', '')} + {renderItem('Deep Dive', 23, 'fa-fish', '')} + {renderItem('Christmas', 27, 'fa-candy-cane', '')} + {renderItem( + 'Halloween', + 28, + '', + + + + + + + + + )} +
+
+
+

Progressive

+
+ {renderItem('Bedtime', 10, 'fa-bed', '')} + {renderItem( + 'Wake Up', + 9, + '', + + + + + + + )} +
+
+
+ ); +} diff --git a/src/components/Home.tsx b/src/components/Home.tsx new file mode 100644 index 0000000..b9dad5d --- /dev/null +++ b/src/components/Home.tsx @@ -0,0 +1,124 @@ +import { useEffect, useState } from 'react'; +import IpModal from './IpModal'; +import Sidebar from './Sidebar'; +import { useBulb } from './BulbContext'; + +export default function Home() { + const { bulb, setBulb } = useBulb(); + const [isEditActive, setIsEditActive] = useState(false); + + const lightSwitchHandler = () => { + window.electronAPI.toggleBulb(); + setBulb((prev) => { + return { ...prev, state: !prev.state }; + }); + }; + + const handleChangeName = (event: React.KeyboardEvent) => { + if (event.key === 'Enter') { + setBulb((prev) => { + return { ...prev, name: (event.target as HTMLInputElement).value }; + }); + + window.electronAPI.setBulbName((event.target as HTMLInputElement).value); + setIsEditActive(false); + } + }; + + const bulbElement = () => ( +
+
+
+
+ +
+ {isEditActive ? ( +
+ +
+ ) : ( +
+ {bulb.name || bulb.moduleName} +
+ + +
+
+ )} +
+
+
+ ); + + const editBtnHandler = () => { + setIsEditActive((prev) => !prev); + }; + + const searchingForBulbElement = () => ( +
+
+
+
+ +
+
+ Searching bulb... +
+ Loading... +
+
+
+

+ Can't find bulb? + +

+
+
+ ); + + return ( +
+ +
+
+
+
+ Lights +
+
+
+ +
{bulb ? bulbElement() : searchingForBulbElement()}
+
+ +
+ ); +} diff --git a/src/components/IpModal.tsx b/src/components/IpModal.tsx new file mode 100644 index 0000000..7af989f --- /dev/null +++ b/src/components/IpModal.tsx @@ -0,0 +1,65 @@ +import { useState } from 'react'; + +export default function IpModal() { + const [value, setValue] = useState(''); + + const setIpHandler = () => { + window.electronAPI.setIp(value); + }; + + return ( + + ); +} diff --git a/src/components/ModalCreateColor.tsx b/src/components/ModalCreateColor.tsx new file mode 100644 index 0000000..516af1d --- /dev/null +++ b/src/components/ModalCreateColor.tsx @@ -0,0 +1,101 @@ +import { useState } from 'react'; +import { useBulb } from './BulbContext'; + +export default function ModalCreateColor() { + const { setBulb } = useBulb(); + + const [colorName, setColorName] = useState(''); + const [colorHex, setColorHex] = useState('#ffffff'); + + const addNewColorHandler = (e: React.FormEvent) => { + e.preventDefault(); + if (!colorName || !colorHex) return; + + window.electronAPI.addCustomColor(colorName, colorHex); + setBulb((prev) => { + return { + ...prev, + customColors: [ + ...prev.customColors, + { + id: + prev.customColors.length === 0 + ? 33 + : prev.customColors[prev.customColors.length - 1].id + 1, + name: colorName, + hex: colorHex, + }, + ], + }; + }); + + setColorName(''); + setColorHex('#ffffff'); + }; + + return ( + + ); +} diff --git a/src/components/ModalEditColor.tsx b/src/components/ModalEditColor.tsx new file mode 100644 index 0000000..501cd4f --- /dev/null +++ b/src/components/ModalEditColor.tsx @@ -0,0 +1,116 @@ +import { useBulb } from './BulbContext'; +import { BulbState } from '../types'; +import { useEffect, useState } from 'react'; + +interface ModalEditColorProps { + currentEditColor: BulbState['customColors'][0]; +} + +export default function ModalEditColor({ currentEditColor }: ModalEditColorProps) { + const { setBulb } = useBulb(); + + const [colorName, setColorName] = useState(''); + const [colorHex, setColorHex] = useState('#ffffff'); + + useEffect(() => { + if (!currentEditColor) return; + + setColorName(currentEditColor.name); + setColorHex(currentEditColor.hex); + }, [currentEditColor]); + + const editColorHandler = (e: React.FormEvent) => { + e.preventDefault(); + setBulb((prev) => { + return { + ...prev, + customColors: prev.customColors.map((color) => + color.id === currentEditColor.id ? { ...color, name: colorName, hex: colorHex } : color + ), + }; + }); + window.electronAPI.editCustomColor(currentEditColor.id, colorName, colorHex); + }; + + const removeColorHandler = () => { + setBulb((prev) => { + return { + ...prev, + customColors: prev.customColors.filter((color) => color.id !== currentEditColor.id), + }; + }); + window.electronAPI.removeCustomColor(currentEditColor.id); + }; + + return ( + + ); +} diff --git a/src/components/Scenes.tsx b/src/components/Scenes.tsx new file mode 100644 index 0000000..8f6104e --- /dev/null +++ b/src/components/Scenes.tsx @@ -0,0 +1,65 @@ +import { useState } from 'react'; +import Dynamic from './Dynamic'; +import Sidebar from './Sidebar'; +import Static from './Static'; +import Custom from './Custom'; + +export default function Scenes() { + const [activeTab, setActiveTab] = useState('static'); + + const renderTab = () => { + switch (activeTab) { + case 'static': + return ; + case 'dynamic': + return ; + case 'custom': + return ; + default: + return ; + } + }; + + return ( +
+ +
+
+
+ Scenes +
+ +
+ {renderTab()} +
+
+ ); +} diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx new file mode 100644 index 0000000..e4f86b4 --- /dev/null +++ b/src/components/Sidebar.tsx @@ -0,0 +1,110 @@ +import logo from '../assets/logo_sidebar.png'; +import { memo, useState } from 'react'; +import { Link, useMatch } from 'react-router-dom'; +import { useBulb } from './BulbContext'; + +function Sidebar() { + const { bulb, setBulb } = useBulb(); + const [isDragging, setIsDragging] = useState(false); + const [brightness, setBrightness] = useState(100); + + const renderItem = (label: string, faIcon: string, ref: string) => ( +
  • + + + {label} + +
  • + ); + + const brightnessHandler = (event: React.ChangeEvent) => { + setBrightness(parseInt(event.target.value)); + }; + + const lightSwitchHandler = () => { + window.electronAPI.toggleBulb(); + setBulb((prev) => { + return { ...prev, state: !prev.state }; + }); + }; + + const handleMouseUp = () => { + if (isDragging) { + window.electronAPI.setBrightness(brightness); + setIsDragging(false); + } + }; + + const handleMouseDown = () => { + setIsDragging(true); + }; + + const renderShortcut = () => ( +
    +
    + + + +
    +
    + {bulb.name || bulb.moduleName} +
    + + +
    +
    +
    + ); + + const visitAuthorHandler = () => window.electronAPI.visitAuthor(); + return ( +
    + + Wiz logo + +
    +
      + {renderItem('Lights', 'fa-lightbulb', '/')} + {renderItem('Scenes', 'fa-image', '/scenes')} + {renderItem('Devices', 'fa-circle-question', '/devices')} +
    + {bulb ? renderShortcut() : null} +
    + + Made by{' '} + + MatiasTK + + +
    + ); +} + +export default memo(Sidebar); diff --git a/src/components/Static.tsx b/src/components/Static.tsx new file mode 100644 index 0000000..2ad5ae0 --- /dev/null +++ b/src/components/Static.tsx @@ -0,0 +1,55 @@ +import { useBulb } from './BulbContext'; + +export default function Static() { + const { bulb, setBulb } = useBulb(); + + const changeSceneHandler = (id: number) => { + setBulb((prev) => { + return { ...prev, sceneId: id, state: true }; + }); + window.electronAPI.setScene(id); + }; + + const renderItem = (name: string, sceneId: number, icon: string) => ( +
    + +
    + ); + + return ( +
    +
    +

    Whites

    +
    + {renderItem('Warm White', 11, 'fa-mug-hot')} + {renderItem('Day Light', 12, 'fa-sun')} + {renderItem('Cold White', 13, 'fa-snowflake')} +
    +
    +
    +

    Functional

    +
    + {renderItem('Night Light', 14, 'fa-moon')} + {renderItem('Cozy', 6, 'fa-couch')} + {renderItem('True Colors', 17, 'fa-palette')} + {renderItem('Relax', 16, 'fa-campground')} + {renderItem('Focus', 15, 'fa-glasses')} + {renderItem('TV Time', 18, 'fa-television')} + {renderItem('Plant Growth', 19, 'fa-seedling')} +
    +
    +
    + ); +} diff --git a/src/constants.ts b/src/constants.ts index c6cb207..8416f4d 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -4,8 +4,9 @@ const icon = require('./assets/icon.ico'); const ICON = nativeImage.createFromPath(path.join(__dirname, icon)); const CONFIG = path.join(app.getPath('userData'), 'config.json'); +const AUTHOR_URL = 'https://www.github.com/MatiasTK'; const MIN_WIDTH = 900; const MIN_HEIGHT = 600; const HIDE_MENU = true; -export { ICON, CONFIG, MIN_WIDTH, MIN_HEIGHT, HIDE_MENU }; +export { ICON, CONFIG, MIN_WIDTH, MIN_HEIGHT, HIDE_MENU, AUTHOR_URL }; diff --git a/src/index.html b/src/index.html index ef3416f..0cdc105 100644 --- a/src/index.html +++ b/src/index.html @@ -4,131 +4,8 @@ WiZ APP - -
    - - - -
    -
    -
    -
    - Lights -
    -
    -
    - - -
    -
    - - -
    - - +
    diff --git a/src/index.ts b/src/index.ts index 1e51280..9575f4b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,8 +1,8 @@ -import { app, BrowserWindow, Tray, ipcMain, Menu, shell } from 'electron'; -import { ICON, MIN_WIDTH, MIN_HEIGHT, HIDE_MENU } from './constants'; +import { app, BrowserWindow, ipcMain, shell } from 'electron'; +import { ICON, MIN_WIDTH, MIN_HEIGHT, HIDE_MENU, AUTHOR_URL } from './constants'; import createTray from './tray'; -import { setUpBulb } from './bulbHelper'; -import { BulbState } from './types'; +import BulbHelper from './bulbHelper'; +import installExtension, { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer'; // This allows TypeScript to pick up the magic constants that's auto-generated by Forge's Webpack // plugin that tells the Electron app where to look for the Webpack-bundled app code (depending on // whether you're running in development or production). @@ -27,21 +27,56 @@ const createWindow = (): void => { }, }); - let bulb: BulbState; + const bulbHelper = new BulbHelper(); createTray(mainWindow, app); ipcMain.on('bulb-state-request', (event) => { - if (bulb) { - event.reply('bulb-state-response', bulb); - return; - } - - setUpBulb().then((b) => { - bulb = b; - event.reply('bulb-state-response', bulb); + bulbHelper.getBulbState().then((res) => { + event.reply('bulb-state-response', res); }); }); + ipcMain.on('toggle-bulb-state', async () => { + await bulbHelper.toggleBulb(); + }); + + ipcMain.on('visit-author', () => { + shell.openExternal(AUTHOR_URL); + }); + + ipcMain.on('set-brightness', async (event, brightness) => { + await bulbHelper.setBrightness(brightness); + }); + + ipcMain.on('set-bulb-name', async (event, name) => { + await bulbHelper.setBulbName(name); + }); + + //TODO: TEST! + ipcMain.on('set-ip', async (event, ip) => { + await bulbHelper.setIp(ip); + }); + + ipcMain.on('set-scene', async (event, sceneId) => { + await bulbHelper.setScene(sceneId); + }); + + ipcMain.on('add-custom-color', async (event, colorName, colorHex) => { + await bulbHelper.addCustomColor(colorName, colorHex); + }); + + ipcMain.on('set-custom-color', async (event, colorId) => { + await bulbHelper.setCustomColor(colorId); + }); + + ipcMain.on('edit-color', async (event, colorId, colorName, colorHex) => { + await bulbHelper.editCustomColor(colorId, colorName, colorHex); + }); + + ipcMain.on('remove-color', async (event, colorId) => { + await bulbHelper.removeCustomColor(colorId); + }); + // and load the index.html of the app. mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY); @@ -55,6 +90,16 @@ const createWindow = (): void => { app.on('ready', createWindow); app.setName('WiZ App'); +app.whenReady().then(() => { + installExtension(REACT_DEVELOPER_TOOLS) + .then((name) => { + console.log(`Added Extension: ${name}`); + }) + .catch((err) => { + console.log('An error occurred: ', err); + }); +}); + // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. diff --git a/src/interface.d.ts b/src/interface.d.ts index 832ac89..4aa2074 100644 --- a/src/interface.d.ts +++ b/src/interface.d.ts @@ -1,6 +1,16 @@ export interface IElectronAPI { bulbStateRequest: () => void; - bulbStateResponse: (callback: (_: Electron.IpcRendererEvent, bulb: BulbState) => void) => void; + bulbStateResponse: (callback: (bulb: BulbState) => void) => void; + toggleBulb: () => void; + setBrightness: (brightness: number) => void; + setBulbName: (name: string) => void; + setIp: (ip: string) => void; + visitAuthor: () => void; + setScene: (sceneId: number) => void; + addCustomColor: (colorName: string, colorHex: string) => void; + setCustomColor: (colorId: number) => void; + editCustomColor: (colorId: number, colorName: string, colorHex: string) => void; + removeCustomColor: (colorId: number) => void; } declare global { diff --git a/src/preload.ts b/src/preload.ts index 1b300e8..7e5f1e6 100644 --- a/src/preload.ts +++ b/src/preload.ts @@ -2,9 +2,22 @@ // https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts import { contextBridge, ipcRenderer } from 'electron'; +import { BulbState } from './types'; contextBridge.exposeInMainWorld('electronAPI', { bulbStateRequest: () => ipcRenderer.send('bulb-state-request'), - bulbStateResponse: (callback: (event: Electron.IpcRendererEvent, ...args: any[]) => void) => - ipcRenderer.on('bulb-state-response', callback), + bulbStateResponse: (callback: (bulb: BulbState) => void) => + ipcRenderer.on('bulb-state-response', (_, bulb) => callback(bulb)), + toggleBulb: () => ipcRenderer.send('toggle-bulb-state'), + setBrightness: (brightness: number) => ipcRenderer.send('set-brightness', brightness), + setBulbName: (name: string) => ipcRenderer.send('set-bulb-name', name), + setIp: (ip: string) => ipcRenderer.send('set-ip', ip), + visitAuthor: () => ipcRenderer.send('visit-author'), + setScene: (sceneId: number) => ipcRenderer.send('set-scene', sceneId), + addCustomColor: (colorName: string, colorHex: string) => + ipcRenderer.send('add-custom-color', colorName, colorHex), + setCustomColor: (colorName: string) => ipcRenderer.send('set-custom-color', colorName), + editCustomColor: (colorId: number, colorName: string, colorHex: string) => + ipcRenderer.send('edit-color', colorId, colorName, colorHex), + removeCustomColor: (colorId: number) => ipcRenderer.send('remove-color', colorId), }); diff --git a/src/react-app-env.d.ts b/src/react-app-env.d.ts new file mode 100644 index 0000000..a0993ed --- /dev/null +++ b/src/react-app-env.d.ts @@ -0,0 +1,4 @@ +declare module '*.png' { + const value: any; + export = value; +} diff --git a/src/renderer.ts b/src/renderer.ts index 04e6746..3a30413 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -28,11 +28,4 @@ import './index.css'; import 'bootstrap'; -import './script.ts'; - -const logo = require('./assets/logo_sidebar.png'); - -const sidebarImage = document.querySelector('.sidebar-image') as HTMLImageElement; -sidebarImage.src = logo; - -console.log('👋 This message is being logged by "renderer.js", included via webpack'); +import './components/App.tsx'; diff --git a/src/types.ts b/src/types.ts index f81eb4f..95f94b9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,7 @@ export type AppData = { bulbName: string; bulbIp: string; - customColors: Array<{ id: number; name: string; color: string }>; + customColors: Array<{ id: number; name: string; hex: string }>; }; export type BulbState = { @@ -28,5 +28,5 @@ export type BulbState = { ip: string; port: number; name: string; - customColors: Array<{ id: number; name: string; color: string }>; + customColors: Array<{ id: number; name: string; hex: string }>; }; diff --git a/tsconfig.json b/tsconfig.json index b046272..fb4cb44 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,9 +11,10 @@ "outDir": "dist", "moduleResolution": "node", "resolveJsonModule": true, + "jsx": "react-jsx", "paths": { "*": ["node_modules/*"] } }, - "include": ["src/**/*", "wikari/**/*", "lib/**/*"] + "include": ["src/**/*", "pages"] } diff --git a/wikari/.gitignore b/wikari/.gitignore deleted file mode 100644 index 9d28a1f..0000000 --- a/wikari/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/node_modules -/lib diff --git a/wikari/.prettierrc b/wikari/.prettierrc deleted file mode 100644 index 0b8d595..0000000 --- a/wikari/.prettierrc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "trailingComma": "all", - "useTabs": true, - "semi": true, - "singleQuote": false, - "quoteProps": "consistent", - "bracketSpacing": true, - "arrowParens": "avoid", - "printWidth": 80 -} diff --git a/wikari/LICENSE b/wikari/LICENSE deleted file mode 100644 index f288702..0000000 --- a/wikari/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/wikari/README.md b/wikari/README.md deleted file mode 100644 index b4fb0de..0000000 --- a/wikari/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# Wikari - -A Node JS library to control **Philips WiZ smart bulbs**, written in TypeScript. - -Wikari is very strongly typed! - -# Installation -```bash -$ npm i wikari -``` - -# API - -The library is fairly simple to use, since you're mostly going to deal with `Bulb` objects: - -```typescript -import { discover, SCENES } from "wikari"; - -const bulbs = await discover({}); - -const bulb = bulbs[0]; - -if (!bulb) return console.log("No bulbs found!"); - -// get the current state of the bulb -// WiZ calls the bulb state "pilot" -// so you have "setPilot" and "getPilot" -console.log(await bulb.getPilot()); - -// whenever the bulb sends a message, log it to the console -bulb.onMessage(console.log); - -// turn the bulb on -await bulb.turn(true); - -// set the color to red -await bulb.color("#f44336"); - -// set the color to some cool and some warm white -await bulb.color({ c: 40, w: 40 }); - -// set the scene to "TV Time" -await bulb.scene(SCENES["TV Time"]); - -// set the bulb to 10_000K white -await bulb.white(10_000); - -// set the bulb brightness to 40% -await bulb.brightness(40); - -// toggle the bulb (turns it off since it was already on) -await bulb.toggle(); - -bulb.closeConnection(); -``` - -# Subscription - -It's possible to subscribe to updates from the bulb. - -```typescript -await bulb.subscribe(); - -bulb.onSync(syncPilotMsg => { - // syncPilotMsg is the updated state of the bulb - // it sends a syncPilot message on state change. - // so for example, if you change the state using - // the WiZ app on your phone, the changes will - // show up here as well. -}); -``` - -# TSDoc - -Most of the functions have TSDoc comments, so you can either hover over them and your IDE will display it, -or just skim through the library source code to find it. - -# Advanced Usage - -If you want complete control over the bulb, or want to mix and match various settings, you can try using the `setPilot` or `sendRaw` functions. -However, you should mostly find the functions in the example above to be enough. - ---- -### What's Wikari? -It's supposed to be WiZ + Hikari (光, "light" in Japanese) diff --git a/wikari/package-lock.json b/wikari/package-lock.json deleted file mode 100644 index 6f58034..0000000 --- a/wikari/package-lock.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "wikari", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "wikari", - "version": "0.1.0", - "license": "GPL-3.0-only", - "devDependencies": { - "@types/node": "^18.8.3", - "typescript": "^4.8.4" - } - }, - "node_modules/@types/node": { - "version": "18.19.15", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.15.tgz", - "integrity": "sha512-AMZ2UWx+woHNfM11PyAEQmfSxi05jm9OlkxczuHeEqmvwPkYj6MWv44gbzDPefYOLysTOFyI3ziiy2ONmUZfpA==", - "dev": true, - "dependencies": { - "undici-types": "~5.26.4" - } - }, - "node_modules/typescript": { - "version": "4.9.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", - "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=4.2.0" - } - }, - "node_modules/undici-types": { - "version": "5.26.5", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", - "dev": true - } - } -} diff --git a/wikari/package.json b/wikari/package.json deleted file mode 100644 index 7c4eeb8..0000000 --- a/wikari/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "wikari", - "version": "0.1.0", - "author": "Udit Karode ", - "license": "GPL-3.0-only", - "description": "a library that lets you interact with Philips WiZ smart lights", - "keywords": [ - "philips", - "wiz", - "smart bulb", - "bulb", - "iot" - ], - "files": [ - "lib" - ], - "scripts": { - "build": "tsc" - }, - "main": "./lib/mod.js", - "types": "./lib/mod.d.ts", - "repository": "https://github.com/uditkarode/wikari", - "devDependencies": { - "@types/node": "^18.8.3", - "typescript": "^4.8.4" - } -} diff --git a/wikari/pnpm-lock.yaml b/wikari/pnpm-lock.yaml deleted file mode 100644 index 19e2831..0000000 --- a/wikari/pnpm-lock.yaml +++ /dev/null @@ -1,21 +0,0 @@ -lockfileVersion: 5.4 - -specifiers: - '@types/node': ^18.8.3 - typescript: ^4.8.4 - -devDependencies: - '@types/node': 18.11.0 - typescript: 4.8.4 - -packages: - - /@types/node/18.11.0: - resolution: {integrity: sha512-IOXCvVRToe7e0ny7HpT/X9Rb2RYtElG1a+VshjwT00HxrM2dWBApHQoqsI6WiY7Q03vdf2bCrIGzVrkF/5t10w==} - dev: true - - /typescript/4.8.4: - resolution: {integrity: sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==} - engines: {node: '>=4.2.0'} - hasBin: true - dev: true diff --git a/wikari/src/bulb.ts b/wikari/src/bulb.ts deleted file mode 100644 index d789065..0000000 --- a/wikari/src/bulb.ts +++ /dev/null @@ -1,597 +0,0 @@ -import dgram from "dgram"; -import EventEmitter from "events"; -import { - DEFAULT_RESPONSE_WAIT_MS, - SCENES, - UDP_BROADCAST_LISTEN_PORT as WIZ_BROADCAST_PORT, - WIZ_BULB_LISTEN_PORT, -} from "./constants"; -import { checkType } from "./type-checker"; -import { - getPilotResponseTemplate, - GetPilotResponse, - Message, - Pilot, - GetSceneArgs, - GenericResponse, - syncPilotResponseTemplate, - SyncPilotAckMsg, - setPilotResponseTemplate, - SyncPilotResponse, -} from "./types"; -import { getRandomMac, hexToRgb, ipAddress } from "./utils"; -import { WikariError, WikariErrorCode } from "./wikari-error"; - -export const enum WikariState { - IDLE, - BINDING, - READY, - CLOSED, - AWAITING_RESPONSE, -} - -/** - * Allows you to interact with a bulb. - * - * Note that upon creation, it will have the state {@link WikariState.IDLE}. - * When the first instance of {@link Bulb} is created, it will try to bind - * to the port that WiZ bulbs broadcast updates to, and will set it's state - * to {@link WikariState.BINDING} while this happens. - * - * Once it's done, this instance along with all future instances are ready - * for communication with the bulb, and the state is set to - * {@link WikariState.READY}. - * - * Whenever the state of the instance changes, it will emit a "state-change" - * event on {@link Bulb.stateEmitter} with the new state as the argument. - * - * Every bulb instance uses the same {@link dgram.Socket} object since each - * bulb instance requires updates from the same port, we can only bind one - * socket to the port. - */ -export class Bulb { - static readonly stateEmitter = new EventEmitter(); - static client = dgram.createSocket("udp4"); - - private static _state = WikariState.IDLE; - static get state() { - return this._state; - } - - responseTimeout: number | undefined; - listenPort: number; - bulbPort: number; - - readonly macIdentifier: string; - readonly address: string; - - constructor( - address: string, - options: { - port?: number; - listenPort?: number; - responseTimeout?: number; - macIdentifier?: string; - }, - ) { - this.address = address; - this.bulbPort = options.port ?? WIZ_BULB_LISTEN_PORT; - this.listenPort = options.listenPort ?? WIZ_BROADCAST_PORT; - this.macIdentifier = options.macIdentifier ?? getRandomMac(); - if (options.responseTimeout) this.responseTimeout = options.responseTimeout; - - if (Bulb.state == WikariState.IDLE) this.initClient(); - } - - static setInstanceState(state: WikariState) { - this._state = state; - this.stateEmitter.emit("state-change", state); - } - - // ####################################################### - // High-level end-user oriented interaction functions - // ####################################################### - - /** - * Calls the given function with the newly received - * message as the argument. - * @param fn callback for when a message is received - */ - onMessage(fn: (msg: Message) => void) { - Bulb.client.on("message", (bulbMsg, rinfo) => { - if (rinfo.address != this.address) return; - try { - const msg: Message = JSON.parse(bulbMsg.toString()); - fn(msg); - } catch {} - }); - } - - /** - * After calling {@link this.subscribe}, the bulb will send - * updates about it's state every 5 seconds. The provided - * callback will be called whenever it does so. - * @param fn callback for when a syncPilot message is received - */ - onSync(fn: (msg: SyncPilotResponse) => void) { - Bulb.client.on("message", (bulbMsg, rinfo) => { - if (rinfo.address != this.address) return; - try { - const msg: Message = JSON.parse(bulbMsg.toString()); - if (checkType(syncPilotResponseTemplate, msg)) fn(msg); - } catch {} - }); - } - - /** - * Sends a subscription message to the bulb, which tells it to send us updates - * about it's state every 5 seconds. You can intercept these updates with the - * {@link this.onSync} function. - * - * @param networkInterface network interface connected to the network the bulb is on - * @returns subscription message response on success, else a {@link WikariError} - */ - async subscribe(networkInterface?: string) { - const listenIp = ipAddress(networkInterface); - if (!listenIp) - throw new Error( - `Unable to obtain the local IP address ${ - networkInterface - ? ` for the network interface '${networkInterface}'` - : "" - }`, - ); - - // Sends a subscription message to the bulb - // It will now notify us about status changes - const result = await this.sendRaw({ - method: "registration", - id: Math.floor(10_000 * Math.random()) + 1, - version: 1, - params: { - register: true, - phoneIp: listenIp, - phoneMac: this.macIdentifier, - }, - }); - - if (!(result instanceof WikariError)) { - Bulb.client.addListener("message", msg => { - try { - const response = JSON.parse(msg.toString()); - - // if we get a syncPilot message, we send back an - // acknowledgement for it, which tells WiZ we are - // still interested in it's status updates - if (checkType(syncPilotResponseTemplate, response)) { - this.sendRaw( - { - method: "syncPilot", - id: response.id, - env: response.env, - result: { - mac: this.macIdentifier, - }, - } as SyncPilotAckMsg, - false, - ); - } - } catch {} - }); - } - - return result; - } - - /** - * Turns the bulb on or off - * - * @example - * ```ts - * // turn on the bulb - * await bulb.state(true); - * - * // turn off the bulb - * await bulb.state(false); - * ``` - * - * @param state new state of the bulb - * @returns response from the bulb on success, {@link WikariError} otherwise - */ - async turn(state: boolean) { - return await this.setPilot({ - state, - }); - } - - /** - * Turns the bulb on if it was off, and vice-versa. - * @returns response from the bulb on success, {@link WikariError} otherwise - */ - async toggle() { - const pilot = await this.getPilot(); - if (pilot instanceof WikariError) return pilot; - - return this.setPilot({ state: !pilot.result.state }); - } - - /** - * Allows you to change the scene. If you're not familiar with the - * numerical scene IDs of the bulb, you can use the {@link SCENES} - * object to determine it. - * - * ```ts - * bulb.setScene(SCENES["Christmas"], { speed: 30, dimming: 25 }) - * ``` - * - * Note that the second argument is strongly typed, and will not let - * you set speed or dimming on scenes that do not support them. - * - * @param sceneId scene ID from 1 to 32 (both inclusive) - * @param args arguments associated with @param sceneId - * @returns response from the bulb on success, {@link WikariError} otherwise - */ - async scene(sceneId: T, args: GetSceneArgs = {}) { - if (sceneId < 1 || sceneId > 32) - return new WikariError( - WikariErrorCode.ArgumentOutOfRange, - { - argument: "sceneId", - lowerLimit: 1, - higherLimit: 32, - provided: sceneId, - }, - "Scene ID must be in the range 1 <> 32", - ); - - for (const [key, value] of Object.entries(args)) { - if (key == "speed" || key == "dimming") { - const v = value as number; - if (v < 1 || v > 100) - return new WikariError( - WikariErrorCode.ArgumentOutOfRange, - { - argument: key, - lowerLimit: 1, - higherLimit: 100, - provided: v, - }, - `Optional argument ${key} must be in the range 1 <> 100`, - ); - } - } - - return await this.setPilot({ - sceneId, - ...args, - }); - } - - async brightness(brightness: number) { - if (brightness < 0 || brightness > 100) - return new WikariError( - WikariErrorCode.ArgumentOutOfRange, - { - argument: "brightness", - lowerLimit: 0, - higherLimit: 100, - provided: brightness, - }, - "Brightness must be in the range 0-100", - ); - - return await this.setPilot({ dimming: brightness }); - } - - /** - * Changes the color to a certain temperature of white. - * ```ts - * bulb.white(5000); - * ``` - * @param temp temperature, range 1000 to 10_000 (both inclusive) - * @returns response from the bulb on success, {@link WikariError} otherwise - */ - async white(temp: number): Promise { - if (temp < 1000 || temp > 10_000) - throw new WikariError( - WikariErrorCode.ArgumentOutOfRange, - { - argument: "temp", - lowerLimit: 1000, - higherLimit: 10_000, - provided: temp, - }, - "Temperature must be in the range 1000 <> 10_000", - ); - - return await this.setPilot({ - temp, - }); - } - - /** - * Sets the bulb to a certain color. - * - * ```ts - * // set the bulb to red color - * await bulb.color("#f44336"); - * - * // set the bulb to some red and some warm white - * await bulb.color({ r: 100, w: 50 }); - * ``` - * - * Here, c is the cool white component and w is the warm white - * component. - * - * When passing an object, each value must be in the range 0-255 - * (both inclusive). - * - * @param color a hex color code, or an rgbcw object - * @returns response from the bulb on success, {@link WikariError} otherwise - */ - async color( - color: - | { r?: number; g?: number; b?: number; c?: number; w?: number } - | `#${string}`, - ): Promise { - if (typeof color == "string") { - const rgbColor = hexToRgb(color); - if (rgbColor instanceof Error) throw rgbColor; - - return await this.setPilot(rgbColor); - } else { - for (const [key, value] of Object.entries(color)) { - if (value < 0 || value > 255) { - throw new WikariError( - WikariErrorCode.ArgumentOutOfRange, - { - argument: key, - lowerLimit: 0, - higherLimit: 255, - provided: value, - }, - `'${key}' must be in the range 0 <> 255`, - ); - } - } - - return await this.setPilot(color); - } - } - - // ###################################### - // Lower-level interaction functions - // ###################################### - private isReadyToSend( - waitForResponse: boolean, - ): WikariError | undefined { - const getError = (msg: string) => { - return new WikariError( - WikariErrorCode.InvalidBulbState, - { - state: Bulb.state, - expectedState: [WikariState.READY], - }, - msg, - ); - }; - - if (Bulb.state != WikariState.READY) { - if (Bulb.state == WikariState.BINDING) - return getError("Still waiting for port binding to finish"); - - if (Bulb.state == WikariState.CLOSED) - return getError("This bulb instance has been closed"); - - if (Bulb.state == WikariState.AWAITING_RESPONSE && waitForResponse) - return getError("Already waiting on a response"); - } - } - - private sendWithWait(message: Message): Promise { - Bulb.setInstanceState(WikariState.AWAITING_RESPONSE); - - return new Promise((resolve, reject) => { - let timer: ReturnType; - - const messageListener = (msg: Buffer, rinfo: dgram.RemoteInfo) => { - // if the message is not from the bulb IP, ignore it - if (rinfo.address != this.address) return; - - try { - const response = JSON.parse(msg.toString()); - - if ("method" in response) { - // not the response to the request we sent - if (response["method"] != message["method"]) return; - } - - if (timer) clearTimeout(timer); - Bulb.client.off("message", messageListener); - - if ("error" in response) { - reject( - new WikariError( - WikariErrorCode.BulbReturnedFailure, - { response }, - "Bulb returned failure", - ), - ); - } else resolve(response); - - Bulb.setInstanceState(WikariState.READY); - } catch (error) { - reject( - new WikariError( - WikariErrorCode.ResponseParseFailed, - { response: msg.toString(), error: error as Error }, - "Failed to parse response JSON", - ), - ); - } - }; - Bulb.client.on("message", messageListener); - - Bulb.client.send( - JSON.stringify(message), - this.bulbPort, - this.address, - error => { - if (error) { - if (timer) clearTimeout(timer); - Bulb.setInstanceState(WikariState.READY); - reject( - new WikariError( - WikariErrorCode.RequestSendError, - { error }, - "Failed to send request to bulb", - ), - ); - } - }, - ); - - // if the request takes longer than the timeout wait, - // we can assume the packet has been lost - const getResponseTimeout = () => - this.responseTimeout ?? DEFAULT_RESPONSE_WAIT_MS; - - timer = setTimeout(() => { - Bulb.client.off("message", messageListener); - reject( - new WikariError( - WikariErrorCode.RequestTimedOut, - { - responseWaitMs: getResponseTimeout(), - }, - "Timed out", - ), - ); - }, getResponseTimeout()); - }); - } - - private sendWithoutWaiting(message: Message): Promise { - // if we're not waiting for a response, we can just wait to see - // if there's no errors in the error callback - return new Promise((resolve, reject) => { - Bulb.client.send( - JSON.stringify(message), - this.bulbPort, - this.address, - error => { - if (error) - reject( - new WikariError( - WikariErrorCode.RequestSendError, - { error }, - "Failed to send request to bulb", - ), - ); - else resolve(message as GenericResponse); - }, - ); - }); - } - - /** - * If you want more control over the sent messages, you can - * use this function. All the higher-level bulb control - * functions (like {@link Bulb.toggle} or {@link Bulb.color}) - * internally use this function. - * - * @param message the message to send to the bulb - * @param waitForResponse whether to wait for a response - * @returns if waitForResponse is true, the response from the - * bulb, otherwise the message to be sent itself - */ - async sendRaw( - message: Message, - waitForResponse = true, - ): Promise { - const error = this.isReadyToSend(waitForResponse); - if (error) throw error; - - if (waitForResponse) { - return this.sendWithWait(message); - } else { - return this.sendWithoutWaiting(message); - } - } - - /** - * Fetches the current pilot/state from the bulb. - * @returns the bulb pilot response - */ - async getPilot(): Promise { - const pilot = await this.sendRaw({ method: "getPilot", params: {} }); - - if (checkType(getPilotResponseTemplate, pilot)) return pilot; - else - throw new WikariError( - WikariErrorCode.ResponseValidationFailed, - { response: pilot }, - "Response validation failed", - ); - } - - /** - * Sets the bulb pilot/state. - * - * This is a low level function to be used if you want more - * control. You should usually find the higher-level - * functions (such as {@link Bulb.color}) enough. - * - * @returns the bulb pilot response - */ - async setPilot(pilot: Pilot): Promise { - const response = await this.sendRaw({ method: "setPilot", params: pilot }); - - if (checkType(setPilotResponseTemplate, response)) return response; - else - throw new WikariError( - WikariErrorCode.ResponseValidationFailed, - { response }, - "Response validation failed", - ); - } - - // ################################## - // UDP Client related functions - // ################################## - private async initClient(): Promise { - Bulb.setInstanceState(WikariState.BINDING); - return new Promise((resolve, reject) => { - const listeningCallback = () => { - Bulb.setInstanceState(WikariState.READY); - resolve(); - }; - Bulb.client.on("listening", listeningCallback); - - const errorCallback = (error: Error) => { - Bulb.client.off("listening", listeningCallback); - reject( - new WikariError( - WikariErrorCode.SocketBindFailed, - { error }, - `Failed to bind to port ${this.listenPort}`, - ), - ); - }; - Bulb.client.on("error", errorCallback); - - Bulb.client.bind(this.listenPort, undefined, () => { - Bulb.client.off("listening", listeningCallback); - Bulb.client.off("error", errorCallback); - }); - }); - } - - closeConnection() { - if (Bulb.state == WikariState.CLOSED) return; - Bulb.setInstanceState(WikariState.CLOSED); - Bulb.stateEmitter.removeAllListeners(); - Bulb.client.removeAllListeners(); - Bulb.client.close(); - } -} diff --git a/wikari/src/constants.ts b/wikari/src/constants.ts deleted file mode 100644 index 1991e3e..0000000 --- a/wikari/src/constants.ts +++ /dev/null @@ -1,56 +0,0 @@ -// times -export const DEFAULT_DISCOVER_WAIT_MS = 1000; -export const DEFAULT_RESPONSE_WAIT_MS = 2000; - -// ports -export const WIZ_BULB_LISTEN_PORT = 38899; -export const UDP_BROADCAST_LISTEN_PORT = 38900; - -// miscellaneous -export const HEX_COLOR_REGEX = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i; -export const POSSIBLE_MAC_CHARACTERS = "0123456789abcdef"; - -// scene info -export const SCENES = { - "Ocean": 1, - "Romance": 2, - "Sunset": 3, - "Party": 4, - "Fireplace": 5, - "Cozy": 6, - "Forest": 7, - "Pastel Colors": 8, - "Wake Up": 9, - "Bedtime": 10, - "Warm White": 11, - "Daylight": 12, - "Cool White": 13, - "Night Light": 14, - "Focus": 15, - "Relax": 16, - "True Colors": 17, - "TV Time": 18, - "Plant Growth": 19, - "Spring": 20, - "Summer": 21, - "Fall": 22, - "Deep Dive": 23, - "Jungle": 24, - "Mojito": 25, - "Club": 26, - "Christmas": 27, - "Halloween": 28, - "Candlelight": 29, - "Golden White": 30, - "Pulse": 31, - "Steampunk": 32, -} as const; - -export const ADJUSTABLE_SPEED_SCENES = [ - 1, 2, 3, 4, 5, 6, 7, 8, 20, 21, 22, 23, 24, 25, 26, 27, 27, 29, 30, 31, 32, -] as const; - -export const ADJUSTABLE_DIMMING_SCENES = [ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 27, 29, 30, 31, 32, -] as const; diff --git a/wikari/src/discover.ts b/wikari/src/discover.ts deleted file mode 100644 index 46f4953..0000000 --- a/wikari/src/discover.ts +++ /dev/null @@ -1,58 +0,0 @@ -import dgram from "dgram"; -import { Bulb } from "./bulb"; -import { DEFAULT_DISCOVER_WAIT_MS, WIZ_BULB_LISTEN_PORT } from "./constants"; -import { checkType } from "./type-checker"; -import { GetPilotMsg, getPilotResponseTemplate } from "./types"; -import { sleep } from "./utils"; - -/** - * Discovers bulbs on a network. - * This is done by sending a request and creating bulb instances from the devices - * that respond. - * - * The first argument contains options for discovery, them being: - * * addr: the address to send the request on (ideally a broadcast address) - * * port: the port that the bulbs listen on - * * waitMs: how long to wait for a response from the bulb - * - * If your local IP addresses do not start with 192.168.1, you'll need to - * pass a custom addr. - * - * @returns an array of {@link Bulb} instances corresponding to discovered bulbs - */ -export async function discover({ - addr = "192.168.1.255", - port = WIZ_BULB_LISTEN_PORT, - waitMs = DEFAULT_DISCOVER_WAIT_MS, -}): Promise { - const client = dgram.createSocket("udp4"); - const bulbs: Bulb[] = []; - const message: GetPilotMsg = { - method: "getPilot", - params: {}, - }; - - if (addr.split(".").includes("255")) { - client.once("listening", function () { - client.setBroadcast(true); - }); - } - - client.send(JSON.stringify(message), port, addr); - - const listener = (msg: Buffer, rinfo: dgram.RemoteInfo) => { - const response = JSON.parse(msg.toString()); - - if (checkType(getPilotResponseTemplate, response)) { - bulbs.push(new Bulb(rinfo.address, { port })); - } - }; - - client.on("message", listener); - await sleep(waitMs); - client.off("message", listener); - - client.close(); - - return bulbs; -} diff --git a/wikari/src/mod.ts b/wikari/src/mod.ts deleted file mode 100644 index cc85687..0000000 --- a/wikari/src/mod.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from "./bulb"; -export * from "./discover"; -export * from "./constants"; -export * from "./types"; -export * from "./wikari-error"; diff --git a/wikari/src/type-checker.ts b/wikari/src/type-checker.ts deleted file mode 100644 index 0edc1bc..0000000 --- a/wikari/src/type-checker.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { Expand } from "./utils"; - -// not the best way to do this, -// but it saves me a dependency... - -type valueType = "string" | "number" | "boolean"; -type valueTypeMap = { - string: string; - number: number; - boolean: boolean; -}; - -/** - * A TypeTemplate is an object denoting the structure of another object - * It can then be used to verify the structure of the said object - * A template has values as a tuple containing the expected type of - * the key and whether it's required. - * - * @example - * An example of a template object is: - * ```ts - * { - * name: ["string", true], - * creditCardInfo: ["string", false] - * } - * ``` - * - * Here, in the target object, `name` must be a string and must be present - * Whereas `creditCardInfo` does not have to be a string, but if it is, it - * must be a string. The template can also be recursive. These templates - * can then be used with the function {@link checkType}. - */ -type TypeTemplate = { - [k: string]: [valueType, boolean] | TypeTemplate; -}; - -/** - * creates a {@link TypeTemplate}. - * returns the argument it receives as-is. - * only for some type haggling. - */ -export const makeTypeTemplate = (v: T) => v; - -type GetKey< - T extends TypeTemplate, - K extends keyof T, - IsRequired extends boolean, -> = T extends TypeTemplate - ? T[K][0] extends valueType - ? T[K][1] extends IsRequired - ? K - : never - : never - : never; - -type RequiredProperties = { - [K in keyof T as GetKey]: T[K] extends TypeTemplate - ? Expand> - : T[K][0] extends valueType - ? valueTypeMap[T[K][0]] - : never; -}; - -type OptionalProperties = { - [K in keyof T as GetKey]?: T[K] extends TypeTemplate - ? Expand> - : T[K][0] extends valueType - ? valueTypeMap[T[K][0]] - : never; -}; - -type NestedProperties = { - [K in keyof T as T[K] extends TypeTemplate - ? K - : never]: T[K] extends TypeTemplate ? FromTypeTemplate : never; -}; - -export type FromTypeTemplate = Expand< - RequiredProperties & OptionalProperties & NestedProperties ->; - -export function checkType( - template: T, - obj: any, -): obj is FromTypeTemplate { - if (typeof obj != "object" || obj == null) return false; - - for (const [key, value] of Object.entries(template)) { - if (Array.isArray(value)) { - const ogType = typeof obj[key]; - const [type, required] = value as [valueType, boolean]; - if (ogType != type) - if (!(ogType == "undefined" && !required)) return false; - } else { - if (!checkType(value as TypeTemplate, obj[key])) return false; - } - } - - return true; -} diff --git a/wikari/src/types.ts b/wikari/src/types.ts deleted file mode 100644 index 36e88f0..0000000 --- a/wikari/src/types.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { - ADJUSTABLE_DIMMING_SCENES, - ADJUSTABLE_SPEED_SCENES, -} from "./constants"; -import { FromTypeTemplate, makeTypeTemplate } from "./type-checker"; - -export const pilotTemplate = makeTypeTemplate({ - // range 1-32 - sceneId: ["number", false], - // range 1-100, is a percentage - speed: ["number", false], - // range 1-100, is a percentage - dimming: ["number", false], - // range 1000-10_000, kelvin - temp: ["number", false], - // range 0-255 - r: ["number", false], - // range 0-255 - g: ["number", false], - // range 0-255 - b: ["number", false], - // range 0-255 - c: ["number", false], - // range 0-255 - w: ["number", false], - // whether the bulb is on or off - state: ["boolean", false], -}); -export type Pilot = FromTypeTemplate; - -type IfExtends = P extends Q ? R : {}; -export type GetSceneArgs = IfExtends< - Scene, - (typeof ADJUSTABLE_SPEED_SCENES)[number], - { speed?: number } -> & - IfExtends< - Scene, - (typeof ADJUSTABLE_DIMMING_SCENES)[number], - { dimming?: number } - >; - -// ############# -// Responses -// ############# -export type GenericResponse = { method: string; params: Record }; - -// getPilot -export const getPilotResponseTemplate = makeTypeTemplate({ - method: ["string", true], - env: ["string", true], - result: { - mac: ["string", true], - rssi: ["number", true], - src: ["string", false], - state: ["boolean", true], - sceneId: ["number", true], - // optional properties - temp: ["number", false], - speed: ["number", false], - r: ["number", false], - g: ["number", false], - b: ["number", false], - c: ["number", false], - w: ["number", false], - dimming: ["number", false], - }, -}); - -export type GetPilotResponse = FromTypeTemplate< - typeof getPilotResponseTemplate ->; - -// setPilot -export const setPilotResponseTemplate = makeTypeTemplate({ - method: ["string", true], - env: ["string", true], - result: { - success: ["boolean", true], - }, -}); - -export type SetPilotType = FromTypeTemplate; - -// syncPilot -export const syncPilotResponseTemplate = makeTypeTemplate({ - method: ["string", true], - env: ["string", true], - id: ["number", false], - params: { - mac: ["string", true], - rssi: ["number", true], - src: ["string", false], - mqttCd: ["number", false], - ts: ["number", false], - ...pilotTemplate, - }, -}); - -export type SyncPilotResponse = FromTypeTemplate< - typeof syncPilotResponseTemplate ->; - -// ########################## -// Messages Sent To Bulb -// ########################## -export interface GenericMsg { - method: string; - params: Record; -} - -export interface SetPilotMsg extends GenericMsg { - method: "setPilot"; - params: Pilot; -} - -export interface GetPilotMsg extends GenericMsg { - method: "getPilot"; - params: {}; -} - -export type SyncPilotMsg = SyncPilotResponse; - -export interface SyncPilotAckMsg { - method: "syncPilot"; - id?: number; - env: string; - result: { - mac: string; - }; -} - -export interface RegistrationMsg extends GenericMsg { - method: "registration"; - id: number; - version: number; - params: { - register: boolean; - phoneIp: string; - phoneMac: string; - }; -} - -export type Message = - | SetPilotMsg - | GetPilotMsg - | SyncPilotMsg - | SyncPilotAckMsg - | RegistrationMsg - | GenericMsg; diff --git a/wikari/src/utils.ts b/wikari/src/utils.ts deleted file mode 100644 index ab5619d..0000000 --- a/wikari/src/utils.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { HEX_COLOR_REGEX, POSSIBLE_MAC_CHARACTERS } from "./constants"; -import os from "os"; - -export const sleep = (ms: number) => - new Promise(resolve => setTimeout(resolve, ms)); - -export const getRandomMac = () => - [...Array(12).keys()] - .map(() => - POSSIBLE_MAC_CHARACTERS.charAt( - Math.floor(Math.random() * POSSIBLE_MAC_CHARACTERS.length), - ), - ) - .join(""); - -export const hexToRgb = (hex: `#${string}`) => { - const result = HEX_COLOR_REGEX.exec(hex); - - return result - ? { - r: parseInt(result[1], 16), - g: parseInt(result[2], 16), - b: parseInt(result[3], 16), - } - : new Error("Invalid hex"); -}; - -export const ipAddress = (networkInterface?: string) => { - const nets = os.networkInterfaces(); - - for (const name of Object.keys(nets)) { - for (const net of nets[name] ?? []) { - // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses - // on node <= v17, 'net.family' is "IPv4" - // since node v18, it's the number 4 or 6 - const ipv4 = typeof net.family === "string" ? "IPv4" : 4; - if (net.family === ipv4 && !net.internal) { - if (networkInterface) { - if (name == networkInterface) return net.address; - } else return net.address; - } - } - } - - return undefined; -}; - -export type Expand = T extends infer O ? { [K in keyof O]: O[K] } : never; diff --git a/wikari/src/wikari-error.ts b/wikari/src/wikari-error.ts deleted file mode 100644 index 7103977..0000000 --- a/wikari/src/wikari-error.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { WikariState } from "./bulb"; - -export const enum WikariErrorCode { - ArgumentOutOfRange, - SocketBindFailed, - InvalidBulbState, - ResponseValidationFailed, - ResponseParseFailed, - RequestSendError, - RequestTimedOut, - BulbReturnedFailure, -} - -export type WErrorArgMap = { - [WikariErrorCode.ArgumentOutOfRange]: { - argument: string; - lowerLimit: number; - higherLimit: number; - provided: number; - }; - - [WikariErrorCode.SocketBindFailed]: { - error: Error; - }; - - [WikariErrorCode.InvalidBulbState]: { - state: WikariState; - expectedState: WikariState[]; - }; - - [WikariErrorCode.ResponseValidationFailed]: { - response: Record; - }; - - [WikariErrorCode.ResponseParseFailed]: { - response: string; - error: Error; - }; - - [WikariErrorCode.RequestSendError]: { - error: Error; - }; - - [WikariErrorCode.RequestTimedOut]: { - responseWaitMs: number; - }; - - [WikariErrorCode.BulbReturnedFailure]: { - response: Record; - }; -}; - -type WikariErrorData = WErrorArgMap[WikariErrorCode]; - -export class WikariError< - T extends WikariErrorCode = WikariErrorCode, -> extends Error { - code: WikariErrorCode; - data: WikariErrorData; - - constructor(code: T, data: WErrorArgMap[T], message: string) { - super(message); - this.code = code; - this.data = data; - } -} diff --git a/wikari/tsconfig.json b/wikari/tsconfig.json deleted file mode 100644 index 5da2bd2..0000000 --- a/wikari/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "outDir": "../lib", - "target": "es2020", - "module": "commonjs", - "strict": true, - "sourceMap": true, - "declaration": true, - "noErrorTruncation": true, - "esModuleInterop": true, - "moduleResolution": "node" - }, - "include": ["src/*", "src/**/*.ts"], - "exclude": ["node_modules", "lib"] -}