├── .gitignore ├── images ├── demo.gif ├── editor.png ├── run1.png ├── run2.png ├── run3.png ├── stlink.jpg ├── install1.png ├── install2.gif ├── install3.png ├── install4.png ├── rls-fail.png ├── animation.gif ├── animation1.gif ├── animation2.gif ├── animation3.gif ├── animation4.gif ├── debug-bar.png ├── pi-spi-pin.jpg ├── trash-close.png ├── vscode-flow.jpg ├── infer-animate.gif ├── pinetime-swd3.jpg ├── typeless-rust.png ├── open-workspace.png ├── pinetime-antenna.png ├── visual-rust-icon.png ├── visual-rust-map.png ├── vs-build-tools.png ├── debug-bar-continue.png ├── rust-source-files.png ├── pi-spi-pinetime-small.jpg ├── vscode-debug-windows.png ├── vsstudio-build-tools.png └── pinetime-pi-pinout-spi.png ├── media ├── vscode │ ├── style.css │ ├── README.md │ ├── modal.js │ ├── message.js │ └── storage.js ├── README.md └── dep.svg ├── resources ├── README.md ├── package-explorer.png ├── light │ ├── document.svg │ ├── edit.svg │ ├── folder.svg │ ├── boolean.svg │ ├── dependency.svg │ ├── refresh.svg │ ├── number.svg │ └── string.svg ├── dark │ ├── edit.svg │ ├── document.svg │ ├── folder.svg │ ├── boolean.svg │ ├── dependency.svg │ ├── refresh.svg │ ├── number.svg │ └── string.svg ├── template.rs └── replay.log ├── .vscodeignore ├── workspace.code-workspace ├── .vscode ├── extensions.json ├── settings.json ├── tasks.json └── launch.json ├── CHANGELOG.md ├── tslint.json ├── src ├── test │ ├── suite │ │ ├── extension.test.ts │ │ └── index.ts │ └── runTest.ts ├── decorate.ts ├── replay.ts ├── declarations.ts ├── extension.ts └── web.ts ├── tsconfig.json ├── .github └── FUNDING.yml ├── vsc-extension-quickstart.md ├── package.json ├── README.md └── README.old.md /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | node_modules 3 | .vscode-test/ 4 | *.vsix 5 | -------------------------------------------------------------------------------- /images/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/demo.gif -------------------------------------------------------------------------------- /images/editor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/editor.png -------------------------------------------------------------------------------- /images/run1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/run1.png -------------------------------------------------------------------------------- /images/run2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/run2.png -------------------------------------------------------------------------------- /images/run3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/run3.png -------------------------------------------------------------------------------- /images/stlink.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/stlink.jpg -------------------------------------------------------------------------------- /images/install1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/install1.png -------------------------------------------------------------------------------- /images/install2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/install2.gif -------------------------------------------------------------------------------- /images/install3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/install3.png -------------------------------------------------------------------------------- /images/install4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/install4.png -------------------------------------------------------------------------------- /images/rls-fail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/rls-fail.png -------------------------------------------------------------------------------- /images/animation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/animation.gif -------------------------------------------------------------------------------- /images/animation1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/animation1.gif -------------------------------------------------------------------------------- /images/animation2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/animation2.gif -------------------------------------------------------------------------------- /images/animation3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/animation3.gif -------------------------------------------------------------------------------- /images/animation4.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/animation4.gif -------------------------------------------------------------------------------- /images/debug-bar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/debug-bar.png -------------------------------------------------------------------------------- /images/pi-spi-pin.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/pi-spi-pin.jpg -------------------------------------------------------------------------------- /images/trash-close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/trash-close.png -------------------------------------------------------------------------------- /images/vscode-flow.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/vscode-flow.jpg -------------------------------------------------------------------------------- /media/vscode/style.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | color: black; /* For VSCode, else text will appear grey */ 3 | } -------------------------------------------------------------------------------- /images/infer-animate.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/infer-animate.gif -------------------------------------------------------------------------------- /images/pinetime-swd3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/pinetime-swd3.jpg -------------------------------------------------------------------------------- /images/typeless-rust.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/typeless-rust.png -------------------------------------------------------------------------------- /resources/README.md: -------------------------------------------------------------------------------- 1 | # resources 2 | 3 | - [`template.rs`](template.rs): Template for new visual programs 4 | -------------------------------------------------------------------------------- /images/open-workspace.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/open-workspace.png -------------------------------------------------------------------------------- /images/pinetime-antenna.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/pinetime-antenna.png -------------------------------------------------------------------------------- /images/visual-rust-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/visual-rust-icon.png -------------------------------------------------------------------------------- /images/visual-rust-map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/visual-rust-map.png -------------------------------------------------------------------------------- /images/vs-build-tools.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/vs-build-tools.png -------------------------------------------------------------------------------- /images/debug-bar-continue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/debug-bar-continue.png -------------------------------------------------------------------------------- /images/rust-source-files.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/rust-source-files.png -------------------------------------------------------------------------------- /images/pi-spi-pinetime-small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/pi-spi-pinetime-small.jpg -------------------------------------------------------------------------------- /images/vscode-debug-windows.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/vscode-debug-windows.png -------------------------------------------------------------------------------- /images/vsstudio-build-tools.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/vsstudio-build-tools.png -------------------------------------------------------------------------------- /resources/package-explorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/resources/package-explorer.png -------------------------------------------------------------------------------- /images/pinetime-pi-pinout-spi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lupyuen/visual-embedded-rust/HEAD/images/pinetime-pi-pinout-spi.png -------------------------------------------------------------------------------- /media/vscode/README.md: -------------------------------------------------------------------------------- 1 | # vscode 2 | 3 | This folder contains functions and stylesheets to override Blockly specifically for VSCode -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | .vscode/** 2 | .vscode-test/** 3 | out/test/** 4 | src/** 5 | .gitignore 6 | vsc-extension-quickstart.md 7 | **/tsconfig.json 8 | **/tslint.json 9 | **/*.map 10 | **/*.ts -------------------------------------------------------------------------------- /workspace.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | }, 6 | { 7 | "path": "media/blockly-mynewt-rust" 8 | } 9 | ], 10 | "settings": { 11 | "typescript.tsc.autoDetect": "off" 12 | } 13 | } -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "ms-vscode.vscode-typescript-tslint-plugin" 6 | ] 7 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to the "visual-embedded-rust" extension will be documented in this file. 4 | 5 | Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file. 6 | 7 | ## [Unreleased] 8 | 9 | - Initial release -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "no-string-throw": true, 4 | "no-unused-expression": true, 5 | "no-duplicate-variable": true, 6 | "curly": true, 7 | "class-name": true, 8 | "semicolon": [ 9 | true, 10 | "always" 11 | ], 12 | "triple-equals": true 13 | }, 14 | "defaultSeverity": "warning" 15 | } 16 | -------------------------------------------------------------------------------- /media/README.md: -------------------------------------------------------------------------------- 1 | # media 2 | 3 | This folder contains JavaScript and CSS assets accessible by the WebView. 4 | 5 | Two repositories need to be cloned into this folder: [blockly-mynewt-rust](https://github.com/lupyuen/blockly-mynewt-rust) and [closure-library](https://github.com/google/closure-library): 6 | 7 | ```bash 8 | cd media 9 | git clone https://github.com/lupyuen/blockly-mynewt-rust 10 | git clone https://github.com/google/closure-library 11 | ``` 12 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "files.exclude": { 4 | "out": false // set this to true to hide the "out" folder with the compiled JS files 5 | }, 6 | "search.exclude": { 7 | "out": true // set this to false to include "out" folder in search results 8 | }, 9 | // Turn off tsc task auto detection since we have the necessary tasks as npm scripts 10 | "typescript.tsc.autoDetect": "off" 11 | } -------------------------------------------------------------------------------- /resources/light/document.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/dark/edit.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/light/edit.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // See https://go.microsoft.com/fwlink/?LinkId=733558 2 | // for the documentation about the tasks.json format 3 | { 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "Package Extension", 8 | "type": "shell", 9 | "command": "vsce package" 10 | }, 11 | { 12 | "type": "npm", 13 | "script": "watch", 14 | "problemMatcher": "$tsc-watch", 15 | "isBackground": true, 16 | "presentation": { 17 | "reveal": "never" 18 | }, 19 | "group": { 20 | "kind": "build", 21 | "isDefault": true 22 | } 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /src/test/suite/extension.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from 'assert'; 2 | import { before } from 'mocha'; 3 | 4 | // You can import and use all API from the 'vscode' module 5 | // as well as import your extension to test it 6 | import * as vscode from 'vscode'; 7 | // import * as myExtension from '../extension'; 8 | 9 | suite('Extension Test Suite', () => { 10 | before(() => { 11 | vscode.window.showInformationMessage('Start all tests.'); 12 | }); 13 | 14 | test('Sample test', () => { 15 | assert.equal(-1, [1, 2, 3].indexOf(5)); 16 | assert.equal(-1, [1, 2, 3].indexOf(0)); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "outDir": "out", 6 | "lib": [ 7 | "es6" 8 | ], 9 | "sourceMap": true, 10 | "rootDir": "src", 11 | "strict": true /* enable all strict type-checking options */ 12 | /* Additional Checks */ 13 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 14 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 15 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 16 | }, 17 | "exclude": [ 18 | "node_modules", 19 | ".vscode-test" 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /resources/dark/document.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/test/runTest.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | 3 | import { runTests } from 'vscode-test'; 4 | 5 | async function main() { 6 | try { 7 | // The folder containing the Extension Manifest package.json 8 | // Passed to `--extensionDevelopmentPath` 9 | const extensionDevelopmentPath = path.resolve(__dirname, '../../'); 10 | 11 | // The path to test runner 12 | // Passed to --extensionTestsPath 13 | const extensionTestsPath = path.resolve(__dirname, './suite/index'); 14 | 15 | // Download VS Code, unzip it and run the integration test 16 | await runTests({ extensionDevelopmentPath, extensionTestsPath }); 17 | } catch (err) { 18 | console.error('Failed to run tests'); 19 | process.exit(1); 20 | } 21 | } 22 | 23 | main(); 24 | -------------------------------------------------------------------------------- /resources/light/folder.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/dark/folder.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/dark/boolean.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/dark/dependency.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/light/boolean.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/light/dependency.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [lupyuen] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: ['paypal.me/lupyuen'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /src/test/suite/index.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | import * as Mocha from 'mocha'; 3 | import * as glob from 'glob'; 4 | 5 | export function run(): Promise { 6 | // Create the mocha test 7 | const mocha = new Mocha({ 8 | ui: 'tdd', 9 | }); 10 | mocha.useColors(true); 11 | 12 | const testsRoot = path.resolve(__dirname, '..'); 13 | 14 | return new Promise((c, e) => { 15 | glob('**/**.test.js', { cwd: testsRoot }, (err, files) => { 16 | if (err) { 17 | return e(err); 18 | } 19 | 20 | // Add files to the test suite 21 | files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); 22 | 23 | try { 24 | // Run the mocha test 25 | mocha.run(failures => { 26 | if (failures > 0) { 27 | e(new Error(`${failures} tests failed.`)); 28 | } else { 29 | c(); 30 | } 31 | }); 32 | } catch (err) { 33 | e(err); 34 | } 35 | }); 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /resources/dark/refresh.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/light/refresh.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // A launch configuration that compiles the extension and then opens it inside a new window 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | { 6 | "version": "0.2.0", 7 | "configurations": [ 8 | { 9 | "name": "Run Extension", 10 | "type": "extensionHost", 11 | "request": "launch", 12 | "runtimeExecutable": "${execPath}", 13 | "args": [ 14 | "--extensionDevelopmentPath=${workspaceFolder}" 15 | ], 16 | "outFiles": [ 17 | "${workspaceFolder}/out/**/*.js" 18 | ], 19 | "preLaunchTask": "npm: watch" 20 | }, 21 | { 22 | "name": "Extension Tests", 23 | "type": "extensionHost", 24 | "request": "launch", 25 | "runtimeExecutable": "${execPath}", 26 | "args": [ 27 | "--extensionDevelopmentPath=${workspaceFolder}", 28 | "--extensionTestsPath=${workspaceFolder}/out/test/suite/index" 29 | ], 30 | "outFiles": [ 31 | "${workspaceFolder}/out/test/**/*.js" 32 | ], 33 | "preLaunchTask": "npm: watch" 34 | } 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /resources/template.rs: -------------------------------------------------------------------------------- 1 | // -- BEGIN BLOCKS --countcount0my_label5my_buttonVisual Rust5my_labelcountmy_buttoncountADD1count1-- END BLOCKS -- -------------------------------------------------------------------------------- /vsc-extension-quickstart.md: -------------------------------------------------------------------------------- 1 | # Welcome to your VS Code Extension 2 | 3 | ## What's in the folder 4 | 5 | * This folder contains all of the files necessary for your extension. 6 | * `package.json` - this is the manifest file in which you declare your extension and command. 7 | * The sample plugin registers a command and defines its title and command name. With this information VS Code can show the command in the command palette. It doesn’t yet need to load the plugin. 8 | * `src/extension.ts` - this is the main file where you will provide the implementation of your command. 9 | * The file exports one function, `activate`, which is called the very first time your extension is activated (in this case by executing the command). Inside the `activate` function we call `registerCommand`. 10 | * We pass the function containing the implementation of the command as the second parameter to `registerCommand`. 11 | 12 | ## Get up and running straight away 13 | 14 | * Press `F5` to open a new window with your extension loaded. 15 | * Run your command from the command palette by pressing (`Ctrl+Shift+P` or `Cmd+Shift+P` on Mac) and typing `Hello World`. 16 | * Set breakpoints in your code inside `src/extension.ts` to debug your extension. 17 | * Find output from your extension in the debug console. 18 | 19 | ## Make changes 20 | 21 | * You can relaunch the extension from the debug toolbar after changing code in `src/extension.ts`. 22 | * You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes. 23 | 24 | 25 | ## Explore the API 26 | 27 | * You can open the full set of our API when you open the file `node_modules/@types/vscode/index.d.ts`. 28 | 29 | ## Run tests 30 | 31 | * Open the debug viewlet (`Ctrl+Shift+D` or `Cmd+Shift+D` on Mac) and from the launch configuration dropdown pick `Extension Tests`. 32 | * Press `F5` to run the tests in a new window with your extension loaded. 33 | * See the output of the test result in the debug console. 34 | * Make changes to `src/test/suite/extension.test.ts` or create new test files inside the `test/suite` folder. 35 | * The provided test runner will only consider files matching the name pattern `**.test.ts`. 36 | * You can create folders inside the `test` folder to structure your tests any way you want. 37 | 38 | ## Go further 39 | 40 | * Reduce the extension size and improve the startup time by [bundling your extension](https://code.visualstudio.com/api/working-with-extensions/testing-extension). 41 | * [Publish your extension](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) on the VSCode extension marketplace. 42 | * Automate builds by setting up [Continuous Integration](https://code.visualstudio.com/api/working-with-extensions/continuous-integration). 43 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "visual-embedded-rust", 3 | "displayName": "Visual Embedded Rust", 4 | "description": "Visual Editor for Embedded Rust", 5 | "version": "1.0.7", 6 | "publisher": "LeeLupYuen", 7 | "icon": "images/visual-rust-icon.png", 8 | "repository": { 9 | "url": "https://github.com/lupyuen/visual-embedded-rust" 10 | }, 11 | "engines": { 12 | "vscode": "^1.32.0" 13 | }, 14 | "categories": [ 15 | "Programming Languages", 16 | "Other" 17 | ], 18 | "activationEvents": [ 19 | "onCommand:visualEmbeddedRust.helloWorld", 20 | "onCommand:visualEmbeddedRust.start", 21 | "onCommand:visualEmbeddedRust.doRefactor", 22 | "onWebviewPanel:visualEmbeddedRust" 23 | ], 24 | "main": "./out/extension.js", 25 | "contributes": { 26 | "commands": [ 27 | { 28 | "command": "visualEmbeddedRust.helloWorld", 29 | "title": "Hello World", 30 | "category": "Visual Embedded Rust" 31 | }, 32 | { 33 | "command": "visualEmbeddedRust.start", 34 | "title": "Visual editor", 35 | "category": "Visual Embedded Rust" 36 | }, 37 | { 38 | "command": "visualEmbeddedRust.doRefactor", 39 | "title": "Do some refactoring", 40 | "category": "Visual Embedded Rust" 41 | } 42 | ], 43 | "menus": { 44 | "editor/title": [ 45 | { 46 | "command": "visualEmbeddedRust.start", 47 | "group": "navigation", 48 | "when": "resourceExtname == .rs" 49 | } 50 | ] 51 | }, 52 | "viewsContainers": { 53 | "activitybar": [ 54 | { 55 | "id": "visual-embedded-rust-declarations", 56 | "title": "Declarations", 57 | "icon": "media/dep.svg" 58 | } 59 | ] 60 | }, 61 | "views": { 62 | "visual-embedded-rust-declarations": [ 63 | { 64 | "id": "visualEmbeddedRustDeclarations", 65 | "name": "All" 66 | } 67 | ] 68 | }, 69 | "colors": [ 70 | { 71 | "id": "visualEmbeddedRust.background0", 72 | "description": "Background #0", 73 | "defaults": { 74 | "dark": "#FF000055", 75 | "light": "#FF000055", 76 | "highContrast": "#FF000055" 77 | } 78 | }, 79 | { 80 | "id": "visualEmbeddedRust.background1", 81 | "description": "Background #1", 82 | "defaults": { 83 | "dark": "#00FF0055", 84 | "light": "#00FF0055", 85 | "highContrast": "#00FF0055" 86 | } 87 | } 88 | ] 89 | }, 90 | "scripts": { 91 | "vscode:prepublish": "npm run compile", 92 | "compile": "tsc -p ./", 93 | "watch": "tsc -watch -p ./", 94 | "pretest": "npm run compile", 95 | "test": "node ./out/test/runTest.js" 96 | }, 97 | "devDependencies": { 98 | "@types/glob": "^7.1.1", 99 | "@types/mocha": "^5.2.6", 100 | "@types/node": "^10.12.21", 101 | "@types/vscode": "^1.32.0", 102 | "glob": "^7.1.4", 103 | "mocha": "^6.1.4", 104 | "typescript": "^3.3.1", 105 | "tslint": "^5.12.1", 106 | "vscode-test": "^1.0.2" 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /media/vscode/modal.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview VSCode modals 3 | * @author luppy@appkaki.com (Lee Lup Yuen) 4 | */ 5 | 'use strict'; 6 | 7 | // Override the Blockly modal functions for alert(), confirm() and prompt() because they are not supported in VSCode 8 | function initModal(vscode) { // Pass in vscode so that we don't expose vscode to global space and cause security problems 9 | console.log('vscode/modal loaded'); 10 | 11 | /** 12 | * Override this because VSCode doesn't support alert(). 13 | * Wrapper to window.alert() that app developers may override to 14 | * provide alternatives to the modal browser window. 15 | * @param {string} message The message to display to the user. 16 | * @param {function()=} opt_callback The callback when the alert is dismissed. 17 | */ 18 | Blockly.alert = function(message, opt_callback) { 19 | // Previously: window.alert(message); 20 | console.error(message); 21 | if (opt_callback) { 22 | opt_callback(); 23 | } 24 | }; 25 | 26 | /** 27 | * Override this because VSCode doesn't support confirm(). 28 | * Wrapper to window.confirm() that app developers may override to 29 | * provide alternatives to the modal browser window. 30 | * @param {string} message The message to display to the user. 31 | * @param {!function(boolean)} callback The callback for handling user response. 32 | */ 33 | Blockly.confirm = function(message, callback) { 34 | // Pass to callback a boolean indicating whether OK (true) or Cancel (false) was selected 35 | // Previously: callback(window.confirm(message)); 36 | console.log(['confirm', message]); 37 | // Set the callback. 38 | confirmResult = result => { 39 | confirmResult = null; 40 | callback(result); 41 | }; 42 | // Call VSCode to prompt. 43 | vscode.postMessage({ 44 | command: 'confirm', 45 | message: message 46 | }); 47 | }; 48 | 49 | /** 50 | * Override this because VSCode doesn't support prompt(). 51 | * Wrapper to window.prompt() that app developers may override to provide 52 | * alternatives to the modal browser window. Built-in browser prompts are 53 | * often used for better text input experience on mobile device. We strongly 54 | * recommend testing mobile when overriding this. 55 | * @param {string} message The message to display to the user. 56 | * @param {string} defaultValue The value to initialize the prompt with. 57 | * @param {!function(string)} callback The callback for handling user response. 58 | */ 59 | Blockly.prompt = function(message, defaultValue, callback) { 60 | // Previously: callback(window.prompt(message, defaultValue)); 61 | console.log(['prompt', message, defaultValue]); 62 | // Set the callback. 63 | promptResult = result => { 64 | promptResult = null; 65 | callback(result); 66 | }; 67 | // Call VSCode to prompt. 68 | vscode.postMessage({ 69 | command: 'prompt', 70 | message: message, 71 | defaultValue: defaultValue, 72 | }); 73 | }; 74 | } -------------------------------------------------------------------------------- /resources/dark/number.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/light/number.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /media/vscode/message.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Visual Blocks Editor 4 | * 5 | * Copyright 2012 Google Inc. 6 | * https://developers.google.com/blockly/ 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @fileoverview Handle command messages from VSCode 23 | * @author luppy@appkaki.com (Lee Lup Yuen) 24 | */ 25 | 'use strict'; 26 | 27 | // Markers for wrapping the XML blocks 28 | var blocks_begin = '-- BEGIN BLOCKS --'; 29 | var blocks_end = '-- END BLOCKS --'; 30 | 31 | // Callbacks for confirm and promp modals. 32 | var confirmResult, promptResult; 33 | 34 | // Handle the message received from VSCode 35 | window.addEventListener('message', event => { 36 | const message = event.data; // The JSON data our extension sent 37 | console.log(['recv msg', JSON.stringify(message).substr(0, 20)]); 38 | switch (message.command) { 39 | // Load the blocks into the workspace. 40 | case 'loadDoc': { 41 | // Text contains `... /* -- BEGIN BLOCKS -- ... -- END BLOCKS -- */`. Extract the blocks. 42 | const text = message.text; 43 | console.log(['loadDoc', text.substr(0, 20)]); 44 | 45 | const beginSplit = text.split(blocks_begin, 2); 46 | if (beginSplit.length < 2) { console.log(blocks_begin + ' not found'); return; } 47 | const endSplit = beginSplit[1].split(blocks_end, 2); 48 | if (endSplit.length < 2) { console.log(blocks_end + ' not found'); return; } 49 | const blocks = endSplit[0]; 50 | 51 | // Set the blocks in the workspace. 52 | var workspace = Blockly.getMainWorkspace(); if (!workspace) { console.log('Missing workspace'); return; } 53 | var xml = Blockly.Xml.textToDom(blocks); 54 | Blockly.Xml.domToWorkspace(xml, workspace); 55 | 56 | // Monitor changes and sync updates to the VSCode document. 57 | BlocklyStorage.monitorChanges_(workspace); 58 | return; 59 | } 60 | 61 | // Receive confirm result from VSCode. We trigger the confirm callback. 62 | case 'confirmResult': { 63 | const result = message.result; 64 | if (confirmResult) { confirmResult(result); } 65 | return; 66 | } 67 | 68 | // Receive prompt result from VSCode. We trigger the prompt callback. 69 | case 'promptResult': { 70 | const result = message.result; 71 | if (promptResult) { promptResult(result); } 72 | return; 73 | } 74 | 75 | default: console.error('Unknown message: ' + JSON.stringify(message)); 76 | } 77 | }); 78 | 79 | function composeDoc(xml, code) { 80 | // Given the XML blocks and the generated Rust code, compose the document to be updated in VSCode. 81 | const doc = [ 82 | code + '\n', 83 | '// ', 84 | blocks_begin, 85 | xml, 86 | blocks_end, 87 | ].join(''); 88 | return doc; 89 | } -------------------------------------------------------------------------------- /resources/dark/string.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/light/string.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /media/dep.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Slice 5 | Created with Sketch. 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/decorate.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | 3 | /* 4 | // create a decorator type that we use to decorate small numbers 5 | const smallNumberDecorationType = vscode.window.createTextEditorDecorationType({ 6 | borderWidth: '1px', 7 | borderStyle: 'solid', 8 | overviewRulerColor: 'blue', 9 | overviewRulerLane: vscode.OverviewRulerLane.Right, 10 | light: { 11 | // this color will be used in light color themes 12 | borderColor: 'darkblue' 13 | }, 14 | dark: { 15 | // this color will be used in dark color themes 16 | borderColor: 'lightblue' 17 | } 18 | }); 19 | 20 | // create a decorator type that we use to decorate large numbers 21 | const largeNumberDecorationType = vscode.window.createTextEditorDecorationType({ 22 | cursor: 'crosshair', 23 | // use a themable color. See package.json for the declaration and default values. 24 | backgroundColor: { id: 'visualEmbeddedRust.largeNumberBackground' } 25 | }); 26 | */ 27 | 28 | // create a decorator type using a themable color. See package.json for the declaration and default values. 29 | const decorationTypes = [ 30 | vscode.window.createTextEditorDecorationType({ 31 | cursor: 'crosshair', 32 | backgroundColor: { id: 'visualEmbeddedRust.background0' } 33 | }), 34 | vscode.window.createTextEditorDecorationType({ 35 | cursor: 'crosshair', 36 | backgroundColor: { id: 'visualEmbeddedRust.background1' } 37 | }), 38 | ]; 39 | 40 | export function decorate(editor: vscode.TextEditor, color: number, startLine: number, startCol: number, endLine: number, endCol: number) { 41 | // Apply decoration to the active editor. All numbers are zero-based. 42 | if (!editor) { return; } 43 | const decorationOptions: vscode.DecorationOptions[][] = [ 44 | [], [] 45 | ]; 46 | const startPos = new vscode.Position(startLine, startCol); 47 | const endPos = new vscode.Position(endLine, endCol); 48 | const decoration = { 49 | range: new vscode.Range(startPos, endPos), 50 | hoverMessage: '' 51 | }; 52 | decorationOptions[color].push(decoration); 53 | for (let i = 0; i < decorationTypes.length; i++) { 54 | editor.setDecorations(decorationTypes[i], decorationOptions[i]); 55 | } 56 | } 57 | 58 | // Called when vs code is activated 59 | export function activate(context: vscode.ExtensionContext) { 60 | // console.log('decorate is activated'); 61 | 62 | /* 63 | let timeout: NodeJS.Timer | undefined = undefined; 64 | 65 | let activeEditor = vscode.window.activeTextEditor; 66 | 67 | if (activeEditor) { 68 | // triggerUpdateDecorations(); 69 | } 70 | 71 | vscode.window.onDidChangeActiveTextEditor(editor => { 72 | activeEditor = editor; 73 | if (editor) { 74 | // triggerUpdateDecorations(); 75 | } 76 | }, null, context.subscriptions); 77 | 78 | vscode.workspace.onDidChangeTextDocument(event => { 79 | if (activeEditor && event.document === activeEditor.document) { 80 | // triggerUpdateDecorations(); 81 | } 82 | }, null, context.subscriptions); 83 | 84 | function updateDecorations() { 85 | if (!activeEditor) { 86 | return; 87 | } 88 | const regEx = /\d+/g; 89 | const text = activeEditor.document.getText(); 90 | const smallNumbers: vscode.DecorationOptions[] = []; 91 | const largeNumbers: vscode.DecorationOptions[] = []; 92 | let match; 93 | while (match = regEx.exec(text)) { 94 | const startPos = activeEditor.document.positionAt(match.index); 95 | const endPos = activeEditor.document.positionAt(match.index + match[0].length); 96 | const decoration = { range: new vscode.Range(startPos, endPos), hoverMessage: 'Number **' + match[0] + '**' }; 97 | if (match[0].length < 3) { 98 | largeNumbers.push(decoration); 99 | } else { 100 | largeNumbers.push(decoration); 101 | } 102 | } 103 | activeEditor.setDecorations(smallNumberDecorationType, smallNumbers); 104 | activeEditor.setDecorations(largeNumberDecorationType, largeNumbers); 105 | } 106 | 107 | 108 | function triggerUpdateDecorations() { 109 | if (timeout) { 110 | clearTimeout(timeout); 111 | timeout = undefined; 112 | } 113 | timeout = setTimeout(updateDecorations, 500); 114 | } 115 | */ 116 | } 117 | -------------------------------------------------------------------------------- /src/replay.ts: -------------------------------------------------------------------------------- 1 | // Replay the recorded inference log 2 | import * as vscode from 'vscode'; 3 | import * as fs from 'fs'; 4 | import * as path from 'path'; 5 | import * as decorate from './decorate'; 6 | import * as declarations from './declarations'; 7 | 8 | // List of log entries to replay 9 | let replayLog: string[] = []; 10 | 11 | // List of interpolated spans to replay 12 | let interpolatedSpans: number[][] = []; 13 | 14 | // Span color: 0 for red, 1 for green 15 | let spanColor: number = 0; 16 | 17 | // Called when VSCode is activated 18 | export function activate(context: vscode.ExtensionContext) { 19 | console.log('replay is activated'); 20 | 21 | // Trigger the replay when document is active. 22 | let timeout: NodeJS.Timer | undefined = undefined; 23 | let activeEditor = vscode.window.activeTextEditor; 24 | if (activeEditor) { triggerReplay(); } 25 | 26 | vscode.window.onDidChangeActiveTextEditor(editor => { 27 | activeEditor = editor; 28 | if (editor) { triggerReplay(); } 29 | }, null, context.subscriptions); 30 | 31 | vscode.workspace.onDidChangeTextDocument(event => { 32 | if (activeEditor && event.document === activeEditor.document) { triggerReplay(); } 33 | }, null, context.subscriptions); 34 | 35 | function triggerReplay() { 36 | if (timeout) { 37 | clearInterval(timeout); 38 | timeout = undefined; 39 | } 40 | // Don't replay for empty Rust file. 41 | if (activeEditor && activeEditor.document.getText().length === 0) { 42 | console.log('Skipping replay for empty document'); 43 | return; 44 | } 45 | // Don't replay for generated Rust code. 46 | if (activeEditor && activeEditor.document.getText().indexOf('BEGIN BLOCKS') >= 0) { 47 | console.log('Skipping replay for document with BEGIN BLOCKS'); 48 | return; 49 | } 50 | // Read the entire replay log and break into lines. 51 | if (replayLog.length === 0) { 52 | const replayPath = path.join(__filename, '..', '..', 'resources', 'replay.log'); 53 | const buf = fs.readFileSync(replayPath); 54 | const log = buf.toString(); 55 | replayLog = log.split('\n'); 56 | console.log('replay read log: ' + replayLog.length); 57 | } 58 | timeout = setInterval(() => { 59 | if (activeEditor) { replay(activeEditor); } 60 | }, 200); 61 | } 62 | } 63 | 64 | // Remember the last span rendered 65 | let lastStartRow: number = 0; 66 | let lastStartCol: number = 0; 67 | let lastEndRow: number = 0; 68 | let lastEndCol: number = 0; 69 | 70 | function replay(editor: vscode.TextEditor) { 71 | // Replay one line of the log. 72 | if (!editor) { return; } 73 | // If there are interpolated spans, replay them. 74 | if (interpolatedSpans.length > 0) { 75 | replayInterpolatedSpan(editor); 76 | return; 77 | } 78 | for (;;) { 79 | // Look for replay lines starting with "#". 80 | if (replayLog.length === 0) { return; } 81 | const line = replayLog.shift(); 82 | if (line === undefined || !line.startsWith('#')) { continue; } 83 | console.log('replay: ' + line); 84 | 85 | if (line.startsWith("#s")) { 86 | // Replay Span: #s src/main.rs | 43 | 8 | 43 | 51 87 | // Show the span as red. 88 | const replayed = replaySpan(editor, line, 0); 89 | if (!replayed) { continue; } // Not replayed because of duplicate, fetch next line. 90 | 91 | } else if (line.startsWith("#m")) { 92 | // Replay Match: #m sensor::set_poll_rate_ms | src/main.rs | 43 | 8 | 43 | 51 93 | // Mark the known declaration. 94 | const s = line.substr(2).split('|'); 95 | declarations.markKnown(s[2].trim()); 96 | // Show the span as green. 97 | const span = s.slice(1).join('|'); 98 | const replayed = replaySpan(editor, span, 1); 99 | 100 | } else if (line.startsWith("#i")) { 101 | // Replay Infer: #i start_sensor_listener | sensor | sensor::set_poll_rate_ms | devname | &Strn 102 | // Mark the pending and known declarations. 103 | const s = line.substr(2).split('|'); 104 | const pendingPath = [s[0].trim(), s[1].trim()].join('|'); 105 | const knownPath = [s[2].trim(), s[3].trim()].join('|'); 106 | const para = s[1].trim(); 107 | const value = s[4].trim(); 108 | const result = declarations.setPendingValue( 109 | pendingPath, 110 | value 111 | ); 112 | if (result) { vscode.window.showInformationMessage(`"${para}" was inferred as "${value}"`); } 113 | declarations.markPending( 114 | pendingPath 115 | ); 116 | declarations.markKnown( 117 | knownPath 118 | ); 119 | // Show the span as green. 120 | const span = [ 121 | '', 122 | lastStartRow + 1, 123 | lastStartCol, 124 | lastEndRow + 1, 125 | lastEndCol 126 | ].join('|'); 127 | const replayed = replaySpan(editor, span, 1); 128 | 129 | } else { continue; } 130 | break; 131 | } 132 | } 133 | 134 | function replaySpan(editor: vscode.TextEditor, line: string, color: number): boolean { 135 | // Replay Span: #s src/main.rs | 43 | 8 | 43 | 51 136 | // Return true if span has been replayed. 137 | if (!editor) { return false; } 138 | const s = line.split('|'); 139 | const startRow = parseInt(s[1]) - 1; 140 | const startCol = parseInt(s[2]); 141 | const endRow = parseInt(s[3]) - 1; 142 | const endCol = parseInt(s[4]); 143 | // If span is unchanged, fetch next line. 144 | if (startRow === lastStartRow 145 | && startCol === lastStartCol 146 | && endRow === lastEndRow 147 | && endCol === lastEndCol 148 | && spanColor === color) { 149 | return false; 150 | } 151 | // Interpolate the span into 3 intermediate spans. 152 | interpolatedSpans = interpolateSpan( 153 | lastStartRow, startRow, 154 | lastStartCol, startCol, 155 | lastEndRow, endRow, 156 | lastEndCol, endCol 157 | ); 158 | // Remember the last span. 159 | lastStartRow = startRow; 160 | lastStartCol = startCol; 161 | lastEndRow = endRow; 162 | lastEndCol = endCol; 163 | spanColor = color; 164 | // Decorate the span. 165 | // Previously: decorate.decorate(editor, startRow, startCol, endRow, endCol); 166 | replayInterpolatedSpan(editor); 167 | return true; 168 | } 169 | 170 | function replayInterpolatedSpan(editor: vscode.TextEditor) { 171 | // Replay the next interpolated span. 172 | if (!editor) { return; } 173 | if (interpolatedSpans.length === 0) { return; } 174 | const span = interpolatedSpans.shift(); 175 | if (span === undefined) { return; } 176 | decorate.decorate(editor, spanColor, span[0], span[1], span[2], span[3]); 177 | } 178 | 179 | function interpolateSpan( 180 | startRow1: number, startRow2: number, 181 | startCol1: number, startCol2: number, 182 | endRow1: number, endRow2: number, 183 | endCol1: number, endCol2: number 184 | ) { 185 | // Interpolate the span into 5 frames. 186 | const frames = 5; 187 | let result: number[][] = []; 188 | let incStartRow = (startRow2 - startRow1) / (frames * 1.0); 189 | let incStartCol = (startCol2 - startCol1) / (frames * 1.0); 190 | let incEndRow = (endRow2 - endRow1) / (frames * 1.0); 191 | let incEndCol = (endCol2 - endCol1) / (frames * 1.0); 192 | // Interpolate (n - 1) frames. 193 | for (let i = 1; i < frames; i++) { 194 | result.push([ 195 | startRow1 + Math.floor(i * incStartRow), 196 | startCol1 + Math.floor(i * incStartCol), 197 | endRow1 + Math.floor(i * incEndRow), 198 | endCol1 + Math.floor(i * incEndCol) 199 | ]); 200 | } 201 | // Push the last frame. 202 | result.push([startRow2, startCol2, endRow2, endCol2]); 203 | return result; 204 | } -------------------------------------------------------------------------------- /src/declarations.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | import * as fs from 'fs'; 3 | import * as path from 'path'; 4 | 5 | // Tree of nodes 6 | let tree: any = { 7 | "To Be Inferred": { 8 | //"start_sensor_listener" : [ ["sensor", "_"], ["sensor_type", "_"], ["poll_time", "_"] ], 9 | "start_sensor_listener" : { "sensor": "_", "sensor_type": "_", "poll_time": "_" }, 10 | }, 11 | "Mynewt API": { 12 | "sensor::set_poll_rate_ms" : { "devname": "&Strn", "poll_rate": "u32" }, 13 | "sensor::mgr_find_next_bydevname" : { "devname": "&Strn", "prev_cursor": "*mut sensor" }, 14 | "sensor::register_listener" : { "sensor": "*mut sensor", "listener": "sensor_listener" }, 15 | "new_sensor_listener" : { "sl_sensor_type": "sensor_type_t", "sl_func": "sensor_data_func" } 16 | }, 17 | }; 18 | 19 | const pendingKey = Object.keys(tree)[0]; 20 | const knownKey = Object.keys(tree)[1]; 21 | let pendingNode: Node | undefined = undefined; 22 | let knownNode: Node | undefined = undefined; 23 | 24 | export function setPendingValue(pathkey: string, value: any) { 25 | // Set the value of this pending node. Return true if successfully set. 26 | const pathSplit = pathkey.split('|'); 27 | const parentPath = pathSplit.slice(0, -1).join('|'); 28 | const key = pathSplit[pathSplit.length - 1]; 29 | const parentTree = getTreeElement([pendingKey, parentPath].join('|')); 30 | // console.log('setPendingValue: ' + pathkey + ' / ' + JSON.stringify(parentTree)); 31 | if (!parentTree || parentTree[key] === undefined) { return false; } 32 | parentTree[key] = value; 33 | 34 | const node = getNode([pendingKey, pathkey].join('|')); 35 | if (node) { node.value = value; } 36 | 37 | if (provider) { provider.refresh(); } 38 | return true; 39 | } 40 | 41 | export function markPending(pathkey: string) { 42 | // Mark this pending node. 43 | const node = getNode([pendingKey, pathkey].join('|')); 44 | if (!node) { return; } 45 | 46 | // Unmark the previous pending node. 47 | if (pendingNode) { pendingNode.prefix = '✅ '; } 48 | pendingNode = node; 49 | 50 | // Mark the known node and refresh the display. 51 | node.prefix = '▶️ '; 52 | if (provider) { provider.refresh(); } 53 | } 54 | 55 | export function markKnown(pathkey: string) { 56 | // Mark this known node. 57 | const node = getNode([knownKey, pathkey].join('|')); 58 | if (!node) { return; } 59 | 60 | // Unmark the previous known node. 61 | if (knownNode) { knownNode.prefix = ''; } 62 | knownNode = node; 63 | 64 | // Mark the known node and refresh the display. 65 | node.prefix = '▶️ '; 66 | if (provider) { provider.refresh(); } 67 | } 68 | 69 | // List of nodes indexed by path e.g. `Mynewt API|sensor::set_poll_rate_ms|devname` 70 | let nodes: {[path: string]: Node} = {}; 71 | 72 | // Each node of the tree. `key` looks like ` 73 | class Node extends vscode.TreeItem { 74 | constructor( 75 | public readonly pathkey: string, 76 | public readonly key: string, 77 | public value: any, 78 | public prefix: string, 79 | public readonly collapsibleState: vscode.TreeItemCollapsibleState, 80 | public readonly command?: vscode.Command 81 | ) { 82 | super(`${prefix}${key}${(value === undefined) ? '' : (': ' + value)}`, collapsibleState); 83 | } 84 | 85 | set label(_: string) {} 86 | 87 | get label(): string { 88 | const { key, value, prefix } = this; 89 | return `${prefix}${key}${(value === undefined) ? '' : (': ' + value)}`; 90 | } 91 | 92 | get tooltip(): string { 93 | return `${this.prefix}${this.key}`; 94 | } 95 | 96 | get description(): string { 97 | return ''; 98 | } 99 | 100 | get icon(): string { 101 | return (this.collapsibleState === vscode.TreeItemCollapsibleState.None) 102 | ? 'string.svg' // Icon for no children 103 | : 'folder.svg'; // Icon for children 104 | } 105 | 106 | iconPath = { 107 | light: path.join(__filename, '..', '..', 'resources', 'light', this.icon), 108 | dark: path.join(__filename, '..', '..', 'resources', 'dark', this.icon) 109 | }; 110 | 111 | contextValue = 'Node'; 112 | } 113 | 114 | function getChildren(pathkey: string): string[] { 115 | // Return the paths of the child nodes. 116 | if (!pathkey) { 117 | return Object.keys(tree); 118 | } 119 | let treeElement = getTreeElement(pathkey); 120 | if (treeElement && typeof treeElement === 'object') { 121 | // Get the child keys. 122 | const childKeys = Object.keys(treeElement); 123 | // console.log('getChildren: ' + pathkey + JSON.stringify(treeElement)); 124 | // Append the child keys to the parent path. 125 | return childKeys.map(key => pathkey + '|' + key); 126 | } 127 | return []; 128 | } 129 | 130 | function getTreeElement(pathkey: string): any { 131 | // Return the subtree for the path e.g. `Mynewt API|sensor::set_poll_rate_ms|devname` 132 | // console.log('getTreeElement ' + pathkey); 133 | let parent = tree; 134 | // Split by `|` and walk the tree. 135 | let pathSplit = pathkey.split('|'); 136 | for (;;) { 137 | let key = pathSplit.shift(); 138 | if (key === undefined) { return null; } 139 | // console.log('getTreeElement key=' + key + ', parent=' + JSON.stringify(parent)); 140 | parent = parent[key]; 141 | if (parent === undefined) { return null; } 142 | if (pathSplit.length === 0) { return parent; } 143 | } 144 | return null; 145 | } 146 | 147 | function getNode(pathkey: string): Node { 148 | if (!nodes[pathkey]) { 149 | // Key is the last part of the path. 150 | let pathSplit = pathkey.split('|'); 151 | let key = pathSplit[pathSplit.length - 1]; 152 | let prefix = ''; 153 | const treeElement = getTreeElement(pathkey); 154 | // If this is a key/value, get the value. 155 | let value: any = undefined; 156 | if (treeElement && typeof treeElement !== 'object') { value = treeElement; } 157 | const collapsibleState = 158 | (treeElement && typeof treeElement === 'object' && Object.keys(treeElement).length) 159 | ? vscode.TreeItemCollapsibleState.Collapsed 160 | : vscode.TreeItemCollapsibleState.None; 161 | nodes[pathkey] = new Node(pathkey, key, value, prefix, collapsibleState); 162 | } 163 | return nodes[pathkey]; 164 | } 165 | 166 | class DeclarationsProvider implements vscode.TreeDataProvider { 167 | 168 | private _onDidChangeTreeData: vscode.EventEmitter = new vscode.EventEmitter(); 169 | readonly onDidChangeTreeData: vscode.Event = this._onDidChangeTreeData.event; 170 | 171 | getChildren(element?: Node): Thenable { 172 | const children = getChildren(element ? element.pathkey : "") 173 | .map(key => getNode(key)); 174 | return Promise.resolve(children); 175 | } 176 | 177 | getTreeItem(element: Node): vscode.TreeItem { 178 | const treeItem = getNode(element.pathkey); 179 | treeItem.id = element.pathkey; 180 | return treeItem; 181 | } 182 | 183 | refresh(): void { 184 | this._onDidChangeTreeData.fire(); 185 | } 186 | 187 | constructor(private workspaceRoot: string) {} 188 | } 189 | 190 | let provider: DeclarationsProvider | undefined = undefined; 191 | let treeView: vscode.TreeView | undefined = undefined; 192 | 193 | // Called when VSCode is activated 194 | export function activate(context: vscode.ExtensionContext) { 195 | // Create the Tree View. 196 | provider = new DeclarationsProvider(vscode.workspace.rootPath || ''); 197 | treeView = vscode.window.createTreeView('visualEmbeddedRustDeclarations', { 198 | treeDataProvider: provider 199 | }); 200 | 201 | // Register the commands. 202 | vscode.commands.registerCommand('visualEmbeddedRustDeclarations.refreshEntry', 203 | () => provider ? provider.refresh() : null); 204 | 205 | vscode.commands.registerCommand('extension.openPackageOnNpm', 206 | moduleName => vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(`https://www.npmjs.com/package/${moduleName}`))); 207 | 208 | vscode.commands.registerCommand('visualEmbeddedRustDeclarations.addEntry', 209 | () => vscode.window.showInformationMessage(`Successfully called add entry.`)); 210 | 211 | vscode.commands.registerCommand('visualEmbeddedRustDeclarations.editEntry', 212 | (node: Node) => vscode.window.showInformationMessage(`Successfully called edit entry on ${node.label}.`)); 213 | 214 | vscode.commands.registerCommand('visualEmbeddedRustDeclarations.deleteEntry', 215 | (node: Node) => vscode.window.showInformationMessage(`Successfully called delete entry on ${node.label}.`)); 216 | } -------------------------------------------------------------------------------- /media/vscode/storage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Visual Blocks Editor 4 | * 5 | * Copyright 2012 Google Inc. 6 | * https://developers.google.com/blockly/ 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | * @fileoverview Loading and saving blocks to VSCode 23 | * @author luppy@appkaki.com (Lee Lup Yuen) 24 | */ 25 | 'use strict'; 26 | 27 | // Create a namespace. 28 | var BlocklyStorage = {}; 29 | 30 | function initStorage(vscode) { // Pass in vscode so that we don't expose vscode to global space and cause security problems 31 | console.log('vscode/storage loaded'); 32 | 33 | /** 34 | * Backup code blocks to localStorage. 35 | * @param {!Blockly.WorkspaceSvg} workspace Workspace. 36 | * @private 37 | */ 38 | BlocklyStorage.backupBlocks_ = function(workspace) { 39 | console.log('backupBlocks_'); 40 | if ('localStorage' in window) { 41 | var xml = Blockly.Xml.workspaceToDom(workspace); 42 | // Gets the current URL, not including the hash. 43 | var url = window.location.href.split('#')[0]; 44 | // window.localStorage.setItem(url, Blockly.Xml.domToText(xml)); 45 | } 46 | }; 47 | 48 | /** 49 | * Bind the localStorage backup function to the unload event. 50 | * @param {Blockly.WorkspaceSvg=} opt_workspace Workspace. 51 | */ 52 | BlocklyStorage.backupOnUnload = function(opt_workspace) { 53 | console.log('backupOnUnload'); 54 | var workspace = opt_workspace || Blockly.getMainWorkspace(); 55 | window.addEventListener('unload', 56 | function() {BlocklyStorage.backupBlocks_(workspace);}, false); 57 | }; 58 | 59 | /** 60 | * Restore code blocks from VSCode. 61 | * @param {Blockly.WorkspaceSvg=} opt_workspace Workspace. 62 | */ 63 | BlocklyStorage.restoreBlocks = function(opt_workspace) { 64 | var url = window.location.href.split('#')[0]; 65 | console.log(['restoreBlocks', url]); 66 | vscode.postMessage({ 67 | command: 'restoreBlocks', 68 | url: url 69 | }); 70 | }; 71 | 72 | /** 73 | * Save blocks to database and return a link containing key to XML. 74 | * @param {Blockly.WorkspaceSvg=} opt_workspace Workspace. 75 | */ 76 | BlocklyStorage.link = function(opt_workspace) { 77 | console.log('link'); 78 | var workspace = opt_workspace || Blockly.getMainWorkspace(); 79 | var xml = Blockly.Xml.workspaceToDom(workspace, true); 80 | // Remove x/y coordinates from XML if there's only one block stack. 81 | // There's no reason to store this, removing it helps with anonymity. 82 | if (workspace.getTopBlocks(false).length == 1 && xml.querySelector) { 83 | var block = xml.querySelector('block'); 84 | if (block) { 85 | block.removeAttribute('x'); 86 | block.removeAttribute('y'); 87 | } 88 | } 89 | var data = Blockly.Xml.domToText(xml); 90 | BlocklyStorage.makeRequest_('/storage', 'xml', data, workspace); 91 | }; 92 | 93 | /** 94 | * Retrieve XML text from database using given key. 95 | * @param {string} key Key to XML, obtained from href. 96 | * @param {Blockly.WorkspaceSvg=} opt_workspace Workspace. 97 | */ 98 | BlocklyStorage.retrieveXml = function(key, opt_workspace) { 99 | console.log('retrieveXml'); 100 | var workspace = opt_workspace || Blockly.getMainWorkspace(); 101 | BlocklyStorage.makeRequest_('/storage', 'key', key, workspace); 102 | }; 103 | 104 | /** 105 | * Global reference to current AJAX request. 106 | * @type {XMLHttpRequest} 107 | * @private 108 | */ 109 | BlocklyStorage.httpRequest_ = null; 110 | 111 | /** 112 | * Fire a new AJAX request. 113 | * @param {string} url URL to fetch. 114 | * @param {string} name Name of parameter. 115 | * @param {string} content Content of parameter. 116 | * @param {!Blockly.WorkspaceSvg} workspace Workspace. 117 | * @private 118 | */ 119 | BlocklyStorage.makeRequest_ = function(url, name, content, workspace) { 120 | console.log('makeRequest_'); 121 | if (BlocklyStorage.httpRequest_) { 122 | // AJAX call is in-flight. 123 | BlocklyStorage.httpRequest_.abort(); 124 | } 125 | BlocklyStorage.httpRequest_ = new XMLHttpRequest(); 126 | BlocklyStorage.httpRequest_.name = name; 127 | BlocklyStorage.httpRequest_.onreadystatechange = 128 | BlocklyStorage.handleRequest_; 129 | BlocklyStorage.httpRequest_.open('POST', url); 130 | BlocklyStorage.httpRequest_.setRequestHeader('Content-Type', 131 | 'application/x-www-form-urlencoded'); 132 | BlocklyStorage.httpRequest_.send(name + '=' + encodeURIComponent(content)); 133 | BlocklyStorage.httpRequest_.workspace = workspace; 134 | }; 135 | 136 | /** 137 | * Callback function for AJAX call. 138 | * @private 139 | */ 140 | BlocklyStorage.handleRequest_ = function() { 141 | console.log('handleRequest_'); 142 | if (BlocklyStorage.httpRequest_.readyState == 4) { 143 | if (BlocklyStorage.httpRequest_.status != 200) { 144 | BlocklyStorage.alert(BlocklyStorage.HTTPREQUEST_ERROR + '\n' + 145 | 'httpRequest_.status: ' + BlocklyStorage.httpRequest_.status); 146 | } else { 147 | var data = BlocklyStorage.httpRequest_.responseText.trim(); 148 | if (BlocklyStorage.httpRequest_.name == 'xml') { 149 | window.location.hash = data; 150 | BlocklyStorage.alert(BlocklyStorage.LINK_ALERT.replace('%1', 151 | window.location.href)); 152 | } else if (BlocklyStorage.httpRequest_.name == 'key') { 153 | if (!data.length) { 154 | BlocklyStorage.alert(BlocklyStorage.HASH_ERROR.replace('%1', 155 | window.location.hash)); 156 | } else { 157 | BlocklyStorage.loadXml_(data, BlocklyStorage.httpRequest_.workspace); 158 | } 159 | } 160 | BlocklyStorage.monitorChanges_(BlocklyStorage.httpRequest_.workspace); 161 | } 162 | BlocklyStorage.httpRequest_ = null; 163 | } 164 | }; 165 | 166 | /** 167 | * Start monitoring the workspace. If a change is made that changes the XML, 168 | * update the VSCode document. 169 | * @param {!Blockly.WorkspaceSvg} workspace Workspace. 170 | * @private 171 | */ 172 | BlocklyStorage.monitorChanges_ = function(workspace) { 173 | console.log('monitorChanges_'); 174 | var startXmlDom = Blockly.Xml.workspaceToDom(workspace); 175 | var startXmlText = Blockly.Xml.domToText(startXmlDom); 176 | 177 | function generateCode() { 178 | // Generate the Rust code and send to VSCode. 179 | console.log('monitorChanges_generateCode'); 180 | var xmlDom = Blockly.Xml.workspaceToDom(workspace); 181 | var xmlText = Blockly.Xml.domToText(xmlDom); 182 | 183 | // Combine the code with the XML, enclosed by `BEGIN BLOCKS`...`END BLOCKS` tags. 184 | var code = Blockly.Rust.workspaceToCode(workspace); 185 | var text = composeDoc(xmlText, code); 186 | 187 | // Send the updated doc to VSCode to update the editor. 188 | vscode.postMessage({ 189 | command: 'updateDoc', 190 | text: text 191 | }); 192 | } 193 | 194 | function change() { 195 | // Callback for changes. Detect whether the Blocks XML has changed. If changed, regenerate the code. 196 | var xmlDom = Blockly.Xml.workspaceToDom(workspace); 197 | var xmlText = Blockly.Xml.domToText(xmlDom); 198 | if (startXmlText == xmlText) { return; } // No changes. 199 | 200 | // Generate the code. 201 | startXmlText = xmlText; 202 | console.log('monitorChanges_change'); 203 | generateCode(); 204 | } 205 | 206 | // Start monitoring for changes. 207 | workspace.addChangeListener(change); 208 | 209 | // On first load, regenerate the Rust code in case the code generator has been updated. 210 | generateCode(); 211 | }; 212 | 213 | /** 214 | * Load blocks from XML. 215 | * @param {string} xml Text representation of XML. 216 | * @param {!Blockly.WorkspaceSvg} workspace Workspace. 217 | * @private 218 | */ 219 | BlocklyStorage.loadXml_ = function(xml, workspace) { 220 | console.log('loadXml_'); 221 | try { 222 | xml = Blockly.Xml.textToDom(xml); 223 | } catch (e) { 224 | BlocklyStorage.alert(BlocklyStorage.XML_ERROR + '\nXML: ' + xml); 225 | return; 226 | } 227 | // Clear the workspace to avoid merge. 228 | workspace.clear(); 229 | Blockly.Xml.domToWorkspace(xml, workspace); 230 | }; 231 | 232 | /** 233 | * Present a text message to the user. 234 | * Designed to be overridden if an app has custom dialogs, or a butter bar. 235 | * @param {string} message Text to alert. 236 | */ 237 | BlocklyStorage.alert = function(message) { 238 | console.error(message); 239 | }; 240 | } -------------------------------------------------------------------------------- /resources/replay.log: -------------------------------------------------------------------------------- 1 | > Executing task in folder test-rust-macros: scripts/expand-macros.sh ; cargo build < 2 | 3 | + rustup default nightly 4 | info: using existing install for 'nightly-x86_64-apple-darwin' 5 | info: default toolchain set to 'nightly-x86_64-apple-darwin' 6 | 7 | nightly-x86_64-apple-darwin unchanged - rustc 1.37.0-nightly (5f9c0448d 2019-06-25) 8 | 9 | + cargo rustc -- -Z unstable-options --pretty expanded 10 | Compiling macros v0.1.0 (/Users/Luppy/mynewt/stm32bluepill-mynewt-sensor/rust/macros) 11 | Compiling mynewt v0.1.0 (/Users/Luppy/mynewt/stm32bluepill-mynewt-sensor/rust/mynewt) 12 | Compiling test-rust-macros v0.1.0 (/Users/Luppy/mynewt/test-rust-macros) 13 | Finished dev [unoptimized + debuginfo] target(s) in 3.86s 14 | Compiling test-rust-macros v0.1.0 (/Users/Luppy/mynewt/test-rust-macros) 15 | fname: "start_sensor_listener" 16 | para: "sensor" 17 | #s src/main.rs | 42 | 29 | 42 | 35 18 | para: "sensor_type" 19 | #s src/main.rs | 42 | 40 | 42 | 51 20 | para: "poll_time" 21 | #s src/main.rs | 42 | 56 | 42 | 65 22 | #s src/main.rs | 42 | 90 | 50 | 5 23 | #s src/main.rs | 43 | 8 | 43 | 55 24 | #s src/main.rs | 43 | 8 | 43 | 53 25 | #s src/main.rs | 43 | 8 | 43 | 51 26 | #s src/main.rs | 43 | 8 | 43 | 51 27 | fname: "sensor::set_poll_rate_ms" 28 | #m sensor::set_poll_rate_ms | src/main.rs | 43 | 8 | 43 | 51 29 | #s src/main.rs | 43 | 33 | 43 | 50 30 | sensor has inferred type &Strn 31 | #s src/main.rs | 43 | 33 | 43 | 39 32 | #i start_sensor_listener | sensor | sensor::set_poll_rate_ms | devname | &Strn 33 | poll_time has inferred type u32 34 | #s src/main.rs | 43 | 41 | 43 | 50 35 | #i start_sensor_listener | poll_time | sensor::set_poll_rate_ms | poll_rate | u32 36 | #s src/main.rs | 43 | 33 | 43 | 50 37 | #s src/main.rs | 43 | 8 | 43 | 51 38 | #s src/main.rs | 43 | 8 | 43 | 51 39 | #s src/main.rs | 43 | 8 | 43 | 53 40 | #s src/main.rs | 44 | 8 | 44 | 83 41 | #s src/main.rs | 44 | 28 | 44 | 81 42 | #s src/main.rs | 44 | 28 | 44 | 79 43 | #s src/main.rs | 44 | 28 | 44 | 79 44 | fname: "sensor::mgr_find_next_bydevname" 45 | #m sensor::mgr_find_next_bydevname | src/main.rs | 44 | 28 | 44 | 79 46 | #s src/main.rs | 44 | 60 | 44 | 78 47 | sensor has inferred type &Strn 48 | #s src/main.rs | 44 | 60 | 44 | 66 49 | #i start_sensor_listener | sensor | sensor::mgr_find_next_bydevname | devname | &Strn 50 | null_mut() has inferred type *mut sensor 51 | #s src/main.rs | 44 | 68 | 44 | 78 52 | #i start_sensor_listener | null_mut() | sensor::mgr_find_next_bydevname | prev_cursor | *mut sensor 53 | #s src/main.rs | 44 | 60 | 44 | 78 54 | #s src/main.rs | 44 | 28 | 44 | 79 55 | #s src/main.rs | 44 | 28 | 44 | 79 56 | #s src/main.rs | 44 | 28 | 44 | 81 57 | #s src/main.rs | 45 | 8 | 48 | 9 58 | #s src/main.rs | 45 | 8 | 48 | 9 59 | #s src/main.rs | 45 | 11 | 45 | 38 60 | #s src/main.rs | 45 | 11 | 45 | 24 61 | #s src/main.rs | 45 | 11 | 45 | 24 62 | #s src/main.rs | 45 | 28 | 45 | 38 63 | #s src/main.rs | 45 | 28 | 45 | 38 64 | fname: "null_mut" 65 | load_decls: test.json, "{\"send_sensor_data\":[[\"sensor_data\",\"&SensorValue\"]]}" 66 | #s src/main.rs | 45 | 28 | 45 | 38 67 | #s src/main.rs | 45 | 11 | 45 | 38 68 | #s src/main.rs | 45 | 39 | 48 | 9 69 | #s src/main.rs | 46 | 12 | 46 | 83 70 | #s src/main.rs | 46 | 27 | 46 | 81 71 | #s src/main.rs | 46 | 27 | 46 | 79 72 | #s src/main.rs | 46 | 27 | 46 | 79 73 | fname: "new_sensor_listener" 74 | #m new_sensor_listener | src/main.rs | 46 | 27 | 46 | 79 75 | #s src/main.rs | 46 | 47 | 46 | 78 76 | sensor_type has inferred type sensor_type_t 77 | #s src/main.rs | 46 | 47 | 46 | 58 78 | #i start_sensor_listener | sensor_type | new_sensor_listener | sl_sensor_type | sensor_type_t 79 | handle_sensor_data has inferred type sensor_data_func 80 | #s src/main.rs | 46 | 60 | 46 | 78 81 | #i start_sensor_listener | handle_sensor_data | new_sensor_listener | sl_func | sensor_data_func 82 | #s src/main.rs | 46 | 47 | 46 | 78 83 | #s src/main.rs | 46 | 27 | 46 | 79 84 | #s src/main.rs | 46 | 27 | 46 | 79 85 | #s src/main.rs | 46 | 27 | 46 | 81 86 | #s src/main.rs | 47 | 12 | 47 | 66 87 | #s src/main.rs | 47 | 12 | 47 | 64 88 | #s src/main.rs | 47 | 12 | 47 | 62 89 | #s src/main.rs | 47 | 12 | 47 | 62 90 | fname: "sensor::register_listener" 91 | #m sensor::register_listener | src/main.rs | 47 | 12 | 47 | 62 92 | #s src/main.rs | 47 | 38 | 47 | 61 93 | sensor_object has inferred type *mut sensor 94 | #s src/main.rs | 47 | 38 | 47 | 51 95 | #i start_sensor_listener | sensor_object | sensor::register_listener | sensor | *mut sensor 96 | listener has inferred type sensor_listener 97 | #s src/main.rs | 47 | 53 | 47 | 61 98 | #i start_sensor_listener | listener | sensor::register_listener | listener | sensor_listener 99 | #s src/main.rs | 47 | 38 | 47 | 61 100 | #s src/main.rs | 47 | 12 | 47 | 62 101 | #s src/main.rs | 47 | 12 | 47 | 62 102 | #s src/main.rs | 47 | 12 | 47 | 64 103 | #s src/main.rs | 45 | 39 | 48 | 9 104 | #s src/main.rs | 45 | 8 | 48 | 9 105 | #s src/main.rs | 49 | 8 | 49 | 14 106 | #s src/main.rs | 49 | 8 | 49 | 14 107 | #s src/main.rs | 49 | 8 | 49 | 14 108 | fname: "Ok" 109 | #s src/main.rs | 49 | 8 | 49 | 14 110 | #s src/main.rs | 42 | 90 | 50 | 5 111 | save_decls: test.json, "{\"start_sensor_listener\":[[\"sensor\",\"&Strn\"],[\"sensor_type\",\"sensor_type_t\"],[\"poll_time\",\"u32\"]],\"send_sensor_data\":[[\"sensor_data\",\"&SensorValue\"]]}" 112 | successfully wrote to test.json 113 | fname: "handle_sensor_data2" 114 | para: "sensor_data" 115 | #s src/main.rs | 55 | 27 | 55 | 38 116 | #s src/main.rs | 55 | 63 | 58 | 5 117 | #s src/main.rs | 56 | 8 | 56 | 41 118 | #s src/main.rs | 56 | 8 | 56 | 39 119 | #s src/main.rs | 56 | 8 | 56 | 37 120 | #s src/main.rs | 56 | 8 | 56 | 37 121 | fname: "send_sensor_data" 122 | #m send_sensor_data | src/main.rs | 56 | 8 | 56 | 37 123 | #s src/main.rs | 56 | 25 | 56 | 36 124 | sensor_data has inferred type &SensorValue 125 | #s src/main.rs | 56 | 25 | 56 | 36 126 | #i handle_sensor_data2 | sensor_data | send_sensor_data | sensor_data | &SensorValue 127 | #s src/main.rs | 56 | 25 | 56 | 36 128 | #s src/main.rs | 56 | 8 | 56 | 37 129 | #s src/main.rs | 56 | 8 | 56 | 37 130 | #s src/main.rs | 56 | 8 | 56 | 39 131 | #s src/main.rs | 57 | 8 | 57 | 14 132 | #s src/main.rs | 57 | 8 | 57 | 14 133 | #s src/main.rs | 57 | 8 | 57 | 14 134 | fname: "Ok" 135 | #s src/main.rs | 57 | 8 | 57 | 14 136 | #s src/main.rs | 55 | 63 | 58 | 5 137 | save_decls: test.json, "{\"handle_sensor_data2\":[[\"sensor_data\",\"&SensorValue\"]],\"send_sensor_data\":[[\"sensor_data\",\"&SensorValue\"]]}" 138 | successfully wrote to test.json 139 | fname: "send_sensor_data" 140 | para: "sensor_data" 141 | #s src/main.rs | 63 | 24 | 63 | 35 142 | #s src/main.rs | 63 | 60 | 74 | 5 143 | #s src/main.rs | 64 | 8 | 64 | 59 144 | #s src/main.rs | 64 | 24 | 64 | 57 145 | #s src/main.rs | 64 | 24 | 64 | 55 146 | #s src/main.rs | 64 | 24 | 64 | 55 147 | fname: "sensor_network::get_device_id" 148 | #s src/main.rs | 64 | 24 | 64 | 55 149 | #s src/main.rs | 64 | 24 | 64 | 57 150 | #s src/main.rs | 65 | 8 | 65 | 78 151 | #s src/main.rs | 65 | 28 | 65 | 76 152 | #s src/main.rs | 65 | 28 | 65 | 74 153 | #s src/main.rs | 65 | 28 | 65 | 74 154 | fname: "sensor_network::init_server_post" 155 | #s src/main.rs | 65 | 28 | 65 | 74 156 | #s src/main.rs | 65 | 28 | 65 | 76 157 | #s src/main.rs | 66 | 8 | 72 | 9 158 | #s src/main.rs | 66 | 8 | 72 | 9 159 | #s src/main.rs | 66 | 11 | 66 | 24 160 | #s src/main.rs | 66 | 11 | 66 | 24 161 | #s src/main.rs | 66 | 25 | 72 | 9 162 | #s src/main.rs | 67 | 12 | 70 | 15 163 | #s src/main.rs | 67 | 26 | 70 | 14 164 | #s src/main.rs | 67 | 26 | 70 | 14 165 | #m coap | src/main.rs | 67 | 26 | 70 | 14 166 | sensor_data has inferred type &SensorValue 167 | #i send_sensor_data | sensor_data | coap | singleton | &SensorValue 168 | #s src/main.rs | 67 | 26 | 70 | 14 169 | #s src/main.rs | 67 | 26 | 70 | 14 170 | #s src/main.rs | 71 | 12 | 71 | 48 171 | #s src/main.rs | 71 | 12 | 71 | 46 172 | #s src/main.rs | 71 | 12 | 71 | 44 173 | #s src/main.rs | 71 | 12 | 71 | 44 174 | fname: "sensor_network::do_server_post" 175 | #s src/main.rs | 71 | 12 | 71 | 44 176 | #s src/main.rs | 71 | 12 | 71 | 46 177 | #s src/main.rs | 66 | 25 | 72 | 9 178 | #s src/main.rs | 66 | 8 | 72 | 9 179 | #s src/main.rs | 73 | 8 | 73 | 14 180 | #s src/main.rs | 73 | 8 | 73 | 14 181 | #s src/main.rs | 73 | 8 | 73 | 14 182 | fname: "Ok" 183 | #s src/main.rs | 73 | 8 | 73 | 14 184 | #s src/main.rs | 63 | 60 | 74 | 5 185 | save_decls: test.json, "{\"send_sensor_data\":[[\"sensor_data\",\"&SensorValue\"]]}" 186 | successfully wrote to test.json 187 | error[E0308]: mismatched types 188 | --> src/main.rs:67:27 189 | | 190 | 67 | let payload = coap!( @json { 191 | | ___________________________^ 192 | 68 | | "device": &device_id, 193 | 69 | | sensor_data, 194 | 70 | | }); 195 | | |______________^ expected i8, found u8 196 | | 197 | = note: expected type `*const i8` 198 | found type `*const u8` 199 | = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 200 | 201 | error[E0308]: mismatched types 202 | --> src/main.rs:67:27 203 | | 204 | 67 | let payload = coap!( @json { 205 | | ___________________________^ 206 | 68 | | "device": &device_id, 207 | 69 | | sensor_data, 208 | 70 | | }); 209 | | |______________^ expected i8, found u8 210 | | 211 | = note: expected type `*const i8` 212 | found type `*const u8` 213 | = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 214 | 215 | error[E0308]: mismatched types 216 | --> src/main.rs:67:27 217 | | 218 | 67 | let payload = coap!( @json { 219 | | ___________________________^ 220 | 68 | | "device": &device_id, 221 | 69 | | sensor_data, 222 | 70 | | }); 223 | | |______________^ expected i8, found u8 224 | | 225 | = note: expected type `*const i8` 226 | found type `*const u8` 227 | = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 228 | 229 | error[E0308]: mismatched types 230 | --> src/main.rs:67:27 231 | | 232 | 67 | let payload = coap!( @json { 233 | | ___________________________^ 234 | 68 | | "device": &device_id, 235 | 69 | | sensor_data, 236 | 70 | | }); 237 | | |______________^ expected i8, found u8 238 | | 239 | = note: expected type `*const i8` 240 | found type `*const u8` 241 | = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 242 | 243 | error[E0308]: mismatched types 244 | --> src/main.rs:67:27 245 | | 246 | 67 | let payload = coap!( @json { 247 | | ___________________________^ 248 | 68 | | "device": &device_id, 249 | 69 | | sensor_data, 250 | 70 | | }); 251 | | |______________^ expected i8, found u8 252 | | 253 | = note: expected type `*const i8` 254 | found type `*const u8` 255 | = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 256 | 257 | error[E0308]: mismatched types 258 | --> src/main.rs:67:27 259 | | 260 | 67 | let payload = coap!( @json { 261 | | ___________________________^ 262 | 68 | | "device": &device_id, 263 | 69 | | sensor_data, 264 | 70 | | }); 265 | | |______________^ expected i8, found u8 266 | | 267 | = note: expected type `*const i8` 268 | found type `*const u8` 269 | = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 270 | 271 | error[E0308]: mismatched types 272 | --> src/main.rs:67:27 273 | | 274 | 67 | let payload = coap!( @json { 275 | | ___________________________^ 276 | 68 | | "device": &device_id, 277 | 69 | | sensor_data, 278 | 70 | | }); 279 | | |______________^ expected i8, found u8 280 | | 281 | = note: expected type `*const i8` 282 | found type `*const u8` 283 | = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 284 | 285 | error: aborting due to 7 previous errors 286 | 287 | For more information about this error, try `rustc --explain E0308`. 288 | error: Could not compile `test-rust-macros`. 289 | 290 | To learn more, run the command again with --verbose. 291 | The terminal process terminated with exit code: 101 292 | 293 | Terminal will be reused by tasks, press any key to close it. 294 | -------------------------------------------------------------------------------- /src/extension.ts: -------------------------------------------------------------------------------- 1 | // Need to install into `media` folder: `blockly-mynewt-rust`, `closure-library` 2 | 3 | // The module 'vscode' contains the VS Code extensibility API 4 | // Import the module and reference it with the alias vscode in your code below 5 | import * as vscode from 'vscode'; 6 | import * as fs from 'fs'; 7 | import * as path from 'path'; 8 | import * as web from './web'; 9 | import * as decorate from './decorate'; 10 | import * as declarations from './declarations'; 11 | import * as replay from './replay'; 12 | 13 | const cats = { 14 | 'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif', 15 | 'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif', 16 | 'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif' 17 | }; 18 | 19 | // Called when extension is activated, the very first time the command is executed 20 | export function activate(context: vscode.ExtensionContext) { 21 | console.log('visual-embedded-rust active: '); // console.log(context); 22 | // vscode.window.showInformationMessage('To edit visually, click the Rust source file'); 23 | 24 | context.subscriptions.push( 25 | vscode.commands.registerCommand('visualEmbeddedRust.start', () => { 26 | CatCodingPanel.createOrShow(context.extensionPath); 27 | }) 28 | ); 29 | 30 | context.subscriptions.push( 31 | vscode.commands.registerCommand('visualEmbeddedRust.doRefactor', () => { 32 | if (CatCodingPanel.currentPanel) { 33 | CatCodingPanel.currentPanel.doRefactor(); 34 | } 35 | }) 36 | ); 37 | 38 | if (vscode.window.registerWebviewPanelSerializer) { 39 | // Make sure we register a serializer in activation event 40 | vscode.window.registerWebviewPanelSerializer(CatCodingPanel.viewType, { 41 | async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel, state: any) { 42 | console.log(`Got state: ${state}`); 43 | CatCodingPanel.revive(webviewPanel, context.extensionPath); 44 | } 45 | }); 46 | } 47 | 48 | // The command has been defined in the package.json file 49 | // Now provide the implementation of the command with registerCommand 50 | // The commandId parameter must match the command field in package.json 51 | let disposable = vscode.commands.registerCommand('visualEmbeddedRust.helloWorld', () => { 52 | // The code you place here will be executed every time your command is executed 53 | 54 | // Display a message box to the user 55 | vscode.window.showInformationMessage('Hello World!'); 56 | }); 57 | 58 | context.subscriptions.push(disposable); 59 | 60 | // To enable replay, the following must be enabled... 61 | 62 | // Activate the decorators. 63 | // decorate.activate(context); 64 | 65 | // Activate the declaration view. 66 | // declarations.activate(context); 67 | 68 | // Disabled the replay log. 69 | // replay.activate(context); 70 | } 71 | 72 | /** 73 | * Manages cat coding webview panels 74 | */ 75 | class CatCodingPanel { 76 | /** 77 | * Track the currently panel. Only allow a single panel to exist at a time. 78 | */ 79 | public static currentPanel: CatCodingPanel | undefined; 80 | 81 | public static readonly viewType = 'visualEmbeddedRust'; 82 | 83 | private readonly _panel: vscode.WebviewPanel; 84 | private readonly _extensionPath: string; 85 | private _disposables: vscode.Disposable[] = []; 86 | private _editor: vscode.TextEditor | undefined; 87 | 88 | public static createOrShow(extensionPath: string) { 89 | console.log('createOrShow'); 90 | const column = (vscode.window.activeTextEditor && vscode.window.activeTextEditor.viewColumn) 91 | ? (vscode.window.activeTextEditor.viewColumn + 1) 92 | : undefined; 93 | 94 | // If we already have a panel, show it. 95 | if (CatCodingPanel.currentPanel) { 96 | CatCodingPanel.currentPanel._panel.reveal(column); 97 | return; 98 | } 99 | 100 | // Otherwise, create a new panel. 101 | const panel = vscode.window.createWebviewPanel( 102 | CatCodingPanel.viewType, 103 | 'Cat Coding', 104 | column || vscode.ViewColumn.One, 105 | { 106 | // Enable javascript in the webview 107 | enableScripts: true, 108 | 109 | // And restrict the webview to only loading content from our extension's `media` directory. 110 | localResourceRoots: [vscode.Uri.file(path.join(extensionPath, 'media'))] 111 | } 112 | ); 113 | 114 | CatCodingPanel.currentPanel = new CatCodingPanel(panel, extensionPath); 115 | } 116 | 117 | public static revive(panel: vscode.WebviewPanel, extensionPath: string) { 118 | console.log('revive'); 119 | CatCodingPanel.currentPanel = new CatCodingPanel(panel, extensionPath); 120 | } 121 | 122 | private constructor(panel: vscode.WebviewPanel, extensionPath: string) { 123 | this._panel = panel; 124 | this._extensionPath = extensionPath; 125 | 126 | // Set the webview's initial html content 127 | this._update(); 128 | 129 | // Listen for when the panel is disposed 130 | // This happens when the user closes the panel or when the panel is closed programatically 131 | this._panel.onDidDispose(() => this.dispose(), null, this._disposables); 132 | 133 | // Update the content based on view changes 134 | this._panel.onDidChangeViewState( 135 | e => { 136 | console.log('onDidChangeViewState'); 137 | if (this._panel.visible) { 138 | this._update(); 139 | } 140 | }, 141 | null, 142 | this._disposables 143 | ); 144 | 145 | // Handle messages from the webview 146 | this._panel.webview.onDidReceiveMessage( 147 | message => { 148 | console.log(JSON.stringify({onDidReceiveMessage: JSON.stringify(message).substr(0, 50)})); 149 | switch (message.command) { 150 | case 'alert': { 151 | vscode.window.showErrorMessage(message.text); 152 | return; 153 | } 154 | 155 | // Restore code blocks. Read the contexts of the active text editor and send to webview to load. 156 | case 'restoreBlocks': { 157 | // Get the active text editor. If none active, return the last active one. 158 | let editor = vscode.window.activeTextEditor; 159 | if (!editor || !CatCodingPanel._isValidEditor(editor)) { 160 | editor = this._editor; 161 | if (!editor || !CatCodingPanel._isValidEditor(editor)) { 162 | editor = vscode.window.visibleTextEditors[0]; 163 | if (!editor || !CatCodingPanel._isValidEditor(editor)) { 164 | console.log('No active editor'); return; 165 | } 166 | } 167 | } 168 | const webview = this._panel.webview; 169 | 170 | // Send a `loadDoc` message to our webview with the text. 171 | function loadDoc(text0: string) { 172 | webview.postMessage({ 173 | command: 'loadDoc', 174 | text: text0, 175 | }); 176 | } 177 | 178 | // Get the text of the doc. If file is not empty, send a `loadDoc` message to our webview with the text. 179 | const text = editor.document.getText(); 180 | if (text.length > 0) { 181 | loadDoc(text); 182 | // Remember the active text editor. We will return this at the next call. 183 | this._editor = editor; 184 | return; 185 | } 186 | 187 | // If file is empty, populate with template. 188 | vscode.window.showInformationMessage('Populate empty Rust file with Visual Embedded Rust program?', 'OK', 'Cancel') 189 | .then(selected => { 190 | if (selected !== 'OK') { return; } 191 | if (!editor) { return; } 192 | const replayPath = path.join(__filename, '..', '..', 'resources', 'template.rs'); 193 | const buf = fs.readFileSync(replayPath); 194 | const template = buf.toString(); 195 | editor.edit(editBuilder => { 196 | // Populate the template and notify webview. 197 | editBuilder.insert(new vscode.Position(0, 0), template); 198 | loadDoc(template); 199 | }); 200 | }); 201 | } 202 | 203 | // Update the Visual Rust document with the generated Rust code and the updated blocks XML. 204 | case 'updateDoc': { 205 | const newText = message.text; 206 | let editor = this._editor; 207 | if (!editor || !CatCodingPanel._isValidEditor(editor)) { console.log('No editor to update'); return; } 208 | editor.edit(editBuilder => { 209 | // Get the range of the entire doc. 210 | if (!editor) { console.log('Missing editor'); return; } 211 | const document = editor.document; 212 | const text = document.getText(); 213 | if (!text) { console.log('Missing text'); return; } 214 | const range = new vscode.Range( 215 | new vscode.Position(0, 0), 216 | document.positionAt(text.length) 217 | ); 218 | // Replace the range by the new text. 219 | editBuilder.replace(range, newText); 220 | }); 221 | return; 222 | } 223 | 224 | // Show an OK/Cancel confirmation message. Post the result (true for OK) back to WebView. 225 | case 'confirm': { 226 | const msg = message.message; 227 | vscode.window.showInformationMessage(msg, 'OK', 'Cancel') 228 | .then(selected => this._panel.webview.postMessage({ 229 | command: 'confirmResult', 230 | result: (selected === 'OK'), 231 | })); 232 | return; 233 | } 234 | 235 | // Prompt for input. Post the result back to WebView. 236 | case 'prompt': { 237 | const msg = message.message; 238 | const defaultValue = message.defaultValue; 239 | vscode.window.showInputBox({ 240 | prompt: message, 241 | value: defaultValue, 242 | }) 243 | .then(result => this._panel.webview.postMessage({ 244 | command: 'promptResult', 245 | result: result, 246 | })); 247 | return; 248 | } 249 | 250 | default: console.error('Unknown message: ' + JSON.stringify(message)); 251 | } 252 | }, 253 | null, 254 | this._disposables 255 | ); 256 | } 257 | 258 | public doRefactor() { 259 | // Send a message to the webview webview. 260 | // You can send any JSON serializable data. 261 | this._panel.webview.postMessage({ command: 'refactor' }); 262 | } 263 | 264 | public dispose() { 265 | CatCodingPanel.currentPanel = undefined; 266 | 267 | // Clean up our resources 268 | this._panel.dispose(); 269 | 270 | while (this._disposables.length) { 271 | const x = this._disposables.pop(); 272 | if (x) { 273 | x.dispose(); 274 | } 275 | } 276 | } 277 | 278 | private static _isValidEditor(editor: vscode.TextEditor): boolean { 279 | // Return true if this is a valid TextEditor with a valid *.rs Visual Rust program. 280 | // If filename is not *.rs, reuse the last active editor. 281 | if (!editor.document) { console.log('Missing document'); return false; } 282 | const filename = editor.document.fileName; 283 | if (!filename) { console.log('Missing filename'); return false; } 284 | if (!filename.endsWith(".rs") && !filename.endsWith(".RS")) { console.log('Not a .rs file'); return false; } 285 | 286 | // Get the text of the doc. 287 | // const text = editor.document.getText(); 288 | // if (!text) { console.log('Missing text'); return false; } 289 | return true; 290 | } 291 | 292 | private _update() { 293 | const z = 1 + 2; 294 | // Vary the webview's content based on where it is located in the editor. 295 | switch (this._panel.viewColumn) { 296 | case vscode.ViewColumn.Two: 297 | this._updateForCat('Compiling Cat'); 298 | return; 299 | 300 | case vscode.ViewColumn.Three: 301 | this._updateForCat('Testing Cat'); 302 | return; 303 | 304 | case vscode.ViewColumn.One: 305 | default: 306 | this._updateForCat('Coding Cat'); 307 | return; 308 | } 309 | } 310 | 311 | private _updateForCat(catName: keyof typeof cats) { 312 | this._panel.title = 'Visual Embedded Rust'; 313 | this._panel.webview.html = this._getHtmlForWebview(cats[catName]); 314 | } 315 | 316 | private _getHtmlForWebview(catGif: string) { 317 | // Local path to main script run in the webview 318 | const scriptPathOnDisk = vscode.Uri.file( 319 | path.join(this._extensionPath, 'media') 320 | ); 321 | // Parameters for the HTML 322 | const scriptUri = scriptPathOnDisk.with({ scheme: 'vscode-resource' }); 323 | const para = { 324 | // URIs we use to load this script in the webview 325 | vscodeUri: scriptUri + '/vscode', // VSCode integration scripts 326 | blocklyUri: scriptUri + '/blockly-mynewt-rust', // Blockly scripts 327 | 328 | // Use a nonce to whitelist which scripts can be run 329 | nonce: getNonce(), 330 | }; 331 | // Return the HTML with the parameters embedded. 332 | return web.getHtml(para); 333 | } 334 | } 335 | 336 | function getNonce() { 337 | let text = ''; 338 | const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; 339 | for (let i = 0; i < 32; i++) { 340 | text += possible.charAt(Math.floor(Math.random() * possible.length)); 341 | } 342 | return text; 343 | } 344 | 345 | // this method is called when your extension is deactivated 346 | export function deactivate() {} 347 | -------------------------------------------------------------------------------- /src/web.ts: -------------------------------------------------------------------------------- 1 | // HTML content for the web view 2 | 3 | export function getHtml(para: any) { 4 | // Return the HTML content for the web view. Derived from media/blockly-mynewt-rust/demos/code/index.html, customised for VSCode 5 | // TODO: Add security policy 6 | return ` 7 | 8 | 9 | 10 | 11 | Visual Rust for PineTime Smart Watch 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 87 | 91 | 92 | 93 | 125 | 126 | 127 | 129 | 130 |
82 |

83 | 84 | ... 85 |

86 |
88 | 89 | 90 |
94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 122 | 123 |
... Rust XML 112 | 115 | 118 | 121 |
124 |
128 |
131 |
132 |

133 |     

134 |     

135 |     

136 |     

137 |     

138 |     
139 | 
140 |     
485 | 
486 | 
487 | 		
488 | `;
489 | }
490 | 
491 | /* TODO: Set content security policy
492 | return `
493 |     
494 |     
495 |         
496 | 
497 |         
501 |         
502 | 
503 |         
504 |         Cat Coding
505 |     
506 |     
507 |         
508 |         

0

509 | 510 | 511 | 512 | `; 513 | */ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | UPDATE: This code in this article has been archived in the [pre-lvgl branch of pinetime-rust-mynewt](https://github.com/lupyuen/pinetime-rust-mynewt/tree/pre-lvgl). The [pinetime-rust-mynewt firmware](https://github.com/lupyuen/pinetime-rust-mynewt) has been revamped to support [Rust Watch Faces on LVGL](https://lupyuen.github.io/pinetime-rust-mynewt/articles/watchface). [Check out the updates](https://lupyuen.github.io/pinetime-rust-mynewt/articles/watchface) 2 | 3 | # visual-embedded-rust 4 | 5 | - Create and edit Embedded Rust programs visually by dragging and dropping blocks 6 | 7 | - Generates Embedded Rust firmware code for [__PineTime Smart Watch__](https://wiki.pine64.org/index.php/PineTime) hosted on [__Apache Mynewt__](https://mynewt.apache.org/) realtime operating system, with [__druid UI Framework__](https://github.com/lupyuen/druid-embedded) 8 | 9 | - Hardware Required: PineTime Smart Watch and Raspberry Pi (preferably Pi 4 with Raspbian) 10 | 11 | ![Demo](images/demo.gif) 12 | 13 | ![Visual Embedded Rust](images/animation.gif) 14 | 15 | # Connect PineTime to Raspberry Pi 16 | 17 | 1️⃣ Carefully pry open the PineTime casing. Use tweezers to pivot the shiny battery gently to the side. Be careful not to break the red and black wires that connect the battery to the watch! 18 | 19 | 2️⃣ Just above the battery we see 4 shiny rings. This is the __[Serial Wire Debug](https://en.wikipedia.org/wiki/JTAG#Serial_Wire_Debug) (SWD)__ Port for PineTime. We’ll use this port to flash our firmware to PineTime. The 4 pins (from left to right) are SWDIO (Data I/O), SWDCLK (Clock), 3.3V, GND. 20 | 21 | 🛈 [_What is “flash memory” / “flashing” / “firmware”? Read this_](https://gist.github.com/lupyuen/41fffaddade277d27c48697bca21d837) 22 | 23 | ![SWD Port on PineTime](images/pinetime-swd3.jpg) 24 | 25 | In the above photo, the SWD pins from left to right are… 26 | 27 | 1. __SWDIO__ (Yellow) 28 | 29 | 1. __SWDCLK__ (Blue) 30 | 31 | 1. __3.3V__ (Red) 32 | 33 | 1. __GND__ (Black) 34 | 35 | The exposed copper wire at the top centre of the photo is the Bluetooth antenna. Bend it upwards so that it doesn’t come into contact with anything. 36 | 37 | ![Bend PineTime antenna](images/pinetime-antenna.png) 38 | 39 | 3️⃣ At lower right we see a pad marked 5V. We’ll connect this pad to Raspberry Pi to charge the battery. If charging of the battery is not needed during development, we may leave5V disconnected. 40 | 41 | 4️⃣ Connect the SWD Port and the 5V Pad (optional) to the Raspberry Pi with [__Solid-Core Wire (22 AWG)__](https://www.adafruit.com/product/288) and [__Female-To-Female Jumper Cables__](https://www.adafruit.com/product/1951)… 42 | 43 | | PineTime | Raspberry Pi | Wire Colour | 44 | | :--- | :--- | :--- | 45 | | `SWDIO` | `Header Pin 19 (MOSI)` | Yellow | 46 | | `SWDCLK` | `Header Pin 23 (SCLK)` | Blue | 47 | | `3.3V` | `3.3V` | Red | 48 | | `GND` | `GND` | Black | 49 | | `5V` | `5V` | Green (Optional) | 50 | 51 | ![Raspberry Pi Pinout](images/pinetime-pi-pinout-spi.png) 52 | 53 | _Based on https://pinout.xyz/_ 54 | 55 | 5️⃣ We may use Raspberry Pi Zero, 1, 2, 3 or 4. 56 | 57 | ![Raspberry Pi Pinout](images/pi-spi-pin.jpg) 58 | 59 | 6️⃣ The PineTime touchscreen needs to be accessible during development, so I mounted PineTime on a [$2 clear box cover from Daiso](https://www.daisojapan.com/p-30955-clear-box-28-x-47-x-19-x-in-12pks.aspx) with Blu Tack and sticky tape. 60 | 61 | ![Connecting PineTime to Raspberry Pi](images/pi-spi-pinetime-small.jpg) 62 | 63 | # Remove PineTime Flash Protection 64 | 65 | PineTime is shipped with preloaded demo firmware. We need to erase the demo firmware and unprotect PineTime’s flash memory so that we may flash our own firmware. 66 | 67 | 🛈 [_What is “flash protection”? Read this_](https://gist.github.com/lupyuen/3ee440542853e1e637582c4efa1b240a) 68 | 69 | 1️⃣ Power on the Raspberry Pi. Open a command prompt and enter the following… 70 | 71 | ```bash 72 | sudo raspi-config 73 | ``` 74 | 75 | Select `Interfacing Options → SPI → Yes` 76 | 77 | Select `Finish` 78 | 79 | At the command prompt, enter the following… 80 | 81 | ```bash 82 | # Remove folders ~/pinetime-rust-mynewt and ~/openocd-spi (if they exist) 83 | rm -rf ~/pinetime-rust-mynewt 84 | rm -rf ~/openocd-spi 85 | 86 | # Download and extract "pinetime-rust-mynewt" folder containing our prebuilt firmware, source files and flashing scripts 87 | sudo apt install -y wget p7zip-full 88 | cd ~ 89 | wget https://github.com/lupyuen/pinetime-rust-mynewt/releases/download/v3.0.3/pinetime-rust-mynewt.7z 90 | 7z x pinetime-rust-mynewt.7z 91 | rm pinetime-rust-mynewt.7z 92 | 93 | # Install build tools for PineTime: VSCode, Rust, gcc, gdb, openocd-spi, newt 94 | cd ~/pinetime-rust-mynewt 95 | scripts/install-pi.sh 96 | 97 | # Latest nightly-2020-04-20 fails with asm error, so we use nightly-2020-02-16 98 | source $HOME/.cargo/env 99 | rustup default nightly-2020-02-16 100 | rustup update 101 | rustup target add thumbv7em-none-eabihf 102 | ``` 103 | 104 | 2️⃣ At the `Welcome to Rust!` prompt, press Enter to select the default option: 105 | 106 | `1) Proceed with installation (default)` 107 | 108 | If you see this error… 109 | 110 | ``` 111 | Cloning into 'openocd-spi/jimtcl'... 112 | fatal: unable to access 'http://repo.or.cz/r/jimtcl.git/': Recv failure: Connection reset by peer 113 | fatal: clone of 'http://repo.or.cz/r/jimtcl.git' into submodule path '/private/tmp/aa/openocd-spi/jimtcl' failed 114 | ``` 115 | 116 | It means that the sub-repository for one of the dependencies jimtcl is temporarily down. You may download the pre-built `openocd-spi` binaries [from this link](https://github.com/lupyuen/pinetime-rust-mynewt/releases/download/openocd-spi2/openocd-spi.7z). Then copy the executable openocd-spi/src/openocd to pinetime-rust-mynewt/openocd/bin/openocd 117 | 118 | 3️⃣ When the installation has completed, enter the following at the command prompt… 119 | 120 | ```bash 121 | # Remove flash protection from PineTime and erase demo firmware 122 | cd ~/pinetime-rust-mynewt 123 | scripts/nrf52-pi/flash-unprotect.sh 124 | ``` 125 | 126 | 4️⃣ We should see `Shut Down And Power Off Your Raspberry Pi`… 127 | 128 | ![Unprotect Flash ROM](https://lupyuen.github.io/images/flash-unprotect.png) 129 | 130 | If we see `Clock Speed` and nothing else after that… 131 | 132 | ``` 133 | Info : BCM2835 SPI SWD driver 134 | Info : SWD only mode enabled 135 | Info : clock speed 31200 kHz 136 | Info : SWD DPIDR 0x2ba01477 137 | ``` 138 | 139 | Then the connection to the SWD Port is probably loose, please check the pins. 140 | 141 | If we don't see this `DPIDR` number, or if we see a different `DPIDR` number... 142 | 143 | ``` 144 | SWD DPIDR 0x2ba01477 145 | ``` 146 | 147 | Then the connection to the SWD Port is most likely loose, please check the pins. 148 | 149 | Also enter `sudo raspi-config` and confirm that the SPI port has been enabled. 150 | 151 | If we see this instead… 152 | 153 | ``` 154 | openocd/bin/openocd: cannot execute binary file: Exec format error 155 | ``` 156 | 157 | Then `install-pi.sh` probably didn’t run correctly. To fix this, copy the `openocd` executable like this… 158 | 159 | ```bash 160 | cp $HOME/openocd-spi/src/openocd $HOME/pinetime-rust-mynewt/openocd/bin/openocd 161 | ``` 162 | 163 | 5️⃣ Shut down and power off your Raspberry Pi. Wait 30 seconds for the red and green LEDs on your Pi to turn off. Power on your Pi. Enter the same commands at a command prompt… 164 | 165 | ```bash 166 | # Remove flash protection from PineTime and erase demo firmware 167 | cd ~/pinetime-rust-mynewt 168 | scripts/nrf52-pi/flash-unprotect.sh 169 | ``` 170 | 171 | 6️⃣ We should see `Flash Is Already Unprotected`… 172 | 173 | PineTime’s demo firmware has been erased and the flash protection has been removed. 174 | 175 | 🛈 [_What is OpenOCD? Why Raspberry Pi and not ROCK64 or Nvidia Jetson Nano? Read this_](https://gist.github.com/lupyuen/18e66c3e81e11050a10d1192c5b84bb0) 176 | 177 | # Edit The Visual Rust Application 178 | 179 | We shall be using VSCode with the Visual Embedded Rust Extension to edit our Visual Rust application graphically. 180 | 181 | 🛈 [_What is VSCode? Is it related to Visual Studio? How is Microsoft involved? Read this_](https://gist.github.com/lupyuen/08e383845d68d3337747e8eb59d0f624) 182 | 183 | 1️⃣ Launch VSCode by clicking the Raspberry Pi Menu (top left corner) → Programming → Code OSS Headmelted 184 | 185 | In VSCode, click `File → Open Folder` 186 | 187 | Under `Home`, select the folder `pinetime-rust-mynewt` and click OK 188 | 189 | When prompted to open the workspace, click Open Workspace 190 | 191 | When prompted to install Extension Recommendations, click `Install All` 192 | 193 | Ignore the message `Unable To Watch For File Changes`. Close the message when it appears. 194 | 195 | 2️⃣ Install the `Visual Embedded Rust` Extension... 196 | 197 | Click `View → Extensions` 198 | 199 | Search for `Visual Embedded Rust` 200 | 201 | Install the extension 202 | 203 | 3️⃣ Enable the Visual Rust application... 204 | 205 | Browse to `rust/app/Cargo.toml` 206 | 207 | Modify the file such that `visual_app` is uncommented and the other options are commented out... 208 | 209 | ```yaml 210 | default = [ # Select the conditional compiled features 211 | # "display_app", # Disable graphics display app 212 | # "ui_app", # Disable druid UI app 213 | "visual_app", # Enable Visual Rust app 214 | # "use_float", # Disable floating-point for GPS geolocation 215 | ] 216 | ``` 217 | 218 | 4️⃣ Edit the Visual Rust application... 219 | 220 | Browse to [`rust/app/src/visual.rs`](https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/rust/app/src/visual.rs) 221 | 222 | Click `Visual Editor` at top right 223 | 224 | ![Click Visual Editor](images/install3.png) 225 | 226 | Use the Visual Editor to edit the Visual Rust application 227 | 228 | ![Editing the Visual Rust application](images/animation.gif) 229 | 230 | 5️⃣ After editing, save the [`visual.rs`](https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/rust/app/src/visual.rs) source file to save the visual program. Don't edit the Rust source file manually, always use the Visual Editor. 231 | 232 | [_Rust Source Code generated from Visual Rust application_](https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/rust/app/src/visual.rs) 233 | 234 | The Visual Rust application shows a button that increments a counter... 235 | 236 | ![Demo](images/demo.gif) 237 | 238 | Let's look at the blocks in the Visual Rust application... 239 | 240 | # On Start 241 | 242 | ![On Start Block](images/animation1.gif) 243 | 244 | Upon starting the Watch App, we initialise the `count` variable to 0. 245 | 246 | This block generates the following Rust code... 247 | 248 | ```rust 249 | /// Application State 250 | #[infer_type] // Infer the missing types 251 | #[derive(Clone, Data, Default)] 252 | struct State { 253 | count: _, 254 | } 255 | 256 | /// Will be run upon startup to launch the app 257 | #[infer_type] // Infer the missing types 258 | pub fn on_start() -> MynewtResult<()> { 259 | console::print("on_start\n"); 260 | // Build a new window 261 | let main_window = WindowDesc::new(ui_builder); 262 | // Create application state 263 | let mut state = State::default(); 264 | state.count = 0; 265 | 266 | // Launch the window with the application state 267 | AppLauncher::with_window(main_window) 268 | .use_simple_logger() 269 | .launch(state) 270 | .expect("launch failed"); 271 | // Return success to `main()` function 272 | Ok(()) 273 | } 274 | ``` 275 | 276 | # Create App 277 | 278 | ![Create App Block](images/animation2.gif) 279 | 280 | We create a Watch App with two Widgets... 281 | 282 | 1. A Label named `my_label` surrounded by padding of 5 pixels 283 | 284 | 1. A Button named `my_button` with the title `Press Me`, surrounded by padding of 5 pixels 285 | 286 | This block generates the following Rust code... 287 | 288 | ```rust 289 | /// Build the UI for the window 290 | #[infer_type] // Infer the missing types 291 | fn ui_builder() -> impl Widget { // `State` is the Application State 292 | console::print("Rust UI builder\n"); console::flush(); 293 | // Create a line of text 294 | // Call `on_my_label_show` to get label text 295 | let my_label_text = LocalizedString::new("hello-counter") 296 | .with_arg("count", on_my_label_show); 297 | // Create a label widget `my_label` 298 | let my_label = Label::new(my_label_text); 299 | // Create a button widget `my_button` 300 | // Call `on_my_button_press` when pressed 301 | let my_button = Button::new("Press Me", on_my_button_press); 302 | 303 | // Create a column 304 | let mut col = Column::new(); 305 | // Add the label widget to the column, centered with padding 306 | col.add_child( 307 | Align::centered( 308 | Padding::new(5.0, 309 | my_label 310 | ) 311 | ), 312 | 1.0 313 | ); 314 | // Add the button widget to the column, with padding 315 | col.add_child( 316 | Padding::new(5.0, 317 | my_button 318 | ), 319 | 1.0 320 | ); 321 | // Return the column containing the widgets 322 | col 323 | } // ; 324 | ``` 325 | 326 | # On Label Show 327 | 328 | ![On Label Show Block](images/animation3.gif) 329 | 330 | This block is called to generate the text that will be shown on the label `my_label`. 331 | 332 | We return the variable `count` for display on the label. 333 | 334 | This block generates the following Rust code... 335 | 336 | ```rust 337 | /// Callback function that will be called to create the formatted text for the label `my_label` 338 | #[infer_type] // Infer the missing types 339 | fn on_my_label_show(state: _, env: _) -> ArgValue { 340 | console::print("on_my_label_show\n"); 341 | state.count.into() 342 | } 343 | ``` 344 | 345 | # On Button Press 346 | 347 | ![On Button Press Block](images/animation4.gif) 348 | 349 | This block is called to when the button `my_button` is pressed. 350 | 351 | We increment the variable `count` by 1. 352 | 353 | This block generates the following Rust code... 354 | 355 | ```rust 356 | /// Callback function that will be called when the button `my_button` is pressed 357 | #[infer_type] // Infer the missing types 358 | fn on_my_button_press(ctx: _, state: _, env: _) { 359 | console::print("on_my_button_press\n"); 360 | state.count = state.count + 1; 361 | } 362 | ``` 363 | 364 | # Build And Flash The Firmware 365 | 366 | We’ll be flashing the PineTime firmware that’s based on open-source [__Apache Mynewt embedded operating system__](https://mynewt.apache.org/). Mynewt OS contains two components that we shall flash to PineTime… 367 | 368 | __Mynewt Bootloader__: This is the C code that’s run whenever we power on PineTime. The Bootloader executes the Mynewt Application upon startup. 369 | 370 | __Mynewt Application__: Contains a Rust application that controls the PineTime functions, and low-level system functions written in C. 371 | 372 | The Bootloader and Application firmware image files may be found at these locations… 373 | 374 | | Mynewt Component | Flash Memory Address | Location of Firmware Image | 375 | | :--- | :--- | :--- | 376 | | Bootloader | `0x0` | `~/pinetime-rust-mynewt/bin/targets/nrf52_boot/app/apps/boot_stub/boot_stub.elf.bin` | 377 | | Application | `0x8000` | `~/pinetime-rust-mynewt/bin/targets/nrf52_my_sensor/app/apps/my_sensor_app/my_sensor_app.img` | 378 | 379 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/hw/bsp/nrf52/bsp.yml_ 380 | 381 | 🛈 [_What is a Bootloader? Read this_](https://gist.github.com/lupyuen/93ba71e0ae5e746e7a68e4513e0a54d8) 382 | 383 | 1️⃣ At the lower left corner, there is a panel `Task Runner`. Click the panel to display the build and flash tasks. 384 | 385 | 2️⃣ In the Task Runner, click `[1] Build Bootloader` 386 | 387 | When the Terminal Panel appears, right-click the `Terminal` tab, select `Move Panel Right` 388 | 389 | After the building the Bootloader, we should see `Done` 390 | 391 | Ignore the message `There Are Task Errors` 392 | 393 | The Bootloader only needs to be built once. 394 | 395 | 3️⃣ In the Task Runner, click `[2] Build Application` 396 | 397 | After the building the Application, we should see `Done` 398 | 399 | If you see the message `Undefined Reference To Main`, click `[2] Build Application` again and it should succeed. 400 | 401 | The Application needs to be rebuilt whenever a source file has been changed. 402 | 403 | 4️⃣ In the Task Runner, click `[3] Image Application` 404 | 405 | After the creating the Firmware Image, we should see `Done` 406 | 407 | 5️⃣ In the Task Runner, click `[4] Flash Bootloader` 408 | 409 | After flashing the Bootloader Firmware to PineTime, we should see `Done` 410 | 411 | 412 | ``` 413 | Flashing Bootloader... 414 | target halted due to debug-request, current mode: Thread 415 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000 416 | Enabled ARM Semihosting to show debug output 417 | ** Programming Started ** 418 | Info : nRF52832-QFAA(build code: E1) 512kB Flash, 64kB RAM 419 | Warn : Adding extra erase range, 0x00000b78 .. 0x00000fff 420 | ** Programming Finished ** 421 | ** Verify Started ** 422 | ** Verified OK ** 423 | 424 | Restarting... 425 | target halted due to debug-request, current mode: Thread 426 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000, semihosting 427 | 428 | **** Done! 429 | ``` 430 | 431 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/logs/load-bootloader-pi.log_ 432 | 433 | The Bootloader only needs to be flashed once. 434 | 435 | 6️⃣ In the Task Runner, click `[5] Flash Application` 436 | 437 | After the flashing the Application Firmware to PineTime, we should see `Done! Press Ctrl-C To Exit`… 438 | 439 | ``` 440 | Flashing Application... 441 | target halted due to debug-request, current mode: Thread 442 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000 443 | Enabled ARM Semihosting to show debug output 444 | ** Programming Started ** 445 | Info : nRF52832-QFAA(build code: E1) 512kB Flash, 64kB RAM 446 | Warn : Adding extra erase range, 0x0003e820 .. 0x0003efff 447 | ** Programming Finished ** 448 | ** Verify Started ** 449 | ** Verified OK ** 450 | 451 | Restarting... 452 | target halted due to debug-request, current mode: Thread 453 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000, semihosting 454 | Enabled ARM Semihosting to show debug output 455 | 456 | **** Done! Press Ctrl-C to exit... 457 | ``` 458 | 459 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/logs/load-application-pi.log_ 460 | 461 | 7️⃣ Our Visual Rust application starts running on PineTime 462 | 463 | ![Demo](images/demo.gif) 464 | 465 | 8️⃣ Click the Trash icon 🗑 near the top right to terminate the application. If we click the Close icon ❌ instead of the Trash icon, the next flash or debug command will fail. 466 | 467 | ![Click the Trash icon, not the Close icon](images/trash-close.png) 468 | 469 | # PineTime Updater 470 | 471 | Alternatively, flash the following two files to PineTime with [__PineTime Updater__](https://github.com/lupyuen/pinetime-updater)... 472 | 473 | 1. __MCUBoot Bootloader__ 474 | 475 | File: `bin/targets/nrf52_boot/app/boot/mynewt/mynewt.elf` 476 | 477 | Address: `0x0` 478 | 479 | 1. __Rust+Mynewt Firmware__ 480 | 481 | File: `bin/targets/nrf52_my_sensor/app/apps/my_sensor_app/my_sensor_app.elf` 482 | 483 | Address: `0x8000` 484 | 485 | # Debug The Firmware 486 | 487 | 1️⃣ Build the application: In the Task Runner, click `[2] Build Application` 488 | 489 | 2️⃣ Click `Debug → Start Debugging` or press `F5` 490 | 491 | This starts the VSCode Debugger and automatically flashes our updated firmware to PineTime. 492 | 493 | 3️⃣ Click `View → Output` 494 | 495 | In the Output Panel, select `Adapter Output` 496 | 497 | The debugging messages will be displayed here. 498 | 499 | 4️⃣ The program has paused at first line of code in our firmware, the Reset Handler. 500 | 501 | In the Debug Toolbar, click `Continue` or press `F5` 502 | 503 | ![Continue](images/debug-bar-continue.png) 504 | 505 | 🛈 [_What’s a Reset Handler? Read this_](https://gist.github.com/lupyuen/b0b7782f21330e292ea65b9c875bd9a7) 506 | 507 | 5️⃣ The debugger now pauses at the first line of the main function that’s defined in rust/app/src/lib.rs 508 | 509 | This is the first line of Rust code in our Rust Application, which will call test_display in a while. 510 | 511 | In the Debug Toolbar, click Continue or press F5 512 | 513 | 🛈 [_What’s a main function? Read this_](https://gist.github.com/lupyuen/5360769a2d92ec50d988cce92622abff) 514 | 515 | # Edit, Build and Debug the Visual Rust Application on Windows 516 | 517 | ![Debugging PineTime Firmware with VSCode on Windows](images/vscode-debug-windows.png) 518 | 519 | To edit, build and debug the Visual Rust Application on Windows, follow these steps... 520 | 521 | ## _[Windows]_ Connect PineTime to ST-Link 522 | 523 | If we’re doing serious development with PineTime, I recommend getting an [ST-Link v2 USB dongle](https://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20180924134644&SearchText=st-link+v2&switch_new_app=y) ($2) that connects PineTime directly to our Windows, macOS or Linux computer. 524 | 525 | ST-Link allows us to flash PineTime directly from our computer, and it even supports firmware debugging (setting breakpoints, checking values of variables at runtime, …) 526 | 527 | Here’s how we connect PineTime to ST-Link… 528 | 529 | ![PineTime connected to ST-Link](images/stlink.jpg) 530 | 531 | | PineTime | ST-Link | Wire Colour | 532 | | :--- | :--- | :--- | 533 | | `SWDIO` | `SWDIO` | Yellow | 534 | | `SWDCLK` | `SWDCLK` | Blue | 535 | | `3.3V` | `3.3V` | Red | 536 | | `GND` | `GND` | Black | 537 | | `5V` | `5V` | Green (Optional) | 538 | 539 | Before connecting ST-Link to our Windows computer, the ST-Link USB driver should be installed... 540 | 541 | Download the ST-Link USB driver from ST-Link Driver Website (email registration required)… 542 | 543 | https://www.st.com/en/development-tools/stsw-link009.html 544 | 545 | Click `Get Software` 546 | 547 | Unzip the downloaded file. Double-click the driver installer: 548 | `dpinst_amd64.exe` 549 | 550 | ## _[Windows]_ Remove PineTime Flash Protection 551 | 552 | This must be done with a Raspberry Pi, not on Windows, because ST-Link is a High-Level Adapter that doesn't implement all flash commands. Follow the instructions above for Raspberry Pi. 553 | 554 | ## _[Windows]_ Install PineTime Build Tools 555 | 556 | 1️⃣ Download the pinetime-rust-mynewt.7z file attached below… 557 | 558 | https://github.com/lupyuen/pinetime-rust-mynewt/releases/download/v3.0.1/pinetime-rust-mynewt.7z 559 | 560 | Expand the `.7z` file with 7zip… 561 | 562 | https://www.7-zip.org/download.html 563 | 564 | 2️⃣ Click here to install Build Tools For Visual Studio 2019: 565 | 566 | https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019 567 | 568 | ![Build Tools For Visual Studio 2019](images/vsstudio-build-tools.png) 569 | 570 | Click the `Individual Components` tab 571 | 572 | Select the following components: 573 | 574 | 1. `Windows 10 SDK (10.0.18362.0)` 575 | 576 | 1. `C++ CMake Tools for Windows` 577 | 578 | 1. (This should be automatically selected) `MSVC v142 — VS 2019 C++ x64/x86 Build Tools` 579 | 580 | 3️⃣ Install `rustup` according to the instructions here: 581 | `rustup.rs` 582 | 583 | Click the link provided to download `rustup‑init.exe` 584 | 585 | Launch the downloaded file `rustup‑init.exe` 586 | 587 | If you see the message `Windows Defender SmartScreen prevented an unrecognised app from starting`… 588 | 589 | Click `More Info` 590 | 591 | Click `Run Anyway` 592 | 593 | At the `Welcome to Rust!` prompt, press Enter to select the default option: 594 | 595 | `1) Proceed with installation (default)` 596 | 597 | 4️⃣ Open the Command Prompt and enter… 598 | 599 | ```cmd 600 | :: Install Rust build tools for Arm Cortex 601 | rustup default nightly 602 | rustup update 603 | rustup target add thumbv7em-none-eabihf 604 | ``` 605 | 606 | 5️⃣ Install [GNU Arm Embedded Toolchain](https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads) for Windows from Arm Developer Website… 607 | 608 | https://developer.arm.com/-/media/Files/downloads/gnu-rm/8-2019q3/RC1.1/gcc-arm-none-eabi-8-2019-q3-update-win32-sha1.exe?revision=fcadabed-d946-49dc-8f78-0732d2f43773?product=GNU%20Arm%20Embedded%20Toolchain,32-bit,,Windows,8-2019-q3-update 609 | 610 | Select this option at the last install step: 611 | `"Add path to environment variable"` 612 | 613 | 6️⃣ Install VSCode… 614 | 615 | https://code.visualstudio.com/ 616 | 617 | ## _[Windows]_ Edit The Visual Rust Application 618 | 619 | 1️⃣ Launch VSCode 620 | 621 | Click `File → Open Folder` 622 | 623 | Select the downloaded folder `pinetime-rust-mynewt` and click OK 624 | 625 | When prompted to open the workspace, click Open Workspace 626 | 627 | When prompted to install Extension Recommendations, click `Install All` 628 | 629 | 2️⃣ Install the `Visual Embedded Rust` Extension... 630 | 631 | Click `View → Extensions` 632 | 633 | Search for `Visual Embedded Rust` 634 | 635 | Install the extension 636 | 637 | 3️⃣ Enable the Visual Rust application... 638 | 639 | Browse to `rust/app/Cargo.toml` 640 | 641 | Modify the file such that `visual_app` is uncommented and the other options are commented out... 642 | 643 | ```yaml 644 | default = [ # Select the conditional compiled features 645 | # "display_app", # Disable graphics display app 646 | # "ui_app", # Disable druid UI app 647 | "visual_app", # Enable Visual Rust app 648 | # "use_float", # Disable floating-point for GPS geolocation 649 | ] 650 | ``` 651 | 652 | 4️⃣ Edit the Visual Rust application... 653 | 654 | Browse to [`rust/app/src/visual.rs`](https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/rust/app/src/visual.rs) 655 | 656 | Click `Visual Editor` at top right 657 | 658 | ![Click Visual Editor](images/install3.png) 659 | 660 | Use the Visual Editor to edit the Visual Rust application 661 | 662 | ![Editing the Visual Rust application](images/animation.gif) 663 | 664 | 5️⃣ After editing, save the [`visual.rs`](https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/rust/app/src/visual.rs) source file to save the visual program. Don't edit the Rust source file manually, always use the Visual Editor. 665 | 666 | ## _[Windows]_ Build And Flash The Firmware 667 | 668 | 1️⃣ At the lower left corner, there is a panel `Task Runner`. Click the panel to display the build and flash tasks. 669 | 670 | 2️⃣ In the Task Runner, click `[1] Build Bootloader` 671 | 672 | When the Terminal Panel appears, right-click the `Terminal` tab, select `Move Panel Right` 673 | 674 | After the building the Bootloader, we should see `Done` 675 | 676 | Ignore the message `There Are Task Errors` 677 | 678 | The Bootloader only needs to be built once. 679 | 680 | 3️⃣ In the Task Runner, click `[2] Build Application` 681 | 682 | After the building the Application, we should see `Done` 683 | 684 | If you see the message `Undefined Reference To Main`, click `[2] Build Application` again and it should succeed. 685 | 686 | The Application needs to be rebuilt whenever a source file has been changed. 687 | 688 | __Note:__ When we run `Build Application`, the build script will overwrite the default `.vscode/launch.json` (meant for Raspberry Pi) with the correct version `.vscode/launch-nrf52.json` (meant for ST-Link on Windows and macOS) 689 | 690 | 4️⃣ In the Task Runner, click `[3] Image Application` 691 | 692 | After the creating the Firmware Image, we should see `Done` 693 | 694 | 5️⃣ In the Task Runner, click `[4] Flash Bootloader` 695 | 696 | After flashing the Bootloader Firmware to PineTime, we should see `Done` 697 | 698 | 699 | ``` 700 | Flashing Bootloader... 701 | target halted due to debug-request, current mode: Thread 702 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000 703 | Enabled ARM Semihosting to show debug output 704 | ** Programming Started ** 705 | Info : nRF52832-QFAA(build code: E1) 512kB Flash, 64kB RAM 706 | Warn : Adding extra erase range, 0x00000b78 .. 0x00000fff 707 | ** Programming Finished ** 708 | ** Verify Started ** 709 | ** Verified OK ** 710 | 711 | Restarting... 712 | target halted due to debug-request, current mode: Thread 713 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000, semihosting 714 | 715 | **** Done! 716 | ``` 717 | 718 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/logs/load-bootloader-pi.log_ 719 | 720 | The Bootloader only needs to be flashed once. 721 | 722 | 6️⃣ In the Task Runner, click `[5] Flash Application` 723 | 724 | After the flashing the Application Firmware to PineTime, we should see `Done! Press Ctrl-C To Exit`… 725 | 726 | ``` 727 | Flashing Application... 728 | target halted due to debug-request, current mode: Thread 729 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000 730 | Enabled ARM Semihosting to show debug output 731 | ** Programming Started ** 732 | Info : nRF52832-QFAA(build code: E1) 512kB Flash, 64kB RAM 733 | Warn : Adding extra erase range, 0x0003e820 .. 0x0003efff 734 | ** Programming Finished ** 735 | ** Verify Started ** 736 | ** Verified OK ** 737 | 738 | Restarting... 739 | target halted due to debug-request, current mode: Thread 740 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000, semihosting 741 | Enabled ARM Semihosting to show debug output 742 | 743 | **** Done! Press Ctrl-C to exit... 744 | ``` 745 | 746 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/logs/load-application-pi.log_ 747 | 748 | 7️⃣ Our Visual Rust application starts running on PineTime 749 | 750 | ![Demo](images/demo.gif) 751 | 752 | 8️⃣ Click the Trash icon 🗑 near the top right to terminate the application. If we click the Close icon ❌ instead of the Trash icon, the next flash or debug command will fail. 753 | 754 | ![Click the Trash icon, not the Close icon](images/trash-close.png) 755 | 756 | ## _[Windows]_ Debug The Firmware 757 | 758 | 1️⃣ Build the application: In the Task Runner, click `[2] Build Application` 759 | 760 | The build script will also overwrite the default `.vscode/launch.json` (meant for Raspberry Pi) with the correct version `.vscode/launch-nrf52.json` (meant for ST-Link on Windows and macOS) 761 | 762 | 2️⃣ Click `Debug → Start Debugging` or press `F5` 763 | 764 | This starts the VSCode Debugger and automatically flashes our updated firmware to PineTime. 765 | 766 | 3️⃣ Click `View → Output` 767 | 768 | In the Output Panel, select `Adapter Output` 769 | 770 | The debugging messages will be displayed here. 771 | 772 | 4️⃣ The program has paused at first line of code in our firmware, the Reset Handler. 773 | 774 | In the Debug Toolbar, click `Continue` or press `F5` 775 | 776 | ![Continue](images/debug-bar-continue.png) 777 | 778 | 🛈 [_What’s a Reset Handler? Read this_](https://gist.github.com/lupyuen/b0b7782f21330e292ea65b9c875bd9a7) 779 | 780 | 5️⃣ The debugger now pauses at the first line of the main function that’s defined in rust/app/src/lib.rs 781 | 782 | This is the first line of Rust code in our Rust Application, which will call test_display in a while. 783 | 784 | In the Debug Toolbar, click Continue or press F5 785 | 786 | 🛈 [_What’s a main function? Read this_](https://gist.github.com/lupyuen/5360769a2d92ec50d988cce92622abff) 787 | 788 | # TODO: Edit, Build and Debug the Visual Rust Application on macOS 789 | -------------------------------------------------------------------------------- /README.old.md: -------------------------------------------------------------------------------- 1 | # visual-embedded-rust 2 | 3 | - Create and edit Embedded Rust programs visually by dragging and dropping blocks 4 | 5 | - Generates Embedded Rust firmware code for PineTime Smart Watch hosted on [Apache Mynewt](https://mynewt.apache.org/) realtime operating system 6 | 7 | # Connect PineTime to Raspberry Pi 8 | 9 | 1️⃣ Carefully pry open the PineTime casing. Use tweezers to pivot the shiny battery gently to the side. Be careful not to break the red and black wires that connect the battery to the watch! 10 | 11 | 2️⃣ Just above the battery we see 4 shiny rings. This is the __[Serial Wire Debug](https://en.wikipedia.org/wiki/JTAG#Serial_Wire_Debug) (SWD)__ Port for PineTime. We’ll use this port to flash our firmware to PineTime. The 4 pins (from left to right) are SWDIO (Data I/O), SWDCLK (Clock), 3.3V, GND. 12 | 13 | 🛈 [_What is “flash memory” / “flashing” / “firmware”? Read this_](https://gist.github.com/lupyuen/41fffaddade277d27c48697bca21d837) 14 | 15 | The exposed copper wire at the top centre of the photo is the Bluetooth antenna. Bend it upwards so that it doesn’t come into contact with anything. 16 | 17 | 3️⃣ At lower right we see a pad marked 5V. We’ll connect this pad to Raspberry Pi to charge the battery. If charging of the battery is not needed during development, we may leave5V disconnected. 18 | 19 | 4️⃣ Connect the SWD Port and the 5V Pad (optional) to the Raspberry Pi with [__Solid-Core Wire (22 AWG)__](https://www.adafruit.com/product/288) and [__Female-To-Female Jumper Cables__](https://www.adafruit.com/product/1951)… 20 | 21 | | PineTime | Raspberry Pi | Wire Colour | 22 | | :--- | :--- | :--- | 23 | | `SWDIO` | `Header Pin 19 (MOSI)` | Yellow | 24 | | `SWDCLK` | `Header Pin 23 (SCLK)` | Blue | 25 | | `3.3V` | `3.3V` | Red | 26 | | `GND` | `GND` | Black | 27 | | `5V` | `5V` | Green (Optional) | 28 | 29 | 5️⃣ We may use Raspberry Pi Zero, 1, 2, 3 or 4. 30 | 31 | 6️⃣ The PineTime touchscreen needs to be accessible during development, so I mounted PineTime on a [$2 clear box cover from Daiso](https://www.daisojapan.com/p-30955-clear-box-28-x-47-x-19-x-in-12pks.aspx) with Blu Tack and sticky tape. 32 | 33 | # Remove PineTime Flash Protection 34 | 35 | PineTime is shipped with preloaded demo firmware. We need to erase the demo firmware and unprotect PineTime’s flash memory so that we may flash our own firmware. 36 | 37 | 🛈 [_What is “flash protection”? Read this_](https://gist.github.com/lupyuen/3ee440542853e1e637582c4efa1b240a) 38 | 39 | 1️⃣ Power on the Raspberry Pi. Open a command prompt and enter the following… 40 | 41 | ```bash 42 | sudo raspi-config 43 | ``` 44 | 45 | Select `Interfacing Options → SPI → Yes` 46 | 47 | Select `Finish` 48 | 49 | At the command prompt, enter the following… 50 | 51 | ```bash 52 | # Remove folders ~/pinetime-rust-mynewt and ~/openocd-spi (if they exist) 53 | rm -rf ~/pinetime-rust-mynewt 54 | rm -rf ~/openocd-spi 55 | 56 | # Download and extract "pinetime-rust-mynewt" folder containing our prebuilt firmware, source files and flashing scripts 57 | sudo apt install -y wget p7zip-full 58 | cd ~ 59 | wget https://github.com/lupyuen/pinetime-rust-mynewt/releases/download/v3.0.3/pinetime-rust-mynewt.7z 60 | 7z x pinetime-rust-mynewt.7z 61 | rm pinetime-rust-mynewt.7z 62 | 63 | # Install build tools for PineTime: VSCode, Rust, gcc, gdb, openocd-spi, newt 64 | cd ~/pinetime-rust-mynewt 65 | scripts/install-pi.sh 66 | ``` 67 | 68 | 2️⃣ At the `Welcome to Rust!` prompt, press Enter to select the default option: 69 | 70 | `1) Proceed with installation (default)` 71 | 72 | If you see this error… 73 | 74 | ``` 75 | Cloning into 'openocd-spi/jimtcl'... 76 | fatal: unable to access 'http://repo.or.cz/r/jimtcl.git/': Recv failure: Connection reset by peer 77 | fatal: clone of 'http://repo.or.cz/r/jimtcl.git' into submodule path '/private/tmp/aa/openocd-spi/jimtcl' failed 78 | ``` 79 | 80 | It means that the sub-repository for one of the dependencies jimtcl is temporarily down. You may download the pre-built `openocd-spi` binaries [from this link](https://github.com/lupyuen/pinetime-rust-mynewt/releases/download/openocd-spi2/openocd-spi.7z). Then copy the executable openocd-spi/src/openocd to pinetime-rust-mynewt/openocd/bin/openocd 81 | 82 | 3️⃣ When the installation has completed, enter the following at the command prompt… 83 | 84 | ```bash 85 | # Remove flash protection from PineTime and erase demo firmware 86 | cd ~/pinetime-rust-mynewt 87 | scripts/nrf52-pi/flash-unprotect.sh 88 | ``` 89 | 90 | 4️⃣ We should see `Shut Down And Power Off Your Raspberry Pi`… 91 | 92 | If you see `Clock Speed` and nothing else after that… 93 | 94 | ``` 95 | Info : BCM2835 SPI SWD driver 96 | Info : SWD only mode enabled 97 | Info : clock speed 31200 kHz 98 | ``` 99 | 100 | Then the connection to the SWD Port is probably loose, check the pins. 101 | 102 | Also enter `sudo raspi-config` and confirm that the SPI port has been enabled. 103 | 104 | If you see this instead… 105 | 106 | ``` 107 | openocd/bin/openocd: cannot execute binary file: Exec format error 108 | ``` 109 | 110 | Then `install-pi.sh` probably didn’t run correctly. To fix this, copy the `openocd` executable like this… 111 | 112 | ```bash 113 | cp $HOME/openocd-spi/src/openocd $HOME/pinetime-rust-mynewt/openocd/bin/openocd 114 | ``` 115 | 116 | 5️⃣ Shut down and power off your Raspberry Pi. Wait 30 seconds for the red and green LEDs on your Pi to turn off. Power on your Pi. Enter the same commands at a command prompt… 117 | 118 | ```bash 119 | # Remove flash protection from PineTime and erase demo firmware 120 | cd ~/pinetime-rust-mynewt 121 | scripts/nrf52-pi/flash-unprotect.sh 122 | ``` 123 | 124 | 6️⃣ We should see `Flash Is Already Unprotected`… 125 | 126 | PineTime’s demo firmware has been erased and the flash protection has been removed. 127 | 128 | 🛈 [_What is OpenOCD? Why Raspberry Pi and not ROCK64 or Nvidia Jetson Nano? Read this_](https://gist.github.com/lupyuen/18e66c3e81e11050a10d1192c5b84bb0) 129 | 130 | # Edit The Visual Rust Application 131 | 132 | We shall be using VSCode with the Visual Embedded Rust Extension to edit our Visual Rust application graphically. 133 | 134 | 🛈 [_What is VSCode? Is it related to Visual Studio? How is Microsoft involved? Read this_](https://gist.github.com/lupyuen/08e383845d68d3337747e8eb59d0f624) 135 | 136 | 1️⃣ Launch VSCode by clicking the Raspberry Pi Menu (top left corner) → Programming → Code OSS Headmelted 137 | 138 | In VSCode, click `File → Open Folder` 139 | 140 | Under `Home`, select the folder `pinetime-rust-mynewt` and click OK 141 | 142 | When prompted to open the workspace, click Open Workspace 143 | 144 | When prompted to install Extension Recommendations, click `Install All` 145 | 146 | Ignore the message `Unable To Watch For File Changes`. Close the message when it appears. 147 | 148 | 2️⃣ Install the `Visual Embedded Rust` Extension... 149 | 150 | Click `View → Extensions` 151 | 152 | Search for `Visual Embedded Rust` 153 | 154 | Install the extension 155 | 156 | 3️⃣ Enable the Visual Rust application... 157 | 158 | Browse to `rust/app/Cargo.toml` 159 | 160 | Modify the file such that `visual_app` is uncommented and the other options are commented out... 161 | 162 | ```yaml 163 | default = [ # Select the conditional compiled features 164 | # "display_app", # Disable graphics display app 165 | # "ui_app", # Disable druid UI app 166 | "visual_app", # Enable Visual Rust app 167 | # "use_float", # Disable floating-point for GPS geolocation 168 | ] 169 | ``` 170 | 171 | 4️⃣ Edit the Visual Rust application... 172 | 173 | Browse to `rust/app/src/visual.rs` 174 | 175 | Click `Visual Editor` at top right 176 | 177 | ![Click Visual Editor](images/install3.png) 178 | 179 | Use the Visual Editor to edit the Visual Rust application 180 | 181 | 5️⃣ After editing, save the `visual.rs` source file to save the visual program. Don't edit the Rust source file manually, always use the Visual Editor. 182 | 183 | # Build And Flash The Visual Rust Application 184 | 185 | We’re now ready to flash our own firmware to PineTime! We’ll be flashing the PineTime firmware that’s based on open-source [__Apache Mynewt embedded operating system__](https://mynewt.apache.org/). Mynewt OS contains two components that we shall flash to PineTime… 186 | 187 | __Mynewt Bootloader__: This is the C code that’s run whenever we power on PineTime. The Bootloader executes the Mynewt Application upon startup. 188 | 189 | __Mynewt Application__: Contains a Rust application that controls the PineTime functions, and low-level system functions written in C. 190 | 191 | The Bootloader and Application firmware image files may be found at these locations… 192 | 193 | | Mynewt Component | Flash Memory Address | Location of Firmware Image | 194 | | :--- | :--- | :--- | 195 | | Bootloader | `0x0` | `~/pinetime-rust-mynewt/bin/targets/nrf52_boot/app/apps/boot_stub/boot_stub.elf.bin` | 196 | | Application | `0x8000` | `~/pinetime-rust-mynewt/bin/targets/nrf52_my_sensor/app/apps/my_sensor_app/my_sensor_app.img` | 197 | 198 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/hw/bsp/nrf52/bsp.yml_ 199 | 200 | 🛈 [_What is a Bootloader? Read this_](https://gist.github.com/lupyuen/93ba71e0ae5e746e7a68e4513e0a54d8) 201 | 202 | 1️⃣ At the lower left corner, there is a panel `Task Runner`. Click the panel to display the build and flash tasks. 203 | 204 | 2️⃣ In the Task Runner, click `[1] Build Bootloader` 205 | 206 | When the Terminal Panel appears, right-click the `Terminal` tab, select `Move Panel Right` 207 | 208 | After the building the Bootloader, we should see `Done` 209 | 210 | Ignore the message `There Are Task Errors` 211 | 212 | 3️⃣ In the Task Runner, click `[2] Build Application` 213 | 214 | After the building the Application, we should see `Done` 215 | 216 | If you see the message `Undefined Reference To Main`, click `[2] Build Application` again and it should succeed. 217 | 218 | 4️⃣ In the Task Runner, click `[3] Image Application` 219 | 220 | After the creating the Firmware Image, we should see `Done` 221 | 222 | 5️⃣ In the Task Runner, click `[4] Flash Bootloader` 223 | 224 | After flashing the Bootloader Firmware to PineTime, we should see `Done` 225 | 226 | 227 | ``` 228 | Flashing Bootloader... 229 | target halted due to debug-request, current mode: Thread 230 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000 231 | Enabled ARM Semihosting to show debug output 232 | ** Programming Started ** 233 | Info : nRF52832-QFAA(build code: E1) 512kB Flash, 64kB RAM 234 | Warn : Adding extra erase range, 0x00000b78 .. 0x00000fff 235 | ** Programming Finished ** 236 | ** Verify Started ** 237 | ** Verified OK ** 238 | 239 | Restarting... 240 | target halted due to debug-request, current mode: Thread 241 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000, semihosting 242 | 243 | **** Done! 244 | ``` 245 | 246 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/logs/load-bootloader-pi.log_ 247 | 248 | The Bootloader only needs to be flashed once. 249 | 250 | 6️⃣ In the Task Runner, click `[5] Flash Application` 251 | 252 | After the flashing the Application Firmware to PineTime, we should see `Done! Press Ctrl-C To Exit`… 253 | 254 | ``` 255 | Flashing Application... 256 | target halted due to debug-request, current mode: Thread 257 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000 258 | Enabled ARM Semihosting to show debug output 259 | ** Programming Started ** 260 | Info : nRF52832-QFAA(build code: E1) 512kB Flash, 64kB RAM 261 | Warn : Adding extra erase range, 0x0003e820 .. 0x0003efff 262 | ** Programming Finished ** 263 | ** Verify Started ** 264 | ** Verified OK ** 265 | 266 | Restarting... 267 | target halted due to debug-request, current mode: Thread 268 | xPSR: 0x01000000 pc: 0x000000d8 msp: 0x20010000, semihosting 269 | Enabled ARM Semihosting to show debug output 270 | 271 | **** Done! Press Ctrl-C to exit... 272 | ``` 273 | 274 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/logs/load-application-pi.log_ 275 | 276 | 7️⃣ Our Visual Rust application starts running on PineTime 277 | 278 | 8️⃣ Click the Trash icon 🗑 near the top right to terminate the application. If we click the Close icon ❌ instead of the Trash icon, the next flash or debug command will fail. 279 | 280 | # TODO: Debug The Visual Rust Application 281 | 282 | # TODO: Flash Bootloader and Application to PineTime 283 | 284 | 285 | 1️⃣ To flash Mynewt Bootloader to PineTime, enter the following at the command prompt… 286 | 287 | ```bash 288 | # Flash Mynewt Bootloader to PineTime 289 | cd ~/pinetime-rust-mynewt 290 | scripts/nrf52-pi/flash-boot.sh 291 | ``` 292 | 293 | 2️⃣ We should see `Done`… 294 | 295 | 296 | 3️⃣ To flash Mynewt Application to PineTime, enter the following at the command prompt… 297 | 298 | ```bash 299 | # Flash Rust+Mynewt Application to PineTime 300 | cd ~/pinetime-rust-mynewt 301 | scripts/nrf52-pi/flash-app.sh 302 | ``` 303 | 304 | 4️⃣ 305 | 306 | 5️⃣ The new PineTime firmware runs after the flashing has been completed. Here are the debugging messages produced by our Rust application… 307 | 308 | ``` 309 | Info : Listening on port 6666 for tcl connections 310 | Info : Listening on port 4444 for telnet connections 311 | TMP create temp_stub_0 312 | NET hwid 4a f8 cf 95 6a be c1 f6 89 ba 12 1a 313 | NET standalone node 314 | Rust test display 315 | ``` 316 | 317 | _From https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/logs/load-application-pi.log_ 318 | 319 | 6️⃣ And we should see some text and graphics on the PineTime screen 320 | 321 | 7️⃣ Press `Ctrl-C` to stop the display of debugging messages. 322 | 323 | We have flashed a simple Rust application located at [`pinetime-rust-mynewt/rust/app/src/display.rs`](https://github.com/lupyuen/pinetime-rust-mynewt/blob/master/rust/app/src/display.rs) that renders some graphics and text to the PineTime display 324 | 325 | [Here’s a good introduction to Rust programming](https://doc.rust-lang.org/book/title-page.html) and [here’s a good overview of Rust](https://doc.rust-lang.org/rust-by-example/) 326 | 327 | How do we modify this Rust application and rebuild the firmware? We have 3 options: 328 | 329 | [Option 1] Build the firmware on a Windows computer, and copy to Pi for flashing 330 | 331 | [Option 2] Build the firmware on a macOS computer, and copy to Pi for flashing 332 | 333 | [Option 3] Build the firmware on a (powerful) Raspberry Pi (or PineBook Pro) and flash directly 334 | 335 | 336 | 337 | 338 | # TODO 339 | 340 | Pi Version: https://github.com/lupyuen/pinetime-rust-mynewt/releases/tag/v3.0.3 341 | 342 | macOS Version: https://github.com/lupyuen/pinetime-rust-mynewt/releases/tag/v3.0.2 343 | 344 | Windows Version: https://github.com/lupyuen/pinetime-rust-mynewt/releases/tag/v3.0.1 345 | 346 | 1. Install `rustup` with support for nightly target `thumbv7em-none-eabihf`. 347 | 348 | Follow the instructions at https://rustup.rs/ 349 | 350 | Then execute... 351 | 352 | ```bash 353 | rustup default nightly 354 | rustup update 355 | rustup target add thumbv7em-none-eabihf 356 | ``` 357 | 358 | 1. Install Arm toolchain `gcc-arm-none-eabi` and the `newt` build tool for Mynewt. Refer to this script... 359 | 360 | [`scripts/install-pi.sh`](scripts/install-pi.sh) 361 | 362 | 1. Clone this repository... 363 | 364 | ```bash 365 | git clone --recursive https://github.com/lupyuen/pinetime-rust-mynewt 366 | ``` 367 | 368 | 1. [`repos`](repos) folder should contain the Mynewt source code. If your `repos` folder is empty, install the Mynewt source code with the `newt install` command: 369 | 370 | ```bash 371 | cd pinetime-rust-mynewt 372 | newt install 373 | ``` 374 | 375 | Ignore the error `Error: Error updating "mcuboot"` 376 | 377 | 1. Build the bootloader... 378 | 379 | ```bash 380 | cd pinetime-rust-mynewt 381 | scripts/nrf52/build-boot.sh 382 | ``` 383 | 384 | 1. Build the application... 385 | 386 | ```bash 387 | scripts/build-app.sh 388 | ``` 389 | 390 | If you see the error `Undefined main`, run `scripts/build-app.sh` again. It should fix the error. 391 | 392 | 1. Create the application firmware image... 393 | 394 | ```bash 395 | scripts/nrf52/image-app.sh 396 | ``` 397 | 398 | 1. Flash the bootloader... 399 | 400 | ```bash 401 | scripts/nrf52-pi/flash-boot.sh 402 | ``` 403 | 404 | 1. Flash the application and run it... 405 | 406 | ```bash 407 | scripts/nrf52-pi/flash-app.sh 408 | ``` 409 | 410 | 1. You may need to edit the scripts to set the right path of OpenOCD. 411 | 412 | Also for Windows, the ST-Link interface for OpenOCD is `stlink-v2.cfg` instead of `stlink.cfg`. 413 | 414 | 1. Check this article in case of problems... 415 | 416 | [_Build and Flash Rust+Mynewt Firmware for PineTime Smart Watch_](https://medium.com/@ly.lee/build-and-flash-rust-mynewt-firmware-for-pinetime-smart-watch-5e14259c55?source=friends_link&sk=150b2a73b84144e5ef25b985e65aebe9) 417 | 418 | 419 | # Documentataion for Previous Version 420 | 421 | The documentation below is being updated 422 | 423 | ## OBSOLETE: Features 424 | 425 | - Generates Embedded Rust code for [STM32 Blue Pill](https://medium.com/swlh/super-blue-pill-like-stm32-blue-pill-but-better-6d341d9347da?source=friends_link&sk=956087171b9b9efcc484ea60b9c78c16) with [Apache Mynewt](https://mynewt.apache.org/) realtime operating system 426 | 427 | Watch the demo... 428 | 429 | [微博视频](https://weibo.com/7285313566/I2MWZ1CnK) 430 | 431 | [YouTube Video](https://youtu.be/ytGa-7q6sqY) 432 | 433 | Read the articles... 434 | 435 | 1. [_"Visual Embedded Rust Programming with Visual Studio Code"_](https://medium.com/@ly.lee/visual-embedded-rust-programming-with-visual-studio-code-1bc1262e398c?source=friends_link&sk=222de63e45993aacd0db5a2e4b1f33c7) 436 | 437 | 1. [_"Advanced Topics for Visual Embedded Rust Programming"_](https://medium.com/@ly.lee/advanced-topics-for-visual-embedded-rust-programming-ebf1627fe397?source=friends_link&sk=01f0ae0e1b82efa9fd6b8e5616c736af) 438 | 439 | 1. [_"Rust Rocks NB-IoT! STM32 Blue Pill with Quectel BC95-G on Apache Mynewt"_](https://medium.com/@ly.lee/rust-rocks-nb-iot-stm32-blue-pill-with-quectel-bc95-g-on-apache-mynewt-ef62a7e28f7e?source=friends_link&sk=aaa21371f68a07c543066b6b89a760f0) 440 | 441 | 1. [_"Visual Programming with Embedded Rust? Yes we can with Apache Mynewt and Google Blockly!"_](https://medium.com/@ly.lee/visual-programming-with-embedded-rust-yes-we-can-with-apache-mynewt-and-google-blockly-8b67ef7412d7?source=friends_link&sk=353fb92b6f20ebf885ff5c9be44fd6f2) 442 | 443 | ## OBSOLETE: Document Contents 444 | 445 | 1. Usage 446 | 447 | 1. Build The Firmware 448 | 449 | 1. Connect The Hardware 450 | 451 | 1. Flash The Firmware To Blue Pill 452 | 453 | 1. Run The Program 454 | 455 | 1. Function 1: On Start 456 | 457 | 1. Function 2: Start Sensor Listener 458 | 459 | 1. Function 3: Handle Sensor Data 460 | 461 | 1. Function 4: Send Sensor Data 462 | 463 | 1. Rust Source Files 464 | 465 | 1. Program Settings 466 | 467 | 1. CoAP: Constrained Application Protocol 468 | 469 | 1. Quectel NB-IoT AT Commands 470 | 471 | 1. Configuring the CoAP Server at thethings.io 472 | 473 | 1. Typeless Rust 474 | 475 | 1. How Small Is Rust? 476 | 477 | 1. Why Blue Pill? Power vs Price Compromise 478 | 479 | 1. Why Apache Mynewt? Evolution of Rust on Bare Metal 480 | 481 | 1. How Safe Is Rust? Safe Wrappers for Mynewt 482 | 483 | 1. Inside The Visual Embedded Rust Extension for Visual Studio Code 484 | 485 | 1. Building The Visual Embedded Rust Extension 486 | 487 | 1. References 488 | 489 | 1. Release Notes 490 | 491 | ## OBSOLETE: Usage 492 | 493 | 1. In Visual Studio Code, Click `File → Open` to open any folder 494 | 495 | ![Click File → Open](images/install1.png) 496 | 497 | 1. In the `Explorer → (Folder Name)` pane at top left, create a new Rust source file, like `lib.rs` 498 | 499 | ![Create a new Rust source file](images/install2.gif) 500 | 501 | 1. Edit the Rust source file. Click `Visual Editor` at top right 502 | 503 | ![Click Visual Editor](images/install3.png) 504 | 505 | 1. When prompted to populate the visual program into the Rust source file, click `OK` 506 | 507 | ![Click OK](images/install4.png) 508 | 509 | 1. Click the Rust source file to see the generated Rust code. Save the file to save the visual program. Don't edit the Rust source file manually, always use the visual editor. 510 | 511 | [Sample Rust source file containing generated Rust code and XML blocks](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/rust/visual/src/lib.rs) 512 | 513 | ![Visual Embedded Rust editor with generated Rust code](images/editor.png) 514 | 515 | ## OBSOLETE: Build The Firmware 516 | 517 | To compile the generated Rust program into Blue Pill firmware... 518 | 519 | 1. Click here to install `Build Tools For Visual Studio 2019`:
520 | https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019 521 | 522 | 1. Click the `Individual Components` tab 523 | 524 | Select the following components:
525 | `Windows 10 SDK (10.0.18362.0)`
526 | `C++ CMake Tools for Windows`
527 | (This should be automatically selected) `MSVC v142 — VS 2019 C++ x64/x86 Build Tools` 528 | 529 | ![Components for Build Tools For Visual Studio 2019](images/vs-build-tools.png) 530 | 531 | 1. Install rustup according to the instructions here:
532 | https://rustup.rs 533 | 534 | Click the link provided to download `rustup‑init.exe`
535 | Launch the downloaded file `rustup‑init.exe`
536 | 537 | If you see the message `Windows Defender SmartScreen prevented an unrecognised app from starting`…
538 | Click `More Info`
539 | Click `Run Anyway`
540 | 541 | At the `Welcome to Rust!` prompt, press Enter to select the default option:
542 | `1) Proceed with installation (default)` 543 | 544 | 1. Open the Windows Command Prompt. Enter into the command prompt: 545 | 546 | ``` 547 | rustup default nightly 548 | rustup update 549 | rustup target add thumbv7m-none-eabi 550 | rustc -V 551 | ``` 552 | 553 | The reported version of rustc should be 1.38.0 or later:
554 | `rustc 1.38.0-nightly (435236b88 2019–08–01)` 555 | 556 | 1. Download the `stm32bluepill-mynewt-sensor.7z` file attached below…
557 | https://github.com/lupyuen/stm32bluepill-mynewt-sensor/releases/tag/v7.0.3 558 | 559 | Expand the `.7z` file with 7zip…
560 | https://www.7-zip.org/download.html 561 | 562 | 1. Install Arm Cross-Compiler and Linker for Windows from Arm Developer Website…
563 | https://developer.arm.com/-/media/Files/downloads/gnu-rm/8-2019q3/RC1.1/gcc-arm-none-eabi-8-2019-q3-update-win32-sha1.exe?revision=fcadabed-d946-49dc-8f78-0732d2f43773?product=GNU%20Arm%20Embedded%20Toolchain,32-bit,,Windows,8-2019-q3-update 564 | 565 | Select this option at the last install step:
566 | `Add path to environment variable` 567 | 568 | 1. Download the ST-Link USB driver from ST-Link Driver Website (email registration required)…
569 | https://www.st.com/en/development-tools/stsw-link009.html 570 | 571 | Click `Get Software`
572 | Unzip the downloaded file. Double-click the driver installer:
573 | `dpinst_amd64.exe` 574 | 575 | 1. Launch Visual Studio Code
576 | Install the extension “Cortex-Debug”…
577 | https://marketplace.visualstudio.com/items?itemName=marus25.cortex-debug 578 | 579 | 1. Click `File → Open Folder` 580 | 581 | Select the downloaded folder `stm32bluepill-mynewt-sensor` 582 | 583 | When prompted to open the workspace, click `Open Workspace` 584 | 585 | ![Open Workspace](images/open-workspace.png) 586 | 587 | 1. Copy your Visual Program source file to `stm32bluepill-mynewt-sensor/rust/app/src/lib.rs`. Overwrite the existing file. 588 | 589 | ![](images/copy-visual-rust.png) 590 | 591 | 1. Delete the files `app_network.rs` and `app_sensor.rs` in that folder 592 | 593 | 1. If you have a Quectel NB-IoT module…
594 | 595 | Open the following file and configure the program settings:
596 | `targets/bluepill_my_sensor/syscfg.yml`
597 | Change the NB-IoT band setting `NBIOT_BAND`. Check with your NB-IoT operator for the band to use. 598 | 599 | 1. Click `Terminal → Run Task → [1] Build bluepill_boot` 600 | 601 | This builds the bootloader, which starts the Apache Mynewt operating system upon startup. If it shows errors, [compare with this build log](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/build-bootloader.log). 602 | 603 | 1. Click `Terminal → Run Task → [2] Build bluepill_my_sensor` 604 | 605 | This builds the firmware containing our Rust program. [Compare with this build log](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/build-application.log). 606 | 607 | When our Rust program has been successfully compiled as Blue Pill ROM firmware, we should see this… 608 | 609 | ![Build Firmware](images/firmware-build.png) 610 | 611 | 1. Click `Terminal → Run Task → [3] Image bluepill_my_sensor` 612 | 613 | This creates the Blue Pill flash image from the firmware. [Compare with this image log](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/image.log) 614 | 615 | If any source files or configuration files are changed, rebuild the application by clicking
616 | `Terminal → Run Task → [2] Build bluepill_my_sensor` 617 | 618 | ## OBSOLETE: Connect The Hardware 619 | 620 | | | | 621 | |:- |:- | 622 | | ![](images/hardware-list.png)
_From top to bottom: STM32 Blue Pill, ST-Link V2, Quectel BC95-G breakout board with antenna, NB-IoT SIM_ | We’ll need the following hardware…

[1] __STM32 Blue Pill:__ Under $2, search [AliExpress](https://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20180924131057&SearchText=stm32f103c8t6+development+board&switch_new_app=y) for `stm32f103c8t6 development board`

[2] __ST-Link V2 USB Adapter:__ Under $2, search [AliExpress](https://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20180924134644&SearchText=st-link+v2&switch_new_app=y) for `st-link v2`

__Optional:__ To transmit data to the NB-IoT network, we’ll also need…

[3] __Quectel BC95-G Global NB-IoT Module__ ([breakout board with antenna](https://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20190725022150&SearchText=bc95-g+nb101&switch_new_app=y))

I ordered mine [from Taobao](https://item.taobao.com/item.htm?id=577310122904). [The manual in Chinese is here](http://rs.iotxx.com/uploads/doc/%E8%B0%B7%E9%9B%A8NB10x%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E%E4%B9%A6-V1.3.pdf).

BC95-G works in all NB-IoT frequency bands worldwide. If you’re buying a different NB-IoT module, check that it supports your local NB-IoT Frequency Band. (For example: In Singapore I’m using NB-IoT Frequency Band 8 with StarHub)

[4] __NB-IoT SIM__ from your local NB-IoT network operator

Many thanks to [StarHub](https://www.starhub.com/) for sponsoring the NB-IoT SIM that I used for this tutorial! 623 | | 624 | 625 | ![Hardware](images/hardware.jpg) 626 | 627 | Connect Blue Pill to Quectel BC95-G and ST-Link as follows… 628 | 629 | | Blue Pill | Quectel BC95-G | ST-Link V2 | Wire Colour | 630 | | :--- | :--- | :--- | :--- | 631 | | `PA2 (UART2 TX2)` | `RXD (Pin 4)` | | Green | 632 | | `PA3 (UART2 RX2)` | `TXD (Pin 3)` | | Blue | 633 | | `GND` | `GND (Pin 1)` | | Black | 634 | | | `VCC (Pin 2)` | `5.0V (Pin 10)` | Yellow | 635 | | `3V3` | | `3.3V (Pin 8)` | Red | 636 | | `DIO` | | `SWDIO (Pin 4)` | Orange | 637 | | `DCLK` | | `SWDCLK (Pin 2)` | Brown | 638 | | `GND` | | `GND (Pin 6)` | Black | 639 | 640 | Both yellow jumpers on Blue Pill should be set to the 0 position, as shown in the above photo. 641 | 642 | | | | 643 | | :- | :- | 644 | | ![SIM partially exposed to show the unusual orientation](images/sim-slot.png)
_SIM partially exposed to show the unusual orientation_ | Note that we are powering the Quectel module with __5V from ST-Link instead of 3.3V from Blue Pill__. That’s because the module requires more power than Blue Pill can provide. (How did I find out? Because the module kept restarting when I powered it from Blue Pill.)

__Check the documentation for your Quectel breakout board to confirm that it supports 5V__. ([Mine does](http://rs.iotxx.com/uploads/doc/%E8%B0%B7%E9%9B%A8NB10x%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E%E4%B9%A6-V1.3.pdf))

__Insert the NB-IoT SIM__ according to the orientation shown in the photo. (Yes the SIM notch faces outward, not inward).

_Remember: Always connect the antenna before powering up the NB-IoT module!_

__If you’re using Windows:__ Make sure that the ST-Link Driver has been installed before connecting ST-Link to your computer 645 | | 646 | 647 | ## OBSOLETE: Flash The Firmware To Blue Pill 648 | 649 | ![Blue Pill and ST-Link connected to USB port](images/stlink.jpg) 650 | 651 | 1. Check that the Blue Pill is connected to ST-Link…
652 | And that the ST-Link is connected to your computer’s USB port.
653 | Now let’s head back to Visual Studio Code… 654 | 655 | 1. Click `Terminal → Run Task → [4] Load bluepill_boot` 656 | 657 | This flashes the bootloader to Blue Pill, to start the Apache Mynewt operating system upon startup. If it shows errors, [compare with this flash log](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/load-bootloader.log). 658 | 659 | 1. Click `Terminal → Run Task → [5] Load bluepill_my_sensor` 660 | 661 | This flashes the firmware (containing our Visual Program) to Blue Pill. If it shows errors, [compare with this flash log](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/load-application.log). 662 | 663 | ## OBSOLETE: Run The Program 664 | 665 | 1. Click `Debug → Start Debugging` 666 | 667 | 1. Click `View → Output` 668 | 669 | Select `Adapter Output` to see the Blue Pill log 670 | 671 | ![Select `Adapter Output`](images/run1.png) 672 | 673 | 1. The debugger pauses at the line with `LoopCopyDataInit` 674 | 675 | Click `Continue` or press `F5` 676 | 677 | ![LoopCopyDataInit](images/run2.png) 678 | 679 | 1. The debugger pauses next at the `main()` function. 680 | 681 | Click `Continue` or press `F5` 682 | 683 | ![`main()` function](images/run3.png) 684 | 685 | Our Blue Pill should now poll its internal temperature sensor every 10 seconds. It should also transmit the temperature data to the CoAP server hosted at thethings.io. 686 | 687 | [The Blue Pill log should look like this](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/visual.log). The log is explained below in the _"Quectel NB-IoT AT Commands"_ section. 688 | 689 | [微博视频](https://weibo.com/7285313566/I2MZOeP0F) 690 | 691 | [YouTube Video](https://youtu.be/PL4Yj3IS5ck) 692 | 693 | Upon clicking the URL `https://blue-pill-geolocate.appspot.com/?device=5cfca8c…` that’s shown in the Blue Pill log, we’ll see a web page that displays the temperature received by the server at thethings.io. 694 | 695 | The server has converted the raw temperature into degrees Celsius. We convert the temperature at the server to conserve RAM and ROM on Blue Pill. 696 | 697 | ![Display of sensor data received from our Blue Pill](images/sensor-web.png)
698 | _Display of sensor data received from our Blue Pill_ 699 | 700 | ## OBSOLETE: Function 1: On Start 701 | 702 | ![On Start](images/visual-program1.png) 703 | 704 | `On Start` marks the start of the program. Here we define some constants — values used by the program that won’t change as the program runs… 705 | 706 | 1. `SENSOR_DEVICE` is the name of the sensor that the program will poll (check periodically). We’ll be polling Blue Pill’s Internal Temperature Sensor, which is named `temp_stm32_0` 707 | 708 | 1. `SENSOR_POLL_TIME` is the time interval (in milliseconds) for polling the sensor. We’ll set this to 10 seconds (or 10,000 milliseconds) 709 | 710 | 1. `TEMP_SENSOR_KEY` is the name of the sensor data field that our program will send to the server. We’ll call it `t` to tell the server we’re sending a temperature value. 711 | 712 | 1. `TEMP_SENSOR_TYPE` is the type of sensor data that our program will send: Raw ambient temperature in whole numbers (integers from 0 to 4095), hence `SENSOR_TYPE_AMBIENT_TEMPERATURE_RAW` 713 | 714 | Why do we send the temperature in raw form instead of the usual decimal (floating-point) form like 28.9 degrees Celsius? That’s because Blue Pill has very limited RAM and ROM. Sending the raw temperature without conversion will save us from reserving RAM and ROM that would be needed for the floating-point conversion. We’ll let the server convert instead. 715 | 716 | By Rust convention, constants are named in uppercase. Hence we name the constants as `SENSOR_DEVICE` instead of sensor_device 717 | 718 | ![](images/visual-program1a.png) 719 | 720 | Next we call the function `start_sensor_listener` to begin polling the temperature sensor every 10 seconds. More about this in the next section. 721 | 722 | ![](images/visual-program1b.png) 723 | 724 | Finally we call `start_server_transport`, which is a system function defined in the `sensor_network` library. This function starts a background task to establish a connection to the NB-IoT network. For this tutorial, we’ll be transmitting sensor data over the NB-IoT network, which is available worldwide. 725 | 726 | It may take a few seconds to complete, but the function executes in the background so it won’t hold up other tasks, like polling the temperature sensor. 727 | 728 | Take note of the Rust convention… `sensor_network::start_server_transport` refers to the function `start_server_transport` that’s found inside the Rust Library `sensor_network`. Rust Libraries are also known as “Crates”. 729 | 730 | How was the `On Start` function created? 731 | By dragging and dropping the blocks from the Blocks Bar at the left of the Visual Program. 732 | That’s how we create a Visual Program… By arranging the blocks to compose a program! 733 | 734 | [微博视频](https://weibo.com/7285313566/I2MOamxS9) 735 | 736 | [YouTube Video](https://youtu.be/Qw1N-01PAy8) 737 | 738 | ![Visual Embedded Rust](images/animation.gif) 739 | 740 | ## OBSOLETE: Function 2: Start Sensor Listener 741 | 742 | ![Start Sensor Listener](images/visual-program2.png) 743 | 744 | `To start_sensor_listener With ...` is the way that we define functions in the Visual Program. Here we define `start_sensor_listener` as a function that accepts 4 parameters (or inputs), whose values we have seen from the previous section… 745 | 746 | 1. `sensor_name`: Name of the sensor to be polled. Set to `SENSOR_DEVICE` (i.e. `temp_stm32_0`) 747 | 748 | 1. `sensor_key`: Name of the sensor data field to be sent to the server. Set to `TEMP_SENSOR_KEY` (i.e. `t`) 749 | 750 | 1. `sensor_type`: Type of sensor data that will be sent to the server. Set to `SENSOR_TYPE_AMBIENT_TEMPERATURE_RAW` 751 | 752 | 1. `poll_time`: Time interval (in milliseconds) for polling the sensor. Set to `SENSOR_POLL_TIME` (i.e. 10,000 milliseconds or 10 seconds) 753 | 754 | ![](images/visual-program2a.png) 755 | 756 | Next we call the system function `set_poll_rate_ms`, defined in the `sensor` library. The `sensor` library comes from the Apache Mynewt operating system, which manages all sensors on Blue Pill. 757 | 758 | By calling the function `set_poll_rate_ms` with `sensor_name` set to `temp_stm32_0` and `poll_time` set to `10000` (milliseconds), we are asking the system to poll the temperature sensor every 10 seconds. And the system will happily fetch the temperature value on our behalf every 10 seconds. 759 | 760 | What shall we do with the temperature value? We’ll define a Listener Function to transmit the data. But first… 761 | 762 | ![](images/visual-program2b.png) 763 | 764 | We call function `mgr_find_next_bydevname` (also from the `sensor` library) to fetch the sensor driver from the system and store it in the variable `sensor_driver`. By passing the `sensor_name` as `temp_stm32_0`, the function returns the driver responsible for managing the temperature sensor. The driver will be used for setting the Listener Function in a while. 765 | 766 | ![](images/visual-program2c.png) 767 | 768 | Before that, we check the sensor driver was actually found. If we had misspelt the name of the sensor, the sensor driver would not be found and it would be set to `null`, a special Rust value that means “nothing”. Hence we check to ensure that `sensor_driver` is not `null`. 769 | 770 | ![](images/visual-program2d.png) 771 | 772 | We create a sensor listener (stored as `listener`) by calling the system function `new_sensor_listener`, passing in the `sensor_key` (set to `t`) and the `sensor_type` (raw ambient temperature). func is the name of the Listener Function that will be called after reading the sensor data: `handle_sensor_data`. Which we’ll cover in the next section. 773 | 774 | ![](images/visual-program2e.png) 775 | 776 | To register the Listener Function in the system, we call the system function `register_listener`, passing in the `sensor_driver` and the sensor listener that we have just created. 777 | 778 | After that, the operating system will automatically read the temperature sensor every 10 seconds and call our function `handle_sensor_data` with the temperature value. 779 | 780 | [微博视频](https://weibo.com/7285313566/I2MWZ1CnK) 781 | 782 | [YouTube Video](https://youtu.be/ytGa-7q6sqY) 783 | 784 | ## OBSOLETE: Function 3: Handle Sensor Data 785 | 786 | ![Handle Sensor Data](images/visual-program3.png) 787 | 788 | How shall we handle the temperature data that has been read? `handle_sensor_data` passes the sensor data to another function `send_sensor_data` that transmits the sensor data to the server. More about `send_sensor_data` in a while. 789 | 790 | The function `handle_sensor_data` doesn’t seem to do much… why did we design the program this way? It’s meant for future expansion — when we need more complicated logic for handling sensor data, we’ll put the logic into `handle_sensor_data` 791 | 792 | `handle_sensor_data` could be extended to handle multiple sensors, aggregating the sensor data before transmitting. Or it could check for certain conditions and decide whether it should transmit the data. This program structure gives us the most room to expand for the future. 793 | 794 | ## OBSOLETE: Function 4: Send Sensor Data 795 | 796 | ![Send Sensor Data](images/visual-program4.png) 797 | 798 | The final function in our program, `send_sensor_data`, is called by `handle_sensor_data` to transmit sensor data. The parameter `sensor_data` contains the field name `t` and the sensor value, like `1715`. Remember that this is a raw temperature value. The server will convert the raw value to degrees Celsius later. 799 | 800 | ![](images/visual-program4a.png) 801 | 802 | We call `get_device_id` from the `sensor_network` library to fetch the Device ID from the system. This is a long string of random letters and digits like `a8b2c7d8e9b2...` Each time we restart Blue Pill we’ll get a different Device ID. We’ll use this Device ID later to identify our Blue Pill uniquely and check whether the server has received the temperature sensor data from our Blue Pill. 803 | 804 | ![](images/visual-program4b.png) 805 | 806 | Next we call `init_server_post` (also from `sensor_network` library) to prepare a sensor data message that will be sent to the server. Because Blue Pill has limited RAM, this function will ensure that only one task is allowed to compose messages at any time. The other tasks will have to wait for their turn. 807 | 808 | ![](images/visual-program4c.png) 809 | 810 | `init_server_post` returns a true/false result (known as a boolean) that indicates whether the NB-IoT network connection has been established. This stored in the variable `network_ready`. 811 | 812 | Only when `network_ready` is true, which means that the device has connected to the NB-IoT network, then we proceed to compose a CoAP Message. 813 | 814 | ![](images/visual-program4d.png) 815 | 816 | What’s a CoAP Message? It’s a standard format for transmitting sensor data over NB-IoT. Here we are transmitting two data values in the CoAP Message... 817 | 818 | 1. `device_id`: The randomly-generated Device ID that uniquely identifies our Blue Pill. This field shall be transmitted with the field name device 819 | 820 | 1. `sensor_data`: Contains the field name `t` and the sensor value, like `1715` 821 | 822 | ![](images/visual-program4e.png) 823 | 824 | The CoAP Message is transmitted only when function `do_server_post` is called. Again this transmission takes place in a background task, so it won’t hold up our program from polling the sensor. 825 | 826 | Notice that `_payload` is named differently… it begins with an underscore `_`. By Rust convention, variables that are set but not read should be named with an underscore `_` as the first character. Because the Rust Compiler will warn us about unused variables. 827 | 828 | This effectively tells the Rust Compiler: _“Yes I’m setting the variable `_payload` and I’m not using the value… Please don’t warn me that I may have misspelt the name `_payload`"_ 829 | 830 | ![](images/visual-program4f.png) 831 | 832 | At the end of the function, we display a URL in the Blue Pill log that contains the Device ID. The URL looks like this: https://blue-pill-geolocate.appspot.com/?device=5cfca8c… 833 | We’ll click this URL to verify that the server has received our sensor data. 834 | 835 | ## OBSOLETE: Rust Source Files 836 | 837 | | | | 838 | |:- |:- | 839 | | ![](images/rust-source-files.png) | The Rust source files are located in the `rust` folder…

`rust/app`: Rust application that polls the internal temperature sensor and transmits the sensor data over NB-IoT

If you’re using Visual Embedded Rust...

Overwrite the file `src/lib.rs` by your Visual Program source file

Delete `app_network.rs` and `app_sensor.rs` in the src folder.

Rebuild the application by clicking

`Terminal → Run Task → [2] Build bluepill_my_sensor`

`rust/visual`: Sample Visual Embedded Rust program

`rust/mynewt`: Rust Safe Wrappers for Mynewt OS and libraries

`rust/macros`: Rust Procedural Macros for generating Safe Wrappers, inferring types and other utility macros like `strn!()` 840 | | 841 | 842 | ## OBSOLETE: Typeless Rust 843 | 844 | To making coding easier for beginners, the extension generates [Typeless Rust code like this](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/rust/visual/src/lib.rs)... 845 | 846 | ```rust 847 | #[infer_type] // Infer the missing types 848 | fn start_sensor_listener(sensor_name: _, sensor_key: _, sensor_type: _, poll_time: _) ... 849 | // Call Mynewt API 850 | sensor::set_poll_rate_ms(sensor_name, poll_time) ? ; 851 | ``` 852 | 853 | When the typeless code is compiled, the [`infer_type` Procedural Macro](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/rust/macros/src/infer_type.rs) infers the types by matching the variables against the Mynewt API... 854 | 855 | ```rust 856 | // Call Mynewt API 857 | sensor::set_poll_rate_ms(sensor_name, poll_time) ? ; 858 | // `sensor_name` inferred as type `&Strn` 859 | // `poll_time` inferred as type `u32` 860 | ``` 861 | 862 | The macro then injects the inferred types into the typeless code... 863 | 864 | ```rust 865 | fn start_sensor_listener(sensor_name: &Strn, sensor_key: &'static Strn, 866 | sensor_type: sensor_type_t, poll_time: u32) ... 867 | ``` 868 | 869 | The inferred types are stored in [`infer.json`](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/infer.json). The enables the `infer_type` macro to infer new types based on types already inferred for other functions... 870 | 871 | ```json 872 | "start_sensor_listener": [ 873 | [ "sensor_name", "&Strn" ], 874 | [ "sensor_key", "&'static Strn" ], 875 | [ "sensor_type", "sensor_type_t" ], 876 | [ "poll_time", "u32" ] 877 | ], 878 | "send_sensor_data": [ 879 | [ "sensor_data", "&SensorValue" ] 880 | ], 881 | "handle_sensor_data": [ 882 | [ "sensor_data", "&SensorValue" ] 883 | ] 884 | ``` 885 | 886 | This diagram illustrates the Type Inference… 887 | 888 | ![How the infer_type macro infers missing types](images/typeless-rust.png)
889 | _How the infer_type macro infers missing types_ 890 | 891 | Here’s an animation (done with Visual Studio Code) that explains how the types were inferred by the `infer_type` macro. At top left are the types to be inferred. At bottom left are the known type signatures from the Mynewt API. 892 | 893 | The `infer_type` macro scans the Typeless Rust program recursively, hence we see the roving red highlight. When the macro finds a match with the Mynewt API, the code flashes green. 894 | 895 | Green ticks at the top left mean that we have successfully inferred the types. 896 | 897 | The recursive Rust code parsing was implemented with the excellent `syn` crate. The `quote` crate was used to emit the transformed Rust code. 898 | 899 | [微博视频](https://weibo.com/7285313566/I2N12aA4W) 900 | 901 | [YouTube Video](https://youtu.be/1SCLlwK5KwE) 902 | 903 | ![How the infer_type macro infers missing types, animated in Visual Studio Code with the Visual Embedded Rust Extension](images/infer-animate.gif)
904 | _How the infer_type macro infers missing types, animated in Visual Studio Code with the Visual Embedded Rust Extension_ 905 | 906 | More details in the article [_"Advanced Topics for Visual Embedded Rust Programming"_](https://medium.com/@ly.lee/advanced-topics-for-visual-embedded-rust-programming-ebf1627fe397?source=friends_link&sk=01f0ae0e1b82efa9fd6b8e5616c736af) 907 | 908 | ## OBSOLETE: Inside The Visual Embedded Rust Extension for Visual Studio Code 909 | 910 | The source code for the Visual Embedded Rust extension is located at github.com/lupyuen/visual-embedded-rust 911 | 912 | The extension is published in the [Visual Studio Marketplace here](https://marketplace.visualstudio.com/items?itemName=LeeLupYuen.visual-embedded-rust&ssr=false#overview) 913 | 914 | The extension wraps the web-based visual code editor from [Google Blockly](https://developers.google.com/blockly/guides/overview) into a [VSCode WebView](https://code.visualstudio.com/api/extension-guides/webview). Blockly uses XML to represent a visual program. 915 | 916 | The extension is activated when we [edit a Rust source file](https://github.com/lupyuen/visual-embedded-rust/blob/master/package.json#L41-L49) (`*.rs`). [Here’s a sample Rust source file containing a Visual Program](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/rust/visual/src/lib.rs) 917 | 918 | There are two parts of the file… 919 | 920 | 1. __Rust Source Code:__ Which is autogenerated by the Blockly Code Generator from the Blockly XML 921 | 922 | 1. __Blockly XML:__ The XML representation of the visual program. It’s located at the bottom of the source file, marked by `BEGIN BLOCKS … END BLOCKS` 923 | 924 | ![Logic Flow in the Visual Embedded Rust Extension](images/vscode-flow.jpg)
925 | _Logic Flow in the Visual Embedded Rust Extension_ 926 | 927 | 1. Main logic for the VSCode Extension is in [extension.ts](https://github.com/lupyuen/visual-embedded-rust/blob/master/src/extension.ts) 928 | 929 | The extension contains two asset folders: 930 | 931 | [`resources`](https://github.com/lupyuen/visual-embedded-rust/tree/master/resources): Contains a [visual program template](https://github.com/lupyuen/visual-embedded-rust/blob/master/resources/template.rs) that will be used to populate empty Rust source files 932 | 933 | [`media`](https://github.com/lupyuen/visual-embedded-rust/tree/master/media): Contains the Blockly JavaScript code that will be embedded in the WebView to render the visual editor and generate Rust source code… 934 | 935 | [`media/blockly-mynewt-rust`](https://github.com/lupyuen/blockly-mynewt-rust) contains the Blockly JavaScript code with a custom Rust Code Generator 936 | 937 | [`media/closure-library`](https://github.com/google/closure-library) is the Google Closure Library needed by Blockly 938 | 939 | [`media/vscode`](https://github.com/lupyuen/visual-embedded-rust/tree/master/media/vscode) contains JavaScript code that enables VSCode Message Passing in the WebView to implement save/load functions and modal prompts 940 | 941 | 1. The extension creates a [WebView that embeds the HTML and JavaScript code](https://github.com/lupyuen/visual-embedded-rust/blob/master/src/extension.ts#L88-L144) from [Google Blockly](https://developers.google.com/blockly/guides/overview). 942 | 943 | [HTML code for the WebView is here](https://github.com/lupyuen/visual-embedded-rust/blob/master/src/web.ts) 944 | 945 | 1. The VSCode Extension and the WebView are running in [separate JavaScript sandboxes](https://code.visualstudio.com/api/extension-guides/webview#scripts-and-message-passing). 946 | 947 | Hence we’ll be using VSCode Message Passing to communicate between the VSCode Extension and WebView, as we shall soon see… 948 | 949 | 1. [When the WebView loads](https://github.com/lupyuen/visual-embedded-rust/blob/master/media/vscode/storage.js#L59-L71), it notifies the VSCode Extension to fetch the contents of the Rust source file. 950 | 951 | The VSCode Extension responds by [passing the contents of the active Rust source file to the WebView](https://github.com/lupyuen/visual-embedded-rust/blob/master/src/extension.ts#L168-L186) via Message Passing. 952 | 953 | The WebView [extracts the Blockly XML](https://github.com/lupyuen/visual-embedded-rust/blob/master/media/vscode/message.js#L40-L60) embedded in the file contents ([at the bottom](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/rust/visual/src/lib.rs#L159)). The WebView refreshes the Blockly workspace with the Blockly XML. 954 | 955 | If the active Rust source file is empty, the VSCode Extension [populates the file](https://github.com/lupyuen/visual-embedded-rust/blob/master/src/extension.ts#L155-L202) with a [template containing Blockly XML](https://github.com/lupyuen/visual-embedded-rust/blob/master/resources/template.rs) 956 | 957 | 1. When the [visual program is updated](https://github.com/lupyuen/visual-embedded-rust/blob/master/media/vscode/storage.js#L194-L207), the WebView sends the [updated Blockly XML and the generated Rust code](https://github.com/lupyuen/visual-embedded-rust/blob/master/media/vscode/message.js#L79-L89) (via [Message Passing](https://github.com/lupyuen/visual-embedded-rust/blob/master/media/vscode/storage.js#L187-L192)) to the VSCode Extension. 958 | 959 | The extension [updates the Rust document](https://github.com/lupyuen/visual-embedded-rust/blob/master/src/extension.ts#L203-L223) in VSCode with the Blockly XML and generated Rust Code. 960 | 961 | 1. The custom-built Rust Code Generator for Blockly is here… 962 | 963 | github.com/lupyuen/blockly-mynewt-rust/blob/master/generators/rust.js 964 | 965 | github.com/lupyuen/blockly-mynewt-rust/tree/master/generators/rust 966 | 967 | The Rust Code Generator for Blockly is [explained in this article](https://medium.com/@ly.lee/visual-programming-with-embedded-rust-yes-we-can-with-apache-mynewt-and-google-blockly-8b67ef7412d7) 968 | 969 | ## OBSOLETE: Building The Visual Embedded Rust Extension 970 | 971 | To build the extension, two repositories need to be cloned into the media folder: [`blockly-mynewt-rust`](https://github.com/lupyuen/blockly-mynewt-rust) and [`closure-library`](https://github.com/google/closure-library): 972 | 973 | ```bash 974 | cd media 975 | git clone https://github.com/lupyuen/blockly-mynewt-rust 976 | git clone https://github.com/google/closure-library 977 | ``` 978 | 979 | ## OBSOLETE: References 980 | 981 | The following files may be useful for reference… 982 | 983 | - [Disassembly of the Rust Application build](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/libapp-demangle.S) 984 | 985 | - [Disassembly of the Rust Crates](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/rustlib-demangle.S) 986 | 987 | - [Disassembly of the entire firmware](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/my_sensor_app.elf.lst) 988 | 989 | - [Memory map of the firmware](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/blob/rust-nbiot/logs/my_sensor_app.elf.map) 990 | 991 | [Read more about hosting Rust applications on Mynewt](https://medium.com/@ly.lee/hosting-embedded-rust-apps-on-apache-mynewt-with-stm32-blue-pill-c86b119fe5f?source=friends_link&sk=f58f4cf6c608fded4b354063e474a93b) 992 | 993 | ## OBSOLETE: Release Notes 994 | 995 | For changelog refer to... 996 | 997 | 1. [`github.com/lupyuen/visual-embedded-rust/commits/master`](https://github.com/lupyuen/visual-embedded-rust/commits/master) 998 | 999 | 1. [`github.com/lupyuen/blockly-mynewt-rust/commits/master`](https://github.com/lupyuen/blockly-mynewt-rust/commits/master) 1000 | 1001 | 1. [`github.com/lupyuen/stm32bluepill-mynewt-sensor/commits/rust-nbiot`](https://github.com/lupyuen/stm32bluepill-mynewt-sensor/commits/rust-nbiot) 1002 | --------------------------------------------------------------------------------