1#include <SerialPort.h>
2
3#include <stdio.h>
4#include <string.h>
5
6
7static int32
8reader_thread(void *data)
9{
10	BSerialPort *port = (BSerialPort *)data;
11	char buffer[128];
12
13	while (true) {
14		ssize_t read = port->Read(buffer, sizeof(buffer));
15		if (read <= 0)
16			continue;
17
18		for (ssize_t i = 0; i < read; i++) {
19			putc(buffer[i], stdout);
20			fflush(stdout);
21		}
22	}
23
24	return 0;
25}
26
27
28int
29main(int argc, char *argv[])
30{
31	BSerialPort port;
32
33	if (argc < 2) {
34		printf("usage: %s <port>\n", argv[0]);
35
36		int32 portCount = port.CountDevices();
37		printf("\tports (%ld):\n", portCount);
38
39		char nameBuffer[B_OS_NAME_LENGTH];
40		for (int32 i = 0; i < portCount; i++) {
41			if (port.GetDeviceName(i, nameBuffer, sizeof(nameBuffer)) != B_OK) {
42				printf("\t\tfailed to retrieve name %ld\n", i);
43				continue;
44			}
45
46			printf("\t\t%s\n", nameBuffer);
47		}
48
49		return 1;
50	}
51
52	status_t result = port.Open(argv[1]);
53	if (result < B_OK) {
54		printf("failed to open port \"%s\": %s\n", argv[1], strerror(result));
55		return result;
56	}
57
58	port.SetDataRate(B_9600_BPS);
59	port.SetDataBits(B_DATA_BITS_8);
60	port.SetStopBits(B_STOP_BITS_1);
61	port.SetParityMode(B_NO_PARITY);
62	port.SetFlowControl(B_NOFLOW_CONTROL);
63
64	thread_id reader = spawn_thread(reader_thread, "serial reader",
65		B_NORMAL_PRIORITY, &port);
66	if (reader < 0) {
67		printf("failed to spawn reader thread\n");
68		return reader;
69	}
70
71	resume_thread(reader);
72
73	char buffer[128];
74	while (true) {
75		char *string = fgets(buffer, sizeof(buffer), stdin);
76		if (string == NULL)
77			continue;
78
79		port.Write(buffer, strlen(string) - 1);
80	}
81
82	return 0;
83}
84