Skip to content

Commit c27e8d1

Browse files
committed
review fixes
1 parent 5c7c22c commit c27e8d1

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

src/js/protocols/CapacitorSocket.js

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,14 @@ function base64ToUint8Array(b64) {
55
const len = binary.length;
66
const bytes = new Uint8Array(len);
77
for (let i = 0; i < len; i++) {
8-
bytes[i] = binary.codePointAt(i); // was using charCodeAt
8+
// The atob() function returns a binary string where each character represents a single byte (0–255).
9+
// codePointAt() is designed for Unicode code points and can return values greater than 255, which will overflow Uint8Array slots and corrupt received data.
10+
// Use charCodeAt(i) to safely extract byte values.
11+
bytes[i] = binary.charCodeAt(i);
912
}
1013
return bytes;
1114
}
1215

13-
async function blob2uint(blob) {
14-
const buffer = await new Response(blob).arrayBuffer();
15-
return new Uint8Array(buffer);
16-
}
17-
1816
class CapacitorSocket extends EventTarget {
1917
constructor() {
2018
super();
@@ -37,12 +35,14 @@ class CapacitorSocket extends EventTarget {
3735

3836
Capacitor.Plugins.BetaflightTcp.addListener("dataReceived", (ev) => {
3937
const bytes = base64ToUint8Array(ev.data);
38+
this.handleReceiveBytes({ detail: bytes });
4039
// Forward raw bytes as detail; Serial/port_usage consume TypedArray.byteLength.
4140
this.dispatchEvent(new CustomEvent("receive", { detail: bytes }));
4241
});
4342

4443
Capacitor.Plugins.BetaflightTcp.addListener("dataReceivedError", (ev) => {
4544
console.warn("TCP read error:", ev.error);
45+
this.handleDisconnect();
4646
});
4747

4848
Capacitor.Plugins.BetaflightTcp.addListener("connectionClosed", () => {
@@ -97,7 +97,7 @@ class CapacitorSocket extends EventTarget {
9797

9898
const url = new URL(path);
9999
const host = url.hostname;
100-
const port = parseInt(url.port, 10);
100+
const port = Number.parseInt(url.port, 10);
101101

102102
console.log(`${this.logHead} Connecting to ${path}`);
103103

@@ -124,18 +124,21 @@ class CapacitorSocket extends EventTarget {
124124
this.connected = !res.success ? this.connected : false;
125125
}
126126
*/
127-
this.connected = false;
128-
this.bytesReceived = 0;
129-
this.bytesSent = 0;
130127

131128
if (this.connected) {
132129
try {
133130
const res = await Capacitor.Plugins.BetaflightTcp.disconnect();
134-
this.connected = !res.success ? this.connected : false;
131+
if (res.success) {
132+
this.connected = false;
133+
}
135134
} catch (e) {
136135
console.error(`${this.logHead}Failed to close socket: ${e}`);
137136
}
138137
}
138+
139+
this.connected = false;
140+
this.bytesReceived = 0;
141+
this.bytesSent = 0;
139142
}
140143

141144
async send(data, cb) {

0 commit comments

Comments
 (0)