tauri-plugin-serialplugin 2.22.0

Access the current process of your Tauri application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
<script lang="ts">
    import { SerialPort } from 'tauri-plugin-serialplugin-api';
    import {
        ClearBuffer,
        DataBits,
        FlowControl,
        Parity,
        StopBits
    } from "../../../../guest-js";

    // Accept port and disconnect callback
    let { portName, onDisconnect } = $props();

    // ========================
    // = Declare $state(...)
    // ========================
    let serialport: SerialPort | undefined = $state(undefined);

    // Connection flag
    let isConnected = $state(false);

    // === Parameters ===
    let baudRate = $state(9600);
    let selectedDataBits = $state(DataBits.Eight);
    let selectedFlowControl = $state(FlowControl.None);
    let selectedParity = $state(Parity.None);
    let selectedStopBits = $state(StopBits.One);
    let timeout = $state(1000);

    // === Data and status ===
    let message = $state('');
    let receivedData = $state('');
    let receivedDataBase64 = $state('');
    let bytesToRead = $state(0);
    let bytesToWrite = $state(0);

    // === Signals ===
    let rtsState = $state(false);
    let dtrState = $state(false);
    let ctsState = $state(false);
    let dsrState = $state(false);
    let riState  = $state(false);
    let cdState  = $state(false);

    // ========================
    // = Lists for <select>   =
    // ========================
    let dataBitsOptions     = $state([DataBits.Five, DataBits.Six, DataBits.Seven, DataBits.Eight]);
    let flowControlOptions  = $state([FlowControl.None, FlowControl.Software, FlowControl.Hardware]);
    let parityOptions       = $state([Parity.None, Parity.Odd, Parity.Even]);
    let stopBitsOptions     = $state([StopBits.One, StopBits.Two]);

    // ------------------------
    // === FUNCTIONS ===
    // ------------------------

    async function connect() {
        try {
            if (!portName) return;

            serialport = new SerialPort({
                path: portName,
                baudRate,
                dataBits: selectedDataBits,
                flowControl: selectedFlowControl,
                parity: selectedParity,
                stopBits: selectedStopBits,
                timeout
            });

            await serialport.open();
            isConnected = true;
            console.log('Connected to port:', portName);

            await serialport.startListening();
            serialport.listen((data) => {
                console.log(`[${portName}] incoming data:`, data);
                receivedData += data;
                updatePortStatus();
            });

            // Event when port is physically disconnected:
            serialport.disconnected(() => {
                isConnected = false;
                console.log(`[${portName}] Disconnected (physically)`);
            });

            updatePortStatus();
        } catch (err) {
            console.error(`Failed to connect to port ${portName}:`, err);
        }
    }

    async function disconnect() {
        try {
            if (serialport) {
                await serialport.close();
                isConnected = false;
                console.log('Disconnected from port:', portName);

                // If parent passed onDisconnect callback — call it
                if (typeof onDisconnect === 'function') {
                    onDisconnect({ port: portName });
                }
            }
        } catch (err) {
            console.error(`Failed to disconnect from port ${portName}:`, err);
        }
    }

    async function sendMessage() {
        if (!serialport || !message) return;
        try {
            await serialport.write(message);
            console.log(`[${portName}] Message sent:`, message);
            message = '';
            updatePortStatus();
        } catch (err) {
            console.error(`Failed to send message on port ${portName}:`, err);
        }
    }

    async function sendBinary() {
        if (!serialport) return;
        try {
            const data = new Uint8Array([1, 2, 3, 4, 5]);
            await serialport.writeBinary(data);
            console.log(`[${portName}] Binary data sent:`, data);
            updatePortStatus();
        } catch (err) {
            console.error(`Failed to send binary data on port ${portName}:`, err);
        }
    }

    async function read() {
        if (!serialport) return;
        try {
            const data = await serialport.read();
            console.log(`[${portName}] Read:`, data);
        } catch (err) {
            console.error(`Failed to read on port ${portName}:`, err);
        }
    }

    async function readBinary() {
        if (!serialport) return;
        try {
            const binaryData = await serialport.readBinary({ size: 3, timeout: 2000 });
            console.log(`[${portName}] Read binary:`, binaryData);
        } catch (err) {
            console.error(`Failed to read binary on port ${portName}:`, err);
        }
    }

    async function updatePortSettings() {
        if (!serialport) return;
        try {
            await serialport.setBaudRate(baudRate);
            await serialport.setDataBits(selectedDataBits);
            await serialport.setFlowControl(selectedFlowControl);
            await serialport.setParity(selectedParity);
            await serialport.setStopBits(selectedStopBits);
            await serialport.setTimeout(timeout);
            console.log(`[${portName}] Port settings updated`);
        } catch (err) {
            console.error(`Failed to update port settings on ${portName}:`, err);
        }
    }

    async function clearBuffers() {
        if (!serialport) return;
        try {
            await serialport.clearBuffer(ClearBuffer.All);
            console.log(`[${portName}] Buffers cleared`);
            updatePortStatus();
        } catch (err) {
            console.error(`Failed to clear buffers on port ${portName}:`, err);
        }
    }

    async function updatePortStatus() {
        if (!serialport) return;
        try {
            bytesToRead = await serialport.bytesToRead();
            bytesToWrite = await serialport.bytesToWrite();
            ctsState = await serialport.readClearToSend();
            dsrState = await serialport.readDataSetReady();
            riState = await serialport.readRingIndicator();
            cdState = await serialport.readCarrierDetect();
        } catch (err) {
            console.error(`Failed to update port status for ${portName}:`, err);
        }
    }

    async function toggleRTS() {
        if (!serialport) return;
        try {
            rtsState = !rtsState;
            await serialport.setRequestToSend(rtsState);
        } catch (err) {
            console.error(`Failed to toggle RTS on ${portName}:`, err);
        }
    }

    async function toggleDTR() {
        if (!serialport) return;
        try {
            dtrState = !dtrState;
            await serialport.setDataTerminalReady(dtrState);
        } catch (err) {
            console.error(`Failed to toggle DTR on ${portName}:`, err);
        }
    }
</script>

<!-- ======================================= -->
<!--            LAYOUT                      -->
<!-- ======================================= -->
<div class="port-container">
    <h2>Port: {portName}</h2>

    {#if isConnected}
        <p class="connected">Status: CONNECTED</p>
    {:else}
        <p class="disconnected">Status: NOT CONNECTED</p>
    {/if}

    <!-- Connection buttons -->
    <div class="row connect-row">
        <button onclick={connect} disabled={isConnected}>Connect</button>
        <button onclick={disconnect} disabled={!isConnected}>Disconnect</button>
    </div>

    <!-- Settings section -->
    <div class="section settings-panel">
        <h3>Port Settings</h3>
        <div class="settings-grid">
            <label>
                Baud Rate
                <input type="number" bind:value={baudRate} />
            </label>

            <label>
                Data Bits
                <select bind:value={selectedDataBits}>
                    {#each dataBitsOptions as bits}
                        <option value={bits}>{bits}</option>
                    {/each}
                </select>
            </label>

            <label>
                Flow Control
                <select bind:value={selectedFlowControl}>
                    {#each flowControlOptions as flow}
                        <option value={flow}>{flow}</option>
                    {/each}
                </select>
            </label>

            <label>
                Parity
                <select bind:value={selectedParity}>
                    {#each parityOptions as parity}
                        <option value={parity}>{parity}</option>
                    {/each}
                </select>
            </label>

            <label>
                Stop Bits
                <select bind:value={selectedStopBits}>
                    {#each stopBitsOptions as sb}
                        <option value={sb}>{sb}</option>
                    {/each}
                </select>
            </label>

            <label>
                Timeout (ms)
                <input type="number" bind:value={timeout} />
            </label>
        </div>

        <button class="update-btn" onclick={updatePortSettings} disabled={!isConnected}>
            Update Settings
        </button>
    </div>

    <!-- Data transfer section -->
    <div class="section data-transfer">
        <h3>Data Transfer</h3>
        <div class="row">
            <input
                    type="text"
                    placeholder="Enter message..."
                    bind:value={message}
                    disabled={!isConnected}
            />
            <button onclick={sendMessage} disabled={!isConnected || !message}>
                Send Text
            </button>
            <button onclick={sendBinary} disabled={!isConnected}>
                Send Binary
            </button>
        </div>

        <div class="row">
            <button onclick={read} disabled={!isConnected}>Read</button>
            <button onclick={readBinary} disabled={!isConnected}>Read Binary</button>
            <button onclick={clearBuffers} disabled={!isConnected}>Clear Buffers</button>
        </div>

        <div class="status-info">
            <p>Bytes to read: {bytesToRead}</p>
            <p>Bytes to write: {bytesToWrite}</p>
        </div>

        <div class="received-data">
            <h4>Received Data:</h4>
            <pre>{receivedData}</pre>
        </div>
    </div>

    <!-- Control signals section -->
    <div class="section control-signals">
        <h3>Control Signals</h3>
        <div class="row signals-row">
            <button
                    onclick={toggleRTS}
                    disabled={!isConnected}
                    class:rts-active={rtsState}
            >
                RTS: {rtsState ? 'ON' : 'OFF'}
            </button>

            <button
                    onclick={toggleDTR}
                    disabled={!isConnected}
                    class:dtr-active={dtrState}
            >
                DTR: {dtrState ? 'ON' : 'OFF'}
            </button>
        </div>

        <div class="signals-indicators">
            <div class:active={ctsState}>CTS: {ctsState ? 'ON' : 'OFF'}</div>
            <div class:active={dsrState}>DSR: {dsrState ? 'ON' : 'OFF'}</div>
            <div class:active={riState}>RI:  {riState ? 'ON' : 'OFF'}</div>
            <div class:active={cdState}>CD:  {cdState ? 'ON' : 'OFF'}</div>
        </div>
    </div>
</div>

<!-- ======================================= -->
<!--            STYLES                      -->
<!-- ======================================= -->
<style>
    .port-container {
        padding: 10px;
        border-radius: 6px;
        background: #fafafa;
        margin-bottom: 20px;
        border: 1px solid #eee;
    }

    h2 {
        margin-top: 0;
        font-weight: 500;
        font-size: 1.2rem;
    }

    .connected {
        color: green;
        font-weight: bold;
    }
    .disconnected {
        color: #999;
        font-weight: bold;
    }

    /* Common blocks / sections */
    .section {
        background: #fff;
        border: 1px solid #eee;
        border-radius: 6px;
        padding: 10px;
        margin-bottom: 1rem;
    }

    .section h3 {
        margin-top: 0;
        font-size: 1rem;
        margin-bottom: 0.5rem;
    }

    /* Row of buttons or fields */
    .row {
        display: flex;
        gap: 10px;
        margin-bottom: 1rem;
    }

    .connect-row {
        margin-bottom: 20px;
    }

    /* Settings grid */
    .settings-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
        gap: 12px;
        margin-bottom: 10px;
    }

    label {
        display: flex;
        flex-direction: column;
        font-weight: 600;
        font-size: 0.9rem;
        color: #333;
    }

    input, select {
        margin-top: 5px;
        padding: 6px;
        font-size: 0.9rem;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    .update-btn {
        margin-top: 5px;
    }

    /* Buttons */
    button {
        border: none;
        background: #2196f3;
        color: white;
        padding: 8px 14px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.9rem;
    }
    button:hover {
        background: #1976d2;
    }
    button:disabled {
        background: #ccc;
        cursor: not-allowed;
    }

    /* Status information */
    .status-info {
        display: flex;
        gap: 1rem;
        font-family: monospace;
        margin: 10px 0;
    }

    .received-data {
        max-height: 150px;
        overflow-y: auto;
        background: #f8f8f8;
        padding: 10px;
        border-radius: 4px;
        margin-top: 10px;
    }
    pre {
        margin: 0;
    }

    /* Control signals */
    .signals-row {
        display: flex;
        gap: 10px;
        margin-bottom: 10px;
    }
    .signals-indicators {
        display: flex;
        gap: 10px;
    }
    .signals-indicators > div {
        background: #f5f5f5;
        padding: 6px 8px;
        border-radius: 4px;
        font-family: monospace;
    }
    .signals-indicators > div.active {
        background: #4caf50;
        color: white;
    }

    .rts-active,
    .dtr-active {
        background: #4caf50;
    }
</style>