jevstrudel.git / packages / serial / serial.mjs
1/*
2serial.mjs - <short description TODO>
3Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/serial/serial.mjs>
4This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <https://www.gnu.org/licenses/>.
5*/
6
7import { Pattern, isPattern } from '@strudel/core';
8
9var writeMessagers = {};
10var choosing = false;
11
12export async function getWriter(name, br) {
13  if (choosing) {
14    return;
15  }
16  choosing = true;
17  if (name in writeMessagers) {
18    return writeMessagers[name];
19  }
20  if ('serial' in navigator) {
21    const port = await navigator.serial.requestPort();
22    await port.open({ baudRate: br });
23    const encoder = new TextEncoder();
24    const writer = port.writable.getWriter();
25    writeMessagers[name] = function (message, chk) {
26      const encoded = encoder.encode(message);
27      if (!chk) {
28        writer.write(encoded);
29      } else {
30        const bytes = new Uint8Array(4);
31        bytes[0] = 124; // | symbol
32        bytes[1] = (chk >> 8) & 0xff;
33        bytes[2] = chk & 0xff;
34        bytes[3] = 59; // semicolon
35        const withchk = new Uint8Array(encoded.length + 4);
36        withchk.set(encoded);
37        withchk.set(bytes, encoded.length);
38        writer.write(withchk);
39      }
40    };
41  } else {
42    throw 'Webserial is not available in this browser.';
43  }
44}
45
46const latency = 0.1;
47
48// crc16 (CCITT-FALSE) https://gist.github.com/tijnkooijmans/10981093
49function crc16(data) {
50  const length = data.length;
51  if (length == 0) {
52    return 0;
53  }
54
55  var crc = 0xffff;
56  for (var i = 0; i < length; ++i) {
57    crc ^= data.charCodeAt(i) << 8;
58    for (var j = 0; j < 8; ++j) {
59      crc = (crc & 0x8000) > 0 ? (crc << 1) ^ 0x1021 : crc << 1;
60    }
61  }
62
63  return crc & 0xffff;
64}
65
66Pattern.prototype.serial = function (br = 115200, sendcrc = false, singlecharids = false, name = 'default') {
67  return this.withHap((hap) => {
68    if (!(name in writeMessagers)) {
69      getWriter(name, br);
70    }
71    const onTrigger = (hap, currentTime, _cps, targetTime) => {
72      var message = '';
73      var chk = 0;
74      if (typeof hap.value === 'object') {
75        if ('action' in hap.value) {
76          var action = hap.value['action'];
77          if (singlecharids) {
78            action = action.charAt(0);
79          }
80          message += action + '(';
81          var first = true;
82          for (var [key, val] of Object.entries(hap.value)) {
83            if (key === 'action') {
84              continue;
85            }
86            if (first) {
87              first = false;
88            } else {
89              message += ',';
90            }
91            if (singlecharids) {
92              key = key.charAt(0);
93            }
94            message += key + ':' + val;
95          }
96          message += ')';
97          if (sendcrc) {
98            chk = crc16(message);
99          }
100        } else {
101          for (const [key, val] of Object.entries(hap.value)) {
102            message += `${key}:${val}`;
103          }
104        }
105      } else {
106        message = hap.value;
107      }
108      const offset = (targetTime - currentTime + latency) * 1000;
109
110      window.setTimeout(function () {
111        writeMessagers[name](message, chk);
112      }, offset);
113    };
114    return hap.setContext({ ...hap.context, onTrigger, dominantTrigger: true });
115  });
116};