├── .gitignore ├── Dockerfile.template ├── LICENSE ├── README.md └── app ├── .bowerrc ├── bower.json ├── index.js ├── libs ├── gui │ ├── ledStrip.js │ └── none.js ├── imageDownloader │ └── imageDownloader.js ├── scanner.js ├── supervisorClient │ └── supervisorClient.js └── writer.js ├── package.json ├── src ├── app.coffee ├── config.coffee ├── connman.coffee ├── dbus-promise.coffee ├── dnsmasq.coffee ├── hostapd.coffee ├── hotspot.coffee ├── public │ ├── img │ │ ├── favicon.png │ │ └── logo.svg │ ├── index.html │ └── js │ │ └── index.js ├── systemd.coffee ├── utils.coffee └── wifi-scan.coffee └── start.sh /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/node,python,osx,linux,windows,node,bower 3 | 4 | ### Node ### 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | 10 | # Runtime data 11 | pids 12 | *.pid 13 | *.seed 14 | *.pid.lock 15 | 16 | # Directory for instrumented libs generated by jscoverage/JSCover 17 | lib-cov 18 | 19 | # Coverage directory used by tools like istanbul 20 | coverage 21 | 22 | # nyc test coverage 23 | .nyc_output 24 | 25 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 26 | .grunt 27 | 28 | # node-waf configuration 29 | .lock-wscript 30 | 31 | # Compiled binary addons (http://nodejs.org/api/addons.html) 32 | build/Release 33 | 34 | # Dependency directories 35 | node_modules 36 | jspm_packages 37 | 38 | # Optional npm cache directory 39 | .npm 40 | 41 | # Optional eslint cache 42 | .eslintcache 43 | 44 | # Optional REPL history 45 | .node_repl_history 46 | 47 | # Output of 'npm pack' 48 | *.tgz 49 | 50 | # Yarn Integrity file 51 | .yarn-integrity 52 | 53 | 54 | 55 | ### Python ### 56 | # Byte-compiled / optimized / DLL files 57 | __pycache__/ 58 | *.py[cod] 59 | *$py.class 60 | 61 | # C extensions 62 | *.so 63 | 64 | # Distribution / packaging 65 | .Python 66 | env/ 67 | build/ 68 | develop-eggs/ 69 | dist/ 70 | downloads/ 71 | eggs/ 72 | .eggs/ 73 | lib/ 74 | lib64/ 75 | parts/ 76 | sdist/ 77 | var/ 78 | *.egg-info/ 79 | .installed.cfg 80 | *.egg 81 | 82 | # PyInstaller 83 | # Usually these files are written by a python script from a template 84 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 85 | *.manifest 86 | *.spec 87 | 88 | # Installer logs 89 | pip-log.txt 90 | pip-delete-this-directory.txt 91 | 92 | # Unit test / coverage reports 93 | htmlcov/ 94 | .tox/ 95 | .coverage 96 | .coverage.* 97 | .cache 98 | nosetests.xml 99 | coverage.xml 100 | *,cover 101 | .hypothesis/ 102 | 103 | # Translations 104 | *.mo 105 | *.pot 106 | 107 | # Django stuff: 108 | local_settings.py 109 | 110 | # Flask stuff: 111 | instance/ 112 | .webassets-cache 113 | 114 | # Scrapy stuff: 115 | .scrapy 116 | 117 | # Sphinx documentation 118 | docs/_build/ 119 | 120 | # PyBuilder 121 | target/ 122 | 123 | # Jupyter Notebook 124 | .ipynb_checkpoints 125 | 126 | # pyenv 127 | .python-version 128 | 129 | # celery beat schedule file 130 | celerybeat-schedule 131 | 132 | # dotenv 133 | .env 134 | 135 | # virtualenv 136 | .venv/ 137 | venv/ 138 | ENV/ 139 | 140 | # Spyder project settings 141 | .spyderproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | 147 | ### OSX ### 148 | *.DS_Store 149 | .AppleDouble 150 | .LSOverride 151 | 152 | # Icon must end with two \r 153 | Icon 154 | # Thumbnails 155 | ._* 156 | # Files that might appear in the root of a volume 157 | .DocumentRevisions-V100 158 | .fseventsd 159 | .Spotlight-V100 160 | .TemporaryItems 161 | .Trashes 162 | .VolumeIcon.icns 163 | .com.apple.timemachine.donotpresent 164 | # Directories potentially created on remote AFP share 165 | .AppleDB 166 | .AppleDesktop 167 | Network Trash Folder 168 | Temporary Items 169 | .apdisk 170 | 171 | 172 | ### Linux ### 173 | *~ 174 | 175 | # temporary files which can be created if a process still has a handle open of a deleted file 176 | .fuse_hidden* 177 | 178 | # KDE directory preferences 179 | .directory 180 | 181 | # Linux trash folder which might appear on any partition or disk 182 | .Trash-* 183 | 184 | # .nfs files are created when an open file is removed but is still being accessed 185 | .nfs* 186 | 187 | 188 | ### Windows ### 189 | # Windows image file caches 190 | Thumbs.db 191 | ehthumbs.db 192 | 193 | # Folder config file 194 | Desktop.ini 195 | 196 | # Recycle Bin used on file shares 197 | $RECYCLE.BIN/ 198 | 199 | # Windows Installer files 200 | *.cab 201 | *.msi 202 | *.msm 203 | *.msp 204 | 205 | # Windows shortcuts 206 | *.lnk 207 | 208 | 209 | ### Node ### 210 | # Logs 211 | 212 | # Runtime data 213 | 214 | # Directory for instrumented libs generated by jscoverage/JSCover 215 | 216 | # Coverage directory used by tools like istanbul 217 | 218 | # nyc test coverage 219 | 220 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 221 | 222 | # node-waf configuration 223 | 224 | # Compiled binary addons (http://nodejs.org/api/addons.html) 225 | 226 | # Dependency directories 227 | 228 | # Optional npm cache directory 229 | 230 | # Optional eslint cache 231 | 232 | # Optional REPL history 233 | 234 | # Output of 'npm pack' 235 | 236 | # Yarn Integrity file 237 | 238 | 239 | 240 | ### Bower ### 241 | bower_components 242 | .bower-cache 243 | .bower-registry 244 | .bower-tmp 245 | -------------------------------------------------------------------------------- /Dockerfile.template: -------------------------------------------------------------------------------- 1 | FROM resin/%%RESIN_MACHINE_NAME%%-node:slim 2 | 3 | # Install apt deps 4 | RUN apt-get update && apt-get install -y \ 5 | build-essential \ 6 | git \ 7 | wget \ 8 | python-dev \ 9 | i2c-tools \ 10 | dnsmasq \ 11 | hostapd \ 12 | iproute2 \ 13 | iw \ 14 | libdbus-1-dev \ 15 | libexpat-dev \ 16 | rfkill && rm -rf /var/lib/apt/lists/* 17 | 18 | # Save source folder 19 | RUN printf "%s\n" "${PWD##}" > SOURCEFOLDER 20 | 21 | RUN mkdir -p /usr/src/app/ 22 | 23 | # Move to /usr/src/app 24 | WORKDIR /usr/src/app 25 | 26 | # Move package to filesystem 27 | COPY "$SOURCEFOLDER/app/package.json" ./ 28 | 29 | # Install NodeJS dependencies via NPM 30 | RUN JOBS=MAX npm i --unsafe-perm --production && npm cache clean 31 | 32 | # Move bower.json to filesystem 33 | COPY "$SOURCEFOLDER/app/bower.json $SOURCEFOLDER/app/.bowerrc" /usr/src/app/ 34 | 35 | # Install 36 | RUN ./node_modules/.bin/bower --allow-root install \ 37 | && ./node_modules/.bin/bower --allow-root cache clean 38 | 39 | # Move app to filesystem 40 | COPY "$SOURCEFOLDER/app" ./ 41 | 42 | # Compile coffee 43 | RUN ./node_modules/.bin/coffee -c ./src 44 | 45 | # Start app 46 | CMD ["bash", "/usr/src/app/start.sh"] 47 | 48 | ## uncomment if you want systemd 49 | ENV INITSYSTEM on 50 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # etcher-headless 2 | [WIP] [etcher](https://etcher.io) based automatic drive flashing device 3 | 4 | this project was hacked in a beautiful night during the resin.io 2016 session - it still is a hack, aiming to be a proof-of-concept for automated multi-flashing device. 5 | 6 | **It will likely change slightly and break until it reaches a more stable condition** 7 | 8 | ![etcher-headless](https://pbs.twimg.com/media/Cw-PB1kW8AAEFhP.jpg:large) 9 | 10 | ## Getting started 11 | 12 | - Sign up on [resin.io](https://dashboard.resin.io/signup) 13 | - go throught the [getting started guide](http://docs.resin.io/raspberrypi/nodejs/getting-started/) and create a new Raspberry Pi 1+/2/3 model B application called `etcherHeadless` 14 | - clone this repository to your local workspace 15 | - set these variables in the `Fleet Configuration` application side tab if you want to use a raspberry Pi 16 | 17 | - `RESIN_HOST_CONFIG_max_usb_current` = `1` 18 | 19 | 20 | - add the _resin remote_ to your local workspace using the useful shortcut in the dashboard UI ![remoteadd](https://raw.githubusercontent.com/resin-io-projects/boombeastic/master/docs/gitresinremote.png) 21 | 22 | - `git push resin master` 23 | - see the magic happening, your device is getting updated Over-The-Air! 24 | 25 | ## Configure via [environment variables](https://docs.resin.io/management/env-vars/) 26 | Variable Name | Default | Description 27 | ------------ | ------------- | ------------- 28 | ETCHER_IMAGE_URL | `NaN` | The URL from which etcher downloads the image to be flashed 29 | PORTAL_SSID | `ResinAP` | the SSID name of the Access Point the device spawns for WiFi configuration 30 | GUI_TYPE | `none` | the Feedback device to be used (for now, you can pick the [Pimoroni blinkt LED strip](https://shop.pimoroni.com/products/blinkt) setting `ledStrip`) 31 | DEBUG | `none` | comma separated modules list that activate verbose logging on the device dashboard (`main`) 32 | 33 | ## How it works 34 | The device downloads the image set via `ETCHER_IMAGE_URL` and then checks for new media attached - every time a new one is found, it flashes the downloaded image on it. Works in parallel so you can attach and flash multiple media at the same time. 35 | 36 | ## License 37 | 38 | Copyright 2016 Resinio Ltd. 39 | 40 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 41 | 42 | 43 | 44 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 45 | -------------------------------------------------------------------------------- /app/.bowerrc: -------------------------------------------------------------------------------- 1 | { 2 | "directory": "src/public/bower_components", 3 | "storage": { 4 | "packages": ".bower-cache", 5 | "registry": ".bower-registry" 6 | }, 7 | "tmp": ".bower-tmp" 8 | } 9 | -------------------------------------------------------------------------------- /app/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "resin-wifi-connect", 3 | "version": "0.0.0", 4 | "homepage": "https://github.com/pcarranzav/resin-wifi-connect", 5 | "authors": [ 6 | "Pablo Carranza Vélez " 7 | ], 8 | "license": "MIT", 9 | "ignore": [ 10 | "**/.*", 11 | "node_modules", 12 | "bower_components", 13 | "src/public/bower_components", 14 | "test", 15 | "tests" 16 | ], 17 | "dependencies": { 18 | "bootstrap": "~3.3.5" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/index.js: -------------------------------------------------------------------------------- 1 | #!/bin/env node 2 | 3 | { 4 | const supervisorClient = require(__dirname + '/libs/supervisorClient/supervisorClient.js'); 5 | const imageDownloader = require(__dirname + '/libs/imageDownloader/imageDownloader.js'); 6 | const guiType = (process.env.GUI_TYPE == null) ? "none" : process.env.GUI_TYPE; 7 | const gui = require(__dirname + '/libs/gui/' + guiType + '.js'); 8 | const chalk = require('chalk'); 9 | const Writer = require(__dirname + '/libs/writer.js'); 10 | const debug = require('debug')('main'); 11 | 12 | gui.ready(); 13 | imageDownloader.download(process.env.ETCHER_IMAGE_URL); 14 | 15 | imageDownloader.on('start', () => { 16 | "use strict"; 17 | gui.downloadStart(); 18 | }); 19 | 20 | imageDownloader.on('error', () => { 21 | "use strict"; 22 | gui.downloadError(); 23 | }); 24 | 25 | imageDownloader.on('complete', () => { 26 | "use strict"; 27 | gui.downloadComplete(); 28 | const writer = Writer.start('/data/resin.img'); 29 | writer.on('progress', (data) => { 30 | debug(data); 31 | progress(data); 32 | }); 33 | 34 | writer.on('done', (data) => { 35 | debug(data); 36 | complete(data); 37 | }); 38 | 39 | writer.on('error', (error) => { 40 | console.error('Error!'); 41 | console.error(error); 42 | }); 43 | }); 44 | 45 | let progress = function(data) { 46 | "use strict"; 47 | if (isWriting(data.state.type)) { 48 | gui.write(identifyDevice(data.device),data.state.percentage); 49 | } else { 50 | gui.verify(identifyDevice(data.device),data.state.percentage); 51 | } 52 | }; 53 | 54 | let complete = function(data) { 55 | "use strict"; 56 | gui.done(identifyDevice(data.device)); 57 | }; 58 | 59 | let identifyDevice = function(data) { 60 | "use strict"; 61 | switch (data) { 62 | case "/dev/sda": 63 | return 4; 64 | case "/dev/sdb": 65 | return 3; 66 | case "/dev/sdc": 67 | return 2; 68 | case "/dev/sdd": 69 | return 1; 70 | default: 71 | return 5; 72 | 73 | } 74 | }; 75 | 76 | let isWriting = function(data) { 77 | "use strict"; 78 | if (data === "write") { 79 | return true; 80 | } else { 81 | return false; 82 | } 83 | }; 84 | 85 | } 86 | -------------------------------------------------------------------------------- /app/libs/gui/ledStrip.js: -------------------------------------------------------------------------------- 1 | #!/bin/env node 2 | 3 | { 4 | const fs = require("fs"); 5 | const Blinkt = require('node-blinkt'); 6 | const leds = new Blinkt(); 7 | 8 | let ledStrip = function() { 9 | "use strict"; 10 | if (!(this instanceof ledStrip)) return new ledStrip(); 11 | this.initialized = false; 12 | this.colors = {}; 13 | }; 14 | 15 | ledStrip.prototype.ready = function() { 16 | "use strict"; 17 | let self = this; 18 | leds.setup(); 19 | leds.clearAll(); 20 | for (let i = 0; i < 8; i++) { 21 | leds.setPixel(i, 0, 0, 0, 0); 22 | leds.sendUpdate(); 23 | } 24 | self.initialized = true; 25 | }; 26 | 27 | ledStrip.prototype.write = function(i,p) { 28 | "use strict"; 29 | let self = this; 30 | leds.setPixel(i, 109, 9, 9, 0.3); 31 | leds.sendUpdate(); 32 | }; 33 | 34 | ledStrip.prototype.verify = function(i,p) { 35 | "use strict"; 36 | let self = this; 37 | leds.setPixel(i, 91, 192, 222, 0.3); 38 | leds.sendUpdate(); 39 | }; 40 | 41 | ledStrip.prototype.done = function(i) { 42 | "use strict"; 43 | let self = this; 44 | leds.setPixel(i, 34, 132, 11, 0.3); 45 | leds.sendUpdate(); 46 | }; 47 | 48 | ledStrip.prototype.downloadStart = function(i) { 49 | "use strict"; 50 | let self = this; 51 | leds.setPixel(7, 91, 192, 222, 0.3); 52 | leds.sendUpdate(); 53 | }; 54 | 55 | ledStrip.prototype.downloadComplete = function(i) { 56 | "use strict"; 57 | let self = this; 58 | leds.setPixel(7, 34, 132, 11, 0.3); 59 | leds.sendUpdate(); 60 | }; 61 | 62 | ledStrip.prototype.downloadError = function(i) { 63 | "use strict"; 64 | let self = this; 65 | leds.setPixel(7, 109, 9, 9, 0.3); 66 | leds.sendUpdate(); 67 | }; 68 | 69 | module.exports = ledStrip(); 70 | 71 | } 72 | -------------------------------------------------------------------------------- /app/libs/gui/none.js: -------------------------------------------------------------------------------- 1 | #!/bin/env node 2 | 3 | { 4 | 5 | let noneGui = function() { 6 | "use strict"; 7 | if (!(this instanceof noneGui)) return new noneGui(); 8 | this.initialized = false; 9 | }; 10 | 11 | noneGui.prototype.ready = function() { 12 | "use strict"; 13 | return true; 14 | }; 15 | 16 | noneGui.prototype.write = function(i,p) { 17 | "use strict"; 18 | return true; 19 | }; 20 | 21 | noneGui.prototype.verify = function(i,p) { 22 | "use strict"; 23 | return true; 24 | }; 25 | 26 | noneGui.prototype.done = function(i) { 27 | "use strict"; 28 | return true; 29 | }; 30 | 31 | noneGui.prototype.downloadStart = function(i) { 32 | "use strict"; 33 | return true; 34 | }; 35 | 36 | noneGui.prototype.downloadComplete = function(i) { 37 | "use strict"; 38 | return true; 39 | }; 40 | 41 | noneGui.prototype.downloadError = function(i) { 42 | "use strict"; 43 | return true; 44 | }; 45 | 46 | module.exports = noneGui(); 47 | 48 | } 49 | -------------------------------------------------------------------------------- /app/libs/imageDownloader/imageDownloader.js: -------------------------------------------------------------------------------- 1 | #!/bin/env node 2 | 3 | { 4 | const EventEmitter = require('events').EventEmitter; 5 | const util = require('util'); 6 | const path = require('path'); 7 | const chalk = require('chalk'); 8 | const fs = require('fs'); 9 | const request = require('request'); 10 | const debug = require('debug')('downloader'); 11 | 12 | let imageDownloader = function() { 13 | 'use strict'; 14 | if (!(this instanceof imageDownloader)) return new imageDownloader(); 15 | }; 16 | util.inherits(imageDownloader, EventEmitter); 17 | 18 | imageDownloader.prototype.download = function(url) { 19 | "use strict"; 20 | let self = this; 21 | let destPath = path.basename(url); 22 | let destFile = fs.createWriteStream('/data/' + destPath); 23 | request 24 | .get(url) 25 | .on('error', function(err) { 26 | self.emit('error',err); 27 | }) 28 | .on('response', function(response) { 29 | self.emit('start',destPath); 30 | }) 31 | .pipe(destFile); 32 | destFile.on('finish', function() { 33 | self.emit('complete',destPath); 34 | }); 35 | }; 36 | 37 | module.exports = new imageDownloader(); 38 | } 39 | -------------------------------------------------------------------------------- /app/libs/scanner.js: -------------------------------------------------------------------------------- 1 | const _ = require('lodash'); 2 | const Bluebird = require('bluebird'); 3 | const drivelist = Bluebird.promisifyAll(require('drivelist')); 4 | 5 | let CURRENT_DRIVES = []; 6 | let WHOLE_DRIVES = []; 7 | 8 | const scan = () => { 9 | "use strict"; 10 | return drivelist.listAsync().then((drives) => { 11 | WHOLE_DRIVES = _.cloneDeep(drives); 12 | return _.map(_.reject(drives, { 13 | system: true 14 | }), 'device'); 15 | }); 16 | }; 17 | 18 | exports.poll = (callback) => { 19 | "use strict"; 20 | return scan().then((drives) => { 21 | const newDrives = _.difference(drives, CURRENT_DRIVES); 22 | if (!_.isEmpty(newDrives)) { 23 | _.each(newDrives, (drive) => { 24 | callback({ 25 | device: drive, 26 | size: _.find(WHOLE_DRIVES, { 27 | device: drive 28 | }).size 29 | }); 30 | }); 31 | } 32 | CURRENT_DRIVES = drives; 33 | 34 | return new Bluebird((resolve, reject) => { 35 | setTimeout(() => { 36 | return exports.poll(callback).then(resolve).catch(reject); 37 | }, 2000); 38 | }); 39 | }); 40 | }; 41 | -------------------------------------------------------------------------------- /app/libs/supervisorClient/supervisorClient.js: -------------------------------------------------------------------------------- 1 | #!/bin/env node 2 | 3 | { 4 | const EventEmitter = require('events').EventEmitter; 5 | const util = require('util'); 6 | const chalk = require('chalk'); 7 | const request = require('request'); 8 | const debug = require('debug')('supervisor'); 9 | 10 | // declaring supervisorClient 11 | let supervisorClient = function() { 12 | 'use strict'; 13 | this.poll = null; 14 | this.status = null; 15 | if (!(this instanceof supervisorClient)) return new supervisorClient(); 16 | }; 17 | util.inherits(supervisorClient, EventEmitter); 18 | 19 | supervisorClient.prototype.start = function (interval, callback) { 20 | 'use strict'; 21 | let self = this; 22 | this.poll = setInterval(function keepalive() { 23 | request(process.env.RESIN_SUPERVISOR_ADDRESS + '/v1/device?apikey=' + process.env.RESIN_SUPERVISOR_API_KEY, function(error, response, body) { 24 | if (!error && response.statusCode == 200) { 25 | body = JSON.parse(body); 26 | debug('supervisor', body); 27 | if (body.status != self.status) { 28 | self.status = body.status; 29 | self.emit('status', body.status); 30 | } 31 | } 32 | }); 33 | }, interval); 34 | callback(); 35 | }; 36 | 37 | supervisorClient.prototype.stop = function() { 38 | 'use strict'; 39 | clearInterval(this.poll); 40 | }; 41 | 42 | module.exports = new supervisorClient(); 43 | } 44 | -------------------------------------------------------------------------------- /app/libs/writer.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events').EventEmitter; 2 | const fs = require('fs'); 3 | const imageWrite = require('etcher-image-write'); 4 | const Bluebird = require('bluebird'); 5 | const umount = Bluebird.promisifyAll(require('umount')); 6 | const scanner = require('./scanner'); 7 | 8 | exports.start = (image) => { 9 | "use strict"; 10 | const emitter = new EventEmitter(); 11 | 12 | scanner.poll((newDrive) => { 13 | console.log(`Unmounting ${newDrive.device}`); 14 | return umount.umountAsync(newDrive.device).then(() => { 15 | console.log(`Unmounted successfully ${newDrive.device}`); 16 | const writer = imageWrite.write({ 17 | fd: fs.openSync(newDrive.device, 'rs+'), 18 | device: newDrive.device, 19 | size: newDrive.size 20 | }, { 21 | stream: fs.createReadStream(image), 22 | size: fs.statSync(image).size 23 | }, { 24 | check: true 25 | }); 26 | 27 | writer.on('progress', function(state) { 28 | emitter.emit('progress', { 29 | device: newDrive.device, 30 | state: state 31 | }); 32 | }); 33 | 34 | writer.on('error', function(error) { 35 | emitter.emit('error', { 36 | device: newDrive.device, 37 | error: error 38 | }); 39 | }); 40 | 41 | writer.on('done', function(results) { 42 | console.log(`Unmounting ${newDrive.device}`); 43 | return umount.umountAsync(newDrive.device).then(() => { 44 | console.log(`Unmounted successfully ${newDrive.device}`); 45 | emitter.emit('done', { 46 | device: newDrive.device, 47 | results: results 48 | }); 49 | }).catch((error) => { 50 | console.error(`Unmounted error ${newDrive.device}`); 51 | emitter.emit('error', { 52 | device: newDrive.device, 53 | error: error 54 | }); 55 | }); 56 | }); 57 | }).catch((error) => { 58 | console.error(`Unmounted error ${newDrive.device}`); 59 | emitter.emit('error', { 60 | device: newDrive.device, 61 | error: error 62 | }); 63 | }); 64 | }).catch((error) => { 65 | emitter.emit('error', { 66 | device: newDrive.device, 67 | error: error 68 | }); 69 | }); 70 | 71 | return emitter; 72 | }; 73 | 74 | // const x = exports.start('/Users/jviotti/Downloads/Images/coreos_production_iso_image.iso'); 75 | 76 | // x.on('error', (error) => { 77 | // console.error('Error!'); 78 | // console.error(error); 79 | // }); 80 | 81 | // x.on('progress', (state) => { 82 | // console.log(state); 83 | // }); 84 | 85 | // x.on('done', (results) => { 86 | // console.log('Done!'); 87 | // console.log(results); 88 | // }); 89 | -------------------------------------------------------------------------------- /app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "etcher-headless", 3 | "version": "0.0.1", 4 | "description": "etcher-based automatic drive flashing device", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/resin-io-playground/etcher-headless.git" 12 | }, 13 | "keywords": [ 14 | "etcher", 15 | "io", 16 | "resin", 17 | "head", 18 | "less", 19 | "headless", 20 | "drive", 21 | "sd", 22 | "card", 23 | "micro", 24 | "flash", 25 | "burn", 26 | "provision", 27 | "device" 28 | ], 29 | "author": { 30 | "name": "curcuz", 31 | "email": "carlo@resin.io", 32 | "url": "https://github.com/curcuz" 33 | }, 34 | "contributors": [{ 35 | "name": "jviotti", 36 | "email": "juan@resin.io", 37 | "url": "https://github.com/jviotti" 38 | }], 39 | "license": "Apache-2.0", 40 | "bugs": { 41 | "url": "https://github.com/resin-io-playground/etcher-headless/issues" 42 | }, 43 | "homepage": "https://github.com/resin-io-playground/etcher-headless#readme", 44 | "jshintConfig": { 45 | "esnext": true, 46 | "strict": true 47 | }, 48 | "dependencies": { 49 | "bluebird": "^3.4.6", 50 | "body-parser": "^1.15.2", 51 | "bower": "^1.7.9", 52 | "chalk": "^1.1.3", 53 | "coffee-script": "~1.9.3", 54 | "dbus": "^0.2.19", 55 | "debug": "^2.3.0", 56 | "download": "^5.0.2", 57 | "drivelist": "^4.0.0", 58 | "etcher-image-write": "^8.1.4", 59 | "express": "^4.14.0", 60 | "i2c": "^0.2.3", 61 | "lodash": "^4.16.6", 62 | "node-blinkt": "^1.0.1", 63 | "request": "^2.78.0", 64 | "umount": "^1.1.5" 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /app/src/app.coffee: -------------------------------------------------------------------------------- 1 | Promise = require 'bluebird' 2 | fs = Promise.promisifyAll(require('fs')) 3 | express = require 'express' 4 | bodyParser = require 'body-parser' 5 | 6 | config = require './config' 7 | 8 | utils = require './utils' 9 | connman = require './connman' 10 | hotspot = require './hotspot' 11 | wifiScan = require './wifi-scan' 12 | 13 | app = express() 14 | 15 | app.use(bodyParser.json()) 16 | app.use(bodyParser.urlencoded(extended: true)) 17 | app.use(express.static(__dirname + '/public')) 18 | 19 | ssids = [] 20 | 21 | app.get '/ssids', (req, res) -> 22 | res.json(ssids) 23 | 24 | app.post '/connect', (req, res) -> 25 | if not (req.body.ssid? and req.body.passphrase?) 26 | return res.sendStatus(400) 27 | 28 | console.log('Selected ' + req.body.ssid) 29 | 30 | res.send('OK') 31 | 32 | data = """ 33 | [service_home_ethernet] 34 | Type = ethernet 35 | Nameservers = 8.8.8.8,8.8.4.4 36 | 37 | [service_home_wifi] 38 | Type = wifi 39 | Name = #{req.body.ssid} 40 | Passphrase = #{req.body.passphrase} 41 | Nameservers = 8.8.8.8,8.8.4.4 42 | 43 | """ 44 | 45 | Promise.all [ 46 | utils.durableWriteFile(config.connmanConfig, data) 47 | hotspot.stop() 48 | ] 49 | # XXX: make it so this delay isn't needed 50 | .delay(1000) 51 | .then -> 52 | connman.waitForConnection(15000) 53 | .then -> 54 | utils.durableWriteFile(config.persistentConfig, data) 55 | .then -> 56 | process.exit() 57 | .catch (e) -> 58 | hotspot.start() 59 | 60 | app.use (req, res) -> 61 | res.redirect('/') 62 | 63 | wifiScan.scanAsync() 64 | .then (results) -> 65 | ssids = results 66 | 67 | hotspot.start() 68 | 69 | app.listen(80) 70 | -------------------------------------------------------------------------------- /app/src/config.coffee: -------------------------------------------------------------------------------- 1 | module.exports = 2 | ssid: process.env.PORTAL_SSID or 'ResinAP' 3 | passphrase: process.env.PORTAL_PASSPHRASE 4 | iface: process.env.PORTAL_INTERFACE or 'wlan0' 5 | gateway: process.env.PORTAL_GATEWAY or '192.168.42.1' 6 | dhcpRange: process.env.PORTAL_DHCP_RANGE or '192.168.42.2,192.168.42.254' 7 | connmanConfig: process.env.PORTAL_CONNMAN_CONFIG or '/host/var/lib/connman/network.config' 8 | persistentConfig: process.env.PORTAL_PERSISTENT_CONFIG or '/data/network.config' 9 | -------------------------------------------------------------------------------- /app/src/connman.coffee: -------------------------------------------------------------------------------- 1 | Promise = require 'bluebird' 2 | DBus = require './dbus-promise' 3 | 4 | dbus = new DBus() 5 | 6 | bus = dbus.getBus('system') 7 | 8 | SERVICE = 'net.connman' 9 | WIFI_OBJECT = '/net/connman/technology/wifi' 10 | TECHNOLOGY_INTERFACE = 'net.connman.Technology' 11 | 12 | exports.waitForConnection = (timeout) -> 13 | console.log('Waiting for connman to connect..') 14 | 15 | bus.getInterfaceAsync(SERVICE, WIFI_OBJECT, TECHNOLOGY_INTERFACE) 16 | .then (wifi) -> 17 | new Promise (resolve, reject, onCancel) -> 18 | handler = (name, value) -> 19 | if name is 'Connected' and value is true 20 | wifi.removeListener('PropertyChanged', handler) 21 | resolve() 22 | 23 | # Listen for 'Connected' signals 24 | wifi.on('PropertyChanged', handler) 25 | 26 | # # But try to read in case we registered the event handler 27 | # # after is was already connected 28 | wifi.GetPropertiesAsync() 29 | .then ({ Connected }) -> 30 | if Connected 31 | wifi.removeListener('PropertyChanged', handler) 32 | resolve() 33 | 34 | setTimeout -> 35 | wifi.removeListener('PropertyChanged', handler) 36 | reject() 37 | , timeout 38 | -------------------------------------------------------------------------------- /app/src/dbus-promise.coffee: -------------------------------------------------------------------------------- 1 | Promise = require 'bluebird' 2 | DBus = require 'dbus' 3 | 4 | Bus = require 'dbus/lib/bus' 5 | Interface = require 'dbus/lib/interface' 6 | 7 | Promise.promisifyAll(Bus.prototype) 8 | Promise.promisifyAll(Interface.prototype) 9 | 10 | oldInit = Interface::init 11 | 12 | Interface::init = (args...) -> 13 | oldInit.apply(this, args) 14 | 15 | for own method of @object.method 16 | this[method + 'Async'] = do (method) -> (args...) -> 17 | new Promise (resolve, reject) => 18 | this[method].timeout = 5000 19 | this[method].finish = resolve 20 | this[method].error = reject 21 | this[method](args...) 22 | 23 | module.exports = DBus 24 | -------------------------------------------------------------------------------- /app/src/dnsmasq.coffee: -------------------------------------------------------------------------------- 1 | Promise = require 'bluebird' 2 | fs = Promise.promisifyAll(require('fs')) 3 | { spawn } = require 'child_process' 4 | 5 | config = require './config' 6 | 7 | ps = null 8 | 9 | configFile = "/tmp/dnsmasq-#{config.iface}.conf" 10 | 11 | exports.start = -> 12 | cfg = 13 | """ 14 | interface=#{config.iface} 15 | address=/#/#{config.gateway} 16 | dhcp-range=#{config.dhcpRange} 17 | bind-interfaces 18 | 19 | """ 20 | 21 | console.log('Starting dnsmasq..') 22 | fs.writeFileAsync(configFile, cfg) 23 | .then -> 24 | ps = spawn('dnsmasq', [ '--keep-in-foreground', '-C', configFile ]) 25 | ps.stdout.pipe(process.stdout) 26 | ps.stderr.pipe(process.stderr) 27 | 28 | exports.stop = -> 29 | if ps is null or ps.exitCode? or ps.signalCode? 30 | return Promise.resolve() 31 | 32 | new Promise (resolve, reject) -> 33 | ps.kill('SIGTERM') 34 | 35 | timeout = setTimeout -> 36 | ps.kill('SIGKILL') 37 | 38 | ps.on 'exit', -> 39 | clearTimeout(timeout) 40 | resolve() 41 | -------------------------------------------------------------------------------- /app/src/hostapd.coffee: -------------------------------------------------------------------------------- 1 | Promise = require 'bluebird' 2 | fs = Promise.promisifyAll(require('fs')) 3 | { spawn } = require 'child_process' 4 | 5 | config = require './config' 6 | 7 | ps = null 8 | 9 | configFile = "/tmp/hostapd-#{config.iface}.conf" 10 | 11 | exports.start = -> 12 | cfg = 13 | """ 14 | ssid=#{config.ssid} 15 | interface=#{config.iface} 16 | channel=6 17 | 18 | """ 19 | 20 | if config.passphrase? 21 | cfg += 22 | """ 23 | wpa=2 24 | wpa_passphrase=#{config.passphrase} 25 | 26 | """ 27 | 28 | console.log('Starting hostapd..') 29 | fs.writeFileAsync(configFile, cfg) 30 | .then -> 31 | ps = spawn('hostapd', [ configFile ]) 32 | ps.stdout.pipe(process.stdout) 33 | ps.stderr.pipe(process.stderr) 34 | 35 | exports.stop = -> 36 | if ps is null or ps.exitCode? or ps.signalCode? 37 | return Promise.resolve() 38 | 39 | new Promise (resolve, reject) -> 40 | ps.kill('SIGTERM') 41 | 42 | timeout = setTimeout -> 43 | ps.kill('SIGKILL') 44 | 45 | ps.on 'exit', -> 46 | clearTimeout(timeout) 47 | resolve() 48 | -------------------------------------------------------------------------------- /app/src/hotspot.coffee: -------------------------------------------------------------------------------- 1 | Promise = require 'bluebird' 2 | { spawn, exec } = require 'child_process' 3 | execAsync = Promise.promisify(exec) 4 | 5 | config = require './config' 6 | 7 | hostapd = require './hostapd' 8 | dnsmasq = require './dnsmasq' 9 | systemd = require './systemd' 10 | 11 | started = false 12 | 13 | exports.start = -> 14 | if started 15 | return Promise.resolve() 16 | 17 | started = true 18 | 19 | console.log('Stopping connman..') 20 | 21 | systemd.stop('connman.service') 22 | .delay(2000) 23 | .then -> 24 | execAsync('rfkill unblock wifi') 25 | .then -> 26 | # XXX: detect if the IP is already set instead of doing `|| true` 27 | execAsync("ip addr add #{config.gateway}/24 dev #{config.iface} || true") 28 | .then -> 29 | hostapd.start() 30 | .then -> 31 | dnsmasq.start() 32 | 33 | exports.stop = -> 34 | if not started 35 | return Promise.resolve() 36 | 37 | started = false 38 | 39 | Promise.all [ 40 | hostapd.stop() 41 | dnsmasq.stop() 42 | ] 43 | .then -> 44 | systemd.start('connman.service') 45 | -------------------------------------------------------------------------------- /app/src/public/img/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/balena-io-experimental/etcher-headless/27ff6c97f15c694ee0312a90681c6f83a8ef350f/app/src/public/img/favicon.png -------------------------------------------------------------------------------- /app/src/public/img/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /app/src/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Resin WiFi chooser 5 | 6 | 7 | 8 | 9 | 10 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 29 | 30 |
31 |
32 |
33 |

Hi! Please choose your wifi from the list.

34 |
35 |
36 |
37 |
38 |
39 |
40 | 41 |
42 | 43 |
44 |
45 |
46 | 47 |
48 | 49 |
50 |
51 |
52 | 53 |
54 |
55 |
56 |
57 | 63 | 69 |
70 | 71 | 72 | -------------------------------------------------------------------------------- /app/src/public/js/index.js: -------------------------------------------------------------------------------- 1 | $(function(){ 2 | $.get("/ssids", function(data){ 3 | if(data.length == 0){ 4 | $('.before-submit').hide(); 5 | $('#no-networks-message').removeClass('hidden'); 6 | } else { 7 | $.each(data, function(i, val){ 8 | $("#ssid-select").append(""); 9 | }); 10 | } 11 | }) 12 | 13 | $('#connect-form').submit(function(ev){ 14 | $.post('/connect', $('#connect-form').serialize(), function(data){ 15 | $('.before-submit').hide(); 16 | $('#submit-message').removeClass('hidden'); 17 | }); 18 | ev.preventDefault(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /app/src/systemd.coffee: -------------------------------------------------------------------------------- 1 | DBus = require './dbus-promise' 2 | 3 | dbus = new DBus() 4 | 5 | bus = dbus.getBus('system') 6 | 7 | SERVICE = 'org.freedesktop.systemd1' 8 | MANAGER_OBJECT = '/org/freedesktop/systemd1' 9 | MANAGER_INTERFACE = 'org.freedesktop.systemd1.Manager' 10 | 11 | exports.start = (unit, mode = 'fail') -> 12 | bus.getInterfaceAsync(SERVICE, MANAGER_OBJECT, MANAGER_INTERFACE) 13 | .then (manager) -> 14 | manager.StartUnitAsync(unit, mode) 15 | 16 | exports.stop = (unit, mode = 'fail') -> 17 | bus.getInterfaceAsync(SERVICE, MANAGER_OBJECT, MANAGER_INTERFACE) 18 | .then (manager) -> 19 | manager.StopUnitAsync(unit, mode) 20 | -------------------------------------------------------------------------------- /app/src/utils.coffee: -------------------------------------------------------------------------------- 1 | Promise = require 'bluebird' 2 | fs = Promise.promisifyAll(require('fs')) 3 | constants = require 'constants' 4 | path = require 'path' 5 | 6 | exports.durableWriteFile = (file, data) -> 7 | fs.writeFileAsync(file + '.tmp', data) 8 | .then -> 9 | fs.openAsync(file + '.tmp', 'r') 10 | .tap(fs.fsyncAsync) 11 | .then(fs.closeAsync) 12 | .then -> 13 | fs.renameAsync(file + '.tmp', file) 14 | .then -> 15 | fs.openAsync(path.dirname(file), 'r', constants.O_DIRECTORY) 16 | .tap(fs.fsyncAsync) 17 | .then(fs.closeAsync) 18 | -------------------------------------------------------------------------------- /app/src/wifi-scan.coffee: -------------------------------------------------------------------------------- 1 | Promise = require 'bluebird' 2 | { exec } = require 'child_process' 3 | execAsync = Promise.promisify(exec) 4 | 5 | config = require './config' 6 | 7 | exports.scanAsync = -> 8 | execAsync("iw #{config.iface} scan ap-force") 9 | .then (output) -> 10 | bsss = {} 11 | bss = null 12 | 13 | for line in output.split('\n') 14 | match = line.match(/^(\t?[A-Za-z]+):? (.*)$/) 15 | 16 | if match isnt null 17 | token = match[1] 18 | value = match[2] 19 | 20 | switch token 21 | when 'BSS' 22 | # BSS a4:2b:8c:82:2c:ba(on wlp8s0) 23 | bss = value[0...17] 24 | bsss[bss] = {} 25 | when '\tSSID' 26 | # SSID: kinaidos-sea-5g 27 | bsss[bss].ssid = value or null 28 | when '\tsignal' 29 | # signal: -80.00 dBm 30 | bsss[bss].signal = Number(value.split(' ')[0]) 31 | 32 | networks = [] 33 | for own bss, details of bsss 34 | networks.push(details) 35 | 36 | # sort by signal strength 37 | return networks.sort((a, b) -> b.signal - a.signal) 38 | -------------------------------------------------------------------------------- /app/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export DBUS_SYSTEM_BUS_ADDRESS=unix:path=/host/run/dbus/system_bus_socket 4 | 5 | # Enable i2c 6 | modprobe i2c-dev || true 7 | 8 | # Start resin-wifi-connect 9 | if [ ! -f /data/network.config ]; then 10 | node src/app.js 11 | else 12 | cp /data/network.config /host/var/lib/connman/network.config 13 | sleep 20; 14 | printf "Checking if we are connected to the internet via a google ping...\n\n" 15 | wget --spider http://google.com 2>&1 16 | if [ $? -eq 0 ]; then 17 | printf "\nconnected to internet, skipping wifi-connect\n\n" 18 | else 19 | printf "\nnot connected, starting wifi-connect\n\n" 20 | node src/app.js 21 | fi 22 | fi 23 | node /usr/src/app/index.js 24 | --------------------------------------------------------------------------------