Skip to content

Commit

Permalink
implement reading from a serial port
Browse files Browse the repository at this point in the history
  • Loading branch information
CrowdHailer committed Oct 22, 2023
1 parent 58e6685 commit ae18256
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/plinth/browser/serial.gleam
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import gleam/javascript/array.{Array}
import gleam/javascript/promise.{Promise}
pub type SerialPort

// https://developer.mozilla.org/en-US/docs/Web/API/Serial/requestPort
@external(javascript, "../../serial_ffi.mjs", "requestPort")
pub fn request_port() -> Promise(Result(SerialPort, Nil))

// https://developer.mozilla.org/en-US/docs/Web/API/Serial/getPorts
@external(javascript, "../../serial_ffi.mjs", "getPorts")
pub fn get_ports() -> Promise(Result(List(SerialPort), Nil))

// https://developer.mozilla.org/en-US/docs/Web/API/SerialPort/getInfo
@external(javascript, "../../serial_ffi.mjs", "getInfo")
pub fn get_info(port: SerialPort) -> Result(#(Int, Int), Nil)

// https://developer.mozilla.org/en-US/docs/Web/API/SerialPort/open
@external(javascript, "../../serial_ffi.mjs", "open")
pub fn open(port: SerialPort, baud_rate: Int) -> Promise(Result(Nil, Nil))

// https://developer.mozilla.org/en-US/docs/Web/API/SerialPort#reading_data_from_a_port
@external(javascript, "../../serial_ffi.mjs", "read")
pub fn read(port: SerialPort, callback: fn(BitString) -> Nil) -> Promise(Result(Nil, Nil))
63 changes: 63 additions & 0 deletions src/serial_ffi.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { Ok, Error, BitString } from "./gleam.mjs";

export async function requestPort() {
try {
const port = await globalThis.navigator.serial.requestPort({ filters: [] });
return new Ok(port);
} catch (error) {
console.warn(error);
return new Error();
}
}

export async function getPorts() {
try {
const ports = await globalThis.navigator.serial.getPorts();
return new Ok(ports);
} catch (error) {
console.warn(error);
return new Error();
}
}

export function getInfo(port) {
try {
const { usbVendorId, usbProductId } = port.getInfo();
return new Ok([usbVendorId, usbProductId]);
} catch (error) {
console.warn(error);
return new Error();
}
}

export async function open(port, baudRate) {
try {
await port.open({ baudRate });
return new Ok();
} catch (error) {
console.warn(error);
return new Error();
}
}

export async function read(port, callback) {
while (port.readable) {
const reader = port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
// |reader| has been canceled.
break;
}
callback(new BitString(value));
// Do something with |value|…
}
return new Ok();
} catch (error) {
return new Error();
} finally {
reader.releaseLock();
}
}
}

0 comments on commit ae18256

Please sign in to comment.