diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 444fd0ef..904aeb4a 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -15,16 +15,20 @@ jobs: uses: actions/checkout@v4 - name: Setup Pages uses: actions/configure-pages@v5 + - uses: actions/setup-node@v4 + with: + node-version: "24.x" + cache: npm - run: npm ci - name: Build docs - run: npm run docs + run: npm run docs -w @microbit/microbit-connection - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: - path: ./docs/build + path: ./packages/microbit-connection/docs/build deploy: - if: ${{ startsWith(github.ref, 'refs/tags/') }} + if: ${{ startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, '-') }} permissions: pages: write id-token: write diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3ea9a69e..fef95aa3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,15 +15,18 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: "20.x" - registry-url: 'https://registry.npmjs.org' + node-version: "24.x" + registry-url: "https://registry.npmjs.org" cache: npm - - uses: microbit-foundation/npm-package-versioner-action@v1 - run: npm ci env: NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - run: npm run format:check + - uses: microbit-foundation/npm-package-versioner-action@v3 + with: + working-directory: packages/microbit-connection - run: npm run ci - - run: npm publish + - run: npm publish -w @microbit/microbit-connection if: github.event_name == 'release' && github.event.action == 'created' env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.gitignore b/.gitignore index 66040e7f..730e9268 100644 --- a/.gitignore +++ b/.gitignore @@ -24,5 +24,8 @@ docs/build *.sln *.sw? -/build +build *.tgz + +# Hex files copied from top-level hex-files/ into app public dirs +apps/*/public/hex-files diff --git a/.npmignore b/.npmignore deleted file mode 100644 index ca264322..00000000 --- a/.npmignore +++ /dev/null @@ -1,27 +0,0 @@ -.* -*.log - -**/tsconfig.json -tsconfig.*.json - -# Test files -setupTests.js -**/*.test.js -**/*.test.js.map -**/*.test.d.ts - -# Sources -src/ -lib/ -public/ -docs/ -examples/ -*.html -*.md - -## this is generated by `npm pack` -*.tgz -package - -dist/ -vite.config.* diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..d4535df8 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,17 @@ +node_modules + +# Build / dist output +build +dist +docs/build + +# Capacitor native projects (have their own tooling) +apps/*/android +apps/*/ios + +# Generated / vendored binaries and lockfiles +apps/*/public/hex-files +hex-files +packages/microbit-connection/examples +package-lock.json +*.hex diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..1da28a15 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,65 @@ +# microbit-connection + +TypeScript library for connecting to BBC micro:bit devices via USB and Bluetooth (BLE), including partial and full (DFU) flashing. Published as `@microbit/microbit-connection` on NPM. + +## Monorepo structure + +npm workspaces monorepo: + +- **`packages/microbit-connection/`** — The library. Dual ESM + CJS build. +- **`apps/demo/`** — Vite + React demo app with Capacitor support for mobile. +- **`third-party/`** — Vendored dependencies (patched dapjs). + +## Commands + +``` +npm run build:lib # Build the library (ESM + CJS) +npm run build # Build everything (lib + demo) +npm run dev # Run demo app dev server +npm test # Run tests (vitest) +npm run format # Prettier format +npm run format:check # Prettier check +npm run docs # Generate TypeDoc docs +``` + +From the library package directory (`packages/microbit-connection/`): + +- `npx vitest run` — Run tests once +- `npx vitest` — Run tests in watch mode + +## Key source areas + +The library source is in `packages/microbit-connection/src/`: + +- **Connection types**: `usb.ts` (WebUSB), `bluetooth.ts` (Web Bluetooth), `usb-radio-bridge.ts` (radio bridge via USB) +- **Flashing**: `flashing/` directory — `flashing-partial.ts` (partial flash over BLE/USB), `flashing-full.ts` (full flash), `nordic-dfu.ts` (DFU via Capacitor plugin), `flashing-v1.ts` (V1-specific) +- **BLE services**: `accelerometer-service.ts`, `button-service.ts`, `uart-service.ts`, `led-service.ts`, `magnetometer-service.ts`, `dfu-service.ts`, `partial-flashing-service.ts`, `device-information-service.ts` +- **Shared**: `device.ts` (core types/interfaces), `events.ts` (typed event target), `bluetooth-profile.ts` (UUIDs), `board-id.ts` + +## Architecture notes + +- Factory functions (`createWebUSBConnection`, `createWebBluetoothConnection`, `createRadioBridgeConnection`) are the public API entry points +- Capacitor platform support: native BLE via `@capacitor-community/bluetooth-le`, native DFU via `@microbit/capacitor-community-nordic-dfu` (from `../nordic-dfu/`). These are peer dependencies. +- `Capacitor.isNativePlatform()` is used to branch between web and native code paths. + +## Related projects + +Note: these paths rely on an {org}/{repo} scheme for checkouts that might not hold for all developers. If projects are not available then ask the user. + +### Capacitor plugins + +- **`../nordic-dfu/`** — Capacitor plugin wrapping the Nordic DFU libraries (iOS: iOSDFULibrary, Android: Android-DFU-Library). The iOS plugin code (`ios/Plugin/Plugin.swift`) configures the DFU initiator. + +### Native apps (reference implementations) + +- **`../microbit-ios/`** — The official micro:bit iOS app. Its DFU flow in `Source/irmLink.m` (lines ~3810-3885) is the reference for how DFU should work on iOS. The bundled `Pods/iOSDFULibrary/` contains the iOS DFU library source, useful for understanding scan/reconnect behaviour. +- **`../microbit-android/`** — The official micro:bit Android app. Its DFU setup in `app/src/main/java/.../ProjectActivity.java` is the reference for Android DFU options. + +### Firmware and bootloader + +- **`../v2-bootloader/`** — micro:bit V2 bootloader. Key files: + - `bootloader/microbit/config/sdk_config.h` — build config (`NRF_DFU_BLE_REQUIRES_BONDS`, `NRF_DFU_BLE_ADV_NAME`) + - `nRF5SDK_mods/components/libraries/bootloader/ble_dfu/nrf_dfu_ble.c` — BLE transport with micro:bit-specific runtime patches (peer data validation, write permission downgrade, advertising name handling) + - `bootloader/main.c` — DFU observer and LED display symbols +- **`../../lancaster-university/codal-microbit-v2/`** — micro:bit V2 runtime (CODAL). BLE stack configuration in `source/bluetooth/MicroBitBLEManager.cpp`. +- **`../../lancaster-university/microbit-dal/`** — micro:bit V1 runtime (DAL). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 00000000..a0061ec0 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,279 @@ +# Migration guide (v0 → v1) + +This guide covers the breaking changes between `0.x` and `1.0`. + +## Subpath exports + +Everything was previously exported from a single entry point. Imports are now split across subpath exports: + +| v0 import | v1 import | +| ------------------------------- | --------------------------------------------------- | +| `@microbit/microbit-connection` | `@microbit/microbit-connection` (shared types only) | +| `@microbit/microbit-connection` | `@microbit/microbit-connection/bluetooth` | +| `@microbit/microbit-connection` | `@microbit/microbit-connection/usb` | +| `@microbit/microbit-connection` | `@microbit/microbit-connection/radio-bridge` | +| `@microbit/microbit-connection` | `@microbit/microbit-connection/universal-hex` | + +The root entry point now only exports shared types and utilities (`ConnectionStatus`, `DeviceError`, `FlashDataError`, `assertConnected`, `ProgressStage`, data types, etc.). Connection-specific factory functions and types must be imported from their subpath. + +```ts +// v0 +import { + createWebUSBConnection, + createWebBluetoothConnection, + createRadioBridgeConnection, + createUniversalHexFlashDataSource, + ConnectionStatus, +} from "@microbit/microbit-connection"; + +// v1 +import { ConnectionStatus } from "@microbit/microbit-connection"; +import { createUSBConnection } from "@microbit/microbit-connection/usb"; +import { createBluetoothConnection } from "@microbit/microbit-connection/bluetooth"; +import { createRadioBridgeConnection } from "@microbit/microbit-connection/radio-bridge"; +import { createUniversalHexFlashDataSource } from "@microbit/microbit-connection/universal-hex"; +``` + +## Renamed exports + +### Factory functions + +| v0 | v1 | +| -------------------------------- | ----------------------------- | +| `createWebUSBConnection()` | `createUSBConnection()` | +| `createWebBluetoothConnection()` | `createBluetoothConnection()` | + +### Connection types + +| v0 | v1 | +| --------------------------------------- | ------------------------------------ | +| `MicrobitWebUSBConnection` | `MicrobitUSBConnection` | +| `MicrobitWebUSBConnectionOptions` | `MicrobitUSBConnectionOptions` | +| `MicrobitWebBluetoothConnection` | `MicrobitBluetoothConnection` | +| `MicrobitWebBluetoothConnectionOptions` | `MicrobitBluetoothConnectionOptions` | + +## Enums → const objects + +`ConnectionStatus`, `ButtonState`, and `DeviceSelectionMode` have all changed from TypeScript `enum` declarations to `as const` objects. Property access like `ConnectionStatus.Connected` still works, but there are some differences: + +- **String values changed casing** — e.g. `"NO_AUTHORIZED_DEVICE"` → `"NoAuthorizedDevice"`. Code that compares against the string literals directly (rather than using the constant) will need updating. +- **Type identity** — the TypeScript type is now a union of literal values (e.g. `"Connected" | "Disconnected" | ...`) rather than the enum type. In practice this rarely matters unless you were using `typeof ConnectionStatus` as a type, which is now the object type rather than the union. Use the `ConnectionStatus` type (not `typeof`) for the union. +- **`ButtonState` numeric values are unchanged** (`0`, `1`, `2`) so runtime behaviour is the same. +- **`DeviceSelectionMode` values are unchanged** (`"AlwaysAsk"`, `"UseAnyAllowed"`). + +### `ConnectionStatus` — non-trivial changes + +Beyond the casing change, several members were added or removed: + +| v0 (enum) | v1 (const) | +| ---------------------- | --------------------------------------------------------------- | +| `SUPPORT_NOT_KNOWN` | Removed — use `checkAvailability()` instead | +| `NOT_SUPPORTED` | Removed — use `checkAvailability()` instead | +| `NO_AUTHORIZED_DEVICE` | `NoAuthorizedDevice` | +| `DISCONNECTED` | `Disconnected` | +| `CONNECTED` | `Connected` | +| `CONNECTING` | `Connecting` | +| `RECONNECTING` | Removed | +| — | `Paused` (new — USB connection suspended due to tab visibility) | + +## `DeviceErrorCode` values renamed + +| v0 | v1 | +| -------------------------- | ----------------------------------- | +| `"update-req"` | `"firmware-update-required"` | +| `"clear-connect"` | `"device-in-use"` | +| `"timeout-error"` | `"timeout"` | +| `"reconnect-microbit"` | `"connection-error"` | +| `"background-comms-error"` | Removed (uses `"connection-error"`) | +| `"service-missing"` | Removed | +| — | `"aborted"` (new) | +| — | `"unsupported"` (new) | +| — | `"disabled"` (new) | +| — | `"permission-denied"` (new) | +| — | `"location-disabled"` (new) | +| — | `"not-connected"` (new) | +| — | `"pairing-information-lost"` (new) | + +## Event system overhaul + +### No longer extends DOM `EventTarget` + +`TypedEventTarget` is no longer a wrapper around the DOM `EventTarget`. It is now a standalone typed event emitter. Listeners receive **plain data objects** instead of `Event` subclass instances. + +### Event classes removed + +The following event classes are removed. Listeners now receive plain data directly: + +| v0 class | v1 listener data | +| ------------------------ | ------------------------------------------------------- | +| `ConnectionStatusEvent` | `ConnectionStatusChange` (`{ status, previousStatus }`) | +| `BackgroundErrorEvent` | `BackgroundErrorData` (`{ error, event? }`) | +| `BeforeRequestDevice` | `void` (no argument) | +| `AfterRequestDevice` | `void` (no argument) | +| `FlashEvent` | `void` (no argument) | +| `AccelerometerDataEvent` | `AccelerometerData` (`{ x, y, z }`) | +| `ButtonEvent` | `ButtonData` (`{ button, state }`) | +| `MagnetometerDataEvent` | `MagnetometerData` (`{ x, y, z }`) | +| `UARTDataEvent` | `UartData` (`{ value }`) | +| `SerialDataEvent` | `SerialData` (`{ data }`) | +| `SerialResetEvent` | `void` | +| `SerialErrorEvent` | Removed (uses backgrounderror) | + +```ts +// v0 +connection.addEventListener("status", (event: ConnectionStatusEvent) => { + console.log(event.status); +}); +connection.addEventListener( + "accelerometerdatachanged", + (event: AccelerometerDataEvent) => { + console.log(event.data.x); + }, +); + +// v1 +connection.addEventListener("status", (data: ConnectionStatusChange) => { + console.log(data.status, data.previousStatus); +}); +connection.addEventListener( + "accelerometerdatachanged", + (data: AccelerometerData) => { + console.log(data.x); + }, +); +``` + +### `addEventListener` / `removeEventListener` options removed + +The v0 `addEventListener` accepted an optional third `options` parameter (matching the DOM API: `once`, `capture`, `passive`). In v1, no options parameter is accepted. + +### `dispatchEvent` / `dispatchTypedEvent` removed + +These are no longer part of the public `TypedEventTarget` API. Event dispatching is internal only. + +### `backgrounderror` event data changed + +| v0 | v1 | +| -------------------------------------------------- | ----------------------------------------------------------------------------- | +| `BackgroundErrorEvent` with `errorMessage: string` | `BackgroundErrorData` with `error: DeviceError` and optional `event?: string` | + +### Button event data changed + +v0 dispatched a `ButtonEvent` with a `state` property and the event type (`"buttonachanged"` / `"buttonbchanged"`) encoded in the event name. + +v1 dispatches a `ButtonData` object with both `button` (`"A"` / `"B"`) and `state` fields. + +### Serial events are USB-only, Bluetooth has UART + +In v0, serial events and `serialWrite()` were on the base `DeviceConnection` interface. In v1, serial is specific to USB and UART is specific to Bluetooth: + +- `"serialdata"`, `"serialreset"`, and `serialWrite(data: string)` are only on `MicrobitUSBConnection`. +- `"uartdata"` and `uartWrite(data: Uint8Array)` are only on `MicrobitBluetoothConnection`. +- `"serialerror"` / `SerialErrorEvent` are removed (errors surface via `"backgrounderror"`). + +## `DeviceConnection` interface changes + +### `connect()` return type + +```ts +// v0 +connect(): Promise; + +// v1 +connect(options?: ConnectOptions): Promise; +``` + +`connect()` no longer returns the final `ConnectionStatus`. It throws a `DeviceError` on failure instead, so the return value is unnecessary — success means connected, failure means an exception with a specific `DeviceErrorCode`. It now also accepts an optional `ConnectOptions` with `progress` and `signal` fields. + +### `getBoardVersion()` return type + +```ts +// v0 +getBoardVersion(): BoardVersion | undefined; + +// v1 +getBoardVersion(): BoardVersion; // throws DeviceError("not-connected") if not connected +``` + +### `flash()` is optional and moved + +`flash()` was not on the base `DeviceConnection` in v0. In v1 it is an optional method on `DeviceConnection` (`flash?(...)`), with concrete implementations on `MicrobitUSBConnection` and `MicrobitBluetoothConnection`. + +### `checkAvailability()` added + +```ts +checkAvailability(): Promise; +``` + +Replaces the old `SUPPORT_NOT_KNOWN` / `NOT_SUPPORTED` connection statuses. + +### `type` property added + +All connections now expose a readonly `type` property (`"usb"`, `"bluetooth"`, or `"radio-bridge"`). + +## `FlashOptions.progress` callback changed + +```ts +// v0 +progress: (percentage: number | undefined, partial: boolean) => void; + +// v1 +progress: ProgressCallback; +// where ProgressCallback = (stage: ProgressStage, progress?: number) => void; +``` + +The callback is now a `ProgressCallback` that receives a `ProgressStage` enum value and an optional 0–1 progress number, rather than a percentage and partial flag. + +## `FlashOptions.partial` default + +`FlashOptions.partial` is now optional and defaults to `true` (was required in v0). + +## Bluetooth getter return types + +Methods that previously returned `T | undefined` now throw if not connected: + +| Method | v0 return | v1 return | +| -------------------------- | -------------------------------- | ------------------- | +| `getAccelerometerData()` | `AccelerometerData \| undefined` | `AccelerometerData` | +| `getAccelerometerPeriod()` | `number \| undefined` | `number` | +| `getLedScrollingDelay()` | `number \| undefined` | `number` | +| `getLedMatrix()` | `LedMatrix \| undefined` | `LedMatrix` | +| `getMagnetometerData()` | `MagnetometerData \| undefined` | `MagnetometerData` | +| `getMagnetometerBearing()` | `number \| undefined` | `number` | +| `getMagnetometerPeriod()` | `number \| undefined` | `number` | + +## USB `getDeviceId()` return type + +```ts +// v0 +getDeviceId(): number | undefined; + +// v1 +getDeviceId(): number; // throws if not connected +``` + +## Removed exports + +The following are no longer exported from the package: + +- `BoardId` — use the connection's own methods instead +- `TypedEventTarget` — internal implementation detail +- `DeviceConnectionEventMap` — event maps are no longer exported as classes +- `SerialConnectionEventMap` — replaced by typed overloads on connection interfaces +- `ServiceConnectionEventMap` — replaced by typed overloads on connection interfaces +- `NullLogging` — not part of public API + +## Tab visibility handling (`pauseOnHidden`) + +In v0, the USB connection unconditionally disconnected when the browser tab became hidden and reconnected when the tab became visible again. The status transitioned to `DISCONNECTED` during this time, making it indistinguishable from a real disconnection. + +In v1, this behaviour is now: + +- **Controllable** — the new `pauseOnHidden` option (default `true`) can be set to `false` to keep the connection open while the tab is hidden. Use this with care: holding the USB interface while the tab is hidden prevents other tabs or applications from connecting to the micro:bit, which can be confusing for users. +- **Observable** — when the connection is paused, the status transitions to `ConnectionStatus.Paused` instead of `Disconnected`, so the UI can distinguish between a temporary pause and a real disconnection. + +Reconnection is still automatic when the tab becomes visible again. If reconnection fails (e.g. another process claimed the USB interface), the status transitions to `Disconnected`. + +## `MicrobitRadioBridgeConnectionOptions.logging` now optional + +Was required in v0, is now optional. diff --git a/README.md b/README.md index 8e69a600..e78210ec 100644 --- a/README.md +++ b/README.md @@ -2,57 +2,76 @@ This documentation is best viewed on the documentation site rather than GitHub or NPM package site. -This is a JavaScript library for micro:bit connections in browsers via USB and Bluetooth. +A TypeScript library for connecting to micro:bit devices via USB and Bluetooth. Works in browsers (via WebUSB and Web Bluetooth) and in native iOS/Android apps (Bluetooth only, via [Capacitor](https://capacitorjs.com/)). -This project is a work in progress. We are extracting WebUSB and Web Bluetooth code from the [micro:bit Python Editor](https://github.com/microbit-foundation/python-editor-v3/) and other projects. The API is not stable and it's not yet recommended that third parties use this project unless they are happy to update usage as the API evolves. +[Available on NPM](https://www.npmjs.com/package/@microbit/microbit-connection). Migrating from an earlier version? See the [migration guide](https://github.com/microbit-foundation/microbit-connection/blob/main/MIGRATION.md). -[Demo page](https://microbit-connection.pages.dev/) for this library. +### Demo apps -[Alpha releases are now on NPM](https://www.npmjs.com/package/@microbit/microbit-connection). +- [Demo app](https://microbit-connection.pages.dev/) ([source](https://github.com/microbit-foundation/microbit-connection/tree/main/apps/demo)) — WebUSB, Web Bluetooth, and Capacitor for native mobile -[micro:bit CreateAI](https://github.com/microbit-foundation/ml-trainer/) is already using this library for WebUSB and Web Bluetooth. +### Projects using this library -[This Python Editor PR](https://github.com/microbit-foundation/python-editor-v3/pull/1190) tracks updating the micro:bit Python Editor to use this library. +- [micro:bit CreateAI](https://github.com/microbit-foundation/ml-trainer/) +- [micro:bit Python Editor](https://github.com/microbit-foundation/python-editor-v3/) + +### Platform support + +| Feature | Web (browser) | Native (Capacitor) | +| -------------------- | ------------- | ------------------ | +| USB connection | WebUSB | Not supported | +| Bluetooth connection | Web Bluetooth | iOS and Android | +| Flash via USB | Yes | Not supported | +| Flash via Bluetooth | Not supported | iOS and Android | + +## Entrypoints + +The library is split into separate entrypoints for tree-shaking. Import shared types from the root and connection-specific code from subpaths: + +| Import path | Contents | +| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `@microbit/microbit-connection` | Shared types and events (`ConnectionStatus`, `DeviceConnection`, `FlashOptions`, etc.) | +| `@microbit/microbit-connection/bluetooth` | `createBluetoothConnection` and Bluetooth connection types | +| `@microbit/microbit-connection/usb` | `createUSBConnection` and USB connection types | +| `@microbit/microbit-connection/universal-hex` | `createUniversalHexFlashDataSource` (depends on `@microbit/microbit-universal-hex`) | +| `@microbit/microbit-connection/radio-bridge` | **Experimental.** `createRadioBridgeConnection` for radio bridge via USB. Limited service support — see JSDoc for details. | ## Usage ### Flash a micro:bit -Instantiate a WebUSB connection using {@link createWebUSBConnection} class and use it to connect to a micro:bit. +Instantiate a WebUSB connection using {@link @microbit/microbit-connection/usb!createUSBConnection | createUSBConnection} and use it to connect to a micro:bit. ```ts -import { createWebUSBConnection } from "@microbit/microbit-connection"; +import { createUSBConnection } from "@microbit/microbit-connection/usb"; -const usb = createWebUSBConnection(); -const connectionStatus = await usb.connect(); +const usb = createUSBConnection(); +await usb.connect(); -console.log("Connection status: ", connectionStatus); +console.log("Connection status: ", usb.status); // "Connected" ``` -{@link ConnectionStatus | Connection status} is `"CONNECTED"` if connection succeeds. - Flash a universal hex that supports both V1 and V2: ```ts -import { createUniversalHexFlashDataSource } from "@microbit/microbit-connection"; +import { createUniversalHexFlashDataSource } from "@microbit/microbit-connection/universal-hex"; await usb.flash(createUniversalHexFlashDataSource(universalHexString), { partial: true, - progress: (percentage: number | undefined) => { - console.log(percentage); + progress: (stage, percentage) => { + console.log(stage, percentage); }, }); ``` This code will also work for non-universal hex files so is a good default for unknown hex files. -Alternatively, you can create and flash a hex for a specific micro:bit version by providing a function that takes a {@link BoardVersion} and returns a hex. +Alternatively, you can create and flash a hex for a specific micro:bit version by providing a function that takes a {@link @microbit/microbit-connection!BoardVersion} and returns a hex. This can reduce download size or help integrate with APIs that produce a hex for a particular device version. This example uses the [@microbit/microbit-fs library](https://microbit-foundation.github.io/microbit-fs/) which can return a hex based on board id. ```ts import { MicropythonFsHex, microbitBoardId } from "@microbit/microbit-fs"; -import { BoardId } from "@microbit/microbit-connection"; const micropythonFs = new MicropythonFsHex([ { hex: microPythonV1HexFile, boardId: microbitBoardId.V1 }, @@ -62,44 +81,104 @@ const micropythonFs = new MicropythonFsHex([ // Flash the device await usb.flash( async (boardVersion) => { - const boardId = BoardId.forVersion(boardVersion).id; - return micropythonFs.getIntelHex(boardId); + return micropythonFs.getIntelHex(microbitBoardId[boardVersion]); }, { partial: true, - progress: (percentage: number | undefined) => { - console.log(percentage); + progress: (stage, percentage) => { + console.log(stage, percentage); }, }, ); ``` -For more examples of using other methods in the {@link MicrobitWebUSBConnection} class, see our [demo code](https://github.com/microbit-foundation/microbit-connection/blob/main/src/demo.ts) for our [demo site](https://microbit-connection.pages.dev/). +#### Post-flash connection state + +The connection state after flashing differs between USB and Bluetooth because they connect to different parts of the micro:bit hardware: + +- **USB** connects to the **interface chip** (running DAPLink firmware), which is separate from the application processor that runs user code. Flashing does not affect the interface chip, so the USB connection remains in `"Connected"` state and serial communication is automatically reinitialised. + +- **Bluetooth** connects directly to the **application processor** (the Nordic nRF51/nRF52 running the user's program and BLE stack). This processor reboots after flashing, so the Bluetooth connection is necessarily lost. The connection is always left in `"Disconnected"` state and callers must call `connect()` again after flashing. + +#### Tab visibility and the Paused state + +By default, a USB connection is automatically paused when the browser tab becomes hidden and reconnected when the tab becomes visible again. This frees the USB interface for other tabs or processes while the user isn't looking at the page. During this time the connection status is `"Paused"`. + +If reconnection fails when the tab becomes visible again (for example, because another process has claimed the USB interface), the connection transitions to `"Disconnected"`. + +To disable this behaviour, pass `pauseOnHidden: false`: + +```ts +const usb = createUSBConnection({ pauseOnHidden: false }); +``` + +For more examples see the [demo app source](https://github.com/microbit-foundation/microbit-connection/tree/main/apps/demo/src). ### Connect via Bluetooth By default, the micro:bit's Bluetooth service is not enabled. Visit our [Bluetooth tech site page](https://tech.microbit.org/bluetooth/) to download a hex file that would enable the bluetooth service. -Instantiate a Bluetooth connection using {@link createWebBluetoothConnection} class and use it to connect to a micro:bit. +Instantiate a Bluetooth connection using {@link @microbit/microbit-connection/bluetooth!createBluetoothConnection | createBluetoothConnection} class and use it to connect to a micro:bit. ```ts -import { createWebBluetoothConnection } from "@microbit/microbit-connection"; +import { createBluetoothConnection } from "@microbit/microbit-connection/bluetooth"; -const bluetooth = createWebBluetoothConnection(); -const connectionStatus = await bluetooth.connect(); +const bluetooth = createBluetoothConnection(); +await bluetooth.connect(); -console.log("Connection status: ", connectionStatus); +console.log("Connection status: ", bluetooth.status); // "Connected" ``` -{@link ConnectionStatus | Connection status} is `"CONNECTED"` if connection succeeds. +For more examples see the [demo app source](https://github.com/microbit-foundation/microbit-connection/tree/main/apps/demo/src). + +### Error handling + +Methods that interact with device features (reading sensors, writing to LEDs, serial communication, etc.) throw a {@link @microbit/microbit-connection!DeviceError | DeviceError} with code `"not-connected"` if called without an active connection: + +```ts +import { DeviceError } from "@microbit/microbit-connection"; + +try { + const data = await bluetooth.getAccelerometerData(); +} catch (e) { + if (e instanceof DeviceError && e.code === "not-connected") { + console.log("Connect to a micro:bit first"); + } +} +``` + +## Known limitations + +### Bluetooth + +### Open link security mode hex file already on micro:bit + +Open link hex files are not common. The most common source is the micro:bit CreateAI. Known issues: + +- **iOS DFU classroom collision risk with open-link firmware**: When performing DFU on iOS with open-link security firmware (no bonding), the Nordic DFU library scans for the bootloader by DFU service UUID and connects to the first matching device. If multiple micro:bits are in bootloader mode simultaneously, the wrong device could be targeted. This does not affect bonded firmware (where the bootloader uses whitelist-filtered advertising) or Android (which reconnects by MAC address). + +- **V1 Android PIN dialog with open-link firmware**: On Android with micro:bit V1, calling `createBond` triggers a passkey entry dialog because the V1 DAL declares `IO_CAPS_DISPLAY_ONLY` even in open-link mode. The micro:bit displays a PIN that the user must enter. This is a bug in the V1 DAL (V2 correctly uses `IO_CAPS_NONE`). There is no BLE-visible indicator of the security mode, so the library cannot detect this situation to avoid it. On V2 you get a harmless (but somewhat pointless) "just works" pairing dialog. + +### No suitable services on the micro:bit to flash + +- **Hex with no partial flashing or DFU control service (V1)**: Some older CreateAI data-collection hex files for micro:bit V1 fall into this category. There's nothing that can be done via Bluetooth. Workaround: flash via WebUSB or drag and drop from a computer. The equivalent V2 hex does have the Secure DFU service (but not partial flashing) which we support. + +## Hardware testing + +The [hardware test app](https://github.com/microbit-foundation/microbit-connection/tree/main/apps/hardware-test) is a human-in-the-loop test runner for USB flashing. It covers partial and full flash, flash fallback paths, serial data integrity after flash, and reconnection after unplug. Run it with: + +```bash +cd apps/hardware-test +npm run dev +``` -For more examples of using other methods in the {@link createWebBluetoothConnection} class, see our [demo code](https://github.com/microbit-foundation/microbit-connection/blob/main/src/demo.ts) for our [demo site](https://microbit-connection.pages.dev/). +The tests prompt you for physical actions (plugging/unplugging) and verify the results automatically. ## License This software is under the MIT open source license. -[SPDX-License-Identifier: MIT](LICENSE) +[SPDX-License-Identifier: MIT](https://github.com/microbit-foundation/microbit-connection/blob/main/LICENSE.md) We use dependencies via the NPM registry as specified by the package.json file under common Open Source licenses. diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 370ab20d..00000000 --- a/TODO.md +++ /dev/null @@ -1,8 +0,0 @@ -- Figure out the interface for flash - - Remove the sim? It's unrelated really. - - Add a JS partial flashing implementation, perhaps based on the prototype app - - Consider a full flash implementation later... for now we'll need to indicate lack of support somehow with a structured error code? - -Doc links for the memory map: -- https://microbit-micropython.readthedocs.io/en/v2-docs/devguide/hexformat.html -- https://github.com/lancaster-university/codal-microbit-v2/blob/master/docs/MemoryMap.md diff --git a/apps/demo/README.md b/apps/demo/README.md new file mode 100644 index 00000000..d19bb89d --- /dev/null +++ b/apps/demo/README.md @@ -0,0 +1,34 @@ +# micro:bit connection demo + +A React demo app for the [`@microbit/microbit-connection`](../../packages/microbit-connection/) library. It exercises USB, Bluetooth, and radio bridge connections, flashing, sensors, LEDs, serial, and UART. + +The same codebase runs as a web app (using WebUSB and Web Bluetooth) and as a native mobile app (using [Capacitor](https://capacitorjs.com/) for Bluetooth and DFU on iOS/Android). + +## Web only + +If you only care about the web demo, you can ignore the Capacitor dependencies entirely. The app detects the platform at runtime via `Capacitor.isNativePlatform()` and the native-only code paths are never reached in a browser. + +```bash +# From the monorepo root +npm run build:lib +npm run dev +``` + +## Mobile (Capacitor) + +To run on iOS or Android you need the native projects. These are not checked in — generate them with: + +```bash +cd apps/demo +npx cap add ios # or android +npx cap sync +npx cap open ios # opens Xcode +``` + +For local development with live reload: + +```bash +npm run dev:apps # Vite dev server on --host +CAP_LOCAL_DEV=1 npx cap sync # points native project at dev server +npx cap run ios # or android +``` diff --git a/apps/demo/android/.gitignore b/apps/demo/android/.gitignore new file mode 100644 index 00000000..48354a3d --- /dev/null +++ b/apps/demo/android/.gitignore @@ -0,0 +1,101 @@ +# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore + +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +# Android Studio 3 in .gitignore file. +.idea/caches +.idea/modules.xml +# Comment next line if keeping position of elements in Navigation Editor is relevant for you +.idea/navEditor.xml + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ +# lint/reports/ + +# Android Profiling +*.hprof + +# Cordova plugins for Capacitor +capacitor-cordova-android-plugins + +# Copied web assets +app/src/main/assets/public + +# Generated Config files +app/src/main/assets/capacitor.config.json +app/src/main/assets/capacitor.plugins.json +app/src/main/res/xml/config.xml diff --git a/apps/demo/android/app/.gitignore b/apps/demo/android/app/.gitignore new file mode 100644 index 00000000..043df802 --- /dev/null +++ b/apps/demo/android/app/.gitignore @@ -0,0 +1,2 @@ +/build/* +!/build/.npmkeep diff --git a/apps/demo/android/app/build.gradle b/apps/demo/android/app/build.gradle new file mode 100644 index 00000000..8af32423 --- /dev/null +++ b/apps/demo/android/app/build.gradle @@ -0,0 +1,54 @@ +apply plugin: 'com.android.application' + +android { + namespace "org.microbit.connection.demo" + compileSdk rootProject.ext.compileSdkVersion + defaultConfig { + applicationId "org.microbit.connection.demo" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + aaptOptions { + // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. + // Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61 + ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' + } + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +repositories { + flatDir{ + dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs' + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" + implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" + implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" + implementation project(':capacitor-android') + testImplementation "junit:junit:$junitVersion" + androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" + implementation project(':capacitor-cordova-android-plugins') +} + +apply from: 'capacitor.build.gradle' + +try { + def servicesJSON = file('google-services.json') + if (servicesJSON.text) { + apply plugin: 'com.google.gms.google-services' + } +} catch(Exception e) { + logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work") +} diff --git a/apps/demo/android/app/capacitor.build.gradle b/apps/demo/android/app/capacitor.build.gradle new file mode 100644 index 00000000..47bc26fd --- /dev/null +++ b/apps/demo/android/app/capacitor.build.gradle @@ -0,0 +1,22 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN + +android { + compileOptions { + sourceCompatibility JavaVersion.VERSION_21 + targetCompatibility JavaVersion.VERSION_21 + } +} + +apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle" +dependencies { + implementation project(':capacitor-community-bluetooth-le') + implementation project(':capacitor-filesystem') + implementation project(':capacitor-preferences') + implementation project(':microbit-capacitor-community-nordic-dfu') + +} + + +if (hasProperty('postBuildExtras')) { + postBuildExtras() +} diff --git a/apps/demo/android/app/proguard-rules.pro b/apps/demo/android/app/proguard-rules.pro new file mode 100644 index 00000000..f1b42451 --- /dev/null +++ b/apps/demo/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/apps/demo/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java b/apps/demo/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java new file mode 100644 index 00000000..f2c2217e --- /dev/null +++ b/apps/demo/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.getcapacitor.myapp; + +import static org.junit.Assert.*; + +import android.content.Context; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + + assertEquals("com.getcapacitor.app", appContext.getPackageName()); + } +} diff --git a/apps/demo/android/app/src/main/AndroidManifest.xml b/apps/demo/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..7a523ab3 --- /dev/null +++ b/apps/demo/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/demo/android/app/src/main/java/org/microbit/connection/demo/MainActivity.java b/apps/demo/android/app/src/main/java/org/microbit/connection/demo/MainActivity.java new file mode 100644 index 00000000..a51ca114 --- /dev/null +++ b/apps/demo/android/app/src/main/java/org/microbit/connection/demo/MainActivity.java @@ -0,0 +1,5 @@ +package org.microbit.connection.demo; + +import com.getcapacitor.BridgeActivity; + +public class MainActivity extends BridgeActivity {} diff --git a/apps/demo/android/app/src/main/res/drawable-land-hdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-land-hdpi/splash.png new file mode 100644 index 00000000..e31573b4 Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-land-hdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-land-mdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-land-mdpi/splash.png new file mode 100644 index 00000000..f7a64923 Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-land-mdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-land-xhdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-land-xhdpi/splash.png new file mode 100644 index 00000000..80772550 Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-land-xhdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-land-xxhdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-land-xxhdpi/splash.png new file mode 100644 index 00000000..14c6c8fe Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-land-xxhdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-land-xxxhdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-land-xxxhdpi/splash.png new file mode 100644 index 00000000..244ca250 Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-land-xxxhdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-port-hdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-port-hdpi/splash.png new file mode 100644 index 00000000..74faaa58 Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-port-hdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-port-mdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-port-mdpi/splash.png new file mode 100644 index 00000000..e944f4ad Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-port-mdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-port-xhdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-port-xhdpi/splash.png new file mode 100644 index 00000000..564a82ff Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-port-xhdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-port-xxhdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-port-xxhdpi/splash.png new file mode 100644 index 00000000..bfabe687 Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-port-xxhdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-port-xxxhdpi/splash.png b/apps/demo/android/app/src/main/res/drawable-port-xxxhdpi/splash.png new file mode 100644 index 00000000..69290712 Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable-port-xxxhdpi/splash.png differ diff --git a/apps/demo/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/apps/demo/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 00000000..c7bd21db --- /dev/null +++ b/apps/demo/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/apps/demo/android/app/src/main/res/drawable/ic_launcher_background.xml b/apps/demo/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000..d5fccc53 --- /dev/null +++ b/apps/demo/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/demo/android/app/src/main/res/drawable/splash.png b/apps/demo/android/app/src/main/res/drawable/splash.png new file mode 100644 index 00000000..f7a64923 Binary files /dev/null and b/apps/demo/android/app/src/main/res/drawable/splash.png differ diff --git a/apps/demo/android/app/src/main/res/layout/activity_main.xml b/apps/demo/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..b5ad1387 --- /dev/null +++ b/apps/demo/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/apps/demo/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/apps/demo/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..036d09bc --- /dev/null +++ b/apps/demo/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/apps/demo/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/apps/demo/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000..036d09bc --- /dev/null +++ b/apps/demo/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..c023e505 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..2127973b Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 00000000..b441f37d Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..72905b85 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..8ed0605c Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 00000000..9502e47a Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..4d1e0771 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..df0f1588 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 00000000..853db043 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..6cdf97c1 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..2960cbb6 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..8e3093a8 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..46de6e25 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..d2ea9abe Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..a40d73e9 Binary files /dev/null and b/apps/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/apps/demo/android/app/src/main/res/values/ic_launcher_background.xml b/apps/demo/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 00000000..c5d5899f --- /dev/null +++ b/apps/demo/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file diff --git a/apps/demo/android/app/src/main/res/values/strings.xml b/apps/demo/android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..f9f3fa4c --- /dev/null +++ b/apps/demo/android/app/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ + + + micro:bit connection demo + micro:bit connection demo + org.microbit.connection.demo + org.microbit.connection.demo + diff --git a/apps/demo/android/app/src/main/res/values/styles.xml b/apps/demo/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..be874e54 --- /dev/null +++ b/apps/demo/android/app/src/main/res/values/styles.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/apps/demo/android/app/src/main/res/xml/file_paths.xml b/apps/demo/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 00000000..bd0c4d80 --- /dev/null +++ b/apps/demo/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/apps/demo/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java b/apps/demo/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java new file mode 100644 index 00000000..02973278 --- /dev/null +++ b/apps/demo/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java @@ -0,0 +1,18 @@ +package com.getcapacitor.myapp; + +import static org.junit.Assert.*; + +import org.junit.Test; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } +} diff --git a/apps/demo/android/build.gradle b/apps/demo/android/build.gradle new file mode 100644 index 00000000..f1b3b0e5 --- /dev/null +++ b/apps/demo/android/build.gradle @@ -0,0 +1,29 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.7.2' + classpath 'com.google.gms:google-services:4.4.2' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: "variables.gradle" + +allprojects { + repositories { + google() + mavenCentral() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/apps/demo/android/capacitor.settings.gradle b/apps/demo/android/capacitor.settings.gradle new file mode 100644 index 00000000..7df5fad8 --- /dev/null +++ b/apps/demo/android/capacitor.settings.gradle @@ -0,0 +1,15 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN +include ':capacitor-android' +project(':capacitor-android').projectDir = new File('../../../node_modules/@capacitor/android/capacitor') + +include ':capacitor-community-bluetooth-le' +project(':capacitor-community-bluetooth-le').projectDir = new File('../../../node_modules/@capacitor-community/bluetooth-le/android') + +include ':capacitor-filesystem' +project(':capacitor-filesystem').projectDir = new File('../../../node_modules/@capacitor/filesystem/android') + +include ':capacitor-preferences' +project(':capacitor-preferences').projectDir = new File('../../../node_modules/@capacitor/preferences/android') + +include ':microbit-capacitor-community-nordic-dfu' +project(':microbit-capacitor-community-nordic-dfu').projectDir = new File('../../../node_modules/@microbit/capacitor-community-nordic-dfu/android') diff --git a/apps/demo/android/gradle.properties b/apps/demo/android/gradle.properties new file mode 100644 index 00000000..2e87c52f --- /dev/null +++ b/apps/demo/android/gradle.properties @@ -0,0 +1,22 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true diff --git a/apps/demo/android/gradle/wrapper/gradle-wrapper.jar b/apps/demo/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..a4b76b95 Binary files /dev/null and b/apps/demo/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/apps/demo/android/gradle/wrapper/gradle-wrapper.properties b/apps/demo/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..c1d5e018 --- /dev/null +++ b/apps/demo/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/apps/demo/android/gradlew b/apps/demo/android/gradlew new file mode 100755 index 00000000..f5feea6d --- /dev/null +++ b/apps/demo/android/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/apps/demo/android/gradlew.bat b/apps/demo/android/gradlew.bat new file mode 100644 index 00000000..9b42019c --- /dev/null +++ b/apps/demo/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/apps/demo/android/settings.gradle b/apps/demo/android/settings.gradle new file mode 100644 index 00000000..3b4431d7 --- /dev/null +++ b/apps/demo/android/settings.gradle @@ -0,0 +1,5 @@ +include ':app' +include ':capacitor-cordova-android-plugins' +project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/') + +apply from: 'capacitor.settings.gradle' \ No newline at end of file diff --git a/apps/demo/android/variables.gradle b/apps/demo/android/variables.gradle new file mode 100644 index 00000000..2c8e4083 --- /dev/null +++ b/apps/demo/android/variables.gradle @@ -0,0 +1,16 @@ +ext { + minSdkVersion = 23 + compileSdkVersion = 35 + targetSdkVersion = 35 + androidxActivityVersion = '1.9.2' + androidxAppCompatVersion = '1.7.0' + androidxCoordinatorLayoutVersion = '1.2.0' + androidxCoreVersion = '1.15.0' + androidxFragmentVersion = '1.8.4' + coreSplashScreenVersion = '1.0.1' + androidxWebkitVersion = '1.12.1' + junitVersion = '4.13.2' + androidxJunitVersion = '1.2.1' + androidxEspressoCoreVersion = '3.6.1' + cordovaAndroidVersion = '10.1.1' +} \ No newline at end of file diff --git a/apps/demo/capacitor.config.ts b/apps/demo/capacitor.config.ts new file mode 100644 index 00000000..fd795d11 --- /dev/null +++ b/apps/demo/capacitor.config.ts @@ -0,0 +1,41 @@ +import type { CapacitorConfig } from "@capacitor/cli"; +import { networkInterfaces } from "os"; + +const config: CapacitorConfig = { + appId: "org.microbit.connection.demo", + appName: "micro:bit connection demo", + webDir: "dist", + plugins: { + BluetoothLe: { + displayStrings: { + scanning: "Scanning...", + cancel: "Cancel", + availableDevices: "Available devices", + noDeviceFound: "No device found", + }, + }, + StatusBar: { + style: "Light", + backgroundColor: "#000000", + overlaysWebView: false, + }, + }, +}; + +function getIP() { + const nets = networkInterfaces(); + for (const name of Object.keys(nets)) { + for (const net of nets[name]!) { + if (net.family === "IPv4" && !net.internal) { + return net.address; + } + } + } + throw new Error("Could not guess Vite server IP"); +} + +if (process.env.CAP_LOCAL_DEV) { + config.server = { url: `http://${getIP()}:5173`, cleartext: true }; +} + +export default config; diff --git a/apps/demo/index.html b/apps/demo/index.html new file mode 100644 index 00000000..a42aafa7 --- /dev/null +++ b/apps/demo/index.html @@ -0,0 +1,16 @@ + + + + + + + micro:bit connection demo + + +
+ + + diff --git a/apps/demo/ios/.gitignore b/apps/demo/ios/.gitignore new file mode 100644 index 00000000..f4702997 --- /dev/null +++ b/apps/demo/ios/.gitignore @@ -0,0 +1,13 @@ +App/build +App/Pods +App/output +App/App/public +DerivedData +xcuserdata + +# Cordova plugins for Capacitor +capacitor-cordova-ios-plugins + +# Generated Config files +App/App/capacitor.config.json +App/App/config.xml diff --git a/apps/demo/ios/App/App.xcodeproj/project.pbxproj b/apps/demo/ios/App/App.xcodeproj/project.pbxproj new file mode 100644 index 00000000..40074483 --- /dev/null +++ b/apps/demo/ios/App/App.xcodeproj/project.pbxproj @@ -0,0 +1,410 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 48; + objects = { + +/* Begin PBXBuildFile section */ + 2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; }; + 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; }; + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; }; + 504EC30D1FED79650016851F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30B1FED79650016851F /* Main.storyboard */; }; + 504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; }; + 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; }; + 50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; }; + A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = ""; }; + 50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = ""; }; + 504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = ""; }; + AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = ""; }; + FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 504EC3011FED79650016851F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 27E2DDA53C4D2A4D1A88CE4A /* Frameworks */ = { + isa = PBXGroup; + children = ( + AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 504EC2FB1FED79650016851F = { + isa = PBXGroup; + children = ( + 504EC3061FED79650016851F /* App */, + 504EC3051FED79650016851F /* Products */, + 7F8756D8B27F46E3366F6CEA /* Pods */, + 27E2DDA53C4D2A4D1A88CE4A /* Frameworks */, + ); + sourceTree = ""; + }; + 504EC3051FED79650016851F /* Products */ = { + isa = PBXGroup; + children = ( + 504EC3041FED79650016851F /* App.app */, + ); + name = Products; + sourceTree = ""; + }; + 504EC3061FED79650016851F /* App */ = { + isa = PBXGroup; + children = ( + 50379B222058CBB4000EE86E /* capacitor.config.json */, + 504EC3071FED79650016851F /* AppDelegate.swift */, + 504EC30B1FED79650016851F /* Main.storyboard */, + 504EC30E1FED79650016851F /* Assets.xcassets */, + 504EC3101FED79650016851F /* LaunchScreen.storyboard */, + 504EC3131FED79650016851F /* Info.plist */, + 2FAD9762203C412B000D30F8 /* config.xml */, + 50B271D01FEDC1A000F3C39B /* public */, + ); + path = App; + sourceTree = ""; + }; + 7F8756D8B27F46E3366F6CEA /* Pods */ = { + isa = PBXGroup; + children = ( + FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */, + AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 504EC3031FED79650016851F /* App */ = { + isa = PBXNativeTarget; + buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */; + buildPhases = ( + 6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */, + 504EC3001FED79650016851F /* Sources */, + 504EC3011FED79650016851F /* Frameworks */, + 504EC3021FED79650016851F /* Resources */, + 9592DBEFFC6D2A0C8D5DEB22 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = App; + productName = App; + productReference = 504EC3041FED79650016851F /* App.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 504EC2FC1FED79650016851F /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 0920; + TargetAttributes = { + 504EC3031FED79650016851F = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */; + compatibilityVersion = "Xcode 8.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 504EC2FB1FED79650016851F; + packageReferences = ( + ); + productRefGroup = 504EC3051FED79650016851F /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 504EC3031FED79650016851F /* App */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 504EC3021FED79650016851F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */, + 50B271D11FEDC1A000F3C39B /* public in Resources */, + 504EC30F1FED79650016851F /* Assets.xcassets in Resources */, + 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */, + 504EC30D1FED79650016851F /* Main.storyboard in Resources */, + 2FAD9763203C412B000D30F8 /* config.xml in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-App-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 9592DBEFFC6D2A0C8D5DEB22 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-App/Pods-App-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 504EC3001FED79650016851F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 504EC30B1FED79650016851F /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 504EC30C1FED79650016851F /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 504EC3101FED79650016851F /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 504EC3111FED79650016851F /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 504EC3141FED79650016851F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 504EC3151FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 504EC3171FED79650016851F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = ""; + INFOPLIST_FILE = App/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 1.0; + OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\""; + PRODUCT_BUNDLE_IDENTIFIER = org.microbit.connection.demo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 504EC3181FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = ""; + INFOPLIST_FILE = App/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = org.microbit.connection.demo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = ""; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 504EC3141FED79650016851F /* Debug */, + 504EC3151FED79650016851F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 504EC3171FED79650016851F /* Debug */, + 504EC3181FED79650016851F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 504EC2FC1FED79650016851F /* Project object */; +} diff --git a/apps/demo/ios/App/App.xcworkspace/contents.xcworkspacedata b/apps/demo/ios/App/App.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..b301e824 --- /dev/null +++ b/apps/demo/ios/App/App.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/apps/demo/ios/App/App.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/apps/demo/ios/App/App.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/apps/demo/ios/App/App.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/apps/demo/ios/App/App/AppDelegate.swift b/apps/demo/ios/App/App/AppDelegate.swift new file mode 100644 index 00000000..c3cd83b5 --- /dev/null +++ b/apps/demo/ios/App/App/AppDelegate.swift @@ -0,0 +1,49 @@ +import UIKit +import Capacitor + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { + // Called when the app was launched with a url. Feel free to add additional processing here, + // but if you want the App API to support tracking app url opens, make sure to keep this call + return ApplicationDelegateProxy.shared.application(app, open: url, options: options) + } + + func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { + // Called when the app was launched with an activity, including Universal Links. + // Feel free to add additional processing here, but if you want the App API to support + // tracking app url opens, make sure to keep this call + return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler) + } + +} diff --git a/apps/demo/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png b/apps/demo/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png new file mode 100644 index 00000000..adf6ba01 Binary files /dev/null and b/apps/demo/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png differ diff --git a/apps/demo/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/demo/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..9b7d382d --- /dev/null +++ b/apps/demo/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images" : [ + { + "filename" : "AppIcon-512@2x.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/apps/demo/ios/App/App/Assets.xcassets/Contents.json b/apps/demo/ios/App/App/Assets.xcassets/Contents.json new file mode 100644 index 00000000..da4a164c --- /dev/null +++ b/apps/demo/ios/App/App/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json b/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json new file mode 100644 index 00000000..d7d96a67 --- /dev/null +++ b/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "splash-2732x2732-2.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "splash-2732x2732-1.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "splash-2732x2732.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png b/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png new file mode 100644 index 00000000..33ea6c97 Binary files /dev/null and b/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png differ diff --git a/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png b/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png new file mode 100644 index 00000000..33ea6c97 Binary files /dev/null and b/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png differ diff --git a/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png b/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png new file mode 100644 index 00000000..33ea6c97 Binary files /dev/null and b/apps/demo/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png differ diff --git a/apps/demo/ios/App/App/Base.lproj/LaunchScreen.storyboard b/apps/demo/ios/App/App/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..e7ae5d78 --- /dev/null +++ b/apps/demo/ios/App/App/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/demo/ios/App/App/Base.lproj/Main.storyboard b/apps/demo/ios/App/App/Base.lproj/Main.storyboard new file mode 100644 index 00000000..b44df7be --- /dev/null +++ b/apps/demo/ios/App/App/Base.lproj/Main.storyboard @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/apps/demo/ios/App/App/Info.plist b/apps/demo/ios/App/App/Info.plist new file mode 100644 index 00000000..b27f65e6 --- /dev/null +++ b/apps/demo/ios/App/App/Info.plist @@ -0,0 +1,57 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + micro:bit connection demo + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + NSBluetoothAlwaysUsageDescription + The micro:bit connection demo app uses Bluetooth to connect to your micro:bit. + NSBluetoothPeripheralUsageDescription + The micro:bit connection demo app uses Bluetooth to connect to your micro:bit. + UIBackgroundModes + + bluetooth-central + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/apps/demo/ios/App/Podfile b/apps/demo/ios/App/Podfile new file mode 100644 index 00000000..0c77cf86 --- /dev/null +++ b/apps/demo/ios/App/Podfile @@ -0,0 +1,27 @@ +require_relative '../../../../node_modules/@capacitor/ios/scripts/pods_helpers' + +platform :ios, '14.0' +use_frameworks! + +# workaround to avoid Xcode caching of Pods that requires +# Product -> Clean Build Folder after new Cordova plugins installed +# Requires CocoaPods 1.6 or newer +install! 'cocoapods', :disable_input_output_paths => true + +def capacitor_pods + pod 'Capacitor', :path => '../../../../node_modules/@capacitor/ios' + pod 'CapacitorCordova', :path => '../../../../node_modules/@capacitor/ios' + pod 'CapacitorCommunityBluetoothLe', :path => '../../../../node_modules/@capacitor-community/bluetooth-le' + pod 'CapacitorFilesystem', :path => '../../../../node_modules/@capacitor/filesystem' + pod 'CapacitorPreferences', :path => '../../../../node_modules/@capacitor/preferences' + pod 'MicrobitCapacitorCommunityNordicDfu', :path => '../../../../node_modules/@microbit/capacitor-community-nordic-dfu' +end + +target 'App' do + capacitor_pods + # Add your Pods here +end + +post_install do |installer| + assertDeploymentTarget(installer) +end diff --git a/apps/demo/ios/App/Podfile.lock b/apps/demo/ios/App/Podfile.lock new file mode 100644 index 00000000..23d7040c --- /dev/null +++ b/apps/demo/ios/App/Podfile.lock @@ -0,0 +1,61 @@ +PODS: + - Capacitor (7.4.5): + - CapacitorCordova + - CapacitorCommunityBluetoothLe (7.3.2): + - Capacitor + - CapacitorCordova (7.4.5) + - CapacitorFilesystem (7.1.8): + - Capacitor + - IONFilesystemLib (~> 1.1.1) + - CapacitorPreferences (7.0.3): + - Capacitor + - IONFilesystemLib (1.1.2) + - MicrobitCapacitorCommunityNordicDfu (7.0.0-microbit.4): + - Capacitor + - NordicDFU (~> 4.16.0) + - NordicDFU (4.16.0): + - ZIPFoundation (= 0.9.19) + - ZIPFoundation (0.9.19) + +DEPENDENCIES: + - "Capacitor (from `../../../../node_modules/@capacitor/ios`)" + - "CapacitorCommunityBluetoothLe (from `../../../../node_modules/@capacitor-community/bluetooth-le`)" + - "CapacitorCordova (from `../../../../node_modules/@capacitor/ios`)" + - "CapacitorFilesystem (from `../../../../node_modules/@capacitor/filesystem`)" + - "CapacitorPreferences (from `../../../../node_modules/@capacitor/preferences`)" + - "MicrobitCapacitorCommunityNordicDfu (from `../../../../node_modules/@microbit/capacitor-community-nordic-dfu`)" + +SPEC REPOS: + trunk: + - IONFilesystemLib + - NordicDFU + - ZIPFoundation + +EXTERNAL SOURCES: + Capacitor: + :path: "../../../../node_modules/@capacitor/ios" + CapacitorCommunityBluetoothLe: + :path: "../../../../node_modules/@capacitor-community/bluetooth-le" + CapacitorCordova: + :path: "../../../../node_modules/@capacitor/ios" + CapacitorFilesystem: + :path: "../../../../node_modules/@capacitor/filesystem" + CapacitorPreferences: + :path: "../../../../node_modules/@capacitor/preferences" + MicrobitCapacitorCommunityNordicDfu: + :path: "../../../../node_modules/@microbit/capacitor-community-nordic-dfu" + +SPEC CHECKSUMS: + Capacitor: 12914e6f1b7835e161a74ebd19cb361efa37a7dd + CapacitorCommunityBluetoothLe: 9aa29c1555fbe797e6b595db824c2acd39a5bdf5 + CapacitorCordova: 31bbe4466000c6b86d9b7f1181ee286cff0205aa + CapacitorFilesystem: c63fc54df41e5a6761785a7f3c49dc696c22e296 + CapacitorPreferences: 913eef88272c13eb6445b21e51fe8ef6635412cc + IONFilesystemLib: 21a63377696b2d8fab5632ecfb7d2ac67bddb68a + MicrobitCapacitorCommunityNordicDfu: fd00d14531eb46f4cc5cfc989d59f46ac12bbcac + NordicDFU: 116a4ec458945889f8e0e71759e03b23c39c3482 + ZIPFoundation: b8c29ea7ae353b309bc810586181fd073cb3312c + +PODFILE CHECKSUM: 3ee5ab709a831f2ba123bf214d783fb91525ba53 + +COCOAPODS: 1.16.2 diff --git a/apps/demo/package.json b/apps/demo/package.json new file mode 100644 index 00000000..48ba560b --- /dev/null +++ b/apps/demo/package.json @@ -0,0 +1,34 @@ +{ + "name": "@microbit/microbit-connection-demo", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "copy-hex": "mkdir -p public/hex-files && cp ../../hex-files/*.hex public/hex-files/", + "dev": "npm run copy-hex && vite", + "dev:apps": "npm run copy-hex && vite --host", + "build": "npm run copy-hex && tsc -b && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@capacitor-community/bluetooth-le": "^7.2.0", + "@capacitor/android": "^7.0.0", + "@capacitor/core": "^7.0.0", + "@capacitor/filesystem": "^7.1.8", + "@capacitor/ios": "^7.0.0", + "@capacitor/preferences": "^7.0.2", + "@microbit/capacitor-community-nordic-dfu": "v7.0.0-microbit.4", + "@microbit/makecode-embed": "^0.5.0", + "@microbit/microbit-connection": "*", + "react": "^18.3.1", + "react-dom": "^18.3.1" + }, + "devDependencies": { + "@capacitor/cli": "^7.0.0", + "@types/react": "^18.3.18", + "@types/react-dom": "^18.3.5", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "~5.6.2", + "vite": "^6.0.5" + } +} diff --git a/apps/demo/src/App.css b/apps/demo/src/App.css new file mode 100644 index 00000000..25d91a0c --- /dev/null +++ b/apps/demo/src/App.css @@ -0,0 +1,509 @@ +/* Shared button styles */ +.btn { + padding: 4px 12px; + font-size: 13px; + border-radius: 4px; + border: 1px solid #ccc; + background: #f5f5f5; + color: #333; + cursor: pointer; + transition: + background 0.15s, + border-color 0.15s; + white-space: nowrap; +} + +.btn:hover:not(:disabled) { + background: #e8e8e8; + border-color: #aaa; +} + +.btn:active:not(:disabled) { + background: #ddd; +} + +.btn-primary { + background: #2563eb; + border-color: #1d4ed8; + color: #fff; +} + +.btn-primary:hover:not(:disabled) { + background: #1d4ed8; + border-color: #1e40af; +} + +.btn-primary:active:not(:disabled) { + background: #1e40af; +} + +.btn-danger { + background: #dc2626; + border-color: #b91c1c; + color: #fff; +} + +.btn-danger:hover:not(:disabled) { + background: #b91c1c; + border-color: #991b1b; +} + +.btn-toggle { + background: #f5f5f5; + border-color: #ccc; + color: #555; +} + +.btn-toggle.active { + background: #dbeafe; + border-color: #2563eb; + color: #1d4ed8; +} + +.btn-toggle:hover:not(:disabled) { + background: #e8e8e8; +} + +.btn-toggle.active:hover:not(:disabled) { + background: #bfdbfe; +} + +/* Input styles */ +.input { + background: #fff; + color: #1a1a1a; + border: 1px solid #ccc; + border-radius: 4px; + padding: 4px 8px; + font-size: 13px; + transition: border-color 0.15s; +} + +.input:focus { + outline: none; + border-color: #2563eb; + box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15); +} + +/* Select styles */ +.select { + background: #fff; + color: #1a1a1a; + border: 1px solid #ccc; + border-radius: 4px; + padding: 4px 8px; + font-size: 13px; + cursor: pointer; + transition: border-color 0.15s; +} + +.select:focus { + outline: none; + border-color: #2563eb; + box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15); +} + +.select:hover { + border-color: #999; +} + +/* Tab content constraint */ +.tab-content { + flex: 1; + overflow: auto; + padding-bottom: 28px; /* space for collapsed log tab */ + transition: padding-bottom 0.2s; +} + +.tab-content.log-open { + padding-bottom: 228px; /* space for expanded log panel */ +} + +/* Tab page padding and max-width */ +.tab-page { + padding: 16px; + max-width: 640px; +} + +/* Section card */ +.section { + margin-bottom: 24px; +} + +.section h2 { + margin: 0 0 8px 0; + font-size: 15px; + font-weight: 600; + color: #333; + letter-spacing: 0.02em; +} + +.section h3 { + margin: 12px 0 6px 0; + font-size: 13px; + font-weight: 600; + color: #555; +} + +/* Control row */ +.control-row { + display: flex; + gap: 8px; + align-items: center; + flex-wrap: wrap; +} + +/* Data display box (serial output, etc.) */ +.data-box { + background: #f8f9fa; + border: 1px solid #ddd; + border-radius: 4px; + padding: 8px; + font-family: monospace; + font-size: 12px; + height: 200px; + overflow: auto; + white-space: pre-wrap; + color: #333; + margin-top: 8px; +} + +/* Sensor data readout */ +.sensor-readout { + font-family: monospace; + font-size: 13px; + background: #f0f4ff; + border: 1px solid #d0daf0; + border-radius: 4px; + padding: 8px 12px; + margin: 8px 0; + display: inline-flex; + gap: 16px; +} + +.sensor-readout .axis { + display: flex; + gap: 4px; +} + +.sensor-readout .axis-label { + color: #666; +} + +.sensor-readout .axis-value { + color: #1d4ed8; + font-variant-numeric: tabular-nums; + min-width: 72px; + text-align: right; +} + +/* Empty state placeholder */ +.empty-state { + color: #737373; + font-size: 13px; + font-style: italic; + padding: 8px 0; +} + +.service-note { + color: #737373; + font-size: 12px; + margin: 0 0 4px; +} + +/* Header */ +.app-header { + display: flex; + align-items: center; + gap: 12px; + padding: 8px 12px; + background: #f5f7fa; + color: #1a1a1a; + flex-wrap: wrap; + border-bottom: 1px solid #ddd; + flex-shrink: 0; +} + +/* Status indicator */ +.status-indicator { + display: flex; + align-items: center; + gap: 6px; + font-size: 13px; +} + +.status-dot { + width: 10px; + height: 10px; + border-radius: 50%; + display: inline-block; + flex-shrink: 0; +} + +.version-badge { + font-size: 11px; + background: #e0e7ef; + padding: 1px 6px; + border-radius: 3px; + color: #555; +} + +/* Tab bar */ +.tab-bar { + display: flex; + background: #f5f7fa; + border-bottom: 1px solid #ddd; + flex-shrink: 0; + overflow-x: auto; +} + +.tab-btn { + padding: 8px 16px; + font-size: 13px; + border: none; + border-bottom: 2px solid transparent; + background: none; + color: #666; + cursor: pointer; + white-space: nowrap; + transition: + color 0.15s, + border-color 0.15s; +} + +.tab-btn:hover { + color: #555; +} + +.tab-btn.active { + border-bottom-color: #2563eb; + color: #1a1a1a; +} + +/* Log panel — expandable from bottom */ +.log-panel { + position: fixed; + bottom: 0; + left: 0; + right: 0; + z-index: 100; + font-family: monospace; + font-size: 12px; + display: flex; + flex-direction: column; + transition: height 0.2s ease; + height: 28px; /* collapsed: just the tab */ + background: #fff; +} + +.log-panel.open { + height: 228px; /* tab (28px) + content (200px) */ +} + +.log-panel-tab { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 8px 0 0; + background: #f5f7fa; + border-top: 1px solid #ddd; + flex-shrink: 0; + height: 28px; +} + +.log-panel-toggle { + display: flex; + align-items: center; + gap: 4px; + padding: 4px 12px; + background: none; + border: none; + color: #666; + font-family: monospace; + font-size: 12px; + cursor: pointer; + height: 100%; + transition: color 0.15s; +} + +.log-panel-toggle:hover { + color: #333; +} + +.log-panel-chevron { + font-size: 10px; +} + +/* Flash overlay dialog */ +.flash-dialog { + box-shadow: + 0 8px 32px rgba(0, 0, 0, 0.2), + 0 2px 8px rgba(0, 0, 0, 0.1); +} + +.flash-dialog h2 { + font-size: 18px; + font-weight: 600; + margin: 0; + color: #1a1a1a; + letter-spacing: -0.01em; +} + +.flash-dialog p { + margin: 0; + font-size: 14px; + line-height: 1.5; + color: #555; +} + +.flash-dialog .dialog-actions { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 4px; +} + +.flash-dialog .btn-dialog-primary { + background-color: #2563eb; + color: #fff; + padding: 10px 16px; + border: none; + border-radius: 6px; + cursor: pointer; + font-size: 14px; + font-weight: 500; + width: 100%; + transition: background 0.15s; +} + +.flash-dialog .btn-dialog-primary:hover:not(:disabled) { + background-color: #1d4ed8; +} + +.flash-dialog .btn-dialog-primary:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.flash-dialog .btn-dialog-secondary { + background: none; + color: #666; + padding: 8px 16px; + border: none; + border-radius: 6px; + cursor: pointer; + font-size: 13px; + width: 100%; + transition: color 0.15s; +} + +.flash-dialog .btn-dialog-secondary:hover { + color: #333; +} + +/* Progress bar */ +.flash-progress-track { + width: 100%; + background: #e5e7eb; + border-radius: 6px; + height: 10px; + overflow: hidden; +} + +.flash-progress-fill { + height: 100%; + background: #2563eb; + border-radius: 6px; + transition: width 0.3s ease; +} + +/* Timings table */ +.flash-timings { + border-collapse: collapse; + font-size: 13px; + width: 100%; + text-align: left; +} + +.flash-timings th { + padding: 6px 10px; + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.05em; + color: #888; + border-bottom: 1px solid #e5e7eb; +} + +.flash-timings td { + padding: 6px 10px; + color: #444; +} + +.flash-timings tbody tr { + border-bottom: 1px solid #f0f0f0; +} + +.flash-timings .timing-value { + text-align: right; + font-variant-numeric: tabular-nums; + font-family: monospace; + font-size: 13px; +} + +.flash-timings .timing-total { + font-weight: 600; + color: #1a1a1a; + border-top: 1px solid #e5e7eb; +} + +/* LED grid (shared between pattern input and LED matrix) */ +.led-grid { + display: grid; +} + +/* Bluetooth pattern input */ +.pattern-grid { + display: grid; + grid-template-columns: repeat(5, 44px); + grid-template-rows: repeat(6, 44px); + gap: 4px; + justify-content: center; +} + +.pattern-cell { + width: 100%; + height: 100%; + padding: 0; + border: 2px solid #ccc; + border-radius: 4px; + cursor: pointer; + transition: + background 0.1s, + border-color 0.1s; +} + +.pattern-cell.lit { + background: #555; + border-color: #888; +} + +.pattern-cell.unlit { + background: #fff; + border-color: #ddd; +} + +.pattern-cell:hover { + border-color: #2563eb; +} + +.pattern-char { + font-size: 1.2rem; + font-weight: bold; + text-align: center; + color: #222; + margin: 0; + display: flex; + align-items: center; + justify-content: center; +} diff --git a/apps/demo/src/App.tsx b/apps/demo/src/App.tsx new file mode 100644 index 00000000..52731995 --- /dev/null +++ b/apps/demo/src/App.tsx @@ -0,0 +1,133 @@ +import { useState } from "react"; +import { LogContext, useLog, useLogState } from "./hooks/use-log.ts"; +import { + ConnectionContext, + useConnectionState, +} from "./hooks/use-connection.ts"; +import { + ErrorDialogContext, + useErrorDialogState, +} from "./hooks/use-error-dialog.ts"; +import ConnectionHeader from "./components/ConnectionHeader.tsx"; +import LogPanel from "./components/LogPanel.tsx"; +import ErrorDialog from "./components/ErrorDialog.tsx"; +import FlashTab from "./components/FlashTab.tsx"; +import SensorsTab from "./components/SensorsTab.tsx"; +import LedsTab from "./components/LedsTab.tsx"; +import SerialTab from "./components/SerialTab.tsx"; +import UartTab from "./components/UartTab.tsx"; +import PinsTab from "./components/PinsTab.tsx"; +import EventsTab from "./components/EventsTab.tsx"; +import "./App.css"; + +type Tab = "flash" | "sensors" | "io" | "pins" | "events" | "serial" | "uart"; + +const tabDefs: { id: Tab; label: string; availableFor: string[] }[] = [ + { id: "flash", label: "Flash", availableFor: ["usb", "bluetooth"] }, + { + id: "sensors", + label: "Sensors", + availableFor: ["bluetooth", "radio-bridge"], + }, + { id: "io", label: "LEDs", availableFor: ["bluetooth"] }, + { id: "pins", label: "Pins", availableFor: ["bluetooth"] }, + { id: "events", label: "Events", availableFor: ["bluetooth"] }, + { id: "serial", label: "Serial", availableFor: ["usb"] }, + { id: "uart", label: "UART", availableFor: ["bluetooth"] }, +]; + +const tabComponents: Record = { + flash: FlashTab, + sensors: SensorsTab, + io: LedsTab, + pins: PinsTab, + events: EventsTab, + serial: SerialTab, + uart: UartTab, +}; + +const AppContent = () => { + const connState = useConnectionState(); + const [activeTab, setActiveTab] = useState("flash"); + const { isOpen } = useLog(); + + if (!connState) { + return
Initializing...
; + } + + const visibleTabs = tabDefs.filter((t) => + t.availableFor.includes(connState.connection.type), + ); + + // If current tab isn't visible for this connection type, switch to first available + const currentTab = visibleTabs.find((t) => t.id === activeTab) + ? activeTab + : visibleTabs[0]?.id ?? "flash"; + + return ( + +
+ + +
+ {visibleTabs.map((tab) => ( + + ))} +
+ +
+ {visibleTabs.map((tab) => { + const Component = tabComponents[tab.id]; + const isActive = currentTab === tab.id; + return ( + + ); + })} +
+ + +
+
+ ); +}; + +const App = () => { + const logState = useLogState(); + const errorDialogState = useErrorDialogState(); + + return ( + + + + + + + ); +}; + +export default App; diff --git a/apps/demo/src/components/BluetoothPatternInput.tsx b/apps/demo/src/components/BluetoothPatternInput.tsx new file mode 100644 index 00000000..28c800cc --- /dev/null +++ b/apps/demo/src/components/BluetoothPatternInput.tsx @@ -0,0 +1,82 @@ +import { useState } from "react"; + +const ledGridLetters: string[][] = [ + ["t", "a", "t", "a", "t"], + ["p", "e", "p", "e", "p"], + ["g", "i", "g", "i", "g"], + ["v", "o", "v", "o", "v"], + ["z", "u", "z", "u", "z"], +]; + +interface BluetoothPatternInputProps { + onDeviceNameChange: (deviceName: string) => void; + initialValue?: string; +} + +const findRowForChar = (char: string, colIdx: number): number => { + for (let rowIdx = 0; rowIdx < ledGridLetters.length; rowIdx++) { + if (ledGridLetters[rowIdx][colIdx] === char) { + return rowIdx; + } + } + return 5; +}; + +const BluetoothPatternInput = ({ + onDeviceNameChange, + initialValue, +}: BluetoothPatternInputProps) => { + const [deviceChars, setDeviceChars] = useState(() => { + if (initialValue && initialValue.length === 5) { + return initialValue.split(""); + } + return Array(5).fill(""); + }); + + const [activeRows, setActiveRows] = useState(() => { + if (initialValue && initialValue.length === 5) { + const chars = initialValue.split(""); + return chars.map((char, colIdx) => findRowForChar(char, colIdx)); + } + return Array(5).fill(5); + }); + + return ( +
+ {ledGridLetters.map((row, rowIdx) => + row.map((_letter, colIdx) => { + const isLit = rowIdx >= activeRows[colIdx]; + return ( +
+ ); +}; + +export default BluetoothPatternInput; diff --git a/apps/demo/src/components/ConnectionHeader.tsx b/apps/demo/src/components/ConnectionHeader.tsx new file mode 100644 index 00000000..62d18dca --- /dev/null +++ b/apps/demo/src/components/ConnectionHeader.tsx @@ -0,0 +1,155 @@ +import { ConnectionStatus, type BondMode } from "@microbit/microbit-connection"; +import { Capacitor } from "@capacitor/core"; +import { useConnection, type AnyConnection } from "../hooks/use-connection.ts"; +import { useErrorDialog } from "../hooks/use-error-dialog.ts"; + +const statusDot: Record = { + [ConnectionStatus.Connected]: "#16a34a", + [ConnectionStatus.Connecting]: "#ca8a04", + [ConnectionStatus.Paused]: "#ca8a04", + [ConnectionStatus.NoAuthorizedDevice]: "#dc2626", + [ConnectionStatus.Disconnected]: "#ea580c", +}; + +const statusLabel: Record = { + [ConnectionStatus.Connected]: "Connected", + [ConnectionStatus.Connecting]: "Connecting...", + [ConnectionStatus.Paused]: "Paused", + [ConnectionStatus.NoAuthorizedDevice]: "Not connected", + [ConnectionStatus.Disconnected]: "Disconnected", +}; + +const ConnectionHeader = () => { + const { + connection, + status, + boardVersion, + setConnectionType, + pauseOnHidden, + setPauseOnHidden, + bondMode, + setBondMode, + } = useConnection(); + const { showError } = useErrorDialog(); + const isNative = Capacitor.isNativePlatform(); + + const connectionOptions: { value: AnyConnection["type"]; label: string }[] = + isNative + ? [{ value: "bluetooth", label: "Bluetooth" }] + : [ + { value: "usb", label: "WebUSB" }, + { value: "bluetooth", label: "Web Bluetooth" }, + { value: "radio-bridge", label: "Radio Bridge" }, + ]; + + return ( +
+ + + {status === ConnectionStatus.Connected ? ( + + ) : ( + + )} + {connection.type === "usb" && ( + + )} + + +
+
+ + {connection.type === "bluetooth" && isNative && ( + + )} + + {(connection.type === "usb" || connection.type === "radio-bridge") && ( + + )} +
+ ); +}; + +export default ConnectionHeader; diff --git a/apps/demo/src/components/Dialog.tsx b/apps/demo/src/components/Dialog.tsx new file mode 100644 index 00000000..23aeec50 --- /dev/null +++ b/apps/demo/src/components/Dialog.tsx @@ -0,0 +1,89 @@ +import { useEffect, useRef } from "react"; + +const overlayStyle: React.CSSProperties = { + position: "fixed", + top: 0, + left: 0, + right: 0, + bottom: 0, + background: "rgba(0,0,0,0.5)", + display: "flex", + alignItems: "center", + justifyContent: "center", + zIndex: 200, +}; + +const dialogStyle: React.CSSProperties = { + background: "#fff", + borderRadius: 12, + padding: "24px", + maxWidth: 420, + width: "90%", + maxHeight: "80vh", + overflow: "auto", + display: "flex", + flexDirection: "column", + gap: "16px", +}; + +/** + * Modal dialog with focus trapping, aria-modal, and aria-labelledby. + */ +const Dialog = ({ + title, + titleId, + titleStyle, + children, +}: { + title: string; + titleId: string; + titleStyle?: React.CSSProperties; + children: React.ReactNode; +}) => { + const dialogRef = useRef(null); + + useEffect(() => { + const dialog = dialogRef.current; + if (!dialog) return; + + const focusable = dialog.querySelectorAll( + 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])', + ); + focusable[0]?.focus(); + + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key !== "Tab" || focusable.length === 0) return; + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + if (e.shiftKey && document.activeElement === first) { + e.preventDefault(); + last.focus(); + } else if (!e.shiftKey && document.activeElement === last) { + e.preventDefault(); + first.focus(); + } + }; + dialog.addEventListener("keydown", handleKeyDown); + return () => dialog.removeEventListener("keydown", handleKeyDown); + }, []); + + return ( +
+
+

+ {title} +

+ {children} +
+
+ ); +}; + +export default Dialog; diff --git a/apps/demo/src/components/ErrorDialog.tsx b/apps/demo/src/components/ErrorDialog.tsx new file mode 100644 index 00000000..ae59130d --- /dev/null +++ b/apps/demo/src/components/ErrorDialog.tsx @@ -0,0 +1,36 @@ +import { useErrorDialog } from "../hooks/use-error-dialog.ts"; +import Dialog from "./Dialog.tsx"; + +const ErrorDialog = () => { + const { error, clearError } = useErrorDialog(); + if (!error) return null; + + return ( + + {error.code && ( +

+ {error.code} +

+ )} +

{error.message}

+
+ +
+
+ ); +}; + +export default ErrorDialog; diff --git a/apps/demo/src/components/EventsTab.tsx b/apps/demo/src/components/EventsTab.tsx new file mode 100644 index 00000000..5e257773 --- /dev/null +++ b/apps/demo/src/components/EventsTab.tsx @@ -0,0 +1,364 @@ +import { useEffect, useState, useCallback, useRef } from "react"; +import type { + GestureData, + ButtonActionData, + MicrobitEventData, +} from "@microbit/microbit-connection"; +import { GestureEvent, ButtonAction } from "@microbit/microbit-connection"; +import type { MicrobitBluetoothConnection } from "@microbit/microbit-connection/bluetooth"; +import { useConnection } from "../hooks/use-connection.ts"; +import { useLog } from "../hooks/use-log.ts"; +import { useErrorDialog } from "../hooks/use-error-dialog.ts"; + +const gestureNames: Record = { + [GestureEvent.TiltUp]: "Tilt up", + [GestureEvent.TiltDown]: "Tilt down", + [GestureEvent.TiltLeft]: "Tilt left", + [GestureEvent.TiltRight]: "Tilt right", + [GestureEvent.FaceUp]: "Face up", + [GestureEvent.FaceDown]: "Face down", + [GestureEvent.Freefall]: "Freefall", + [GestureEvent.Acceleration3g]: "3g", + [GestureEvent.Acceleration6g]: "6g", + [GestureEvent.Acceleration8g]: "8g", + [GestureEvent.Shake]: "Shake", + [GestureEvent.Acceleration2g]: "2g", +}; + +const buttonActionNames: Record = { + [ButtonAction.Down]: "Down", + [ButtonAction.Up]: "Up", + [ButtonAction.Click]: "Click", + [ButtonAction.LongClick]: "Long click", + [ButtonAction.Hold]: "Hold", + [ButtonAction.DoubleClick]: "Double click", +}; + +const GestureSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const [gesture, setGesture] = useState(null); + const [listening, setListening] = useState(false); + + useEffect(() => { + if (!listening) return; + const listener = (d: GestureData) => { + setGesture(gestureNames[d.gesture] ?? `Unknown (${d.gesture})`); + }; + connection.addEventListener("gesturechanged", listener); + return () => { + connection.removeEventListener("gesturechanged", listener); + }; + }, [connection, listening]); + + return ( +
+

Gestures

+
+ +
+ {gesture !== null ? ( +
+ + + {gesture} + + +
+ ) : ( +

+ {listening + ? "Shake or tilt the micro:bit..." + : "Press Listen to start receiving gesture events."} +

+ )} +
+ ); +}; + +const ButtonClicksSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const [lastA, setLastA] = useState("-"); + const [lastB, setLastB] = useState("-"); + const [lastAB, setLastAB] = useState("-"); + const [lastLogo, setLastLogo] = useState("-"); + const [listening, setListening] = useState(false); + + useEffect(() => { + if (!listening) return; + const onA = (d: ButtonActionData) => { + setLastA(buttonActionNames[d.action] ?? String(d.action)); + }; + const onB = (d: ButtonActionData) => { + setLastB(buttonActionNames[d.action] ?? String(d.action)); + }; + const onAB = (d: ButtonActionData) => { + setLastAB(buttonActionNames[d.action] ?? String(d.action)); + }; + const onLogo = (d: ButtonActionData) => { + setLastLogo(buttonActionNames[d.action] ?? String(d.action)); + }; + connection.addEventListener("buttonaaction", onA); + connection.addEventListener("buttonbaction", onB); + connection.addEventListener("buttonabaction", onAB); + connection.addEventListener("logoaction", onLogo); + return () => { + connection.removeEventListener("buttonaaction", onA); + connection.removeEventListener("buttonbaction", onB); + connection.removeEventListener("buttonabaction", onAB); + connection.removeEventListener("logoaction", onLogo); + }; + }, [connection, listening]); + + return ( +
+

Button Events

+
+ +
+
+ + A: + + {lastA} + + + + B: + + {lastB} + + + + A+B: + + {lastAB} + + + + Logo: + + {lastLogo} + + +
+
+ ); +}; + +const RawEventsSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [listening, setListening] = useState(false); + const [source, setSource] = useState("0"); + const [value, setValue] = useState("0"); + const [entries, setEntries] = useState([]); + const logRef = useRef(null); + + useEffect(() => { + if (!listening) return; + const listener = (d: MicrobitEventData) => { + setEntries((prev) => { + const next = [...prev, `source=${d.source} value=${d.value}`]; + return next.length > 100 ? next.slice(-100) : next; + }); + }; + connection.addEventListener("microbitevent", listener); + return () => { + connection.removeEventListener("microbitevent", listener); + }; + }, [connection, listening]); + + useEffect(() => { + if (logRef.current) { + logRef.current.scrollTop = logRef.current.scrollHeight; + } + }, [entries]); + + const subscribe = useCallback(async () => { + try { + const s = parseInt(source, 10); + const v = parseInt(value, 10); + await connection.subscribeToEvent(s, v); + log("event", `Subscribed to source=${s} value=${v}`); + } catch (e) { + showError(e); + } + }, [connection, source, value, log, showError]); + + return ( +
+

Raw Events

+
+ +
+
+ + + + +
+
+ {entries.length > 0 + ? entries.join("\n") + : listening + ? "Waiting for events..." + : "Listen and subscribe to see raw events."} +
+
+ ); +}; + +const SendEventSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [source, setSource] = useState(""); + const [value, setValue] = useState(""); + + const send = useCallback(async () => { + try { + const s = parseInt(source, 10); + const v = parseInt(value, 10); + await connection.sendEvent(s, v); + log("event", `Sent source=${s} value=${v}`); + } catch (e) { + showError(e); + } + }, [connection, source, value, log, showError]); + + return ( +
+

Send Event

+
+ + + +
+
+ ); +}; + +const EventsTab = () => { + const { connection } = useConnection(); + + if (connection.type !== "bluetooth") { + return ( +
+
+

Events require a Bluetooth connection.

+
+
+ ); + } + + return ( +
+

Requires: Event Service

+ + + + +
+ ); +}; + +export default EventsTab; diff --git a/apps/demo/src/components/FlashOverlay.tsx b/apps/demo/src/components/FlashOverlay.tsx new file mode 100644 index 00000000..1d2b6a8b --- /dev/null +++ b/apps/demo/src/components/FlashOverlay.tsx @@ -0,0 +1,176 @@ +import { Step } from "../hooks/use-flashing.ts"; +import BluetoothPatternInput from "./BluetoothPatternInput.tsx"; +import Dialog from "./Dialog.tsx"; + +interface FlashOverlayProps { + step: Step; + setStep: (step: Step) => void; + handleClose: () => void; + handleFlash: () => void; + setDeviceName: (name: string) => void; + deviceName: string | null; +} + +const FlashOverlay = ({ + step, + setStep, + handleClose, + handleFlash, + setDeviceName, + deviceName, +}: FlashOverlayProps) => { + switch (step.name) { + case "initial": + return ( + +

Do you want to send this program to your micro:bit?

+
+ + +
+
+ ); + + case "pair-mode": + return ( + +

Press reset on the micro:bit three times.

+

+ If your micro:bit has not been updated in a while, hold button A and + B and press reset. +

+
+ + +
+
+ ); + + case "enter-pattern": + return ( + + +
+ + +
+
+ ); + + case "flashing": { + const progressPercent = + step.progress !== undefined + ? Math.round(step.progress * 100) + : undefined; + return ( + + {progressPercent !== undefined && ( +
+
+
+ )} +

{step.message}

+
+ ); + } + + case "success": { + const total = step.timings.reduce((s, t) => s + t.durationMs, 0); + return ( + + {step.timings.length > 0 && ( + + + + + + + + + {step.timings.map((t, i) => ( + + + + + ))} + + + + + +
StageDuration
{t.stage} + {(t.durationMs / 1000).toFixed(1)}s +
Total{(total / 1000).toFixed(1)}s
+ )} +
+ +
+
+ ); + } + + case "flash-error": + return ( + +

{step.children}

+
+ + +
+
+ ); + + default: + return null; + } +}; + +export default FlashOverlay; diff --git a/apps/demo/src/components/FlashTab.tsx b/apps/demo/src/components/FlashTab.tsx new file mode 100644 index 00000000..4cc27ab7 --- /dev/null +++ b/apps/demo/src/components/FlashTab.tsx @@ -0,0 +1,216 @@ +import { useState, useRef } from "react"; +import { useFlashing } from "../hooks/use-flashing.ts"; +import FlashOverlay from "./FlashOverlay.tsx"; +import MakeCodeOverlay from "./MakeCodeOverlay.tsx"; + +interface CannedHexFile { + name: string; + path: string; + label: string; +} + +const cannedHexFiles: CannedHexFile[] = [ + { + name: "bluetooth-v1-no-magnetometer.hex", + path: "/hex-files/bluetooth-v1-no-magnetometer.hex", + label: "Bluetooth V1 (No Magnetometer)", + }, + { + name: "bluetooth-v2.hex", + path: "/hex-files/bluetooth-v2.hex", + label: "Bluetooth V2", + }, + { + name: "data-collection-program.hex", + path: "/hex-files/data-collection-program.hex", + label: "Data Collection Program", + }, + { + name: "serial-counter-makecode.hex", + path: "/hex-files/serial-counter-makecode.hex", + label: "Serial Counter (MakeCode)", + }, + { + name: "serial-counter-python.hex", + path: "/hex-files/serial-counter-python.hex", + label: "Serial Counter (Python)", + }, + { + name: "microbit-data-collection-just-works-universal.hex", + path: "/hex-files/microbit-data-collection-just-works-universal.hex", + label: "Data Collection (new, just works)", + }, + { + name: "microbit-data-collection-no-pairing-universal.hex", + path: "/hex-files/microbit-data-collection-no-pairing-universal.hex", + label: "Data Collection (new, no pairing)", + }, + { + name: "local-sensors-radio-bridge.hex", + path: "/hex-files/local-sensors-radio-bridge.hex", + label: "Local Sensors Radio Bridge", + }, + { + name: "createai-project.hex", + path: "/hex-files/createai-project.hex", + label: "CreateAI project", + }, + { + name: "meet-the-microbit.hex", + path: "/hex-files/meet-the-microbit.hex", + label: "Meet the micro:bit", + }, + { + name: "microbit-beating-heart.hex", + path: "/hex-files/microbit-beating-heart.hex", + label: "Beating Heart", + }, + { + name: "microbit-micropython-v1.hex", + path: "/hex-files/microbit-micropython-v1.hex", + label: "MicroPython V1", + }, + { + name: "microbit-micropython-v2.hex", + path: "/hex-files/microbit-micropython-v2.hex", + label: "MicroPython V2", + }, + { + name: "microbit-v1-battery-level.hex", + path: "/hex-files/microbit-v1-battery-level.hex", + label: "V1 Battery Level", + }, + { + name: "microbit-v2-battery-voltage-v1.0.0.hex", + path: "/hex-files/microbit-v2-battery-voltage-v1.0.0.hex", + label: "V2 Battery Voltage", + }, + { + name: "python-editor-default.hex", + path: "/hex-files/python-editor-default.hex", + label: "Python Editor Default", + }, +]; + +const FlashTab = () => { + const [showMakeCode, setShowMakeCode] = useState(false); + const { + step, + setStep, + startFlashing, + open, + handleClose, + handleFlash, + deviceName, + setDeviceName, + } = useFlashing(); + const fileInputRef = useRef(null); + const [selectedHex, setSelectedHex] = useState<{ + name: string; + hex?: string; + path?: string; + } | null>(null); + + const handleFileSelected = (event: React.ChangeEvent) => { + const file = event.target.files?.[0]; + if (file) { + const reader = new FileReader(); + reader.onload = (e) => { + const hex = e.target?.result as string; + setSelectedHex({ name: file.name, hex }); + }; + reader.readAsText(file); + } + }; + + const handleHexSelectionChange = ( + event: React.ChangeEvent, + ) => { + const selectedValue = event.target.value; + if (selectedValue === "browse") { + setSelectedHex(null); + fileInputRef.current?.click(); + } else { + const hexFile = cannedHexFiles.find((f) => f.path === selectedValue); + if (hexFile) { + setSelectedHex(hexFile); + } + } + }; + + const handleFlashButtonClick = async () => { + if (!selectedHex) { + fileInputRef.current?.click(); + return; + } + + if (selectedHex.hex) { + startFlashing({ name: selectedHex.name, hex: selectedHex.hex }); + } else if (selectedHex.path) { + const response = await fetch(selectedHex.path); + if (!response.ok) { + return; + } + const hex = await response.text(); + startFlashing({ name: selectedHex.name, hex }); + } + }; + + return ( +
+
+

Flash

+
+ + +
+ +
+ +
+

MakeCode

+ +

+ Create a program in MakeCode and flash it directly. +

+
+ + {showMakeCode && ( + setShowMakeCode(false)} /> + )} + {open && ( + + )} +
+ ); +}; + +export default FlashTab; diff --git a/apps/demo/src/components/LedGrid.tsx b/apps/demo/src/components/LedGrid.tsx new file mode 100644 index 00000000..e7516236 --- /dev/null +++ b/apps/demo/src/components/LedGrid.tsx @@ -0,0 +1,39 @@ +interface LedGridProps { + /** 5x5 boolean grid, row-major. */ + grid: boolean[][]; + /** Called when a cell is toggled. */ + onToggle?: (row: number, col: number) => void; + /** Cell size in px. Defaults to 44. */ + cellSize?: number; + /** Gap between cells in px. Defaults to 4. */ + gap?: number; +} + +const LedGrid = ({ grid, onToggle, cellSize = 44, gap = 4 }: LedGridProps) => { + return ( +
+ {grid.map((row, rowIdx) => + row.map((lit, colIdx) => ( +
+ ); +}; + +export default LedGrid; diff --git a/apps/demo/src/components/LedsTab.tsx b/apps/demo/src/components/LedsTab.tsx new file mode 100644 index 00000000..e5b95242 --- /dev/null +++ b/apps/demo/src/components/LedsTab.tsx @@ -0,0 +1,178 @@ +import { useState, useCallback } from "react"; +import type { MicrobitBluetoothConnection } from "@microbit/microbit-connection/bluetooth"; +import { useConnection } from "../hooks/use-connection.ts"; +import { useLog } from "../hooks/use-log.ts"; +import { useErrorDialog } from "../hooks/use-error-dialog.ts"; +import LedGrid from "./LedGrid.tsx"; + +const emptyMatrix = (): boolean[][] => + Array.from({ length: 5 }, () => Array(5).fill(false)); + +const TextSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [text, setText] = useState(""); + + const sendText = useCallback(async () => { + try { + await connection.setLedText(text); + log("led", `Text set: "${text}"`); + } catch (e) { + showError(e); + } + }, [connection, text, log, showError]); + + return ( +
+

Text

+
+ setText(e.target.value)} + placeholder="Text to display" + className="input" + style={{ width: 200 }} + /> + +
+
+ ); +}; + +const ScrollingDelaySection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [delay, setDelay] = useState(""); + + const getDelay = useCallback(async () => { + try { + const d = await connection.getLedScrollingDelay(); + if (d !== undefined) { + setDelay(String(d)); + } + } catch (e) { + showError(e); + } + }, [connection, showError]); + + const setDelayValue = useCallback(async () => { + try { + await connection.setLedScrollingDelay(parseInt(delay, 10)); + log("led", `Scrolling delay set to ${delay}ms`); + } catch (e) { + showError(e); + } + }, [connection, delay, log, showError]); + + return ( +
+

Scrolling Delay

+
+ setDelay(e.target.value)} + placeholder="ms" + className="input" + style={{ width: 100 }} + /> + + +
+
+ ); +}; + +const MatrixSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [matrix, setMatrix] = useState(emptyMatrix); + + const getMatrix = useCallback(async () => { + try { + const m = await connection.getLedMatrix(); + setMatrix(m); + } catch (e) { + showError(e); + } + }, [connection, showError]); + + const sendMatrix = useCallback(async () => { + try { + await connection.setLedMatrix(matrix); + log("led", "Matrix updated"); + } catch (e) { + showError(e); + } + }, [connection, matrix, log, showError]); + + const handleToggle = useCallback((row: number, col: number) => { + setMatrix((prev) => { + const next = prev.map((r) => [...r]); + next[row][col] = !next[row][col]; + return next; + }); + }, []); + + return ( +
+

Matrix

+ +
+ + + +
+
+ ); +}; + +const LedsTab = () => { + const { connection } = useConnection(); + + if (connection.type !== "bluetooth") { + return ( +
+
+

LEDs require a Bluetooth connection.

+
+
+ ); + } + + return ( +
+

Requires: LED Service

+ + + +
+ ); +}; + +export default LedsTab; diff --git a/apps/demo/src/components/LogPanel.tsx b/apps/demo/src/components/LogPanel.tsx new file mode 100644 index 00000000..ea5bd411 --- /dev/null +++ b/apps/demo/src/components/LogPanel.tsx @@ -0,0 +1,86 @@ +import { useEffect, useRef } from "react"; +import { useLog } from "../hooks/use-log.ts"; + +const levelColors: Record = { + info: "#666", + warn: "#b45309", + error: "#dc2626", + data: "#2563eb", +}; + +const LogPanel = () => { + const { entries, isOpen, setIsOpen, clear } = useLog(); + const bottomRef = useRef(null); + + useEffect(() => { + bottomRef.current?.scrollIntoView({ behavior: "smooth" }); + }, [entries.length]); + + return ( +
+
+ + {isOpen && ( + + )} +
+ {isOpen && ( +
+
+ {entries.map((entry) => { + const time = new Date(entry.timestamp); + const ts = + time.toTimeString().slice(0, 8) + + "." + + String(time.getMilliseconds()).padStart(3, "0"); + return ( +
+ {ts}{" "} + + [{entry.source}] + {" "} + {entry.message} +
+ ); + })} +
+
+
+ )} +
+ ); +}; + +export default LogPanel; diff --git a/apps/demo/src/components/MakeCodeOverlay.tsx b/apps/demo/src/components/MakeCodeOverlay.tsx new file mode 100644 index 00000000..3e613d30 --- /dev/null +++ b/apps/demo/src/components/MakeCodeOverlay.tsx @@ -0,0 +1,84 @@ +import { useCallback } from "react"; +import { MakeCodeFrame, MakeCodeProject } from "@microbit/makecode-embed"; +import { useFlashing } from "../hooks/use-flashing.ts"; +import FlashOverlay from "./FlashOverlay.tsx"; + +const starterProject = { + text: { + "main.blocks": + 'IconNames.Heart', + "main.ts": "basic.showIcon(IconNames.Heart)\n", + "README.md": " ", + "pxt.json": JSON.stringify({ + name: "Untitled", + dependencies: { + core: "*", + radio: "*", + }, + description: "", + files: ["main.blocks", "main.ts", "README.md"], + preferredEditor: "blocksprj", + }), + }, +} as MakeCodeProject; + +interface MakeCodeOverlayProps { + onClose: () => void; +} + +const MakeCodeOverlay = ({ onClose }: MakeCodeOverlayProps) => { + const { + step, + setStep, + startFlashing, + open, + handleClose, + handleFlash, + deviceName, + setDeviceName, + } = useFlashing(); + + const initialProject = useCallback(async () => [starterProject], []); + + const handleDownload = useCallback( + async (download: { name: string; hex: string }) => { + startFlashing(download); + }, + [startFlashing], + ); + + return ( +
+ + {open && ( + + )} +
+ ); +}; + +export default MakeCodeOverlay; diff --git a/apps/demo/src/components/PinsTab.tsx b/apps/demo/src/components/PinsTab.tsx new file mode 100644 index 00000000..7c0fced7 --- /dev/null +++ b/apps/demo/src/components/PinsTab.tsx @@ -0,0 +1,336 @@ +import { useEffect, useState, useCallback } from "react"; +import type { PinData } from "@microbit/microbit-connection"; +import type { MicrobitBluetoothConnection } from "@microbit/microbit-connection/bluetooth"; +import { useConnection } from "../hooks/use-connection.ts"; +import { useLog } from "../hooks/use-log.ts"; +import { useErrorDialog } from "../hooks/use-error-dialog.ts"; + +const PINS = [0, 1, 2]; + +const PinConfigSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [analogPins, setAnalogPins] = useState>(new Set()); + const [inputPins, setInputPins] = useState>(new Set()); + + const readConfig = useCallback(async () => { + try { + const [analog, input] = await Promise.all([ + connection.getAnalogPins(), + connection.getInputPins(), + ]); + setAnalogPins(new Set(analog.filter((p) => PINS.includes(p)))); + setInputPins(new Set(input.filter((p) => PINS.includes(p)))); + log("pins", `Analog: [${analog}], Input: [${input}]`); + } catch (e) { + showError(e); + } + }, [connection, log, showError]); + + const writeConfig = useCallback(async () => { + try { + await connection.setAnalogPins([...analogPins]); + await connection.setInputPins([...inputPins]); + log( + "pins", + `Config written — analog: [${[...analogPins]}], input: [${[...inputPins]}]`, + ); + } catch (e) { + showError(e); + } + }, [connection, analogPins, inputPins, log, showError]); + + const toggleAnalog = (pin: number) => { + setAnalogPins((prev) => { + const next = new Set(prev); + next.has(pin) ? next.delete(pin) : next.add(pin); + return next; + }); + }; + + const toggleInput = (pin: number) => { + setInputPins((prev) => { + const next = new Set(prev); + next.has(pin) ? next.delete(pin) : next.add(pin); + return next; + }); + }; + + return ( +
+

Pin Configuration

+ + + + + + + + + + {PINS.map((pin) => ( + + + + + + ))} + +
+ Pin + AnalogInput
+ P{pin} + + toggleAnalog(pin)} + /> + + toggleInput(pin)} + /> +
+
+ + +
+
+ ); +}; + +const PinDataSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [pinValues, setPinValues] = useState>(new Map()); + const [listening, setListening] = useState(false); + const [writePin, setWritePin] = useState(0); + const [writeValue, setWriteValue] = useState(""); + + useEffect(() => { + if (!listening) return; + const listener = (d: PinData) => { + setPinValues((prev) => { + const next = new Map(prev); + for (const pv of d.data) { + next.set(pv.pin, pv.value); + } + return next; + }); + }; + connection.addEventListener("pinchanged", listener); + return () => { + connection.removeEventListener("pinchanged", listener); + }; + }, [connection, listening]); + + const readAll = useCallback(async () => { + try { + const data = await connection.readPins(); + const next = new Map(); + for (const pv of data) { + next.set(pv.pin, pv.value); + } + setPinValues(next); + log( + "pins", + `Read: ${data.map((d) => `P${d.pin}=${d.value}`).join(", ") || "(none)"}`, + ); + } catch (e) { + showError(e); + } + }, [connection, log, showError]); + + const writePin_ = useCallback(async () => { + try { + const value = parseInt(writeValue, 10); + await connection.writePins([{ pin: writePin, value }]); + log("pins", `Wrote P${writePin}=${value}`); + } catch (e) { + showError(e); + } + }, [connection, writePin, writeValue, log, showError]); + + const displayPins = PINS.filter((p) => pinValues.has(p)); + + return ( +
+

Pin Data

+
+ + +
+ {displayPins.length > 0 ? ( +
+ {displayPins.map((pin) => ( + + P{pin}: + + {pinValues.get(pin)} + + + ))} +
+ ) : ( +

+ {listening + ? "Waiting for pin changes..." + : "Configure pins as inputs above, then Listen or Read."} +

+ )} +

Write output pin

+
+ + setWriteValue(e.target.value)} + placeholder="Value" + className="input" + style={{ width: 60 }} + /> + +
+
+ ); +}; + +const PwmSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [pin, setPin] = useState(0); + const [value, setValue] = useState(""); + const [period, setPeriod] = useState(""); + + const writePwm = useCallback(async () => { + try { + const v = parseInt(value, 10); + const p = parseInt(period, 10); + await connection.writePinPwm(pin, { value: v, period: p }); + log("pins", `PWM P${pin}: value=${v}, period=${p}us`); + } catch (e) { + showError(e); + } + }, [connection, pin, value, period, log, showError]); + + return ( +
+

PWM

+
+ + + + +
+
+ ); +}; + +const PinsTab = () => { + const { connection } = useConnection(); + + if (connection.type !== "bluetooth") { + return ( +
+
+

Pins require a Bluetooth connection.

+
+
+ ); + } + + return ( +
+

Requires: IO Pin Service

+ + + +
+ ); +}; + +export default PinsTab; diff --git a/apps/demo/src/components/SensorsTab.tsx b/apps/demo/src/components/SensorsTab.tsx new file mode 100644 index 00000000..081a9fb2 --- /dev/null +++ b/apps/demo/src/components/SensorsTab.tsx @@ -0,0 +1,430 @@ +import { useEffect, useState, useCallback } from "react"; +import type { + AccelerometerData, + MagnetometerData, + ButtonData, + TemperatureData, +} from "@microbit/microbit-connection"; +import type { MicrobitBluetoothConnection } from "@microbit/microbit-connection/bluetooth"; +import type { MicrobitRadioBridgeConnection } from "@microbit/microbit-connection/radio-bridge"; +import { useConnection } from "../hooks/use-connection.ts"; +import { useLog } from "../hooks/use-log.ts"; +import { useErrorDialog } from "../hooks/use-error-dialog.ts"; + +type ServiceConnection = + | MicrobitBluetoothConnection + | MicrobitRadioBridgeConnection; + +const AxisReadout = ({ + data, +}: { + data: { x: number; y: number; z: number }; +}) => ( +
+ + x: + {data.x.toFixed(3)} + + + y: + {data.y.toFixed(3)} + + + z: + {data.z.toFixed(3)} + +
+); + +const AccelerometerSection = ({ + connection, +}: { + connection: ServiceConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [data, setData] = useState(null); + const [listening, setListening] = useState(false); + const [period, setPeriod] = useState(""); + + useEffect(() => { + if (!listening) return; + const listener = (d: AccelerometerData) => setData(d); + connection.addEventListener("accelerometerdatachanged", listener); + return () => { + connection.removeEventListener("accelerometerdatachanged", listener); + }; + }, [connection, listening]); + + const getPeriod = useCallback(async () => { + try { + if (connection.type === "bluetooth") { + const p = await connection.getAccelerometerPeriod(); + setPeriod(String(p)); + } + } catch (e) { + showError(e); + } + }, [connection, showError]); + + const setPeriodValue = useCallback(async () => { + try { + if (connection.type === "bluetooth") { + await connection.setAccelerometerPeriod(parseInt(period, 10)); + log("accel", `Period set to ${period}ms`); + } + } catch (e) { + showError(e); + } + }, [connection, period, log, showError]); + + return ( +
+

Accelerometer Service

+
+ +
+ {data ? ( + + ) : ( +

+ {listening + ? "Waiting for data..." + : "Press Listen to start receiving accelerometer data."} +

+ )} + {connection.type === "bluetooth" && ( +
+ + + +
+ )} +
+ ); +}; + +const MagnetometerSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [data, setData] = useState(null); + const [listening, setListening] = useState(false); + const [period, setPeriod] = useState(""); + const [bearing, setBearing] = useState(null); + + useEffect(() => { + if (!listening) return; + const listener = (d: MagnetometerData) => setData(d); + connection.addEventListener("magnetometerdatachanged", listener); + return () => { + connection.removeEventListener("magnetometerdatachanged", listener); + }; + }, [connection, listening]); + + const getPeriod = useCallback(async () => { + try { + const p = await connection.getMagnetometerPeriod(); + setPeriod(String(p)); + } catch (e) { + showError(e); + } + }, [connection, showError]); + + const setPeriodValue = useCallback(async () => { + try { + await connection.setMagnetometerPeriod(parseInt(period, 10)); + log("mag", `Period set to ${period}ms`); + } catch (e) { + showError(e); + } + }, [connection, period, log, showError]); + + const handleGetBearing = useCallback(async () => { + try { + const b = await connection.getMagnetometerBearing(); + setBearing(b); + log("mag", `Bearing: ${b} degrees`); + } catch (e) { + showError(e); + } + }, [connection, log, showError]); + + const handleCalibrate = useCallback(async () => { + try { + log("mag", "Triggering calibration..."); + await connection.triggerMagnetometerCalibration(); + } catch (e) { + showError(e); + } + }, [connection, log, showError]); + + return ( +
+

Magnetometer Service

+
+ +
+ {data ? ( + + ) : ( +

+ {listening + ? "Waiting for data..." + : "Press Listen to start receiving magnetometer data."} +

+ )} +
+ + + +
+
+ + +
+ {bearing !== null && ( +

+ Bearing: {bearing} degrees +

+ )} +
+ ); +}; + +const TemperatureSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [celsius, setCelsius] = useState(null); + const [listening, setListening] = useState(false); + const [period, setPeriod] = useState(""); + + useEffect(() => { + if (!listening) return; + const listener = (d: TemperatureData) => setCelsius(d.celsius); + connection.addEventListener("temperaturechanged", listener); + return () => { + connection.removeEventListener("temperaturechanged", listener); + }; + }, [connection, listening]); + + const readTemperature = useCallback(async () => { + try { + const t = await connection.getTemperature(); + setCelsius(t); + log("temp", `Temperature: ${t} °C`); + } catch (e) { + showError(e); + } + }, [connection, log, showError]); + + const getPeriod = useCallback(async () => { + try { + const p = await connection.getTemperaturePeriod(); + setPeriod(String(p)); + } catch (e) { + showError(e); + } + }, [connection, showError]); + + const setPeriodValue = useCallback(async () => { + try { + await connection.setTemperaturePeriod(parseInt(period, 10)); + log("temp", `Period set to ${period}ms`); + } catch (e) { + showError(e); + } + }, [connection, period, log, showError]); + + return ( +
+

Temperature Service

+
+ + +
+ {celsius !== null ? ( +
+ + + {celsius} °C + + +
+ ) : ( +

+ {listening + ? "Waiting for data..." + : "Press Listen or Read to get temperature."} +

+ )} +
+ + + +
+
+ ); +}; + +const ButtonsSection = ({ connection }: { connection: ServiceConnection }) => { + const { log } = useLog(); + const [buttonA, setButtonA] = useState("-"); + const [buttonB, setButtonB] = useState("-"); + const [listening, setListening] = useState(false); + + useEffect(() => { + if (!listening) return; + const listenerA = (data: ButtonData) => { + setButtonA(String(data.state)); + log("button", `A: ${data.state}`); + }; + const listenerB = (data: ButtonData) => { + setButtonB(String(data.state)); + log("button", `B: ${data.state}`); + }; + connection.addEventListener("buttonachanged", listenerA); + connection.addEventListener("buttonbchanged", listenerB); + return () => { + connection.removeEventListener("buttonachanged", listenerA); + connection.removeEventListener("buttonbchanged", listenerB); + }; + }, [connection, listening, log]); + + return ( +
+

Button Service

+
+ +
+
+ + A: + + {buttonA} + + + + B: + + {buttonB} + + +
+
+ ); +}; + +const SensorsTab = () => { + const { connection } = useConnection(); + + if (connection.type === "usb") return null; + + return ( +
+ + {connection.type === "bluetooth" && ( + <> + + + + )} + +
+ ); +}; + +export default SensorsTab; diff --git a/apps/demo/src/components/SerialTab.tsx b/apps/demo/src/components/SerialTab.tsx new file mode 100644 index 00000000..bd8f510a --- /dev/null +++ b/apps/demo/src/components/SerialTab.tsx @@ -0,0 +1,84 @@ +import { useEffect, useState, useRef } from "react"; +import type { SerialData } from "@microbit/microbit-connection/usb"; +import { useConnection } from "../hooks/use-connection.ts"; +import { useLog } from "../hooks/use-log.ts"; + +const SerialTab = () => { + const { connection } = useConnection(); + const { log } = useLog(); + + const [serialLines, setSerialLines] = useState([]); + const [serialListening, setSerialListening] = useState(false); + const serialBufferRef = useRef(""); + const serialEndRef = useRef(null); + + useEffect(() => { + if (connection.type !== "usb" || !serialListening) return; + + const resetListener = () => { + serialBufferRef.current = ""; + log("serial", "Serial reset"); + }; + const dataListener = (event: SerialData) => { + for (const char of event.data) { + if (char === "\n") { + const line = serialBufferRef.current; + serialBufferRef.current = ""; + setSerialLines((prev) => { + const next = [...prev, line]; + return next.length > 200 ? next.slice(-200) : next; + }); + log("serial", line, "data"); + } else if (char !== "\r") { + serialBufferRef.current += char; + } + } + }; + + connection.addEventListener("serialreset", resetListener); + connection.addEventListener("serialdata", dataListener); + return () => { + connection.removeEventListener("serialreset", resetListener); + connection.removeEventListener("serialdata", dataListener); + }; + }, [connection, serialListening, log]); + + useEffect(() => { + serialEndRef.current?.scrollIntoView({ behavior: "smooth" }); + }, [serialLines.length]); + + return ( +
+
+

Serial

+
+ + +
+ {serialLines.length > 0 ? ( +
+ {serialLines.map((line, i) => ( +
{line}
+ ))} +
+
+ ) : ( +

+ {serialListening + ? "Waiting for serial data..." + : "Press Listen to start receiving serial data."} +

+ )} +
+
+ ); +}; + +export default SerialTab; diff --git a/apps/demo/src/components/UartTab.tsx b/apps/demo/src/components/UartTab.tsx new file mode 100644 index 00000000..e57d13ad --- /dev/null +++ b/apps/demo/src/components/UartTab.tsx @@ -0,0 +1,128 @@ +import { useEffect, useState, useCallback, useRef } from "react"; +import type { UartData } from "@microbit/microbit-connection"; +import type { MicrobitBluetoothConnection } from "@microbit/microbit-connection/bluetooth"; +import { useConnection } from "../hooks/use-connection.ts"; +import { useLog } from "../hooks/use-log.ts"; +import { useErrorDialog } from "../hooks/use-error-dialog.ts"; + +const ReceiveSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const [lines, setLines] = useState([]); + const [listening, setListening] = useState(false); + const endRef = useRef(null); + + useEffect(() => { + if (!listening) return; + const listener = (event: UartData) => { + const value = new TextDecoder().decode(event.value); + setLines((prev) => { + const next = [...prev, value]; + return next.length > 200 ? next.slice(-200) : next; + }); + log("uart", value, "data"); + }; + connection.addEventListener("uartdata", listener); + return () => { + connection.removeEventListener("uartdata", listener); + }; + }, [connection, listening, log]); + + useEffect(() => { + endRef.current?.scrollIntoView({ behavior: "smooth" }); + }, [lines.length]); + + return ( +
+

Receive

+
+ + +
+ {lines.length > 0 ? ( +
+ {lines.map((line, i) => ( +
{line}
+ ))} +
+
+ ) : ( +

+ {listening + ? "Waiting for UART data..." + : "Press Listen to start receiving UART data."} +

+ )} +
+ ); +}; + +const WriteSection = ({ + connection, +}: { + connection: MicrobitBluetoothConnection; +}) => { + const { log } = useLog(); + const { showError } = useErrorDialog(); + const [text, setText] = useState(""); + + const handleWrite = useCallback(async () => { + try { + const encoded = new TextEncoder().encode(text); + await connection.uartWrite(encoded); + log("uart", `Sent: ${text}`); + } catch (e) { + showError(e); + } + }, [connection, text, log, showError]); + + return ( +
+

Write

+
+