messages.ts (1298B)
1 import { err_msg, type ResolveErrorMsg } from "@radroots/utils"; 2 import { BLE_ERROR, type BleErrorMessage } from "./error.js"; 3 import type { BleMessageEncoding, BleMessageInput } from "./types.js"; 4 5 export const ble_message_bytes = (value: BleMessageInput): ResolveErrorMsg<Uint8Array, BleErrorMessage> => { 6 if (typeof value === "string") { 7 if (typeof TextEncoder === "undefined") return err_msg(BLE_ERROR.invalid_message); 8 return new TextEncoder().encode(value); 9 } 10 if (value instanceof ArrayBuffer) return new Uint8Array(value); 11 if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); 12 return err_msg(BLE_ERROR.invalid_message); 13 }; 14 15 export const ble_message_buffer_source = (bytes: Uint8Array): ArrayBufferView<ArrayBuffer> => { 16 if (bytes.buffer instanceof ArrayBuffer) return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); 17 const copy = new Uint8Array(bytes.byteLength); 18 copy.set(bytes); 19 return copy; 20 }; 21 22 export const ble_message_text = (bytes: Uint8Array, encoding: BleMessageEncoding = "utf-8"): string | undefined => { 23 if (typeof TextDecoder === "undefined") return; 24 try { 25 return new TextDecoder(encoding).decode(bytes); 26 } catch { 27 return; 28 } 29 };