728x90

웹 브라우저에서 시리얼 포트를 직접 제어할 수 있는 Web Serial API를 사용할 수 있습니다. 이 API는 사용자가 브라우저를 통해 시리얼 포트와 직접 상호작용할 수 있도록 지원합니다. 그러나 이 API는 현재 Chromium 기반 브라우저(예: Google Chrome, Microsoft Edge)에서만 사용할 수 있습니다.

다음은 Web Serial API를 사용하여 시리얼 포트와 통신하는 방법을 설명합니다:

1. Web Serial API 기본 사용법

Web Serial API를 사용하면 사용자의 시리얼 포트를 탐색하고, 연결하며, 데이터를 읽고 쓸 수 있습니다.

기본 예제:

<!DOCTYPE html>
<html>
<head>
    <title>Web Serial API Example</title>
</head>
<body>
    <h1>Web Serial API Example</h1>
    <button id="connect">Connect</button>
    <button id="disconnect" disabled>Disconnect</button>
    <button id="send" disabled>Send Data</button>
    <textarea id="output" rows="10" cols="30"></textarea>

    <script>
        let port;
        let reader;
        let writer;

        document.getElementById('connect').addEventListener('click', async () => {
            try {
                port = await navigator.serial.requestPort();
                await port.open({ baudRate: 9600 });

                // Enable buttons
                document.getElementById('disconnect').disabled = false;
                document.getElementById('send').disabled = false;

                const output = document.getElementById('output');
                const decoder = new TextDecoder();

                // Start reading data
                reader = port.readable.getReader();
                readLoop();

                async function readLoop() {
                    while (true) {
                        const { value, done } = await reader.read();
                        if (done) {
                            // Reader has been canceled
                            break;
                        }
                        output.value += decoder.decode(value, { stream: true });
                    }
                }
            } catch (error) {
                console.error('Error connecting to serial port:', error);
            }
        });

        document.getElementById('disconnect').addEventListener('click', async () => {
            try {
                if (reader) {
                    reader.releaseLock();
                }
                if (port) {
                    await port.close();
                }
                document.getElementById('disconnect').disabled = true;
                document.getElementById('send').disabled = true;
            } catch (error) {
                console.error('Error disconnecting from serial port:', error);
            }
        });

        document.getElementById('send').addEventListener('click', async () => {
            try {
                if (port && port.writable) {
                    writer = port.writable.getWriter();
                    const data = new TextEncoder().encode('Hello, Serial Port!');
                    await writer.write(data);
                    writer.releaseLock();
                }
            } catch (error) {
                console.error('Error writing to serial port:', error);
            }
        });
    </script>
</body>
</html>

2. 설명

  • Connect 버튼: 사용자가 시리얼 포트를 선택하고 연결을 시도합니다. 성공적으로 연결되면 disconnectsend 버튼이 활성화됩니다.
  • Disconnect 버튼: 현재 연결된 시리얼 포트를 닫습니다.
  • Send 버튼: 시리얼 포트에 데이터를 전송합니다.
  • Output textarea: 시리얼 포트에서 수신된 데이터를 표시합니다.

3. 보안 및 권한

  • HTTPS 필요: Web Serial API는 보안상의 이유로 HTTPS 환경에서만 작동합니다. 로컬에서 테스트할 때도 localhost에서 제공하는 로컬 서버를 사용할 수 있습니다.
  • 권한 요청: 브라우저는 사용자에게 시리얼 포트 접근 권한을 요청합니다. 사용자가 수락해야만 시리얼 포트에 접근할 수 있습니다.

4. 주의사항

  • 브라우저 호환성: Web Serial API는 현재 Chrome 및 Edge 브라우저에서 지원됩니다. 다른 브라우저에서는 사용할 수 없습니다.
  • 기기 및 포트 접근: 사용자의 시스템에 연결된 시리얼 포트 및 장치에 따라 작동 여부가 달라질 수 있습니다.

이와 같은 방식으로 Web Serial API를 활용하여 시리얼 포트와의 통신을 웹 브라우저 내에서 직접 처리할 수 있습니다.

728x90
반응형

+ Recent posts