From 01d3fce58b62105375c1fc39ffc357d9e8d4ee53 Mon Sep 17 00:00:00 2001 From: Benjamin Christau Date: Mon, 19 Feb 2024 16:18:58 +0100 Subject: [PATCH] Move WS lib import into ws_hal --- engine/HAL/BROWSER/hal_script.py | 2 +- examples/projects/browser/led/src/main.mjs | 4 --- network/ws_network/HAL/BROWSER/ws_hal.cpp | 29 +++++++++++++++++++--- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/engine/HAL/BROWSER/hal_script.py b/engine/HAL/BROWSER/hal_script.py index 33a72a673..75d01550f 100644 --- a/engine/HAL/BROWSER/hal_script.py +++ b/engine/HAL/BROWSER/hal_script.py @@ -48,4 +48,4 @@ RANLIB=cheerp_bin_path + "/llvm-ar s") # Replace the output filename with the appropriate extension - e.Replace(PROGNAME="program.js") + e.Replace(PROGNAME="program.mjs") diff --git a/examples/projects/browser/led/src/main.mjs b/examples/projects/browser/led/src/main.mjs index fc86db7e2..8aadc17e5 100644 --- a/examples/projects/browser/led/src/main.mjs +++ b/examples/projects/browser/led/src/main.mjs @@ -1,9 +1,5 @@ import program from '../.pio/build/browser/program.mjs'; -if (globalThis.WebSocket === undefined) { - globalThis.WebSocket = await import('ws').then((mod) => mod.WebSocket); -} - program() .then(({ Luos_Init, Led_Init, Luos_Loop, Led_Loop, Ws_Init, Ws_Loop }) => { Luos_Init(); diff --git a/network/ws_network/HAL/BROWSER/ws_hal.cpp b/network/ws_network/HAL/BROWSER/ws_hal.cpp index a83411bf3..b8af396a4 100644 --- a/network/ws_network/HAL/BROWSER/ws_hal.cpp +++ b/network/ws_network/HAL/BROWSER/ws_hal.cpp @@ -21,6 +21,11 @@ extern "C" using namespace client; +namespace [[cheerp::genericjs]] client +{ + Promise *import(const String &path); +} + /******************************************************************************* * Definitions ******************************************************************************/ @@ -63,9 +68,7 @@ void WsHAL_ReceptionWeb(const std::vector &data) clientWebsocket->send(arrayBufferView); } - -[[cheerp::genericjs]] void WsHAL_InitWeb() -{ +[[cheerp::genericjs]] void WsHAL_AddWsEventHandlers() { clientWebsocket = new WebSocket(s_url); clientWebsocket->addEventListener( "open", @@ -87,6 +90,26 @@ void WsHAL_ReceptionWeb(const std::vector &data) })); } +[[cheerp::genericjs]] void WsHAL_InitWeb() +{ + bool isBrowser; + __asm__("typeof %1 !== 'undefined'" : "=r"(isBrowser) : "r"(&client::window)); + if (isBrowser) { + clientWebsocket = new WebSocket(s_url); + WsHAL_AddWsEventHandlers(); + } + else + { + client::import("ws") + ->then(cheerp::Callback([](client::Object *lib) { + __asm__("globalThis.WebSocket=%0.WebSocket" ::"r"(lib)); + })) + ->then(cheerp::Callback([]() { + WsHAL_AddWsEventHandlers(); + })); + } +} + /////////////////////////Luos Library Needed function/////////////////////////// /******************************************************************************