-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathserial.zig
More file actions
1283 lines (1103 loc) · 42.6 KB
/
Copy pathserial.zig
File metadata and controls
1283 lines (1103 loc) · 42.6 KB
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
pub fn list(io: Io) !PortIterator {
return try switch (builtin.os.tag) {
.windows => WindowsPortIterator.init(),
.linux => LinuxPortIterator.init(io),
.macos => DarwinPortIterator.init(io),
else => @compileError("OS is not supported for port iteration"),
};
}
pub fn list_info(io: Io) !InformationIterator {
return try switch (builtin.os.tag) {
.windows => WindowsInformationIterator.init(),
.linux => LinuxInformationIterator.init(io),
else => @compileError("OS is not supported for information iteration"),
};
}
pub const PortIterator = switch (builtin.os.tag) {
.windows => WindowsPortIterator,
.linux => LinuxPortIterator,
.macos => DarwinPortIterator,
else => @compileError("OS is not supported for port iteration"),
};
pub const InformationIterator = switch (builtin.os.tag) {
.windows => WindowsInformationIterator,
.linux => LinuxInformationIterator,
// .linux, .macos => @panic("'Port Information' not yet implemented for this OS"),
else => @compileError("OS is not supported for information iteration"),
};
pub const SerialPortDescription = struct {
file_name: []const u8,
display_name: []const u8,
driver: ?[]const u8,
};
pub const PortInformation = struct {
port_name: []const u8,
system_location: []const u8,
friendly_name: []const u8,
description: []const u8,
manufacturer: []const u8,
serial_number: []const u8,
// TODO: review whether to remove `hw_id`.
// Is this useless/being used in a Windows-only way?
hw_id: []const u8,
vid: u16,
pid: u16,
};
const HKEY = std.os.windows.HKEY;
const HWND = std.os.windows.HANDLE;
const HDEVINFO = std.os.windows.HANDLE;
const DEVINST = std.os.windows.DWORD;
const SP_DEVINFO_DATA = extern struct {
cbSize: std.os.windows.DWORD,
classGuid: std.os.windows.GUID,
devInst: std.os.windows.DWORD,
reserved: std.os.windows.ULONG_PTR,
};
const WindowsPortIterator = struct {
const Self = @This();
key: HKEY,
index: u32,
name: [256:0]u8 = undefined,
name_size: u32 = 256,
data: [256]u8 = undefined,
filepath_data: [256]u8 = undefined,
data_size: u32 = 256,
pub fn init() !Self {
const HKEY_LOCAL_MACHINE = @as(HKEY, @ptrFromInt(0x80000002));
var self: Self = undefined;
self.index = 0;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM\\", 0, std.os.windows.ACCESS_MASK.Specific.Key.READ, &self.key) != 0)
return error.WindowsError;
return self;
}
pub fn deinit(self: *Self) void {
_ = RegCloseKey(self.key);
self.* = undefined;
}
pub fn next(self: *Self) !?SerialPortDescription {
defer self.index += 1;
self.name_size = 256;
self.data_size = 256;
return switch (RegEnumValueA(self.key, self.index, &self.name, &self.name_size, null, null, &self.data, &self.data_size)) {
0 => SerialPortDescription{
.file_name = try std.fmt.bufPrint(&self.filepath_data, "\\\\.\\{s}", .{self.data[0 .. self.data_size - 1]}),
.display_name = self.data[0 .. self.data_size - 1],
.driver = self.name[0..self.name_size],
},
259 => null,
else => error.WindowsError,
};
}
};
const WindowsInformationIterator = struct {
const Self = @This();
index: std.os.windows.DWORD,
device_info_set: HDEVINFO,
port_buffer: [256:0]u8,
sys_buffer: [256:0]u8,
name_buffer: [256:0]u8,
desc_buffer: [256:0]u8,
man_buffer: [256:0]u8,
serial_buffer: [256:0]u8,
hw_id: [256:0]u8,
const Property = enum(std.os.windows.DWORD) {
SPDRP_DEVICEDESC = 0x00000000,
SPDRP_MFG = 0x0000000B,
SPDRP_FRIENDLYNAME = 0x0000000C,
};
// GUID taken from <devguid.h>
const DIGCF_PRESENT = 0x00000002;
const DIGCF_DEVICEINTERFACE = 0x00000010;
const device_setup_tokens = .{
.{ std.os.windows.GUID{ .Data1 = 0x4d36e978, .Data2 = 0xe325, .Data3 = 0x11ce, .Data4 = .{ 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 } }, DIGCF_PRESENT },
.{ std.os.windows.GUID{ .Data1 = 0x4d36e96d, .Data2 = 0xe325, .Data3 = 0x11ce, .Data4 = .{ 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 } }, DIGCF_PRESENT },
.{ std.os.windows.GUID{ .Data1 = 0x86e0d1e0, .Data2 = 0x8089, .Data3 = 0x11d0, .Data4 = .{ 0x9c, 0xe4, 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73 } }, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE },
.{ std.os.windows.GUID{ .Data1 = 0x2c7089aa, .Data2 = 0x2e0e, .Data3 = 0x11d1, .Data4 = .{ 0xb1, 0x14, 0x00, 0xc0, 0x4f, 0xc2, 0xaa, 0xe4 } }, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE },
};
pub fn init() !Self {
var self: Self = undefined;
self.index = 0;
inline for (device_setup_tokens) |token| {
const guid = token[0];
const flags = token[1];
self.device_info_set = SetupDiGetClassDevsW(
&guid,
null,
null,
flags,
);
if (self.device_info_set != std.os.windows.INVALID_HANDLE_VALUE) break;
}
if (self.device_info_set == std.os.windows.INVALID_HANDLE_VALUE) return error.WindowsError;
return self;
}
pub fn deinit(self: *Self) void {
_ = SetupDiDestroyDeviceInfoList(self.device_info_set);
self.* = undefined;
}
pub fn next(self: *Self) !?PortInformation {
var device_info_data: SP_DEVINFO_DATA = .{
.cbSize = @sizeOf(SP_DEVINFO_DATA),
.classGuid = std.mem.zeroes(std.os.windows.GUID),
.devInst = 0,
.reserved = 0,
};
if (SetupDiEnumDeviceInfo(self.device_info_set, self.index, &device_info_data) != std.os.windows.BOOL.TRUE) {
return null;
}
defer self.index += 1;
var info: PortInformation = std.mem.zeroes(PortInformation);
@memset(&self.hw_id, 0);
// NOTE: have not handled if port startswith("LPT")
var length = getPortName(&self.device_info_set, &device_info_data, &self.port_buffer);
info.port_name = self.port_buffer[0..length];
info.system_location = try std.fmt.bufPrint(&self.sys_buffer, "\\\\.\\{s}", .{info.port_name});
length = deviceRegistryProperty(&self.device_info_set, &device_info_data, Property.SPDRP_FRIENDLYNAME, &self.name_buffer);
info.friendly_name = self.name_buffer[0..length];
length = deviceRegistryProperty(&self.device_info_set, &device_info_data, Property.SPDRP_DEVICEDESC, &self.desc_buffer);
info.description = self.desc_buffer[0..length];
length = deviceRegistryProperty(&self.device_info_set, &device_info_data, Property.SPDRP_MFG, &self.man_buffer);
info.manufacturer = self.man_buffer[0..length];
if (SetupDiGetDeviceInstanceIdA(
self.device_info_set,
&device_info_data,
@ptrCast(&self.hw_id),
255,
null,
) == std.os.windows.BOOL.TRUE) {
length = @as(u32, @truncate(std.mem.indexOfSentinel(u8, 0, &self.hw_id)));
info.hw_id = self.hw_id[0..length];
length = parseSerialNumber(&self.hw_id, &self.serial_buffer) catch 0;
if (length == 0) {
length = getParentSerialNumber(device_info_data.devInst, &self.hw_id, &self.serial_buffer) catch 0;
}
info.serial_number = self.serial_buffer[0..length];
info.vid = parseVendorId(&self.hw_id) catch 0;
info.pid = parseProductId(&self.hw_id) catch 0;
} else {
return error.WindowsError;
}
return info;
}
fn getPortName(device_info_set: *const HDEVINFO, device_info_data: *SP_DEVINFO_DATA, port_name: [*]u8) std.os.windows.DWORD {
const hkey: HKEY = SetupDiOpenDevRegKey(
device_info_set.*,
device_info_data,
0x00000001, // #define DICS_FLAG_GLOBAL
0,
0x00000001, // #define DIREG_DEV,
std.os.windows.ACCESS_MASK.Specific.Key.READ,
);
defer {
_ = RegCloseKey(hkey);
}
inline for (.{ "PortName", "PortNumber" }) |key_token| {
var port_length: std.os.windows.DWORD = std.os.windows.NAME_MAX;
var data_type: std.os.windows.DWORD = 0;
const result = RegQueryValueExA(
hkey,
@as(std.os.windows.LPSTR, @ptrCast(@constCast(key_token))),
null,
&data_type,
port_name,
&port_length,
);
// if this is valid, return now
if (result == 0 and port_length > 0) {
return port_length;
}
}
return 0;
}
fn deviceRegistryProperty(device_info_set: *const HDEVINFO, device_info_data: *SP_DEVINFO_DATA, property: Property, property_str: [*]u8) std.os.windows.DWORD {
var data_type: std.os.windows.DWORD = 0;
var bytes_required: std.os.windows.DWORD = std.os.windows.MAX_PATH;
const result = SetupDiGetDeviceRegistryPropertyA(
device_info_set.*,
device_info_data,
@intFromEnum(property),
&data_type,
property_str,
std.os.windows.NAME_MAX,
&bytes_required,
);
if (result == std.os.windows.BOOL.FALSE) {
std.debug.print("GetLastError: {}\n", .{std.os.windows.GetLastError()});
bytes_required = 0;
}
return bytes_required;
}
fn getParentSerialNumber(devinst: DEVINST, devid: []const u8, serial_number: [*]u8) !std.os.windows.DWORD {
if (std.mem.startsWith(u8, devid, "FTDI")) {
// Should not be called on "FTDI" so just return the serial number.
return try parseSerialNumber(devid, serial_number);
} else if (std.mem.startsWith(u8, devid, "USB")) {
// taken from pyserial
const max_usb_device_tree_traversal_depth = 5;
const start_vidpid = std.mem.indexOf(u8, devid, "VID") orelse return error.WindowsError;
const vidpid_slice = devid[start_vidpid .. start_vidpid + 17]; // "VIDxxxx&PIDxxxx"
// keep looping over parent device to extract serial number if it contains the target VID and PID.
var depth: u8 = 0;
var child_inst: DEVINST = devinst;
while (depth <= max_usb_device_tree_traversal_depth) : (depth += 1) {
var parent_id: DEVINST = undefined;
var local_buffer: [256:0]u8 = std.mem.zeroes([256:0]u8);
if (CM_Get_Parent(&parent_id, child_inst, 0) != 0) return error.WindowsError;
if (CM_Get_Device_IDA(parent_id, @ptrCast(&local_buffer), 256, 0) != 0) return error.WindowsError;
defer child_inst = parent_id;
if (!std.mem.containsAtLeast(u8, local_buffer[0..255], 1, vidpid_slice)) continue;
const length = try parseSerialNumber(local_buffer[0..255], serial_number);
if (length > 0) return length;
}
}
return error.WindowsError;
}
fn parseSerialNumber(devid: []const u8, serial_number: [*]u8) !std.os.windows.DWORD {
var delimiter: ?[]const u8 = undefined;
if (std.mem.startsWith(u8, devid, "USB")) {
delimiter = "\\&";
} else if (std.mem.startsWith(u8, devid, "FTDI")) {
delimiter = "\\+";
} else {
// What to do here?
delimiter = null;
}
if (delimiter) |del| {
var it = std.mem.tokenizeAny(u8, devid, del);
// throw away the start
_ = it.next();
while (it.next()) |segment| {
if (std.mem.startsWith(u8, segment, "VID_")) continue;
if (std.mem.startsWith(u8, segment, "PID_")) continue;
// If "MI_{d}{d}", this is an interface number. The serial number will have to be
// sourced from the parent node. Probably do not have to check all these conditions.
if (segment.len == 5 and std.mem.eql(u8, "MI_", segment[0..3]) and std.ascii.isDigit(segment[3]) and std.ascii.isDigit(segment[4])) return 0;
@memcpy(serial_number, segment);
return @as(std.os.windows.DWORD, @truncate(segment.len));
}
}
return error.WindowsError;
}
fn parseVendorId(devid: []const u8) !u16 {
var delimiter: ?[]const u8 = undefined;
if (std.mem.startsWith(u8, devid, "USB")) {
delimiter = "\\&";
} else if (std.mem.startsWith(u8, devid, "FTDI")) {
delimiter = "\\+";
} else {
delimiter = null;
}
if (delimiter) |del| {
var it = std.mem.tokenizeAny(u8, devid, del);
while (it.next()) |segment| {
if (std.mem.startsWith(u8, segment, "VID_")) {
return try std.fmt.parseInt(u16, segment[4..], 16);
}
}
}
return error.WindowsError;
}
fn parseProductId(devid: []const u8) !u16 {
var delimiter: ?[]const u8 = undefined;
if (std.mem.startsWith(u8, devid, "USB")) {
delimiter = "\\&";
} else if (std.mem.startsWith(u8, devid, "FTDI")) {
delimiter = "\\+";
} else {
delimiter = null;
}
if (delimiter) |del| {
var it = std.mem.tokenizeAny(u8, devid, del);
while (it.next()) |segment| {
if (std.mem.startsWith(u8, segment, "PID_")) {
return try std.fmt.parseInt(u16, segment[4..], 16);
}
}
}
return error.WindowsError;
}
};
extern "advapi32" fn RegOpenKeyExA(
key: HKEY,
lpSubKey: std.os.windows.LPCSTR,
ulOptions: std.os.windows.DWORD,
samDesired: std.os.windows.REGSAM,
phkResult: *HKEY,
) callconv(.winapi) std.os.windows.LSTATUS;
extern "advapi32" fn RegCloseKey(key: HKEY) callconv(.winapi) std.os.windows.LSTATUS;
extern "advapi32" fn RegEnumValueA(
hKey: HKEY,
dwIndex: std.os.windows.DWORD,
lpValueName: std.os.windows.LPSTR,
lpcchValueName: *std.os.windows.DWORD,
lpReserved: ?*std.os.windows.DWORD,
lpType: ?*std.os.windows.DWORD,
lpData: [*]std.os.windows.BYTE,
lpcbData: *std.os.windows.DWORD,
) callconv(.winapi) std.os.windows.LSTATUS;
extern "advapi32" fn RegQueryValueExA(
hKey: HKEY,
lpValueName: std.os.windows.LPSTR,
lpReserved: ?*std.os.windows.DWORD,
lpType: ?*std.os.windows.DWORD,
lpData: ?[*]std.os.windows.BYTE,
lpcbData: ?*std.os.windows.DWORD,
) callconv(.winapi) std.os.windows.LSTATUS;
extern "setupapi" fn SetupDiGetClassDevsW(
classGuid: ?*const std.os.windows.GUID,
enumerator: ?std.os.windows.PCWSTR,
hwndParanet: ?HWND,
flags: std.os.windows.DWORD,
) callconv(.winapi) HDEVINFO;
extern "setupapi" fn SetupDiEnumDeviceInfo(
devInfoSet: HDEVINFO,
memberIndex: std.os.windows.DWORD,
device_info_data: *SP_DEVINFO_DATA,
) callconv(.winapi) std.os.windows.BOOL;
extern "setupapi" fn SetupDiDestroyDeviceInfoList(device_info_set: HDEVINFO) callconv(.winapi) std.os.windows.BOOL;
extern "setupapi" fn SetupDiOpenDevRegKey(
device_info_set: HDEVINFO,
device_info_data: *SP_DEVINFO_DATA,
scope: std.os.windows.DWORD,
hwProfile: std.os.windows.DWORD,
keyType: std.os.windows.DWORD,
samDesired: std.os.windows.REGSAM,
) callconv(.winapi) HKEY;
extern "setupapi" fn SetupDiGetDeviceRegistryPropertyA(
hDevInfo: HDEVINFO,
pSpDevInfoData: *SP_DEVINFO_DATA,
property: std.os.windows.DWORD,
propertyRegDataType: ?*std.os.windows.DWORD,
propertyBuffer: ?[*]std.os.windows.BYTE,
propertyBufferSize: std.os.windows.DWORD,
requiredSize: ?*std.os.windows.DWORD,
) callconv(.winapi) std.os.windows.BOOL;
extern "setupapi" fn SetupDiGetDeviceInstanceIdA(
device_info_set: HDEVINFO,
device_info_data: *SP_DEVINFO_DATA,
deviceInstanceId: *?std.os.windows.CHAR,
deviceInstanceIdSize: std.os.windows.DWORD,
requiredSize: ?*std.os.windows.DWORD,
) callconv(.winapi) std.os.windows.BOOL;
extern "cfgmgr32" fn CM_Get_Parent(
pdnDevInst: *DEVINST,
dnDevInst: DEVINST,
ulFlags: std.os.windows.ULONG,
) callconv(.winapi) std.os.windows.DWORD;
extern "cfgmgr32" fn CM_Get_Device_IDA(
dnDevInst: DEVINST,
buffer: std.os.windows.LPSTR,
bufferLen: std.os.windows.ULONG,
ulFlags: std.os.windows.ULONG,
) callconv(.winapi) std.os.windows.DWORD;
const LinuxPortIterator = struct {
const Self = @This();
const root_dir = "/sys/class/tty";
// ls -hal /sys/class/tty/*/device/driver
io: std.Io,
dir: std.Io.Dir,
iterator: std.Io.Dir.Iterator,
full_path_buffer: [std.fs.max_path_bytes]u8 = undefined,
driver_path_buffer: [std.fs.max_path_bytes]u8 = undefined,
pub fn init(io: std.Io) !Self {
var dir = try std.Io.Dir.openDirAbsolute(io, root_dir, .{ .iterate = true });
errdefer dir.close(io);
return Self{
.io = io,
.dir = dir,
.iterator = dir.iterate(),
};
}
pub fn deinit(self: *Self) void {
self.dir.close(self.io);
self.* = undefined;
}
pub fn next(self: *Self) !?SerialPortDescription {
while (true) {
if (try self.iterator.next(self.io)) |entry| {
// not a dir => we don't care
var tty_dir = self.dir.openDir(self.io, entry.name, .{}) catch continue;
defer tty_dir.close(self.io);
// we need the device dir
// no device dir => virtual device
var device_dir = tty_dir.openDir(self.io, "device", .{}) catch continue;
defer device_dir.close(self.io);
// We need the symlink for "driver"
const link_len = device_dir.readLink(self.io, "driver", &self.driver_path_buffer) catch continue;
// full_path_buffer
// driver_path_buffer
var fba = std.heap.FixedBufferAllocator.init(&self.full_path_buffer);
const path = try std.fs.path.join(fba.allocator(), &.{
"/dev/",
entry.name,
});
return SerialPortDescription{
.file_name = path,
.display_name = path,
.driver = std.fs.path.basename(self.driver_path_buffer[0..link_len]),
};
} else {
return null;
}
}
return null;
}
};
const LinuxInformationIterator = struct {
const Self = @This();
const root_dir = "/sys/class/tty";
index: u8,
io: std.Io,
dir: std.Io.Dir,
iterator: std.Io.Dir.Iterator,
driver_path_buffer: [std.fs.max_path_bytes]u8 = undefined,
sys_buffer: [256:0]u8 = undefined,
desc_buffer: [256:0]u8 = undefined,
man_buffer: [256:0]u8 = undefined,
serial_buffer: [256:0]u8 = undefined,
port: PortInformation = undefined,
pub fn init(io: std.Io) !Self {
var dir = try std.Io.Dir.openDirAbsolute(io, root_dir, .{ .iterate = true });
errdefer dir.close(io);
return Self{ .index = 0, .io = io, .dir = dir, .iterator = dir.iterate() };
}
pub fn deinit(self: *Self) void {
self.dir.close(self.io);
self.* = undefined;
}
pub fn next(self: *Self) !?PortInformation {
self.index += 1;
while (try self.iterator.next(self.io)) |entry| {
@memset(&self.sys_buffer, 0);
@memset(&self.desc_buffer, 0);
@memset(&self.man_buffer, 0);
@memset(&self.serial_buffer, 0);
@memset(&self.driver_path_buffer, 0);
// not a dir => we don't care
var tty_dir = self.dir.openDir(self.io, entry.name, .{}) catch continue;
defer tty_dir.close(self.io);
// we need the device dir
// no device dir => virtual device
var device_dir = tty_dir.openDir(self.io, "device", .{}) catch continue;
defer device_dir.close(self.io);
// start filling port informations
{
var fba = std.heap.FixedBufferAllocator.init(&self.sys_buffer);
self.port.system_location = try std.fs.path.join(fba.allocator(), &.{
"/dev/",
entry.name,
});
self.port.friendly_name = entry.name;
self.port.port_name = entry.name;
self.port.hw_id = "N/A";
}
// We need the symlink for "driver"
const subsystem_link_len = device_dir.readLink(self.io, "subsystem", &self.driver_path_buffer) catch continue;
const subsystem = std.fs.path.basename(self.driver_path_buffer[0..subsystem_link_len]);
var device_path_len: usize = undefined;
if (std.mem.eql(u8, subsystem, "usb") == true) {
const parent = try device_dir.openDir(self.io, "../", .{});
device_path_len = try parent.realPath(self.io, &self.driver_path_buffer);
} else if (std.mem.eql(u8, subsystem, "usb-serial") == true) {
const parent = try device_dir.openDir(self.io, "../../", .{});
device_path_len = try parent.realPath(self.io, &self.driver_path_buffer);
} else {
//must be remove to manage other device type
self.port.description = "Not Managed";
self.port.manufacturer = "Not Managed";
self.port.serial_number = "Not Managed";
self.port.vid = 0;
self.port.pid = 0;
return self.port;
}
var data_dir = std.Io.Dir.openDirAbsolute(self.io, self.driver_path_buffer[0..device_path_len], .{}) catch continue;
defer data_dir.close(self.io);
var tmp: [4]u8 = undefined;
{
self.port.manufacturer = data_dir.readFile(self.io, "manufacturer", &self.man_buffer) catch "N/A";
Self.clean_file_read(&self.man_buffer);
self.port.description = data_dir.readFile(self.io, "product", &self.desc_buffer) catch "N/A";
Self.clean_file_read(&self.desc_buffer);
self.port.serial_number = data_dir.readFile(self.io, "serial", &self.serial_buffer) catch "N/A";
Self.clean_file_read(&self.serial_buffer);
}
{
@memset(&tmp, 0);
_ = data_dir.readFile(self.io, "idVendor", &tmp) catch 0;
self.port.vid = try std.fmt.parseInt(u16, &tmp, 16);
}
{
@memset(&tmp, 0);
_ = data_dir.readFile(self.io, "idProduct", &tmp) catch 0;
self.port.pid = try std.fmt.parseInt(u16, &tmp, 16);
}
return self.port;
}
return null;
}
fn clean_file_read(buf: []u8) void {
for (buf) |*item| {
if (item.* == '\n') {
item.* = 0;
break;
}
}
}
};
const DarwinPortIterator = struct {
const Self = @This();
const root_dir = "/dev/";
io: std.Io,
dir: std.Io.Dir,
iterator: std.Io.Dir.Iterator,
full_path_buffer: [std.fs.max_path_bytes]u8 = undefined,
driver_path_buffer: [std.fs.max_path_bytes]u8 = undefined,
pub fn init(io: std.Io) !Self {
var dir = try std.Io.Dir.openDirAbsolute(io, root_dir, .{ .iterate = true });
errdefer dir.close();
return Self{
.io = io,
.dir = dir,
.iterator = dir.iterate(),
};
}
pub fn deinit(self: *Self) void {
self.dir.close(self.io);
self.* = undefined;
}
pub fn next(self: *Self) !?SerialPortDescription {
while (true) {
if (try self.iterator.next()) |entry| {
if (!std.mem.startsWith(u8, entry.name, "cu.")) {
continue;
} else {
var fba = std.heap.FixedBufferAllocator.init(&self.full_path_buffer);
const path = try std.fs.path.join(fba.allocator(), &.{
"/dev/",
entry.name,
});
return SerialPortDescription{
.file_name = path,
.display_name = path,
.driver = "darwin",
};
}
} else {
return null;
}
}
return null;
}
};
pub const Parity = enum(u8) {
/// No parity bit is used
none = 'N',
/// Parity bit is `0` when an even number of bits is set in the data.
even = 'E',
/// Parity bit is `0` when an odd number of bits is set in the data.
odd = 'O',
/// Parity bit is always `1`
mark = 'M',
/// Parity bit is always `0`
space = 'S',
};
pub const StopBits = enum(u2) {
/// The length of the stop bit is 1 bit
one = 1,
/// The length of the stop bit is 2 bits
two = 2,
};
pub const Handshake = enum {
/// No handshake is used
none,
/// XON-XOFF software handshake is used.
software,
/// Hardware handshake with RTS/CTS is used.
hardware,
};
pub const WordSize = enum(u4) {
five = 5,
six = 6,
seven = 7,
eight = 8,
};
pub const SerialConfig = struct {
const Self = @This();
/// Symbol rate in bits/second. Not that these
/// include also parity and stop bits.
baud_rate: u32,
/// Parity to verify transport integrity.
parity: Parity = .none,
/// Number of stop bits after the data
stop_bits: StopBits = .one,
/// Number of data bits per word.
/// Allowed values are 5, 6, 7, 8
word_size: WordSize = .eight,
/// Defines the handshake protocol used.
handshake: Handshake = .none,
pub fn format(self: Self, writer: *Io.Writer) !void {
return writer.print("{d}@{d}{c}{d}{s}", .{
self.baud_rate,
@intFromEnum(self.word_size),
@intFromEnum(self.parity),
@intFromEnum(self.stop_bits),
switch (self.handshake) {
.none => "",
.hardware => " RTS/CTS",
.software => " XON/XOFF",
},
});
}
};
const CBAUD = 0o000000010017; //Baud speed mask (not in POSIX).
const CMSPAR = 0o010000000000;
const CRTSCTS = 0o020000000000;
const VTIME = 5;
const VMIN = 6;
const VSTART = 8;
const VSTOP = 9;
/// This function configures a serial port with the given config.
/// `port` is an already opened serial port, on windows these
/// are either called `\\.\COMxx\` or `COMx`, on unixes the serial
/// port is called `/dev/ttyXXX`.
pub fn configureSerialPort(port: std.Io.File, config: SerialConfig) !void {
switch (builtin.os.tag) {
.windows => {
var dcb = std.mem.zeroes(DCB);
dcb.DCBlength = @sizeOf(DCB);
if (GetCommState(port.handle, &dcb) == std.os.windows.BOOL.FALSE)
return error.WindowsError;
// std.log.err("{s} {s}", .{ dcb, flags });
dcb.BaudRate = config.baud_rate;
dcb.flags = @bitCast(DCBFlags{
.fParity = config.parity != .none,
.fOutxCtsFlow = config.handshake == .hardware,
.fOutX = config.handshake == .software,
.fInX = config.handshake == .software,
.fRtsControl = @as(u2, if (config.handshake == .hardware) 1 else 0),
});
dcb.wReserved = 0;
dcb.ByteSize = switch (config.word_size) {
.five => @as(u8, 5),
.six => @as(u8, 6),
.seven => @as(u8, 7),
.eight => @as(u8, 8),
};
dcb.Parity = switch (config.parity) {
.none => @as(u8, 0),
.even => @as(u8, 2),
.odd => @as(u8, 1),
.mark => @as(u8, 3),
.space => @as(u8, 4),
};
dcb.StopBits = switch (config.stop_bits) {
.one => @as(u2, 0),
.two => @as(u2, 2),
};
dcb.XonChar = 0x11;
dcb.XoffChar = 0x13;
dcb.wReserved1 = 0;
if (SetCommState(port.handle, &dcb) == std.os.windows.BOOL.FALSE)
return error.WindowsError;
},
.linux, .macos => |tag| {
var settings = try std.posix.tcgetattr(port.handle);
var macos_nonstandard_baud = false;
const baudmask: std.c.speed_t = switch (tag) {
.macos => mapBaudToMacOSEnum(config.baud_rate) orelse b: {
macos_nonstandard_baud = true;
break :b @enumFromInt(@as(u64, @bitCast(settings.cflag)));
},
.linux => try mapBaudToLinuxEnum(config.baud_rate),
else => unreachable,
};
// initialize CFLAG with the baudrate bits
settings.cflag = @bitCast(@intFromEnum(baudmask));
settings.cflag.PARODD = config.parity == .odd or config.parity == .mark;
settings.cflag.PARENB = config.parity != .none;
settings.cflag.CLOCAL = config.handshake == .none;
settings.cflag.CSTOPB = config.stop_bits == .two;
settings.cflag.CREAD = true;
settings.cflag.CSIZE = switch (config.word_size) {
.five => .CS5,
.six => .CS6,
.seven => .CS7,
.eight => .CS8,
};
settings.iflag = .{};
settings.iflag.INPCK = config.parity != .none;
settings.iflag.IXON = config.handshake == .software;
settings.iflag.IXOFF = config.handshake == .software;
// these are common between linux and macos
// settings.iflag.IGNBRK = false;
// settings.iflag.BRKINT = false;
// settings.iflag.IGNPAR = false;
// settings.iflag.PARMRK = false;
// settings.iflag.ISTRIP = false;
// settings.iflag.INLCR = false;
// settings.iflag.IGNCR = false;
// settings.iflag.ICRNL = false;
// settings.iflag.IXANY = false;
// settings.iflag.IMAXBEL = false;
// settings.iflag.IUTF8 = false;
// these are where they diverge
if (builtin.os.tag == .linux) {
if (@hasField(std.c.tc_cflag_t, "CMSPAR")) {
settings.cflag.CMSPAR = config.parity == .mark;
}
if (@hasField(std.c.tc_cflag_t, "CRTSCTS")) {
settings.cflag.CRTSCTS = config.handshake == .hardware;
}
// settings.cflag.ADDRB = false;
// settings.iflag.IUCLC = false;
// these are actually the same, but for simplicity
// just setting baud on mac with cfsetspeed
}
if (builtin.os.tag == .macos) {
settings.cflag.CCTS_OFLOW = config.handshake == .hardware;
settings.cflag.CRTS_IFLOW = config.handshake == .hardware;
// settings.cflag.CIGNORE = false;
// settings.cflag.CDTR_IFLOW = false;
// settings.cflag.CDSR_OFLOW = false;
// settings.cflag.CCAR_OFLOW = false;
}
if (!macos_nonstandard_baud) {
settings.ispeed = baudmask;
settings.ospeed = baudmask;
}
settings.oflag = .{};
settings.lflag = .{};
settings.cc[VMIN] = 1;
settings.cc[VSTOP] = 0x13; // XOFF
settings.cc[VSTART] = 0x11; // XON
settings.cc[VTIME] = 0;
try std.posix.tcsetattr(port.handle, .NOW, settings);
if (builtin.os.tag == .macos and macos_nonstandard_baud) {
const IOSSIOSPEED: c_uint = 0x80085402;
const speed: c_uint = @intCast(config.baud_rate);
if (std.c.ioctl(port.handle, @bitCast(IOSSIOSPEED), &speed) == -1) {
return error.UnsupportedBaudRate;
}
}
},
else => @compileError("unsupported OS, please implement!"),
}
}
const Flush = enum {
input,
output,
both,
};
/// Flushes the serial port `port`. If `input` is set, all pending data in
/// the receive buffer is flushed, if `output` is set all pending data in
/// the send buffer is flushed.
pub fn flushSerialPort(port: std.Io.File, flush: Flush) !void {
switch (builtin.os.tag) {
.windows => {
const mode: std.os.windows.DWORD = switch (flush) {
.input => PURGE_RXCLEAR,
.output => PURGE_TXCLEAR,
.both => PURGE_TXCLEAR | PURGE_RXCLEAR,
};
if (PurgeComm(port.handle, mode) == std.os.windows.BOOL.FALSE)
return error.FlushError;
},
.linux => {
const TCFLSH = 0x540B;
const mode: usize = switch (flush) {
.input => 0, // TCIFLUSH
.output => 1, // TCOFLUSH
.both => 2, // TCIOFLUSH
};
if (0 != std.os.linux.syscall3(.ioctl, @as(usize, @bitCast(@as(isize, port.handle))), TCFLSH, mode))
return error.FlushError;
},
.macos => {
const TCIFLUSH = 1;
const TCOFLUSH = 2;
const TCIOFLUSH = 3;
const tcflush = @extern(fn (c_int, c_int) c_int, .{ .name = "tcflush" });
const mode: c_int = switch (flush) {
.input => TCIFLUSH,
.output => TCOFLUSH,
.both => TCIOFLUSH,
};
if (0 != tcflush(port.handle, mode))
return error.FlushError;
},
else => @compileError("unsupported OS, please implement!"),
}
}
pub const ControlPins = struct {
rts: ?bool = null,
dtr: ?bool = null,
};
pub fn changeControlPins(port: std.Io.File, pins: ControlPins) !void {
switch (builtin.os.tag) {
.windows => {
const CLRDTR = 6;
const CLRRTS = 4;
const SETDTR = 5;
const SETRTS = 3;
if (pins.dtr) |dtr| {
if (EscapeCommFunction(port.handle, if (dtr) SETDTR else CLRDTR) == 0)
return error.WindowsError;
}
if (pins.rts) |rts| {
if (EscapeCommFunction(port.handle, if (rts) SETRTS else CLRRTS) == 0)
return error.WindowsError;