Skip to content

Commit

Permalink
Merge pull request #58 from poporonnet/fix/56-lint-error
Browse files Browse the repository at this point in the history
fix: lintのエラー対応
  • Loading branch information
tufusa authored May 20, 2024
2 parents df015d3 + 4190c39 commit d010ac4
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 88 deletions.
63 changes: 28 additions & 35 deletions src/libs/mrubyWriterConnector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { Result, Success, Failure } from "./result";
export const targets = ["ESP32", "RBoard"] as const;
export type Target = (typeof targets)[number];

type Logger = (message?: any, ...params: any[]) => void;
type Logger = (message: string, ...params: unknown[]) => void;
type Listener = (buffer: string[]) => void;

type Reader = ReadableStreamDefaultReader<Uint8Array>;
type Writer = WritableStreamDefaultWriter<Uint8Array>;
type Event = "AttemptToEnterWriteMode" | "SuccessToExitWriteMode";
type Job = { job: Promise<any>; description: string };
type Job = { job: Promise<Result<unknown, Error>>; description: string };

const baudRates: Record<Target, number> = {
ESP32: 115200,
Expand Down Expand Up @@ -149,7 +149,7 @@ export class MrubyWriterConnector {
this.handleText(`\r\n> ${command}\r\n`);
console.log("Send", { command });

return await this.sendData(this.encoder.encode(command));
return this.sendData(this.encoder.encode(command));
}

async writeCode(
Expand Down Expand Up @@ -187,47 +187,43 @@ export class MrubyWriterConnector {
return Failure.error("No port.");
}

const send = new Promise<Result<string, Error>>(async (resovle, reject) => {
const send = async (): Promise<Result<string, Error>> => {
const readerRes = this.getSubReader();
const writerRes = this.getWriter();
if (readerRes.isFailure()) {
reject(readerRes);
return;
return readerRes;
}
if (writerRes.isFailure()) {
reject(writerRes);
return;
return writerRes;
}

this.currentSubReader = readerRes.value;
const writer = writerRes.value;

const request = await this.write(writer, chunk);
if (request.isFailure()) {
reject(request);
return;
return request;
}

const response = await this.readLine(this.currentSubReader);
if (response.isFailure()) {
reject(response);
return;
return response;
}
if (!response.value.startsWith("+")) {
reject(
Failure.error("Failed to enter write mode.", { cause: response })
);
return;
return Failure.error("Failed to enter write mode.", {
cause: response,
});
}

resovle(response);

this.currentSubReader.releaseLock();
writer.releaseLock();
});

this.jobQueue.push({ job: send, description: "send data" });
return await send;
return response;
};

const sendJob = send();
this.jobQueue.push({ job: sendJob, description: "send data" });
return await sendJob;
}

private async completeJobs() {
Expand Down Expand Up @@ -351,26 +347,25 @@ export class MrubyWriterConnector {
return Failure.error("Cannot write serial port.");
}

const enter = new Promise<Result<null, Error>>(async (resolve, reject) => {
const enter = async (): Promise<Result<null, Error>> => {
const response = await this.sendData(this.encoder.encode("\r\n\r\n"));
if (response.isFailure()) {
reject(response);
return;
return response;
}
if (!response.value.includes("+OK mruby/c")) {
reject(Failure.error("Cannot enter write mode"));
return;
return Failure.error("Cannot enter write mode");
}

this._writeMode = true;
resolve(Success.value(null));
});
return Success.value(null);
};

const enterJob = enter();
this.jobQueue.push({
job: enter,
job: enterJob,
description: "attempt to enter write mode",
});
return await enter;
return await enterJob;
}

private async onExitWriteMode(): Promise<Success<null>> {
Expand Down Expand Up @@ -424,15 +419,13 @@ export class MrubyWriterConnector {

private async readLine(reader: Reader): Promise<Result<string, Error>> {
let line = "";
while (true) {
while (!line.endsWith("\r\n")) {
const res = await this.read(reader);
if (res.isFailure()) return res;

line += res.value;

if (line.endsWith("\r\n")) {
return Success.value(line);
}
}

return Success.value(line);
}
}
4 changes: 2 additions & 2 deletions src/libs/result.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export type Result<T, E extends Error> = Success<T> | Failure<E>;

interface IResult {
isSuccess(): this is Success<any>;
isFailure(): this is Failure<any>;
isSuccess(): this is Success<unknown>;
isFailure(): this is Failure<Error>;
}

export class Success<T> implements IResult {
Expand Down
8 changes: 4 additions & 4 deletions src/libs/utility.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Target, targets } from "./mrubyWriterConnector"
import { Target, targets } from "./mrubyWriterConnector";

export const isTarget = (object: any): object is Target => {
return targets.includes(object);
}
export const isTarget = (value: string): value is Target => {
return (targets as readonly string[]).includes(value);
};
97 changes: 50 additions & 47 deletions src/pages/home.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Box,
Button,
Expand Down Expand Up @@ -53,7 +53,7 @@ export const Home = () => {

const targetItem = localStorage.getItem("target");
const [target, setTarget] = useState<Target | undefined>(
isTarget(targetItem) ? targetItem : undefined
targetItem && isTarget(targetItem) ? targetItem : undefined
);
const autoConnectItem = localStorage.getItem("autoConnect");
const [autoConnectMode, setAutoConnectMode] = useState<boolean>(
Expand All @@ -75,6 +75,52 @@ export const Home = () => {
status: "idle",
});

const read = useCallback(async () => {
const res = await connector.startListen();
console.log(res);
if (res.isFailure()) {
alert(
`受信中にエラーが発生しました。\n${res.error}\ncause: ${res.error.cause}`
);
}
}, [connector]);

const connect = useCallback(async () => {
const res = await connector.connect(
async () => await navigator.serial.requestPort()
);
if (res.isFailure()) {
alert(`ポートを取得できませんでした。\n${res.error}`);
console.log(res);
return;
}
await read();
}, [connector, read]);

const send = useCallback(
async (text: string) => {
const res = await connector.sendCommand(text);
console.log(res);
if (res.isFailure()) {
alert(
`送信中にエラーが発生しました。\n${res.error}\ncause: ${res.error.cause}`
);
}
},
[connector]
);

const writeCode = useCallback(async () => {
if (!code) return;
const res = await connector.writeCode(code, { execute: true });
console.log(res);
if (res.isFailure()) {
alert(
`書き込み中にエラーが発生しました。\n${res.error}\ncause: ${res.error.cause}`
);
}
}, [connector, code]);

useEffect(() => {
const compile = async () => {
setCompileStatus({ status: "idle" });
Expand Down Expand Up @@ -115,7 +161,7 @@ export const Home = () => {
};

compile();
}, []);
}, [id]);

useEffect(() => {
if (!autoConnectMode) return;
Expand All @@ -137,50 +183,7 @@ export const Home = () => {
};

autoConnect();
}, []);

const connect = async () => {
const res = await connector.connect(
async () => await navigator.serial.requestPort()
);
if (res.isFailure()) {
alert(`ポートを取得できませんでした。\n${res.error}`);
console.log(res);
return;
}
await read();
};

const read = async () => {
const res = await connector.startListen();
console.log(res);
if (res.isFailure()) {
alert(
`受信中にエラーが発生しました。\n${res.error}\ncause: ${res.error.cause}`
);
}
};

const send = async (text: string) => {
const res = await connector.sendCommand(text);
console.log(res);
if (res.isFailure()) {
alert(
`送信中にエラーが発生しました。\n${res.error}\ncause: ${res.error.cause}`
);
}
};

const writeCode = async () => {
if (!code) return;
const res = await connector.writeCode(code, { execute: true });
console.log(res);
if (res.isFailure()) {
alert(
`書き込み中にエラーが発生しました。\n${res.error}\ncause: ${res.error.cause}`
);
}
};
}, [autoConnectMode, connector, read]);

return (
<Box
Expand Down

0 comments on commit d010ac4

Please sign in to comment.