Skip to content

Core ​

Legacy v1 docs

v1 is on security fixes only. See v2 docs for the current release.

Core is the base class for all v1 devices. You always subclass it — never instantiate it directly.

typescript
import { Core, Devices } from "webserial-core";

class MyDevice extends Core {
  constructor() {
    super({ baudRate: 9600 });
    this.__internal__.device.type = "my-device";
    Devices.registerType("my-device");
    Devices.add(this);
    this.getResponseAsString();
  }

  serialSetConnectionConstant() {
    return this.add0x(this.parseStringToBytes("CONNECT"));
  }

  serialMessage(code) {
    this.dispatch("serial:message", { code });
  }
}

Constructor ​

typescript
new Core(options?: CoreConstructorParams)
ParameterTypeDefaultDescription
filtersSerialPortFilter[] | nullnullFilters passed to navigator.serial.requestPort()
config_portSerialOptions{ baudRate: 9600, dataBits: 8, stopBits: 1, parity: "none", bufferSize: 32768, flowControl: "none" }Serial port configuration
no_devicenumber1Device instance number (used by the registry)
device_listen_on_channelnumber | string1Channel/port number passed to serialSetConnectionConstant
bypassSerialBytesConnectionbooleanfalseSkip automatic connection-byte sending
socketbooleanfalseUse Socket.io bridge instead of direct Web Serial
transformStreamfalse | TransformStreamfalseCustom transform stream to inject into the read pipeline

Methods to implement in subclass ​

serialSetConnectionConstant(listenOnPort?) ​

Called automatically during connection. Must return the bytes to send for device handshake.

typescript
serialSetConnectionConstant(listenOnPort = 1): string | Uint8Array | string[] | number[] | null

Example

javascript
serialSetConnectionConstant() {
  return this.add0x(this.parseStringToBytes("CONNECT"));
}

serialMessage(code) ​

Called for every message received from the device. Parse and dispatch events here.

typescript
serialMessage(code: string | Uint8Array | string[] | ArrayBuffer): void

Example

javascript
serialMessage(codex) {
  if (codex === "connected") {
    this.dispatch("serial:message", { name: "connected", no_code: 100 });
  }
}

serialCorruptMessage(code) (optional) ​

Called when a received message fails validation. Override to handle corrupt responses.

typescript
serialCorruptMessage(code: Uint8Array | string[] | string | null): void

Connection methods ​

connect() ​

Opens the system port picker (if no port is already saved) and establishes the serial connection.

typescript
connect(): Promise<boolean>

Returns true when connected.


disconnect(detail?) ​

Closes the serial port and emits serial:disconnected.

typescript
disconnect(detail?: object | null): Promise<void>

serialConnect() ​

Low-level connect (no port picker). Reopens a previously granted port.

typescript
serialConnect(): Promise<void>

serialDisconnect() ​

Low-level close of the serial port streams.

typescript
serialDisconnect(): Promise<void>

serialForget() ​

Calls port.forget() to revoke the browser permission for the saved port.

typescript
serialForget(): Promise<boolean>

Queue methods ​

appendToQueue(arr, action) ​

Enqueues bytes to be written to the device. Sends internal:queue to process the next item.

typescript
appendToQueue(
  arr: string | Uint8Array | string[] | number[],
  action: string
): Promise<void>

sendConnect() ​

Sends the connection-constant bytes through the queue.

typescript
sendConnect(): Promise<void>

sendCustomCode({ code }) ​

Enqueues arbitrary bytes with action "custom".

typescript
sendCustomCode({ code }: { code: string | Uint8Array | string[] | number[] }): Promise<void>

clearSerialQueue() ​

Empties the command queue immediately.

typescript
clearSerialQueue(): void

softReload() ​

Clears the last error state and emits serial:soft-reload.

typescript
softReload(): void

Response format helpers ​

Call exactly one of these in your constructor:

javascript
this.getResponseAsUint8Array(); // default — Uint8Array
this.getResponseAsString(); // decoded string (TextDecoder)
this.getResponseAsArrayHex(); // string[] of hex values
this.getResponseAsArrayBuffer(); // ArrayBuffer

Properties ​

State ​

PropertyTypeDescription
isConnectedbooleantrue when the port is open and readable/writable
isConnectingbooleantrue while the connection handshake is in progress
isDisconnectedbooleantrue when not connected
lastActionstring | nullThe action string of the last queued command

Identity ​

PropertyTypeDescription
uuidstringAuto-generated crypto.randomUUID()
typeDevicestringDevice type string (e.g. "arduino")
deviceNumbernumberInstance number set via no_device in the constructor

Queue ​

PropertyTypeDescription
queueQueueData[]Current pending items in the send queue

Port configuration ​

PropertyTypeDescription
serialFiltersSerialPortFilter[]Get/set port filters (throws if connected)
serialConfigPortSerialOptionsGet/set port options (throws if connected)
portPathstring | nullCOM/tty path hint for socket mode
portVendorIdstring | number | nullUSB vendor ID hint for socket mode
portProductIdstring | number | nullUSB product ID hint for socket mode
useRTSCTSbooleanEnable RTS/CTS hardware flow control

Response parsing ​

PropertyTypeDescription
fixedBytesMessagenumber | nullExpect exactly N bytes per message; null = variable
timeoutBeforeResponseBytesnumberInter-byte silence (ms) before declaring a response complete. Default 50
responseDelimitedbooleanUse responseLimiter to split messages
responseLimiterstring | RegExp | nullDelimiter for message boundaries
responsePrefixLimitedbooleanLimiter appears at the start of each message
responseSufixLimitedbooleanLimiter appears at the end of each message (default true)
bypassSerialBytesConnectionbooleanSkip connection-byte dispatch
connectionBytesUint8ArrayRead-only computed connection bytes

Socket mode ​

PropertyTypeDescription
useSocketbooleanWhether socket mode is active
socketPortParser"byte-length" | "inter-byte-timeout"Parser type for the socket bridge
socketPortParserIntervalnumberInter-byte timeout (ms) for socket parser
socketPortParserLengthnumberFixed byte length for socket parser
configDeviceSocketobjectFull config object sent to the socket bridge

Byte-conversion utilities ​

typescript
parseStringToBytes(string: string, end?: string): string[]
parseStringToTextEncoder(string: string, end?: string): Uint8Array
parseUint8ToHex(array: Uint8Array): string[]
parseHexToUint8(array: string[]): Uint8Array
stringArrayToUint8Array(strings: string[]): Uint8Array
parseUint8ArrayToString(array: Uint8Array | string[]): string
stringToArrayHex(string: string): string[]
stringToArrayBuffer(string: string, end?: string): ArrayBufferLike
hexToAscii(hex: string | number): string
asciiToHex(asciiString: string): string
decToHex(dec: number | string): string
hexToDec(hex: string): number
hexMaker(val?: string, min?: number): string
add0x(bytes: string[]): string[]
bytesToHex(bytes: string[]): string[]
sumHex(arr: string[]): string
validateBytes(data: string | Uint8Array | string[] | number[]): Uint8Array

Released under the MIT License.