Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support multiple named serial connections, change default baudrate #551

Merged
merged 1 commit into from
Nov 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions packages/serial/serial.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@ This program is free software: you can redistribute it and/or modify it under th

import { Pattern, isPattern } from '@strudel.cycles/core';

var writeMessage;
var writeMessagers = {};
var choosing = false;

export async function getWriter(br = 38400) {
export async function getWriter(name, br) {
if (choosing) {
return;
}
choosing = true;
if (writeMessage) {
return writeMessage;
if (name in writeMessagers) {
return writeMessagers[name];
}
if ('serial' in navigator) {
const port = await navigator.serial.requestPort();
await port.open({ baudRate: br });
const encoder = new TextEncoder();
const writer = port.writable.getWriter();
writeMessage = function (message, chk) {
writeMessagers[name] = function (message, chk) {
const encoded = encoder.encode(message);
if (!chk) {
writer.write(encoded);
Expand Down Expand Up @@ -63,10 +63,10 @@ function crc16(data) {
return crc & 0xffff;
}

Pattern.prototype.serial = function (br = 38400, sendcrc = false, singlecharids = false) {
Pattern.prototype.serial = function (br = 115200, sendcrc = false, singlecharids = false, name = 'default') {
return this.withHap((hap) => {
if (!writeMessage) {
getWriter(br);
if (!(name in writeMessagers)) {
getWriter(name, br);
}
const onTrigger = (time, hap, currentTime) => {
var message = '';
Expand Down Expand Up @@ -108,7 +108,7 @@ Pattern.prototype.serial = function (br = 38400, sendcrc = false, singlecharids
const offset = (time - currentTime + latency) * 1000;

window.setTimeout(function () {
writeMessage(message, chk);
writeMessagers[name](message, chk);
}, offset);
};
return hap.setContext({ ...hap.context, onTrigger, dominantTrigger: true });
Expand Down