migrate to typescript

This commit is contained in:
2023-07-07 12:24:23 +02:00
parent e6df93b7ea
commit d63cf541fb
19 changed files with 132 additions and 176 deletions

View File

@@ -1,19 +1,26 @@
import {writable} from "svelte/store"
import {CharaDevice} from "$lib/serial/device.js"
import {CharaDevice} from "$lib/serial/device"
/** @type {import('svelte/store').Writable<import('./device.js').CharaDevice>} */
export const serialPort = writable()
export const serialPort = writable<CharaDevice>()
/** @type {import('svelte/store').Writable<Array<{type: 'input' | 'output' | 'system'; value: string}>>} */
export const serialLog = writable([])
export interface SerialLogEntry {
type: "input" | "output" | "system"
value: string
}
/** @type {import('svelte/store').Writable<Array<{actions: number[]; phrase: string}>>} */
export const chords = writable([])
export const serialLog = writable<SerialLogEntry[]>([])
/** @type {import('svelte/store').Writable<[number[], number[], number[]]>} */
export const layout = writable([[], [], []])
export interface Chord {
actions: number[]
phrase: string
}
export const chords = writable<Chord[]>([])
export type CharaLayout = [number[], number[], number[]]
export const layout = writable<CharaLayout>([[], [], []])
/** @type {import('svelte/store').Writable<boolean>} */
export const syncing = writable(false)
/** @type {CharaDevice} */
@@ -24,7 +31,7 @@ export async function initSerial() {
device ??= new CharaDevice()
serialPort.set(device)
const parsedLayout = [[], [], []]
const parsedLayout: CharaLayout = [[], [], []]
for (let layer = 1; layer <= 3; layer++) {
for (let i = 0; i < 90; i++) {
parsedLayout[layer - 1][i] = await device.getLayoutKey(layer, i)

View File

@@ -1,5 +1,6 @@
import {LineBreakTransformer} from "$lib/serial/line-break-transformer.js"
import {serialLog} from "$lib/serial/connection.js"
import {LineBreakTransformer} from "$lib/serial/line-break-transformer"
import {serialLog} from "$lib/serial/connection"
import type {Chord} from "$lib/serial/connection"
export const VENDOR_ID = 0x239a
@@ -11,29 +12,22 @@ export async function hasSerialPermission() {
}
export class CharaDevice {
/** @type {Promise<SerialPort>} */
#port
/** @type {Promise<ReadableStreamDefaultReader<string>>} */
#reader
private readonly port: Promise<SerialPort>
private readonly reader: Promise<ReadableStreamDefaultReader<string>>
#encoder = new TextEncoder()
private readonly abortController1 = new AbortController()
private readonly abortController2 = new AbortController()
#abortController1 = new AbortController()
#abortController2 = new AbortController()
private lock?: Promise<true>
/** @type {Promise<true> | undefined} */
#lock
/** @type {Promise<string>} */
version
/** @type {Promise<string>} */
deviceId
version: Promise<string>
deviceId: Promise<string>
/**
* @param baudRate
*/
constructor(baudRate = 115200) {
this.#port = navigator.serial.getPorts().then(async ports => {
this.port = navigator.serial.getPorts().then(async ports => {
const port =
ports.find(it => it.getInfo().usbVendorId === VENDOR_ID) ??
(await navigator.serial.requestPort({filters: [{usbVendorId: VENDOR_ID}]}))
@@ -42,7 +36,7 @@ export class CharaDevice {
serialLog.update(it => {
it.push({
type: "system",
value: `Connected; ID: 0x${info.usbProductId.toString(16)}; Vendor: 0x${info.usbVendorId.toString(
value: `Connected; ID: 0x${info.usbProductId?.toString(16)}; Vendor: 0x${info.usbVendorId?.toString(
16,
)}`,
})
@@ -50,29 +44,27 @@ export class CharaDevice {
})
return port
})
this.#reader = this.#port.then(async port => {
this.reader = this.port.then(async port => {
const decoderStream = new TextDecoderStream()
void port.readable.pipeTo(decoderStream.writable, {signal: this.#abortController1.signal})
void port.readable!.pipeTo(decoderStream.writable, {signal: this.abortController1.signal})
return decoderStream.readable
.pipeThrough(new TransformStream(new LineBreakTransformer()), {signal: this.#abortController2.signal})
return decoderStream
.readable!.pipeThrough(new TransformStream(new LineBreakTransformer()), {
signal: this.abortController2.signal,
})
.getReader()
})
this.#lock = this.#reader.then(() => {
this.#lock = undefined
this.lock = this.reader.then(() => {
delete this.lock
return true
})
this.version = this.send("VERSION")
this.deviceId = this.send("ID")
}
/**
* @returns {Promise<string>}
*/
async #read() {
return this.#reader.then(async it => {
/** @type {string} */
const result = await it.read().then(({value}) => value)
private async internalRead() {
return this.reader.then(async it => {
const result: string = await it.read().then(({value}) => value!)
serialLog.update(it => {
it.push({
type: "output",
@@ -86,12 +78,10 @@ export class CharaDevice {
/**
* Send a command to the device
* @param command {string}
* @returns {Promise<void>}
*/
async #send(...command) {
const port = await this.#port
const writer = port.writable.getWriter()
private async internalSend(...command: string[]) {
const port = await this.port
const writer = port.writable!.getWriter()
try {
serialLog.update(it => {
it.push({
@@ -108,35 +98,32 @@ export class CharaDevice {
/**
* Read/write to serial port
* @template T
* @param callback {(send: (...commands: string) => Promise<void>, read: () => Promise<string>) => T | Promise<T>}
* @returns Promise<T>
*/
async runWith(callback) {
while (this.#lock) {
await this.#lock
async runWith<T>(
callback: (send: typeof this.internalSend, read: typeof this.internalRead) => T | Promise<T>,
): Promise<T> {
while (this.lock) {
await this.lock
}
const send = this.#send.bind(this)
const read = this.#read.bind(this)
const exec = new Promise(async resolve => {
let result
const send = this.internalSend.bind(this)
const read = this.internalRead.bind(this)
const exec = new Promise<T>(async resolve => {
let result!: T
try {
result = await callback(send, read)
} finally {
this.#lock = undefined
this.lock = undefined
resolve(result)
}
})
this.#lock = exec.then(() => true)
this.lock = exec.then(() => true)
return exec
}
/**
* Send to serial port
* @param command {string}
* @returns Promise<string>
*/
async send(...command) {
async send(...command: string[]) {
return this.runWith(async (send, read) => {
await send(...command)
const commandString = command.join(" ").replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
@@ -144,20 +131,13 @@ export class CharaDevice {
})
}
/**
* @returns {Promise<number>}
*/
async getChordCount() {
async getChordCount(): Promise<number> {
return Number.parseInt(await this.send("CML C0"))
}
/**
* @param index {number}
* @returns {Promise<{actions: number[]; phrase: string, unk: number}>}
*/
async getChord(index) {
async getChord(index: number): Promise<Chord> {
const chord = await this.send(`CML C1 ${index}`)
const [keys, rawPhrase, b] = chord.split(" ")
const [keys, rawPhrase] = chord.split(" ")
let phrase = []
for (let i = 0; i < rawPhrase.length; i += 2) {
phrase.push(Number.parseInt(rawPhrase.substring(i, i + 2), 16))
@@ -175,16 +155,10 @@ export class CharaDevice {
return {
actions,
phrase: String.fromCodePoint(...phrase),
unk: Number(b),
}
}
/**
* @param layer {number}
* @param id {number}
* @returns {Promise<number>}
*/
async getLayoutKey(layer, id) {
async getLayoutKey(layer: number, id: number) {
const layout = await this.send(`VAR B3 A${layer} ${id}`)
const [position] = layout.split(" ").map(Number)
return position

View File

@@ -1,17 +0,0 @@
import keymapCodes from "$lib/assets/keymap_codes.json"
import keySymbols from "$lib/assets/key-symbols.json"
/** @type {Record<number, import('./keymap.js').KeyInfo>} */
export const KEYMAP_CODES = Object.fromEntries(
keymapCodes.map(([code, charset, id, title, description]) => [
code,
{
code: Number(code),
title: title || undefined,
charset: charset || undefined,
id: id || undefined,
symbol: id ? keySymbols[id] || undefined : undefined,
description: description || undefined,
},
]),
)

View File

@@ -1,3 +1,6 @@
import keymapCodes from "$lib/assets/keymap_codes.json"
import keySymbols from "$lib/assets/key-symbols.json"
export interface KeyInfo {
/**
* Numeric action code
@@ -45,3 +48,17 @@ export type CharsetCategory =
| "Keybard"
| "CharaChorder"
| "CharaChorder One"
export const KEYMAP_CODES: Record<number, KeyInfo> = Object.fromEntries(
keymapCodes.map(([code, charset, id, title, description]) => [
code,
{
code: Number(code),
title: title || undefined,
charset: (charset || undefined) as CharsetCategory,
id: id || undefined,
symbol: id ? keySymbols[id as keyof typeof keySymbols] || undefined : undefined,
description: description || undefined,
},
]),
)

View File

@@ -1,21 +1,18 @@
// @ts-check
export class LineBreakTransformer {
constructor() {
this.chunks = ""
}
private chunks = ""
// noinspection JSUnusedGlobalSymbols
transform(chunk, controller) {
transform(chunk: string, controller: TransformStreamDefaultController) {
this.chunks += chunk
const lines = this.chunks.split("\r\n")
this.chunks = lines.pop()
this.chunks = lines.pop()!
for (const line of lines) {
controller.enqueue(line)
}
}
// noinspection JSUnusedGlobalSymbols
flush(controller) {
flush(controller: TransformStreamDefaultController) {
controller.enqueue(this.chunks)
}
}