Skip to content

Commit

Permalink
Fix ws reception in browser
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-rabault committed Feb 20, 2024
1 parent 8b4f88a commit 9dc740b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 20 deletions.
12 changes: 4 additions & 8 deletions examples/projects/browser/led/src/main.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import program from '../.pio/build/browser/program.mjs';
import program from "../.pio/build/browser/program.mjs";

program()
.then(({ Luos_Init, Led_Init, Luos_Loop, Led_Loop, Ws_Init, Ws_Loop }) => {
Expand All @@ -12,15 +12,11 @@ program()
Led_Loop();
};

return new Promise(() =>
typeof window !== 'undefined'
? requestAnimationFrame(mainLoop)
: setInterval(mainLoop, 0),
);
return new Promise(() => setInterval(mainLoop, 10));
})
.catch((err) => {
console.error('Error', err);
if (typeof window === 'undefined') {
console.error("Error", err);
if (typeof window === "undefined") {
process.exit(-1);
}
});
26 changes: 14 additions & 12 deletions network/ws_network/HAL/BROWSER/ws_hal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ void WsHAL_ReceptionWeb(const std::vector<uint8_t> &data)
clientWebsocket->send(arrayBufferView);
}

[[cheerp::genericjs]] void WsHAL_AddWsEventHandlers() {
[[cheerp::genericjs]] void WsHAL_AddWsEventHandlers()
{
clientWebsocket = new WebSocket(s_url);
clientWebsocket->set_binaryType("arraybuffer");
clientWebsocket->addEventListener(
"open",
cheerp::Callback(openEventCallback));
Expand All @@ -81,31 +83,31 @@ void WsHAL_ReceptionWeb(const std::vector<uint8_t> &data)
cheerp::Callback(errorEventCallback));
clientWebsocket->addEventListener(
"message",
cheerp::Callback([](MessageEvent *e) {
auto *dataArray = (Uint8Array *)e->get_data();
cheerp::Callback([](MessageEvent *e)
{
auto *dataBuffer = (ArrayBuffer *)e->get_data();
auto *dataArray = new Uint8Array(dataBuffer);
std::vector<uint8_t> wasmData(dataArray->get_length());
Uint8Array *wasmDataArray = cheerp::MakeTypedArray(wasmData.data(), wasmData.size());
wasmDataArray->set(dataArray);
WsHAL_ReceptionWeb(wasmData);
}));
WsHAL_ReceptionWeb(wasmData); }));
}

[[cheerp::genericjs]] void WsHAL_InitWeb()
{
bool isBrowser;
__asm__("typeof %1 !== 'undefined'" : "=r"(isBrowser) : "r"(&client::window));
if (isBrowser) {
if (isBrowser)
{
WsHAL_AddWsEventHandlers();
}
else
{
client::import("ws")
->then(cheerp::Callback([](client::Object *lib) {
__asm__("globalThis.WebSocket=%0.WebSocket" ::"r"(lib));
}))
->then(cheerp::Callback([]() {
WsHAL_AddWsEventHandlers();
}));
->then(cheerp::Callback([](client::Object *lib)
{ __asm__("globalThis.WebSocket=%0.WebSocket" ::"r"(lib)); }))
->then(cheerp::Callback([]()
{ WsHAL_AddWsEventHandlers(); }));
}
}

Expand Down

0 comments on commit 9dc740b

Please sign in to comment.