]> sigrok.org Git - libserialport.git/blame - examples/port_info.c
Add examples directory with two example programs.
[libserialport.git] / examples / port_info.c
CommitLineData
8c1a14e6
ML
1#include <libserialport.h>
2#include <stdio.h>
3
4/* Example of how to get information about a serial port. */
5
6int main(int argc, char **argv)
7{
8 /* Get the port name from the command line. */
9 if (argc != 2) {
10 printf("Usage: %s <port name>\n", argv[0]);
11 return -1;
12 }
13 char *port_name = argv[1];
14
15 /* A pointer to a struct sp_port, which will refer to
16 * the port found. */
17 struct sp_port *port;
18
19 printf("Looking for port %s.\n", port_name);
20
21 /* Call sp_get_port_by_name() to find the port. The port
22 * pointer will be updated to refer to the port found. */
23 enum sp_return result = sp_get_port_by_name(port_name, &port);
24
25 if (result != SP_OK)
26 {
27 printf("sp_get_port_by_name() failed!\n");
28 return -1;
29 }
30
31 /* Display some basic information about the port. */
32 printf("Port name: %s\n", sp_get_port_name(port));
33 printf("Description: %s\n", sp_get_port_description(port));
34
35 /* Identify the transport which this port is connected through,
36 * e.g. native port, USB or Bluetooth. */
37 enum sp_transport transport = sp_get_port_transport(port);
38
39 if (transport == SP_TRANSPORT_NATIVE)
40 {
41 /* This is a "native" port, usually directly connected
42 * to the system rather than some external interface. */
43 printf("Type: Native\n");
44 }
45 else if (transport == SP_TRANSPORT_USB)
46 {
47 /* This is a USB to serial converter of some kind. */
48 printf("Type: USB\n");
49
50 /* Display string information from the USB descriptors. */
51 printf("Manufacturer: %s\n", sp_get_port_usb_manufacturer(port));
52 printf("Product: %s\n", sp_get_port_usb_product(port));
53 printf("Serial: %s\n", sp_get_port_usb_serial(port));
54
55 /* Display USB vendor and product IDs. */
56 int usb_vid, usb_pid;
57 sp_get_port_usb_vid_pid(port, &usb_vid, &usb_pid);
58 printf("VID: %04X PID: %04X\n", usb_vid, usb_pid);
59
60 /* Display bus and address. */
61 int usb_bus, usb_address;
62 sp_get_port_usb_bus_address(port, &usb_bus, &usb_address);
63 printf("Bus: %d Address: %d\n", usb_bus, usb_address);
64 }
65 else if (transport == SP_TRANSPORT_BLUETOOTH)
66 {
67 /* This is a Bluetooth serial port. */
68 printf("Type: Bluetooth\n");
69
70 /* Display Bluetooth MAC address. */
71 printf("MAC: %s\n", sp_get_port_bluetooth_address(port));
72 }
73
74 printf("Freeing port.\n");
75
76 /* Free the port structure created by sp_get_port_by_name(). */
77 sp_free_port(port);
78
79 /* Note that this will also free the port name and other
80 * strings retrieved from the port structure. If you want
81 * to keep these, copy them before freeing the port. */
82
83 return 0;
84}