@@ -432,6 +442,7 @@ 加载固件
+
@@ -454,6 +465,8 @@ 加载固件
+
+
@@ -467,6 +480,9 @@ 加载固件
+
+
+
@@ -487,6 +503,10 @@ 加载固件
+
+
+
+
@@ -577,6 +597,11 @@ 加载固件
+
+
+
+
打开官方原图
+
diff --git a/platform/web/public-browser-runtime.js b/platform/web/public-browser-runtime.js
index 788763dc5..7520d78af 100644
--- a/platform/web/public-browser-runtime.js
+++ b/platform/web/public-browser-runtime.js
@@ -18,13 +18,15 @@ import { portBUnitExample } from './public-port-b-examples.js';
import { pwmUnitExample } from './public-pwm-unit-examples.js';
import { THERMAL_ID, thermalExample } from './public-thermal-example.js';
import { cores3SensorExample } from './public-cores3-sensor-examples.js';
-import { displayUnitExample, hasDisplayUnitFrame } from './public-display-unit-examples.js';
+import { DISPLAY_MODULE_ID, displayUnitExample, hasDisplayUnitFrame } from './public-display-unit-examples.js';
import { ASR_UNIT_ID, ECG_MODULE_ID, uartUnitExample } from './public-uart-unit-examples.js';
import { isWeightSample, serialSensorExample } from './public-serial-sensor-examples.js';
import { dofBoard } from './public-dof-examples.js';
import { moduleRadioAttachment } from './public-module-radio-examples.js';
import { instrumentExample,instrumentSamplesAvailable } from './public-instrument-examples.js';
import { serialMqttAttachment } from './public-mqtt-unit-examples.js';
+import { espNowExample } from './public-espnow-example.js';
+import { gatewayH2Example } from './public-gateway-h2-examples.js';
import { RUI3_MODULE_ID, RUI3_MODULE_BOARD } from './public-rui3-module-example.js';
import { FINGER_BOARD, FINGER_ID, FINGERPRINT2_BOARD, FINGERPRINT2_ID } from './public-fingerprint2-examples.js';
import { SERVOS8_ID, SERVOS8_BOARD } from './public-8servos-examples.js';
@@ -34,23 +36,25 @@ import { AUDIO_MODULE_BOARD, AUDIO_MODULE_ID, PDM_UNIT_BOARD, PDM_UNIT_ID } from
import { envBoard } from './public-env-examples.js';
import { facesModuleExample } from './public-faces-module.js';
import { WLAN_AP_EXAMPLE_ID, TCP_SERVER_EXAMPLE_ID, MODBUS_TCP_SERVER_EXAMPLE_ID, EASY_TCP_SERVER_EXAMPLE_ID, ARDUINO_RTC_EXAMPLE_ID, ARDUINO_RTC_FIRMWARE,
- ARDUINO_RTC_WIFI, LABEL_PLUS_EXAMPLE_ID, labelPlusEndpoint, networkFixtureSource, usesExampleStation, usesTextTcpPeer } from './public-network-fixtures.js';
+ ARDUINO_RTC_WIFI, LABEL_PLUS_EXAMPLE_ID, LAN_MODULE_EXAMPLE_ID, MQTT_SSL_EXAMPLE_ID, labelPlusEndpoint, networkFixtureSource,
+ usesExampleStation, usesTextTcpPeer, usesWorkbenchTls } from './public-network-fixtures.js';
import { QRCODE_MODULE_ID, QRCODE_MODULE_BOARD, QRCODE_MODULE_FIRMWARE } from './public-qrcode-module.js';
import { USB_HID_FIRMWARE, usbHidExample } from './public-usb-hid-examples.js';
import { MODBUS_RTU_FIRMWARE, modbusRtuExample } from './public-modbus-rtu.js';
import admittedBoards from './esp32sim-browser-boards.json' with {type:'json'};
-export const ESP32SIM_SOURCE_COMMIT = 'd1c930adffaa8d94d03856eb0276df17da668002';
+export const ESP32SIM_SOURCE_COMMIT = 'c51955bc06e123b98a371208e12598a0152354ac';
export const ESP32SIM_LEGACY_COMMIT = '3cd3db3b7202e9fc559328c7247c11134c0437f9';
export const ESP32SIM_DUAL_KMETER_BOARD = 'm5stack-cores3+dual-kmeter';
const CAP_RADIO_KIND = Object.freeze({cc1101:'02',lora1262:'01',lora868:'01',sx1276:'03'});
+const PAIRED_RADIO_KIND = Object.freeze({...CAP_RADIO_KIND,'e220-433':'03'});
export const ESP32SIM_CAP_RADIO_MAX_BYTES = 266;
export function esp32simCapRadioBoard(protocol) {
return protocol!=='sx1276' && Object.hasOwn(CAP_RADIO_KIND,protocol) ? `m5stack-cardputer-adv+${protocol}` : null;
}
export function validEsp32simCapRadioFrame(frame, protocol) {
- return Object.hasOwn(CAP_RADIO_KIND,protocol) && typeof frame === 'string'
- && frame.startsWith(CAP_RADIO_KIND[protocol]) && /^(?:[0-9a-f]{2}){11,266}$/.test(frame);
+ return Object.hasOwn(PAIRED_RADIO_KIND,protocol) && typeof frame === 'string'
+ && frame.startsWith(PAIRED_RADIO_KIND[protocol]) && /^(?:[0-9a-f]{2}){11,266}$/.test(frame);
}
const CURRENT_PROFILES = new Map(admittedBoards.map(profile => [profile.deviceId,profile]));
@@ -210,7 +214,7 @@ export class PublicBrowserRuntime {
try { data = JSON.parse(message.text); } catch { this.onSerial(String(message.text)); }
if (data?.t === 'serial') this.receiveSerial(data);
else if (data?.t === 'emu') this.onSerial(`[emulator] ${data.msg}\n`);
- else if (['mic-input','module-llm','ir-envelope','dual-kmeter-temperature','ultrasonic-distance','cap-radio-state','cap-radio-frame','cap-gps','qrcode-module-result','faces-input','env-sample','mini-scales-adc','finger-input','fingerprint2-input','hall-magnet','rui3-payload','drive-module-sample','nbiot-mqtt-message','mqtt-unit-message','instrument-sample','rs232-line','dof-sample','cores3-sensor-sample','usb-module-input','port-b-key','port-b-adc','weight-unit-sample','thermal-scene','uart-example-sample','unit-example-value','rtu-peer','cardkb-key','usb-hid-host','review-server-send','review-http-data'].includes(data?.t)) {
+ else if (['mic-input','module-llm','ir-envelope','dual-kmeter-temperature','ultrasonic-distance','cap-radio-state','cap-radio-frame','cap-gps','qrcode-module-result','faces-input','env-sample','mini-scales-adc','finger-input','fingerprint2-input','hall-magnet','rui3-payload','espnow-peer','gateway-h2-join','drive-module-sample','nbiot-mqtt-message','mqtt-unit-message','instrument-sample','rs232-line','dof-sample','cores3-sensor-sample','usb-module-input','port-b-key','port-b-adc','weight-unit-sample','thermal-scene','uart-example-sample','unit-example-value','rtu-peer','cardkb-key','usb-hid-host','review-server-send','review-http-data','review-tls-ready','display-module-frame'].includes(data?.t)) {
const pending = this.pending.get(data.t);
if (pending) {
this.pending.delete(data.t);
@@ -320,10 +324,17 @@ export class PublicBrowserRuntime {
if (serialMqttAttachment(data.unit) && typeof value?.['mqtt-listening'] === 'boolean') {
this.lastUnitExampleState = {kind:data.unit,listening:value['mqtt-listening']};
}
+ if (gatewayH2Example(data.unit) && ['ready','joined','bound','light-on'].every(key => typeof value?.[key] === 'boolean')) {
+ this.lastUnitExampleState={kind:data.unit,ready:value.ready,joined:value.joined,bound:value.bound,light:value['light-on']};
+ }
if (data.unit === RUI3_MODULE_ID && typeof value?.listening === 'boolean') {
this.lastUnitExampleState = {kind:data.unit, listening:value.listening};
}
const displayUnit = displayUnitExample(data.unit);
+ if (data.unit===DISPLAY_MODULE_ID && value?.width===displayUnit.width && value.height===displayUnit.height
+ && ['id-reads','i2c-read-bytes','i2c-write-bytes','timing-commands','draw-commands'].every(key=>count(value[key]))) {
+ this.lastUnitExampleState = {kind:data.unit,...value};
+ }
if (displayUnit && hasDisplayUnitFrame(displayUnit, value)
&& count(value.commands) && count(value['data-bytes'])) {
this.lastUnitExampleState = {kind:data.unit, ...value};
@@ -340,8 +351,8 @@ export class PublicBrowserRuntime {
const portrait = this.profile.deviceId === 'cardputer-adv' && (rotation === -90 || rotation === 90);
this.display = {orientation:portrait ? 'portrait' : 'landscape',deviceRotationDeg:portrait ? rotation : 0};
this.onState(this.observe());
- if (this.status === 'running' && (['relay','ultrasonic-i2c',SERVOS8_ID,RUI3_MODULE_ID,THERMAL_ID].includes(this.profile.unitExample)
- || usbModuleExample(this.profile.unitExample) || displayUnitExample(this.profile.unitExample)
+ if (this.status === 'running' && (['relay','ultrasonic-i2c',SERVOS8_ID,RUI3_MODULE_ID,THERMAL_ID,LAN_MODULE_EXAMPLE_ID].includes(this.profile.unitExample)
+ || gatewayH2Example(this.profile.unitExample) || usbModuleExample(this.profile.unitExample) || displayUnitExample(this.profile.unitExample)
|| uartUnitExample(this.profile.unitExample) || driveModuleExample(this.profile.unitExample)
|| serialMqttAttachment(this.profile.unitExample)
|| pwmUnitExample(this.profile.unitExample) || portBUnitExample(this.profile.unitExample)
@@ -455,8 +466,9 @@ export class PublicBrowserRuntime {
return value;
}
- async start({device, firmware, signal, audio, sidecarArchive, unitExample, capExample, sx1262Example, networkFixture} = {}) {
+ async start({device, firmware, signal, audio, sidecarArchive, unitExample, capExample, sx1262Example, networkFixture, peerImage} = {}) {
this.stop();
+ this.fixtureCertificate = null;
const generation = this.generation;
const profile = getBrowserProfile(typeof device === 'string' ? device : device?.id, this.availableProfiles);
requireValue(profile, 'browser_board_unsupported', '该设备尚未接入浏览器内核,请连接 Device Service。');
@@ -473,7 +485,7 @@ export class PublicBrowserRuntime {
this.display = null; this.lastFrame = null; this.servo = null;
this.lastUnitExampleState = null; this.nextUnitObservationAt = 0;
this.advKeys = new Map(); this.advFnKeys = new Set();
- this.saved = {device:profile.deviceId,firmware:firmware.slice(0),sidecarArchive,unitExample,capExample,sx1262Example,networkFixture};
+ this.saved = {device:profile.deviceId,firmware:firmware.slice(0),sidecarArchive,unitExample,capExample,sx1262Example,networkFixture,peerImage};
this.controller = new AbortController();
const cancel = () => this.stop();
signal?.addEventListener('abort', cancel, {once:true});
@@ -500,6 +512,11 @@ export class PublicBrowserRuntime {
profile.board = `m5stack-cores3+${documentedUnit}`;
profile.unitExample = documentedUnit;
}
+ if (networkFixture === LAN_MODULE_EXAMPLE_ID) {
+ const board = 'm5stack-cores3+lan-module';
+ requireValue(this.availableProfiles?.includes(board), 'browser_fixture_mismatch', '浏览器内核缺少 LAN Module。');
+ Object.assign(profile, {board,unitExample:LAN_MODULE_EXAMPLE_ID});
+ }
const gps = capGpsExample(unitExample);
const gpioUnit = gpioUnitBoard(unitExample);
const dof = dofBoard(unitExample);
@@ -613,6 +630,18 @@ export class PublicBrowserRuntime {
&& firmwareInputSha256 === QRCODE_MODULE_FIRMWARE,
'browser_attachment_mismatch', '此 MQTT 例程需使用匹配的 CoreS3 编程固件和浏览器内核。');
Object.assign(profile,{board,unitExample});
+ } else if (espNowExample(unitExample)) {
+ const {board}=espNowExample(unitExample);
+ requireValue(profile.deviceId === 'cores3' && this.availableProfiles?.includes(board)
+ && firmwareInputSha256 === QRCODE_MODULE_FIRMWARE,
+ 'browser_attachment_mismatch', 'ESP-NOW 需使用匹配的 CoreS3 编程固件和浏览器内核。');
+ Object.assign(profile,{board,unitExample});
+ } else if (gatewayH2Example(unitExample)) {
+ const {board}=gatewayH2Example(unitExample);
+ requireValue(profile.deviceId === 'cores3' && this.availableProfiles?.includes(board)
+ && firmwareInputSha256 === QRCODE_MODULE_FIRMWARE,
+ 'browser_attachment_mismatch', 'Gateway H2 需使用匹配的 CoreS3 编程固件和浏览器内核。');
+ Object.assign(profile,{board,unitExample});
} else if (unitExample === RUI3_MODULE_ID) {
requireValue(profile.deviceId === 'cores3' && this.availableProfiles?.includes(RUI3_MODULE_BOARD)
&& firmwareInputSha256 === QRCODE_MODULE_FIRMWARE,
@@ -771,7 +800,29 @@ export class PublicBrowserRuntime {
const address=labelPlusEndpoint(new TextDecoder('utf-8',{fatal:true}).decode(asset.bytes));
requireValue(address, 'browser_attachment_mismatch', '官方 LabelPlus 例程缺少可用的虚拟对端。');
worker.postMessage({op:'review-tcp',mode:networkFixture,address});
- } else if (usesExampleStation(networkFixture)) worker.postMessage({op:'review-tcp',mode:networkFixture});
+ } else if (usesExampleStation(networkFixture)&&!usesWorkbenchTls(networkFixture)) {
+ worker.postMessage({op:'review-tcp',mode:networkFixture});
+ }
+ if (usesWorkbenchTls(networkFixture)) {
+ const runtimeUrl = assetUrl('platform/runtime/workbench-tls/runtime.json', this.root);
+ const descriptor = await this.fetchImpl(runtimeUrl, {signal:this.controller.signal});
+ requireValue(descriptor.ok, 'browser_fixture_unavailable', '缺少虚拟 TLS 对端。');
+ const tls = await descriptor.json();
+ const wasmSource = tls.schema_version === 1 && tls.assets?.['fixture.wasm'];
+ requireValue(wasmSource && Number.isInteger(wasmSource.bytes) && wasmSource.bytes > 0,
+ 'browser_fixture_unavailable', 'HTTPS 对端信息无效。');
+ const fixture = await loadVerifiedRuntimeAsset(assetUrl('platform/runtime/workbench-tls/fixture.wasm', this.root), {
+ signal:this.controller.signal,fetchImpl:this.fetchImpl,maxBytes:12*1024*1024,
+ expectedSha256:wasmSource.sha256,expectedBytes:wasmSource.bytes,
+ });
+ active();
+ const image = peerImage?.slice(0);
+ const ready = await this.ask('review-tls-ready',
+ {op:'review-tls',mode:networkFixture,wasm:fixture.bytes,...(image ? {image} : {})},
+ image ? [fixture.bytes,image] : [fixture.bytes]);
+ requireValue(ready.ok, 'browser_fixture_unavailable', '无法启动虚拟 TLS 对端。');
+ if (networkFixture === MQTT_SSL_EXAMPLE_ID) this.fixtureCertificate = ready.certificate;
+ }
if (arduinoRtc) worker.postMessage({op:'wifi',spec:ARDUINO_RTC_WIFI});
if (profile.camera) await this.queueInput({t:'camera-pattern',enabled:1});
requireValue((await this.ask('started', {op:'start',appDirect:false})).started, 'browser_boot_failed', '客体启动失败,请查看串口。'); active();
@@ -807,6 +858,7 @@ export class PublicBrowserRuntime {
});
}
stop() {
+ this.fixtureCertificate = null;
this.generation++; this.consoleEpoch++; this.uartOwner = null; this.controller?.abort(); this.signalCleanup?.(); this.signalCleanup = null;
this.worker?.terminate(); this.worker = null;
this.audioPlayer?.close(); this.audioPlayer = null;
@@ -961,6 +1013,14 @@ export class PublicBrowserRuntime {
'invalid_port_b_adc', 'ADC 输入应为 0 到 4095 的整数。');
const reply = await this.ask(t,{op:'text',data:JSON.stringify({t,raw})});
return {accepted:reply.ok === true};
+ } else if (event?.type === 'display-module-frame') {
+ const t=event.type;
+ requireValue(this.status==='running' && this.profile.unitExample===DISPLAY_MODULE_ID,
+ 'browser_attachment_mismatch', '此会话未连接 Display Module。');
+ const reply=await this.ask(t,{op:'text',data:JSON.stringify({t})});
+ requireValue(hasDisplayUnitFrame(displayUnitExample(DISPLAY_MODULE_ID),reply.value),
+ 'invalid_display_frame', '显示模块尚无可读取的画面。');
+ return reply.value;
} else if (event?.type === 'thermal-scene') {
const {type:t,scene} = event;
requireValue(this.status === 'running' && this.profile.unitExample === THERMAL_ID && ['left','right'].includes(scene),
@@ -1036,6 +1096,19 @@ export class PublicBrowserRuntime {
const t = event.type;
const reply = await this.ask(t,{op:'text',data:JSON.stringify({t,message})});
return {accepted:reply.ok === true};
+ } else if (event?.type === 'espnow-peer') {
+ const {action}=event;
+ requireValue(this.status === 'running' && espNowExample(this.profile.unitExample)
+ && ['attach','detach'].includes(action), 'invalid_espnow_peer', '请先运行 ESP-NOW 例程。');
+ const t=event.type;
+ const reply=await this.ask(t,{op:'text',data:JSON.stringify({t,action})});
+ return {accepted:reply.ok === true};
+ } else if (event?.type === 'gateway-h2-join') {
+ requireValue(this.status === 'running' && gatewayH2Example(this.profile.unitExample),
+ 'invalid_gateway_h2_input', '请先运行 Gateway H2 例程。');
+ const t=event.type;
+ const reply=await this.ask(t,{op:'text',data:JSON.stringify({t})});
+ return {accepted:reply.ok === true};
} else if (event?.type === 'rui3-payload') {
const {payload} = event;
requireValue(this.status === 'running' && this.profile.unitExample === RUI3_MODULE_ID
diff --git a/platform/web/public-display-unit-examples.js b/platform/web/public-display-unit-examples.js
index 67c0ae576..85c428d1b 100644
--- a/platform/web/public-display-unit-examples.js
+++ b/platform/web/public-display-unit-examples.js
@@ -1,6 +1,13 @@
const root = 'https://raw.githubusercontent.com/m5stack/uiflow-micropython/a61a29409f09f1f4bebae05e15c4bd6dcc4956b6/examples/';
+export const DISPLAY_MODULE_ID = 'display-module';
+
const displays = {
+ [DISPLAY_MODULE_ID]: {
+ name:'Display Module', path:'module/display/cores3_display_example.py', width:1280, height:720,
+ bytes:1169, format:'rgb-runs',
+ sha256:'82aa4ce1a286bd335e6b20c08b9c3f2bb871734a4602438d1bc11cc93b3d3ae5',
+ },
glass: {
name:'GLASS', path:'unit/glass/cores3_glass_example.py', width:128, height:64, bytes:1067,
sha256:'da89f78e176ccfb18c181fd45d747f27e074627fb507e0b21d3d07ebcc3de3ee',
@@ -31,6 +38,19 @@ export function displayUnitExample(id) {
export function hasDisplayUnitFrame(display, state) {
if (state?.width !== display.width || state.height !== display.height) return false;
const pixels = display.width * display.height;
+ if (display.format === 'rgb-runs') {
+ const runs=state['rgb-runs'];
+ if (!Array.isArray(runs) || runs.length>8192) return false;
+ let count=0;
+ for (const run of runs) {
+ if (!Array.isArray(run) || run.length!==2) return false;
+ const [length,color]=run;
+ if (!Number.isInteger(length) || length<1 || !Number.isInteger(color) || color<0 || color>0xffffff) return false;
+ count+=length;
+ if (count>pixels) return false;
+ }
+ return count===pixels;
+ }
if (display.format === 'rgb565le') {
const frame = state['frame-rgb565le'];
return typeof frame === 'string' && frame.length === pixels * 4 && /^[0-9a-f]+$/.test(frame);
@@ -39,11 +59,25 @@ export function hasDisplayUnitFrame(display, state) {
state.frame.every(byte => Number.isInteger(byte) && byte >= 0 && byte <= 255);
}
-export function drawDisplayUnitFrame(canvas, {width,height,frame,'frame-rgb565le':rgb565le}) {
+export function drawDisplayUnitFrame(canvas, {width,height,frame,'frame-rgb565le':rgb565le,'rgb-runs':rgbRuns}) {
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
const image = ctx.createImageData(width,height);
+ if (rgbRuns) {
+ let offset=0;
+ for (const [length,color] of rgbRuns) {
+ const [r,g,b]=[color>>16,(color>>8)&255,color&255];
+ for (let pixel=0; pixel2048 ||
+ !/^-----BEGIN CERTIFICATE-----\n[A-Za-z0-9+/=]+\n-----END CERTIFICATE-----\n$/.test(pem)) {
+ throw new Error('虚拟 MQTT CA 无效。');
+ }
+ signal?.throwIfAborted();
+ if (!current()) throw new DOMException('设备会话已改变。','AbortError');
+ const bytes=encoder.encode(pem);
+ const expected=sha256Bytes(bytes);
+ const encoded=btoa(String.fromCharCode(...bytes));
+ const {stdout,stderr}=await runner.run(`def _m5_install_fixture_ca():
+ import os, binascii, hashlib
+ folder = "/flash/certificate"
+ dest = folder + "/emqxsl-ca.crt"
+ staged = dest + ".fixture"
+ try: os.mkdir(folder)
+ except OSError as error:
+ if error.args[0] != 17: raise
+ with open(staged,"wb") as f:
+ f.write(binascii.a2b_base64(b'${encoded}'))
+ with open(staged,"rb") as f:
+ digest = binascii.hexlify(hashlib.sha256(f.read()).digest()).decode()
+ if digest != "${expected}": raise ValueError("fixture CA digest mismatch")
+ os.rename(staged,dest)
+ print("M5_TLS_CA",digest)
+try:
+ _m5_install_fixture_ca()
+finally:
+ del _m5_install_fixture_ca
+`,{signal});
+ if (!current()) throw new DOMException('设备会话已改变。','AbortError');
+ if (stderr || stdout.trim()!==`M5_TLS_CA ${expected}`) throw new Error('虚拟 MQTT CA 导入失败。');
+}
diff --git a/platform/web/public.js b/platform/web/public.js
index 45423c232..4c89bc227 100644
--- a/platform/web/public.js
+++ b/platform/web/public.js
@@ -4,7 +4,7 @@ import {composeUIFlowWorkbenchFirmware,loadUIFlowWorkbenchProfiles,getUIFlowWork
import {openQemuPeerPair,newQemuPeerCode} from './public-qemu-peer-pair.js';
import {capGpsExample} from './public-cap-gps-examples.js';
import {GNSS_EXAMPLE_ID,supportsQemuGnssWorkbench} from './public-qemu-gnss-example.js';
-import {MODBUS_TCP_SERVER_EXAMPLE_ID,LABEL_PLUS_EXAMPLE_ID,NETWORK_STATION_PREP,networkFixtureSource,usesExampleStation,usesTextTcpPeer} from './public-network-fixtures.js';
+import {IMAGEPLUS_HTTPS_EXAMPLE_ID,IMAGEPLUS_PEER_IMAGE,LAN_MODULE_EXAMPLE_ID,MODBUS_TCP_SERVER_EXAMPLE_ID,LABEL_PLUS_EXAMPLE_ID,MQTT_SSL_EXAMPLE_ID,NETWORK_STATION_PREP,networkFixtureSource,usesExampleStation,usesTextTcpPeer,usesWorkbenchTls} from './public-network-fixtures.js';
import {QRCODE_MODULE_ID,QRCODE_MODULE_BOARD,QRCODE_MODULE_FIRMWARE,qrcodeModuleExample} from './public-qrcode-module.js';
import {FINGER_ID,FINGERPRINT2_ID,fingerprint2Example} from './public-fingerprint2-examples.js';
import {SERVOS8_ID,servos8Example} from './public-8servos-examples.js';
@@ -17,13 +17,15 @@ import {pwmUnitExample} from './public-pwm-unit-examples.js';
import {THERMAL_ID, thermalExample} from './public-thermal-example.js';
import {ASR_UNIT_ID, ECG_MODULE_ID, uartUnitExample} from './public-uart-unit-examples.js';
import {cores3SensorExample} from './public-cores3-sensor-examples.js';
-import {drawDisplayUnitFrame, displayUnitExample} from './public-display-unit-examples.js';
+import {DISPLAY_MODULE_ID, drawDisplayUnitFrame, displayUnitExample} from './public-display-unit-examples.js';
import {serialSensorExample} from './public-serial-sensor-examples.js';
import {dofBoard,dofExample} from './public-dof-examples.js';
import {moduleRadioExample,moduleRadioAttachment} from './public-module-radio-examples.js';
import {instrumentExample,instrumentSamplesAvailable} from './public-instrument-examples.js';
import {nbiotExample} from './public-nbiot-examples.js';
import {mqttUnitExample,serialMqttAttachment} from './public-mqtt-unit-examples.js';
+import {espNowExample} from './public-espnow-example.js';
+import {gatewayH2Example} from './public-gateway-h2-examples.js';
import {RUI3_MODULE_ID,rui3ModuleExample} from './public-rui3-module-example.js';
import {MINI_SCALES_ID,miniScalesExample} from './public-mini-scales.js';
import {MODULE_LLM_EXAMPLE_ID,moduleLlmExample} from './public-module-llm-example.js';
@@ -33,7 +35,7 @@ import {facesModuleExample} from './public-faces-module.js';
import {MODBUS_RTU_FIRMWARE,modbusRtuExample} from './public-modbus-rtu.js';
import {USB_HID_FIRMWARE,usbHidExample} from './public-usb-hid-examples.js';
import {PublicMicroPythonRunner} from './public-micropython.js';
-import {importWorkbenchResource} from './public-workbench-resources.js';
+import {importWorkbenchFixtureCa,importWorkbenchResource} from './public-workbench-resources.js';
import {assetUrl, siteRoot, resolveDevice, parseLaunchConfig, buildShareUrl, normalizeServiceUrl, selectExecutionLane} from './public-config.js';
import {downloadFirmware, normalizeFirmwareSha256, DEFAULT_MAX_FIRMWARE_BYTES, sha256Buffer} from './public-firmware.js';
import {loadVerifiedRuntimeAsset} from './public-verified-assets.js';
@@ -166,7 +168,7 @@ function availableDualKmeterSource(profile, workbench) {
return dualKmeterExampleSource(getQemuBrowserProfile('cores3',state.qemuProfiles),workbench,state.config.browser_dual_kmeter_example);
}
function documentedAttachmentExample(id) {
- return mqttUnitExample(id) || nbiotExample(id) || instrumentExample(id) || uartUnitExample(id) || portAUnitExample(id) || moduleRadioExample(id) || driveModuleExample(id) || usbModuleExample(id) || displayUnitExample(id) || pwmUnitExample(id) || portBUnitExample(id) || serialSensorExample(id) || dofExample(id) || thermalExample(id) || cores3SensorExample(id) || audioModuleExample(id) || gpioUnitExample(id) || rui3ModuleExample(id) || capGpsExample(id) || moduleLlmExample(id) || fingerprint2Example(id) || miniScalesExample(id) || servos8Example(id) || envExample(id) || facesModuleExample(id) || qrcodeModuleExample(id);
+ return espNowExample(id) || gatewayH2Example(id) || mqttUnitExample(id) || nbiotExample(id) || instrumentExample(id) || uartUnitExample(id) || portAUnitExample(id) || moduleRadioExample(id) || driveModuleExample(id) || usbModuleExample(id) || displayUnitExample(id) || pwmUnitExample(id) || portBUnitExample(id) || serialSensorExample(id) || dofExample(id) || thermalExample(id) || cores3SensorExample(id) || audioModuleExample(id) || gpioUnitExample(id) || rui3ModuleExample(id) || capGpsExample(id) || moduleLlmExample(id) || fingerprint2Example(id) || miniScalesExample(id) || servos8Example(id) || envExample(id) || facesModuleExample(id) || qrcodeModuleExample(id);
}
function availableAttachmentSource(profile, workbench, id) {
const example=documentedAttachmentExample(id);
@@ -208,6 +210,7 @@ function reference(device = state.selected) {
const networkId=$('referenceExample').value, networkSource=networkFixtureSource(networkId);
if (networkSource) {
if(profile?.deviceId!=='cores3'||workbench?.firmwareSHA256!==QRCODE_MODULE_FIRMWARE
+ ||usesWorkbenchTls(networkId)&&!state.config.browser_esp32sim_workbench_tls
||state.config.browser_runtime_engine!=='esp32sim')return null;
return {name:`CoreS3 ${networkSource.name} · UIFlow2 v2.5.3`,composedWorkbench:true,networkFixture:networkId,
sha256:workbench.firmwareSHA256};
@@ -525,13 +528,19 @@ function updateBrowserUnitExample(run) {
: pwm?'等待 PWM 信号':'';
const displayUnit=live&&displayUnitExample(kind);
$('browserOledPanel').hidden=!displayUnit;
+ const hdmi=displayUnit&&kind===DISPLAY_MODULE_ID;
+ const hdmiButton=$('browserDisplayModuleSnapshot');
+ hdmiButton.hidden=$('browserDisplayModuleStatus').hidden=!hdmi;
+ hdmiButton.disabled=!hdmi||controller.status!=='running'||reading?.kind!==kind||!reading['draw-commands']||!!run.hdmiPending;
+ $('browserDisplayModuleStatus').textContent=hdmi?run.hdmiError||'':'';
if(displayUnit){
$('browserOledTitle').textContent=displayUnit.name;
const canvas=$('browserOledCanvas');
- canvas.hidden=reading?.kind!==kind;
- if(!canvas.hidden&&run.oledFrame!==reading){
- drawDisplayUnitFrame(canvas,reading);
- run.oledFrame=reading;
+ const frame=hdmi?run.hdmiFrame:reading?.kind===kind?reading:null;
+ canvas.hidden=!frame;
+ if(frame&&run.oledFrame!==frame){
+ drawDisplayUnitFrame(canvas,frame);
+ run.oledFrame=frame;
}
}
const thermal=live&&kind===THERMAL_ID;
@@ -602,6 +611,19 @@ function updateBrowserUnitExample(run) {
}
$('browserNbiotSend').disabled=!subscribed||controller.status!=='running'||!!run?.nbiotPending;
$('browserNbiotStatus').textContent=nbiot?run.nbiotStatus||(subscribed?'客体已订阅。':'等待客体订阅。'):'';
+ const espnow=live&&espNowExample(kind);
+ $('browserEspNowPanel').hidden=!espnow;
+ $('browserEspNowToggle').disabled=!espnow||controller.status!=='running'||!!run?.espnowPending;
+ $('browserEspNowToggle').textContent=espnow&&run.espnowAttached?'断开虚拟对端':'连接虚拟对端';
+ $('browserEspNowStatus').textContent=espnow?run.espnowError||'':'';
+ const gateway=live&&gatewayH2Example(kind);
+ const gatewayState=gateway&&reading?.kind===kind?reading:null;
+ $('browserGatewayH2Panel').hidden=!gateway;
+ $('browserGatewayH2Join').disabled=!gatewayState?.ready||gatewayState.joined
+ ||controller.status!=='running'||!!run?.gatewayH2Pending;
+ $('browserGatewayH2Status').textContent=gateway?run.gatewayH2Error||(gatewayState?.bound
+ ?(gatewayState.light?'灯具已开启。':'灯具已关闭。')
+ :gatewayState?.joined?'灯具正在绑定。':gatewayState?.ready?'网络已就绪。':'等待客体建立网络。'):'';
const rui3=live&&kind===RUI3_MODULE_ID;
const rui3Listening=rui3&&reading?.kind===RUI3_MODULE_ID&&reading.listening;
const payload=$('browserRui3Payload');
@@ -929,6 +951,10 @@ async function runPython() {
const {stdout,stderr}=await run.python.run(NETWORK_STATION_PREP,{signal:state.abort?.signal,timeoutMs:90000});
if(!current())return;
if(stderr||!/M5_FIXTURE_STA 10\.0\.2\.15/.test(stdout))throw new Error('无法连接虚拟网络。');
+ if (run.controller.receipt.networkFixture === MQTT_SSL_EXAMPLE_ID) {
+ await importWorkbenchFixtureCa(run.controller.fixtureCertificate, run.python, {signal:state.abort?.signal,current});
+ if(!current())return;
+ }
run.networkEpoch=epoch;
} finally {
run.preparingNetwork=false;
@@ -1069,6 +1095,9 @@ function updateCapability() {
&& state.run.controller.status === 'running' && state.run.controller.profile?.inputs?.camera;
$('browserCameraInput').hidden = !cameraEnabled;
if (cameraEnabled) $('browserCameraPanel').hidden = false;
+ $('browserImagePlusSetting').hidden = selectedLane !== 'browser' || reference()?.networkFixture !== IMAGEPLUS_HTTPS_EXAMPLE_ID;
+ $('browserImagePlusDownload').href = IMAGEPLUS_PEER_IMAGE.url;
+ $('browserImagePlusFile').disabled = state.busy;
$('browserSidecarSetting').hidden = selectedLane !== 'browser' || browserProfile(device?.id)?.chip !== 'esp32p4'
|| state.config.browser_runtime_engine !== 'esp32sim';
$('browserSidecarFile').disabled = state.busy;
@@ -1155,7 +1184,8 @@ function renderDetails() {
for(const option of $('referenceExample').options)option.hidden=option.value==='uiflow-cloud'
? !serviceCloudStartup() : usbHidExample(option.value)
? !availableUsbHidSource(profile,workbench,option.value) : networkFixtureSource(option.value)
- ? profile?.deviceId!=='cores3'||workbench?.firmwareSHA256!==QRCODE_MODULE_FIRMWARE||state.config.browser_runtime_engine!=='esp32sim' : modbusRtuExample(option.value)
+ ? profile?.deviceId!=='cores3'||workbench?.firmwareSHA256!==QRCODE_MODULE_FIRMWARE||state.config.browser_runtime_engine!=='esp32sim'
+ ||usesWorkbenchTls(option.value)&&!state.config.browser_esp32sim_workbench_tls : modbusRtuExample(option.value)
? !availableModbusRtuSource(profile,workbench,option.value) : documentedAttachmentExample(option.value)
? !availableAttachmentSource(profile,workbench,option.value) : option.value===DUAL_KMETER_EXAMPLE_ID
? !availableDualKmeterSource(profile,workbench) : option.value===drawingExampleId
@@ -1175,7 +1205,8 @@ function renderDetails() {
: ref?.usbHidSource
? '运行官方例程后连接虚拟 USB 主机。输入 CardKB 按键或操作触屏,然后读取 HID 报文。'
: ref?.networkFixture
- ? (usesExampleStation(ref.networkFixture)?'运行例程前,工作台会连接本次会话的虚拟网络。':'启动后载入并运行官方例程。虚拟客户端会连接来宾的热点。')
+ ? (ref.networkFixture===LAN_MODULE_EXAMPLE_ID?'运行原例程,通过虚拟有线端口读取 HTTPS 响应。'
+ : usesExampleStation(ref.networkFixture)?'运行例程前,工作台会连接本次会话的虚拟网络。':'启动后载入并运行官方例程。虚拟客户端会连接来宾的热点。')
: ref?.modbusSource
? (ref.modbusId==='acssr-rtu'?'运行官方例程后,触摸来宾屏幕上的开关。'
:'加载并运行官方例程。主站连接虚拟从站,从站可接收虚拟主站的读写请求。')
@@ -1191,6 +1222,7 @@ function renderDetails() {
:portBUnitExample(ref.moduleSource.attachment)?.rmt?'运行原例程后按电源键,查看 Port B 的 RMT 输出。'
:portBUnitExample(ref.moduleSource.attachment)?'运行例程后操作可用的 Port B 输入,查看来宾读数或输出。'
:pwmUnitExample(ref.moduleSource.attachment)?'运行官方例程,查看 Unit 引脚的 PWM 输出。'
+ :ref.moduleSource.attachment===DISPLAY_MODULE_ID?'运行官方例程并读取显示模块画面。'
:displayUnitExample(ref.moduleSource.attachment)?'运行官方例程后,在工作台查看通过 I²C 绘制的 Unit 画面。'
:thermalExample(ref.moduleSource.attachment)?'运行官方例程并切换模拟热源位置。'
:ref.moduleSource.attachment===ASR_UNIT_ID?'运行官方例程,发送模拟的 ASR 命令。'
@@ -1205,6 +1237,8 @@ function renderDetails() {
:instrumentSamplesAvailable(ref.moduleSource.attachment)?'选择虚拟采样,查看来宾画面读数。'
:ref.moduleSource.attachment==='rs232-module'?'从 RS232 发送一行,查看来宾串口输出。'
:serialMqttAttachment(ref.moduleSource.attachment)?'运行官方例程,待客体订阅后发布消息。'
+ :espNowExample(ref.moduleSource.attachment)?'连接虚拟对端后,在串口输出中查看原版例程收到的数据。'
+ :gatewayH2Example(ref.moduleSource.attachment)?'运行原版例程后加入虚拟灯具,再按设备电源键切换灯具。'
:ref.moduleSource.attachment===RUI3_MODULE_ID?'运行官方例程并触摸来宾屏幕。模块开始监听后,发送一条模拟消息。'
:ref.moduleSource.attachment===MINI_SCALES_ID?'启动后载入并运行官方例程,再调整模拟 ADC 读数。'
:[AUDIO_MODULE_ID,PDM_UNIT_ID].includes(ref.moduleSource.attachment)?'启动时打开声音,载入并运行官方例程。录音例程可先导入麦克风 WAV。'
@@ -1840,9 +1874,18 @@ async function startRun(audio) {
const sidecarFile = browserProfile(state.selected.id)?.chip === 'esp32p4' && $('browserSidecarFile').files[0];
if (sidecarFile && sidecarFile.size > 1024 * 1024) throw new Error('Tab5 C6 ZIP 文件超过 1 MiB。');
const sidecarArchive = sidecarFile ? await sidecarFile.arrayBuffer() : undefined;
+ let peerImage;
+ if (run.networkFixture === IMAGEPLUS_HTTPS_EXAMPLE_ID) {
+ const file = $('browserImagePlusFile').files[0];
+ if (!file || file.size !== IMAGEPLUS_PEER_IMAGE.bytes) throw new Error('请选择官方 Image+ PNG。');
+ peerImage = await file.arrayBuffer();
+ if (await sha256Buffer(peerImage, {signal:abort.signal}) !== IMAGEPLUS_PEER_IMAGE.sha256)
+ throw new Error('Image+ PNG 的 SHA-256 不匹配。');
+ }
if (!active(run) || abort.signal.aborted) return;
await run.controller.start({device: state.selected.id,firmware:loaded.bytes,signal:abort.signal,...gnssOptions,...radioOptions,
...(sidecarArchive ? {sidecarArchive} : {}),
+ ...(peerImage ? {peerImage} : {}),
...(run.dualKmeterSource ? {unitExample:DUAL_KMETER_EXAMPLE_ID} : {}),
...(run.networkFixture ? {networkFixture:run.networkFixture} : {}),
...(run.moduleSource ? {unitExample:run.moduleSource.attachment||QRCODE_MODULE_ID} : {}),
@@ -2594,6 +2637,20 @@ for (const [id,action] of [['browserPortBKeyPress','press'],['browserPortBKeyRel
}
});
}
+$('browserDisplayModuleSnapshot').addEventListener('click',async()=>{
+ const run=state.run;
+ if(!active(run)||$('browserDisplayModuleSnapshot').disabled)return;
+ run.hdmiPending=true;
+ run.hdmiError='';
+ updateBrowserUnitExample(run);
+ try {
+ run.hdmiFrame=await run.controller.input({type:'display-module-frame'});
+ } catch(cause) { run.hdmiError=cause.message; }
+ finally {
+ run.hdmiPending=false;
+ if(active(run))updateBrowserUnitExample(run);
+ }
+});
for (const [id,scene] of [['browserThermalLeft','left'],['browserThermalRight','right']]) {
$(id).addEventListener('click',async()=>{
const run=state.run;
@@ -2729,6 +2786,36 @@ $('browserNbiotPanel').addEventListener('submit',async(event)=>{
if(active(run))updateBrowserUnitExample(run);
}
});
+$('browserEspNowToggle').addEventListener('click',async()=>{
+ const run=state.run;
+ if(!active(run)||$('browserEspNowToggle').disabled)return;
+ const action=run.espnowAttached?'detach':'attach';
+ run.espnowPending=true;
+ updateBrowserUnitExample(run);
+ try {
+ const {accepted}=await run.controller.input({type:'espnow-peer',action});
+ if(accepted)run.espnowAttached=action==='attach';
+ run.espnowError=accepted?'':'暂时无法切换对端连接。';
+ } catch(cause) { run.espnowError=cause.message; }
+ finally {
+ run.espnowPending=false;
+ if(active(run))updateBrowserUnitExample(run);
+ }
+});
+$('browserGatewayH2Join').addEventListener('click',async()=>{
+ const run=state.run;
+ if(!active(run)||$('browserGatewayH2Join').disabled)return;
+ run.gatewayH2Pending=true;
+ updateBrowserUnitExample(run);
+ try {
+ const {accepted}=await run.controller.input({type:'gateway-h2-join'});
+ run.gatewayH2Error=accepted?'':'灯具暂时无法加入。';
+ } catch(cause) { run.gatewayH2Error=cause.message; }
+ finally {
+ run.gatewayH2Pending=false;
+ if(active(run))updateBrowserUnitExample(run);
+ }
+});
$('browserRui3Send').addEventListener('click',async()=>{
const run=state.run;
if(!active(run)||$('browserRui3Send').disabled)return;
diff --git a/platform/web/vendor/esp32sim/UPSTREAM.md b/platform/web/vendor/esp32sim/UPSTREAM.md
index a8958f65e..4d0f3d277 100644
--- a/platform/web/vendor/esp32sim/UPSTREAM.md
+++ b/platform/web/vendor/esp32sim/UPSTREAM.md
@@ -1,7 +1,7 @@
# esp32sim browser execution glue
The ES modules and MIT license in this directory come from the
-[M5Stack esp32sim fork](https://github.com/m5agent/esp32sim/tree/d1c930adffaa8d94d03856eb0276df17da668002).
+[M5Stack esp32sim fork](https://github.com/m5agent/esp32sim/tree/c51955bc06e123b98a371208e12598a0152354ac).
The browser runtime extends the
[backend completion milestone](https://github.com/m5agent/esp32sim/tree/m5-milestone-backend-complete-20261201).
It includes PaperMono and PaperColor timed PM1 input and PaperColor SPI SD.
diff --git a/platform/web/vendor/esp32sim/https-app.mjs b/platform/web/vendor/esp32sim/https-app.mjs
new file mode 100644
index 000000000..745c6e865
--- /dev/null
+++ b/platform/web/vendor/esp32sim/https-app.mjs
@@ -0,0 +1,43 @@
+// The documentation fixture consumes the HTTP request after the TLS endpoint
+// decrypts it. It serves fixed content without accessing the guest's URL.
+const encode = new TextEncoder();
+const decode = new TextDecoder('utf-8', {fatal: true});
+const maxHeaderBytes = 4096;
+const maxBodyBytes = 32 * 1024;
+const maxOutputChunk = 16 * 1024;
+
+export function serveHttpsFixture(flow, bytes, endpoint) {
+ if (flow.replied || flow.pending.byteLength + bytes.byteLength > maxHeaderBytes) {
+ throw new Error('Invalid fixture HTTP request size');
+ }
+ const pending = new Uint8Array(flow.pending.byteLength + bytes.byteLength);
+ pending.set(flow.pending);
+ pending.set(bytes, flow.pending.byteLength);
+ flow.pending = pending;
+ const message = decode.decode(pending);
+ const endOfHeaders = message.indexOf('\r\n\r\n');
+ if (endOfHeaders === -1) return null;
+
+ const [request, ...headers] = message.slice(0, endOfHeaders).split('\r\n');
+ const validRequest = request === 'GET ' + endpoint.path + ' HTTP/1.0'
+ || request === 'GET ' + endpoint.path + ' HTTP/1.1';
+ const hosts = headers.filter(line => /^host:/i.test(line));
+ const validHost = hosts.length === 1 && hosts[0].slice(5).trim().toLowerCase() === endpoint.name;
+ if (!validRequest || !validHost || endOfHeaders + 4 !== message.length) {
+ throw new Error('Request is outside the documented HTTPS fixture');
+ }
+ if (!(endpoint.body instanceof Uint8Array) || endpoint.body.length > maxBodyBytes) {
+ throw new Error('Invalid fixture HTTP response size');
+ }
+ const response = encode.encode(
+ 'HTTP/1.0 200 OK\r\nContent-Type: ' + endpoint.contentType
+ + '\r\nContent-Length: ' + endpoint.body.length + '\r\nConnection: close\r\n\r\n',
+ );
+ const chunks = [response];
+ for (let offset = 0; offset < endpoint.body.length; offset += maxOutputChunk) {
+ chunks.push(endpoint.body.subarray(offset, offset + maxOutputChunk));
+ }
+ flow.replied = true;
+ flow.pending = new Uint8Array();
+ return chunks;
+}
diff --git a/platform/web/vendor/esp32sim/source.json b/platform/web/vendor/esp32sim/source.json
index 2b9596d40..54b30e590 100644
--- a/platform/web/vendor/esp32sim/source.json
+++ b/platform/web/vendor/esp32sim/source.json
@@ -2,14 +2,14 @@
"schema_version": 1,
"repository": "https://github.com/m5agent/esp32sim",
"upstream": "https://github.com/mikroverk/esp32sim",
- "commit": "d1c930adffaa8d94d03856eb0276df17da668002",
+ "commit": "c51955bc06e123b98a371208e12598a0152354ac",
"license": "MIT",
"scope": "WASM worker, pacing and block JIT glue only; no firmware or ROM",
"files": {
"worker.js": {
"source_path": "web/wasm/worker.js",
- "sha256": "715d1dd55eddd89b3f5de36cc8b1b42689fab42f12db958437bdf250c8686925",
- "bytes": 26015
+ "sha256": "052eb060790b8e45188c6fb88d7e211a41fdde56eddd926136adf628477a6d75",
+ "bytes": 30564
},
"jit.mjs": {
"source_path": "web/wasm/jit.mjs",
@@ -40,6 +40,16 @@
"source_path": "web/wasm/review-modbus-tcp.mjs",
"sha256": "1e3bbf557f274ee6f754b2d4954f3563d1a0392fd1a4a988a9f03427dee08298",
"bytes": 3711
+ },
+ "https-app.mjs": {
+ "source_path": "web/wasm/https-app.mjs",
+ "sha256": "03c3627d90cb307286e32c9977fc234ef6fe66ee283695eb882b708428425a9e",
+ "bytes": 1986
+ },
+ "tls-worker-peer.mjs": {
+ "source_path": "web/wasm/tls-worker-peer.mjs",
+ "sha256": "0ed6c183d9a0fb7296859fd13802ae6ac393f80d299d4af80e840f6fee6df8e0",
+ "bytes": 1991
}
}
}
diff --git a/platform/web/vendor/esp32sim/tls-worker-peer.mjs b/platform/web/vendor/esp32sim/tls-worker-peer.mjs
new file mode 100644
index 000000000..80cc9ef04
--- /dev/null
+++ b/platform/web/vendor/esp32sim/tls-worker-peer.mjs
@@ -0,0 +1,55 @@
+// Runs in the dedicated emulator Worker. The NAT relay supplies encrypted
+// bytes for an already admitted endpoint. This module never opens a socket.
+export async function createTlsWorkerPeer(wasmBytes, Go, serverName) {
+ const runtime = new Go();
+ const {instance} = await WebAssembly.instantiate(wasmBytes, runtime.importObject);
+ const initialized = Promise.withResolvers();
+ globalThis.onFixtureTlsReady = initialized.resolve;
+ runtime.run(instance).catch(initialized.reject);
+ await initialized.promise;
+ delete globalThis.onFixtureTlsReady;
+ const der = globalThis.fixtureTlsConfigure(serverName);
+ if (!(der instanceof Uint8Array)) throw new Error('Unable to initialize the fixture certificate');
+ const pem = '-----BEGIN CERTIFICATE-----\n' + btoa(String.fromCharCode(...der))
+ + '\n-----END CERTIFICATE-----\n';
+ const flows = new Set();
+
+ function close(id) {
+ flows.delete(id);
+ globalThis.fixtureTlsClose(id);
+ }
+
+ function open(id, events) {
+ if (flows.has(id)) return false;
+ if (!globalThis.fixtureTlsOpen(id, (kind, value) => {
+ queueMicrotask(() => {
+ if (!flows.has(id)) return;
+ try {
+ if (kind === 'ciphertext') events.ciphertext(value);
+ else if (kind === 'plaintext') events.plaintext(value);
+ else if (kind === 'handshake') events.handshake(value);
+ else {
+ close(id);
+ if (kind === 'closed') events.closed();
+ else events.failed();
+ }
+ } catch {
+ close(id);
+ events.failed();
+ }
+ });
+ })) return false;
+ flows.add(id);
+ return true;
+ }
+
+ return {
+ pem,
+ open,
+ close,
+ closeAll() { for (const id of flows) close(id); },
+ receive(id, data) { return flows.has(id) && globalThis.fixtureTlsFeed(id, data); },
+ reply(id, data) { return flows.has(id) && globalThis.fixtureTlsReply(id, data); },
+ finish(id) { return flows.has(id) && globalThis.fixtureTlsFinish(id); },
+ };
+}
diff --git a/platform/web/vendor/esp32sim/worker.js b/platform/web/vendor/esp32sim/worker.js
index d7a302979..0b613b1bf 100644
--- a/platform/web/vendor/esp32sim/worker.js
+++ b/platform/web/vendor/esp32sim/worker.js
@@ -2,6 +2,8 @@ import { createJitHost } from './jit.mjs';
import { createPacing } from './pacing.mjs';
import { applyExperiments } from './experiments.mjs';
import { serveReviewMqtt } from './review-mqtt.mjs';
+import { createTlsWorkerPeer } from './tls-worker-peer.mjs';
+import { serveHttpsFixture } from './https-app.mjs';
import { makeModbusRequest, newModbusRegisters, readModbusStream, respondToModbus } from './review-modbus-tcp.mjs';
let pacing = createPacing();
// Optional host-stage diagnostics. Run entry is not controller consumption;
@@ -41,6 +43,23 @@ function reviewEndpoint(mode, address) {
|| first === 192 && second === 168)) return null;
return {address,port:8000};
}
+const reviewTlsEndpoints = Object.freeze({
+ 'lan-module': {
+ address:[192,0,2,52], port:443, name:'wttr.in', wired:true,
+ path:'/?format=%22%C,%20%t%22', contentType:'text/plain', body:enc.encode('M5 weather fixture: Clear +19 C'),
+ },
+ 'imageplus-https': {
+ address:[192,0,2,54], port:443, name:'static-cdn.m5stack.com',
+ path:'/resource/public/assets/aboutus/m5logo2022.png', contentType:'image/png',
+ },
+ 'mqtt-over-ssl': {
+ address:[192,0,2,55], port:8883, name:'y90166f4.ala.cn-hangzhou.emqxsl.cn', mqtt:true,
+ },
+ 'https-get': {
+ address:[192,0,2,53], port:443, name:'httpbin.org',
+ path:'/get', contentType:'application/json', body:enc.encode('{"M5 HTTPS":"fixture response","path":"/get"}'),
+ },
+});
const emptyBytes = new Uint8Array();
let reviewTcp = null;
function reviewEvent(kind,id,arg=0,bytes=emptyBytes) {
@@ -89,11 +108,55 @@ function drainReviewTcp() {
reviewTcp.denied++;
reviewEvent(2,id,3);
}else{
- flows.set(id,{pending:emptyBytes,connected:false,subscribed:false});
+ const flow = {pending:emptyBytes,connected:false,subscribed:false,replied:false};
+ const tls = reviewTcp.tlsPeer;
+ if (tls && !tls.open(id, {
+ ciphertext(data) {
+ if (reviewEvent(3,id,0,data) !== data.length) throw new Error('TLS fixture response is full');
+ },
+ plaintext(data) {
+ if (endpoint.mqtt) {
+ const {responses,close} = serveReviewMqtt(flow,data,reviewTcp);
+ for (const chunk of responses) {
+ if (!tls.reply(id,chunk)) throw new Error('MQTT TLS fixture response queue is full');
+ }
+ if (close && !tls.finish(id)) throw new Error('MQTT TLS fixture close queue is full');
+ return;
+ }
+ const response = serveHttpsFixture(flow,data,endpoint);
+ if (!response) return;
+ for (const chunk of response) {
+ if (!tls.reply(id,chunk)) throw new Error('TLS fixture response queue is full');
+ }
+ if (!tls.finish(id)) throw new Error('TLS fixture close queue is full');
+ reviewTcp.exchanges++;
+ },
+ handshake() {
+ reviewTcp.tlsHandshakes++;
+ if (!endpoint.mqtt) reviewTcp.handshakes++;
+ },
+ closed() { flows.delete(id); reviewEvent(4,id); },
+ failed() { flows.delete(id); reviewTcp.denied++; reviewEvent(5,id); },
+ })) {
+ reviewTcp.denied++;
+ reviewEvent(2,id,3);
+ continue;
+ }
+ flows.set(id,flow);
reviewTcp.connects++;
reviewEvent(1,id,4096);
}
}else if(op===2&&flows.has(id)){
+ if (reviewTcp.tlsPeer) {
+ if (reviewTcp.tlsPeer.receive(id,bytes)) reviewEvent(6,id,size);
+ else {
+ reviewTcp.tlsPeer.close(id);
+ flows.delete(id);
+ reviewTcp.denied++;
+ reviewEvent(5,id);
+ }
+ continue;
+ }
if (reviewTcp.mode === 'label-plus') {
try {
const response = respondReviewHttp(flows.get(id), bytes, reviewTcp.httpData);
@@ -168,6 +231,7 @@ function drainReviewTcp() {
}else if(op===3&&flows.has(id)){
reviewEvent(4,id);
}else if(op===4){
+ reviewTcp.tlsPeer?.close(id);
flows.delete(id);
}else if(op===5||op===6){
reviewTcp.denied++;
@@ -421,6 +485,39 @@ onmessage = async (ev) => {
// the Network panel: the station's frames as type-5 messages (a module without the export has none)
else if (m.netmon && wasm.esp32sim_netmon) wasm.esp32sim_netmon(emu);
}
+ else if (m.op === 'review-tls') {
+ let ok = false;
+ let certificate;
+ const mode = m.mode;
+ const preset = Object.hasOwn(reviewTlsEndpoints,mode) ? reviewTlsEndpoints[mode] : null;
+ if (preset && m.wasm instanceof ArrayBuffer && !reviewTcp && !reviewServer && wasm.esp32sim_nat_relay) {
+ try {
+ let endpoint = preset;
+ if (mode === 'imageplus-https') {
+ if (!(m.image instanceof ArrayBuffer) || m.image.byteLength !== 21772) throw new Error('missing ImagePlus fixture PNG');
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256',m.image));
+ const hex = Array.from(digest,byte=>byte.toString(16).padStart(2,'0')).join('');
+ if (hex !== 'af67b4d946924504fafd390099638056ab7e6975f3fc920b20392e85e7114dc0')
+ throw new Error('ImagePlus fixture PNG mismatch');
+ endpoint = {...preset,body:new Uint8Array(m.image)};
+ }
+ if (!endpoint.wired && withBytes(enc.encode('ssid=M5ExampleNet'),(p,n)=>wasm.esp32sim_wifi(emu,p,n)) !== 0)
+ throw new Error('restricted TLS Wi-Fi configuration is unavailable');
+ if (wasm.esp32sim_nat_relay(emu,3) !== 0) throw new Error('restricted TLS relay is unavailable');
+ await import('../../../runtime/workbench-tls/wasm_exec.js');
+ const tlsPeer = await createTlsWorkerPeer(m.wasm,globalThis.Go,endpoint.name);
+ reviewTcp = {
+ mode, endpoint, tlsPeer, flows:new Map(),
+ connects:0, exchanges:0, denied:0, handshakes:0, tlsHandshakes:0, subscriptions:0, last:null,
+ };
+ if (endpoint.mqtt) certificate = tlsPeer.pem;
+ ok = true;
+ } catch (error) {
+ setupError ||= String(error);
+ }
+ }
+ postMessage({text:JSON.stringify({t:'review-tls-ready',ok,certificate})});
+ }
else if (m.op === 'review-tcp') {
const mode=m.mode||'tcp-client';
const endpoint=reviewEndpoint(mode,m.address);
@@ -441,7 +538,7 @@ onmessage = async (ev) => {
}
else if (m.op === 'review-tcp-state') {
const value=reviewTcp&&{connects:reviewTcp.connects,exchanges:reviewTcp.exchanges,
- handshakes:reviewTcp.handshakes,subscriptions:reviewTcp.subscriptions,denied:reviewTcp.denied,last:reviewTcp.last};
+ handshakes:reviewTcp.handshakes,tlsHandshakes:reviewTcp.tlsHandshakes,subscriptions:reviewTcp.subscriptions,denied:reviewTcp.denied,last:reviewTcp.last};
postMessage({text:JSON.stringify({t:'review-tcp-state',value})});
}
else if (m.op === 'wifi-station') {