diff --git a/vendor/github.com/mikepb/go-serial/README.md b/vendor/github.com/mikepb/go-serial/README.md new file mode 100644 index 0000000..c2eaf65 --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/README.md @@ -0,0 +1,81 @@ +# Go Serial + +[![GoDoc](https://godoc.org/github.com/mikepb/go-serial?status.svg)](https://godoc.org/github.com/mikepb/go-serial) + +Package serial provides a binding to libserialport for serial port +functionality. Serial ports are commonly used with embedded systems, +such as the Arduino platform. + +## Usage + +```go +package main + +import ( + "github.com/mikepb/go-serial" + "log" +) + +func main() { + options := serial.RawOptions + options.BitRate = 115200 + p, err := options.Open("/dev/tty") + if err != nil { + log.Panic(err) + } + + defer p.Close() + + buf := make([]byte, 1) + if c, err := p.Read(buf); err != nil { + log.Panic(err) + } else { + log.Println(buf) + } +} +``` + +## Documentation + +https://godoc.org/github.com/mikepb/go-serial + + +## License + + Copyright 2014 Michael Phan-Ba + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Files from the libserialport library are licensed under the GNU Lesser General +Public License. These files include in the header the notice that follows. + + This file is part of the libserialport project. + + Copyright (C) 2010-2012 Bert Vermeulen + Copyright (C) 2010-2012 Uwe Hermann + Copyright (C) 2013-2014 Martin Ling + Copyright (C) 2013 Matthias Heidbrink + Copyright (C) 2014 Aurelien Jacobs + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . diff --git a/vendor/github.com/mikepb/go-serial/libserialport.h b/vendor/github.com/mikepb/go-serial/libserialport.h new file mode 100644 index 0000000..64f4e9f --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/libserialport.h @@ -0,0 +1,1430 @@ +/* + * This file is part of the libserialport project. + * + * Copyright (C) 2013 Martin Ling + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/** + * @mainpage libserialport API + * + * Introduction + * ============ + * + * libserialport is a minimal library written in C that is intended to take + * care of the OS-specific details when writing software that uses serial ports. + * + * By writing your serial code to use libserialport, you enable it to work + * transparently on any platform supported by the library. + * + * The operations that are supported are: + * + * - @ref Enumeration (obtaining a list of serial ports on the system) + * - @ref Ports + * - @ref Configuration (baud rate, parity, etc.) + * - @ref Signals (modem control lines, breaks, etc.) + * - @ref Data + * - @ref Waiting + * - @ref Errors + * + * libserialport is an open source project released under the LGPL3+ license. + * + * API principles + * ============== + * + * The API is simple, and designed to be a minimal wrapper around the serial + * port support in each OS. + * + * Most functions take a pointer to a struct sp_port, which represents a serial + * port. These structures are always allocated and freed by the library, using + * the functions in the @ref Enumeration "Enumeration" section. + * + * Most functions have return type @ref sp_return and can return only four + * possible error values: + * + * - @ref SP_ERR_ARG means that a function was called with invalid + * arguments. This implies a bug in the caller. The arguments passed would + * be invalid regardless of the underlying OS or serial device involved. + * + * - @ref SP_ERR_FAIL means that the OS reported a failure. The error code or + * message provided by the OS can be obtained by calling sp_last_error_code() + * or sp_last_error_message(). + * + * - @ref SP_ERR_SUPP indicates that there is no support for the requested + * operation in the current OS, driver or device. No error message is + * available from the OS in this case. There is either no way to request + * the operation in the first place, or libserialport does not know how to + * do so in the current version. + * + * - @ref SP_ERR_MEM indicates that a memory allocation failed. + * + * All of these error values are negative. + * + * Calls that succeed return @ref SP_OK, which is equal to zero. Some functions + * declared @ref sp_return can also return a positive value for a successful + * numeric result, e.g. sp_blocking_read() or sp_blocking_write(). + */ + +#ifndef LIBSERIALPORT_LIBSERIALPORT_H +#define LIBSERIALPORT_LIBSERIALPORT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#ifdef _WIN32 +#include +#endif + +/** Return values. */ +enum sp_return { + /** Operation completed successfully. */ + SP_OK = 0, + /** Invalid arguments were passed to the function. */ + SP_ERR_ARG = -1, + /** A system error occured while executing the operation. */ + SP_ERR_FAIL = -2, + /** A memory allocation failed while executing the operation. */ + SP_ERR_MEM = -3, + /** The requested operation is not supported by this system or device. */ + SP_ERR_SUPP = -4 +}; + +/** Port access modes. */ +enum sp_mode { + /** Open port for read access. */ + SP_MODE_READ = 1, + /** Open port for write access. */ + SP_MODE_WRITE = 2, + /** Open port for read and write access. */ + SP_MODE_READ_WRITE = 3 +}; + +/** Port events. */ +enum sp_event { + /* Data received and ready to read. */ + SP_EVENT_RX_READY = 1, + /* Ready to transmit new data. */ + SP_EVENT_TX_READY = 2, + /* Error occured. */ + SP_EVENT_ERROR = 4 +}; + +/** Buffer selection. */ +enum sp_buffer { + /** Input buffer. */ + SP_BUF_INPUT = 1, + /** Output buffer. */ + SP_BUF_OUTPUT = 2, + /** Both buffers. */ + SP_BUF_BOTH = 3 +}; + +/** Parity settings. */ +enum sp_parity { + /** Special value to indicate setting should be left alone. */ + SP_PARITY_INVALID = -1, + /** No parity. */ + SP_PARITY_NONE = 0, + /** Odd parity. */ + SP_PARITY_ODD = 1, + /** Even parity. */ + SP_PARITY_EVEN = 2, + /** Mark parity. */ + SP_PARITY_MARK = 3, + /** Space parity. */ + SP_PARITY_SPACE = 4 +}; + +/** RTS pin behaviour. */ +enum sp_rts { + /** Special value to indicate setting should be left alone. */ + SP_RTS_INVALID = -1, + /** RTS off. */ + SP_RTS_OFF = 0, + /** RTS on. */ + SP_RTS_ON = 1, + /** RTS used for flow control. */ + SP_RTS_FLOW_CONTROL = 2 +}; + +/** CTS pin behaviour. */ +enum sp_cts { + /** Special value to indicate setting should be left alone. */ + SP_CTS_INVALID = -1, + /** CTS ignored. */ + SP_CTS_IGNORE = 0, + /** CTS used for flow control. */ + SP_CTS_FLOW_CONTROL = 1 +}; + +/** DTR pin behaviour. */ +enum sp_dtr { + /** Special value to indicate setting should be left alone. */ + SP_DTR_INVALID = -1, + /** DTR off. */ + SP_DTR_OFF = 0, + /** DTR on. */ + SP_DTR_ON = 1, + /** DTR used for flow control. */ + SP_DTR_FLOW_CONTROL = 2 +}; + +/** DSR pin behaviour. */ +enum sp_dsr { + /** Special value to indicate setting should be left alone. */ + SP_DSR_INVALID = -1, + /** DSR ignored. */ + SP_DSR_IGNORE = 0, + /** DSR used for flow control. */ + SP_DSR_FLOW_CONTROL = 1 +}; + +/** XON/XOFF flow control behaviour. */ +enum sp_xonxoff { + /** Special value to indicate setting should be left alone. */ + SP_XONXOFF_INVALID = -1, + /** XON/XOFF disabled. */ + SP_XONXOFF_DISABLED = 0, + /** XON/XOFF enabled for input only. */ + SP_XONXOFF_IN = 1, + /** XON/XOFF enabled for output only. */ + SP_XONXOFF_OUT = 2, + /** XON/XOFF enabled for input and output. */ + SP_XONXOFF_INOUT = 3 +}; + +/** Standard flow control combinations. */ +enum sp_flowcontrol { + /** No flow control. */ + SP_FLOWCONTROL_NONE = 0, + /** Software flow control using XON/XOFF characters. */ + SP_FLOWCONTROL_XONXOFF = 1, + /** Hardware flow control using RTS/CTS signals. */ + SP_FLOWCONTROL_RTSCTS = 2, + /** Hardware flow control using DTR/DSR signals. */ + SP_FLOWCONTROL_DTRDSR = 3 +}; + +/** Input signals. */ +enum sp_signal { + /** Clear to send. */ + SP_SIG_CTS = 1, + /** Data set ready. */ + SP_SIG_DSR = 2, + /** Data carrier detect. */ + SP_SIG_DCD = 4, + /** Ring indicator. */ + SP_SIG_RI = 8 +}; + +/** Transport types. */ +enum sp_transport { + /** Native platform serial port. */ + SP_TRANSPORT_NATIVE, + /** USB serial port adapter. */ + SP_TRANSPORT_USB, + /** Bluetooth serial port adapter. */ + SP_TRANSPORT_BLUETOOTH +}; + +/** + * @struct sp_port + * An opaque structure representing a serial port. + */ +struct sp_port; + +/** + * @struct sp_port_config + * An opaque structure representing the configuration for a serial port. + */ +struct sp_port_config; + +/** + * @struct sp_event_set + * A set of handles to wait on for events. + */ +struct sp_event_set { + /** Array of OS-specific handles. */ + void *handles; + /** Array of bitmasks indicating which events apply for each handle. */ + enum sp_event *masks; + /** Number of handles. */ + unsigned int count; +}; + +/** +@defgroup Enumeration Port enumeration +@{ +*/ + +/** + * Obtain a pointer to a new sp_port structure representing the named port. + * + * The user should allocate a variable of type "struct sp_port *" and pass a + * pointer to this to receive the result. + * + * The result should be freed after use by calling sp_free_port(). + * + * If any error is returned, the variable pointed to by port_ptr will be set + * to NULL. Otherwise, it will be set to point to the newly allocated port. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr); + +/** + * Free a port structure obtained from sp_get_port_by_name() or sp_copy_port(). + * + * @since 0.1.0 + */ +void sp_free_port(struct sp_port *port); + +/** + * List the serial ports available on the system. + * + * The result obtained is an array of pointers to sp_port structures, + * terminated by a NULL. The user should allocate a variable of type + * "struct sp_port **" and pass a pointer to this to receive the result. + * + * The result should be freed after use by calling sp_free_port_list(). + * If a port from the list is to be used after freeing the list, it must be + * copied first using sp_copy_port(). + * + * If any error is returned, the variable pointed to by list_ptr will be set + * to NULL. Otherwise, it will be set to point to the newly allocated array. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_list_ports(struct sp_port ***list_ptr); + +/** + * Make a new copy of a sp_port structure. + * + * The user should allocate a variable of type "struct sp_port *" and pass a + * pointer to this to receive the result. + * + * The copy should be freed after use by calling sp_free_port(). + * + * If any error is returned, the variable pointed to by copy_ptr will be set + * to NULL. Otherwise, it will be set to point to the newly allocated copy. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr); + +/** + * Free a port list obtained from sp_list_ports(). + * + * This will also free all the sp_port structures referred to from the list; + * any that are to be retained must be copied first using sp_copy_port(). + * + * @since 0.1.0 + */ +void sp_free_port_list(struct sp_port **ports); + +/** + * @} + * @defgroup Ports Opening, closing and querying ports + * @{ + */ + +/** + * Open the specified serial port. + * + * @param port Pointer to port structure. + * @param flags Flags to use when opening the serial port. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_open(struct sp_port *port, enum sp_mode flags); + +/** + * Close the specified serial port. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_close(struct sp_port *port); + +/** + * Get the name of a port. + * + * The name returned is whatever is normally used to refer to a port on the + * current operating system; e.g. for Windows it will usually be a "COMn" + * device name, and for Unix it will be a device path beginning with "/dev/". + * + * @param port Pointer to port structure. + * + * @return The port name, or NULL if an invalid port is passed. The name + * string is part of the port structure and may not be used after the + * port structure has been freed. + * + * @since 0.1.0 + */ +char *sp_get_port_name(const struct sp_port *port); + +/** + * Get a description for a port, to present to end user. + * + * @param port Pointer to port structure. + * + * @return The port description, or NULL if an invalid port is passed. + * The description string is part of the port structure and may not be used + * after the port structure has been freed. + * + * @since 0.2.0 + */ +char *sp_get_port_description(struct sp_port *port); + +/** + * Get the transport type used by a port. + * + * @param port Pointer to port structure. + * + * @return The port transport type. + * + * @since 0.2.0 + */ +enum sp_transport sp_get_port_transport(struct sp_port *port); + +/** + * Get the USB bus number and address on bus of a USB serial adapter port. + * + * @param port Pointer to port structure. + * @param usb_bus Pointer to variable to store USB bus. + * @param usb_address Pointer to variable to store USB address + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.2.0 + */ +enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port, + int *usb_bus, int *usb_address); + +/** + * Get the USB Vendor ID and Product ID of a USB serial adapter port. + * + * @param port Pointer to port structure. + * @param usb_vid Pointer to variable to store USB VID. + * @param usb_pid Pointer to variable to store USB PID + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.2.0 + */ +enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port, int *usb_vid, int *usb_pid); + +/** + * Get the USB manufacturer string of a USB serial adapter port. + * + * @param port Pointer to port structure. + * + * @return The port manufacturer string, or NULL if an invalid port is passed. + * The manufacturer string is part of the port structure and may not be used + * after the port structure has been freed. + * + * @since 0.2.0 + */ +char *sp_get_port_usb_manufacturer(const struct sp_port *port); + +/** + * Get the USB product string of a USB serial adapter port. + * + * @param port Pointer to port structure. + * + * @return The port product string, or NULL if an invalid port is passed. + * The product string is part of the port structure and may not be used + * after the port structure has been freed. + * + * @since 0.2.0 + */ +char *sp_get_port_usb_product(const struct sp_port *port); + +/** + * Get the USB serial number string of a USB serial adapter port. + * + * @param port Pointer to port structure. + * + * @return The port serial number, or NULL if an invalid port is passed. + * The serial number string is part of the port structure and may not be used + * after the port structure has been freed. + * + * @since 0.2.0 + */ +char *sp_get_port_usb_serial(const struct sp_port *port); + +/** + * Get the MAC address of a Bluetooth serial adapter port. + * + * @param port Pointer to port structure. + * + * @return The port MAC address, or NULL if an invalid port is passed. + * The MAC address string is part of the port structure and may not be used + * after the port structure has been freed. + * + * @since 0.2.0 + */ +char *sp_get_port_bluetooth_address(const struct sp_port *port); + +/** + * Get the operating system handle for a port. + * + * The type of the handle depends on the operating system. On Unix based + * systems, the handle is a file descriptor of type "int". On Windows, the + * handle is of type "HANDLE". The user should allocate a variable of the + * appropriate type and pass a pointer to this to receive the result. + * + * To obtain a valid handle, the port must first be opened by calling + * sp_open() using the same port structure. + * + * After the port is closed or the port structure freed, the handle may + * no longer be valid. + * + * @warning This feature is provided so that programs may make use of + * OS-specific functionality where desired. Doing so obviously + * comes at a cost in portability. It also cannot be guaranteed + * that direct usage of the OS handle will not conflict with the + * library's own usage of the port. Be careful. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr); + +/** + * @} + * @defgroup Configuration Setting port parameters + * @{ + */ + +/** + * Allocate a port configuration structure. + * + * The user should allocate a variable of type "struct sp_config *" and pass a + * pointer to this to receive the result. The variable will be updated to + * point to the new configuration structure. The structure is opaque and must + * be accessed via the functions provided. + * + * All parameters in the structure will be initialised to special values which + * are ignored by sp_set_config(). + * + * The structure should be freed after use by calling sp_free_config(). + * + * @param config_ptr Pointer to variable to receive result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_new_config(struct sp_port_config **config_ptr); + +/** + * Free a port configuration structure. + * + * @param config Pointer to configuration structure. + * + * @since 0.1.0 + */ +void sp_free_config(struct sp_port_config *config); + +/** + * Get the current configuration of the specified serial port. + * + * The user should allocate a configuration structure using sp_new_config() + * and pass this as the config parameter. The configuration structure will + * be updated with the port configuration. + * + * Any parameters that are configured with settings not recognised or + * supported by libserialport, will be set to special values that are + * ignored by sp_set_config(). + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config); + +/** + * Set the configuration for the specified serial port. + * + * For each parameter in the configuration, there is a special value (usually + * -1, but see the documentation for each field). These values will be ignored + * and the corresponding setting left unchanged on the port. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config); + +/** + * Set the baud rate for the specified serial port. + * + * @param port Pointer to port structure. + * @param baudrate Baud rate in bits per second. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_baudrate(struct sp_port *port, int baudrate); + +/** + * Get the baud rate from a port configuration. + * + * The user should allocate a variable of type int and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param baudrate_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_baudrate(const struct sp_port_config *config, int *baudrate_ptr); + +/** + * Set the baud rate in a port configuration. + * + * @param config Pointer to configuration structure. + * @param baudrate Baud rate in bits per second, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_baudrate(struct sp_port_config *config, int baudrate); + +/** + * Set the data bits for the specified serial port. + * + * @param port Pointer to port structure. + * @param bits Number of data bits. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_bits(struct sp_port *port, int bits); + +/** + * Get the data bits from a port configuration. + * + * The user should allocate a variable of type int and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param bits_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_bits(const struct sp_port_config *config, int *bits_ptr); + +/** + * Set the data bits in a port configuration. + * + * @param config Pointer to configuration structure. + * @param bits Number of data bits, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_bits(struct sp_port_config *config, int bits); + +/** + * Set the parity setting for the specified serial port. + * + * @param port Pointer to port structure. + * @param parity Parity setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_parity(struct sp_port *port, enum sp_parity parity); + +/** + * Get the parity setting from a port configuration. + * + * The user should allocate a variable of type enum sp_parity and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param parity_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_parity(const struct sp_port_config *config, enum sp_parity *parity_ptr); + +/** + * Set the parity setting in a port configuration. + * + * @param config Pointer to configuration structure. + * @param parity Parity setting, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_parity(struct sp_port_config *config, enum sp_parity parity); + +/** + * Set the stop bits for the specified serial port. + * + * @param port Pointer to port structure. + * @param stopbits Number of stop bits. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_stopbits(struct sp_port *port, int stopbits); + +/** + * Get the stop bits from a port configuration. + * + * The user should allocate a variable of type int and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param stopbits_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_stopbits(const struct sp_port_config *config, int *stopbits_ptr); + +/** + * Set the stop bits in a port configuration. + * + * @param config Pointer to configuration structure. + * @param stopbits Number of stop bits, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_stopbits(struct sp_port_config *config, int stopbits); + +/** + * Set the RTS pin behaviour for the specified serial port. + * + * @param port Pointer to port structure. + * @param rts RTS pin mode. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_rts(struct sp_port *port, enum sp_rts rts); + +/** + * Get the RTS pin behaviour from a port configuration. + * + * The user should allocate a variable of type enum sp_rts and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param rts_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_rts(const struct sp_port_config *config, enum sp_rts *rts_ptr); + +/** + * Set the RTS pin behaviour in a port configuration. + * + * @param config Pointer to configuration structure. + * @param rts RTS pin mode, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_rts(struct sp_port_config *config, enum sp_rts rts); + +/** + * Set the CTS pin behaviour for the specified serial port. + * + * @param port Pointer to port structure. + * @param cts CTS pin mode. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_cts(struct sp_port *port, enum sp_cts cts); + +/** + * Get the CTS pin behaviour from a port configuration. + * + * The user should allocate a variable of type enum sp_cts and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param cts_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_cts(const struct sp_port_config *config, enum sp_cts *cts_ptr); + +/** + * Set the CTS pin behaviour in a port configuration. + * + * @param config Pointer to configuration structure. + * @param cts CTS pin mode, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_cts(struct sp_port_config *config, enum sp_cts cts); + +/** + * Set the DTR pin behaviour for the specified serial port. + * + * @param port Pointer to port structure. + * @param dtr DTR pin mode. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_dtr(struct sp_port *port, enum sp_dtr dtr); + +/** + * Get the DTR pin behaviour from a port configuration. + * + * The user should allocate a variable of type enum sp_dtr and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param dtr_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_dtr(const struct sp_port_config *config, enum sp_dtr *dtr_ptr); + +/** + * Set the DTR pin behaviour in a port configuration. + * + * @param config Pointer to configuration structure. + * @param dtr DTR pin mode, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_dtr(struct sp_port_config *config, enum sp_dtr dtr); + +/** + * Set the DSR pin behaviour for the specified serial port. + * + * @param port Pointer to port structure. + * @param dsr DSR pin mode. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_dsr(struct sp_port *port, enum sp_dsr dsr); + +/** + * Get the DSR pin behaviour from a port configuration. + * + * The user should allocate a variable of type enum sp_dsr and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param dsr_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_dsr(const struct sp_port_config *config, enum sp_dsr *dsr_ptr); + +/** + * Set the DSR pin behaviour in a port configuration. + * + * @param config Pointer to configuration structure. + * @param dsr DSR pin mode, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_dsr(struct sp_port_config *config, enum sp_dsr dsr); + +/** + * Set the XON/XOFF configuration for the specified serial port. + * + * @param port Pointer to port structure. + * @param xon_xoff XON/XOFF mode. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_xon_xoff(struct sp_port *port, enum sp_xonxoff xon_xoff); + +/** + * Get the XON/XOFF configuration from a port configuration. + * + * The user should allocate a variable of type enum sp_xonxoff and pass a pointer to this + * to receive the result. + * + * @param config Pointer to configuration structure. + * @param xon_xoff_ptr Pointer to variable to store result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_config_xon_xoff(const struct sp_port_config *config, enum sp_xonxoff *xon_xoff_ptr); + +/** + * Set the XON/XOFF configuration in a port configuration. + * + * @param config Pointer to configuration structure. + * @param xon_xoff XON/XOFF mode, or -1 to retain current setting. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_xon_xoff(struct sp_port_config *config, enum sp_xonxoff xon_xoff); + +/** + * Set the flow control type in a port configuration. + * + * This function is a wrapper that sets the RTS, CTS, DTR, DSR and + * XON/XOFF settings as necessary for the specified flow control + * type. For more fine-grained control of these settings, use their + * individual configuration functions. + * + * @param config Pointer to configuration structure. + * @param flowcontrol Flow control setting to use. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol); + +/** + * Set the flow control type for the specified serial port. + * + * This function is a wrapper that sets the RTS, CTS, DTR, DSR and + * XON/XOFF settings as necessary for the specified flow control + * type. For more fine-grained control of these settings, use their + * individual configuration functions. + * + * @param port Pointer to port structure. + * @param flowcontrol Flow control setting to use. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol); + +/** + * @} + * @defgroup Data Reading, writing, and flushing data + * @{ +*/ + +/** + * Read bytes from the specified serial port, blocking until complete. + * + * @warning If your program runs on Unix, defines its own signal handlers, and + * needs to abort blocking reads when these are called, then you + * should not use this function. It repeats system calls that return + * with EINTR. To be able to abort a read from a signal handler, you + * should implement your own blocking read using sp_nonblocking_read() + * together with a blocking method that makes sense for your program. + * E.g. you can obtain the file descriptor for an open port using + * sp_get_port_handle() and use this to call select() or pselect(), + * with appropriate arrangements to return if a signal is received. + * + * @param port Pointer to port structure. + * @param buf Buffer in which to store the bytes read. + * @param count Requested number of bytes to read. + * @param timeout Timeout in milliseconds, or zero to wait indefinitely. + * + * @return The number of bytes read on success, or a negative error code. If + * the number of bytes returned is less than that requested, the + * timeout was reached before the requested number of bytes was + * available. If timeout is zero, the function will always return + * either the requested number of bytes or a negative error code. + * + * @since 0.1.0 + */ +enum sp_return sp_blocking_read(struct sp_port *port, void *buf, size_t count, unsigned int timeout); + +/** + * Read bytes from the specified serial port, without blocking. + * + * @param port Pointer to port structure. + * @param buf Buffer in which to store the bytes read. + * @param count Maximum number of bytes to read. + * + * @return The number of bytes read on success, or a negative error code. The + * number of bytes returned may be any number from zero to the maximum + * that was requested. + * + * @since 0.1.0 + */ +enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf, size_t count); + +/** + * Write bytes to the specified serial port, blocking until complete. + * + * Note that this function only ensures that the accepted bytes have been + * written to the OS; they may be held in driver or hardware buffers and not + * yet physically transmitted. To check whether all written bytes have actually + * been transmitted, use the sp_output_waiting() function. To wait until all + * written bytes have actually been transmitted, use the sp_drain() function. + * + * @warning If your program runs on Unix, defines its own signal handlers, and + * needs to abort blocking writes when these are called, then you + * should not use this function. It repeats system calls that return + * with EINTR. To be able to abort a write from a signal handler, you + * should implement your own blocking write using sp_nonblocking_write() + * together with a blocking method that makes sense for your program. + * E.g. you can obtain the file descriptor for an open port using + * sp_get_port_handle() and use this to call select() or pselect(), + * with appropriate arrangements to return if a signal is received. + * + * @param port Pointer to port structure. + * @param buf Buffer containing the bytes to write. + * @param count Requested number of bytes to write. + * @param timeout Timeout in milliseconds, or zero to wait indefinitely. + * + * @return The number of bytes written on success, or a negative error code. + * If the number of bytes returned is less than that requested, the + * timeout was reached before the requested number of bytes was + * written. If timeout is zero, the function will always return + * either the requested number of bytes or a negative error code. In + * the event of an error there is no way to determine how many bytes + * were sent before the error occured. + * + * @since 0.1.0 + */ +enum sp_return sp_blocking_write(struct sp_port *port, const void *buf, size_t count, unsigned int timeout); + +/** + * Write bytes to the specified serial port, without blocking. + * + * Note that this function only ensures that the accepted bytes have been + * written to the OS; they may be held in driver or hardware buffers and not + * yet physically transmitted. To check whether all written bytes have actually + * been transmitted, use the sp_output_waiting() function. To wait until all + * written bytes have actually been transmitted, use the sp_drain() function. + * + * @param port Pointer to port structure. + * @param buf Buffer containing the bytes to write. + * @param count Maximum number of bytes to write. + * + * @return The number of bytes written on success, or a negative error code. + * The number of bytes returned may be any number from zero to the + * maximum that was requested. + * + * @since 0.1.0 + */ +enum sp_return sp_nonblocking_write(struct sp_port *port, const void *buf, size_t count); + +/** + * Gets the number of bytes waiting in the input buffer. + * + * @param port Pointer to port structure. + * + * @return Number of bytes waiting on success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_input_waiting(struct sp_port *port); + +/** + * Gets the number of bytes waiting in the output buffer. + * + * @param port Pointer to port structure. + * + * @return Number of bytes waiting on success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_output_waiting(struct sp_port *port); + +/** + * Flush serial port buffers. Data in the selected buffer(s) is discarded. + * + * @param port Pointer to port structure. + * @param buffers Which buffer(s) to flush. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers); + +/** + * Wait for buffered data to be transmitted. + * + * @warning If your program runs on Unix, defines its own signal handlers, and + * needs to abort draining the output buffer when when these are + * called, then you should not use this function. It repeats system + * calls that return with EINTR. To be able to abort a drain from a + * signal handler, you would need to implement your own blocking + * drain by polling the result of sp_output_waiting(). + * + * @param port Pointer to port structure. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_drain(struct sp_port *port); + +/** + * @} + * @defgroup Waiting Waiting for events + * @{ + */ + +/** + * Allocate storage for a set of events. + * + * The user should allocate a variable of type struct sp_event_set *, + * then pass a pointer to this variable to receive the result. + * + * The result should be freed after use by calling sp_free_event_set(). + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_new_event_set(struct sp_event_set **result_ptr); + +/** + * Add events to a struct sp_event_set for a given port. + * + * The port must first be opened by calling sp_open() using the same port + * structure. + * + * After the port is closed or the port structure freed, the results may + * no longer be valid. + * + * @param event_set Event set to update. + * @param port Pointer to port structure. + * @param mask Bitmask of events to be waited for. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_add_port_events(struct sp_event_set *event_set, + const struct sp_port *port, enum sp_event mask); + +/** + * Wait for any of a set of events to occur. + * + * @param event_set Event set to wait on. + * @param timeout Timeout in milliseconds, or zero to wait indefinitely. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_wait(struct sp_event_set *event_set, unsigned int timeout); + +/** + * Free a structure allocated by sp_new_event_set(). + * + * @since 0.1.0 + */ +void sp_free_event_set(struct sp_event_set *event_set); + +/** + * @} + * @defgroup Signals Port signalling operations + * @{ + */ + +/** + * Gets the status of the control signals for the specified port. + * + * The user should allocate a variable of type "enum sp_signal" and pass a + * pointer to this variable to receive the result. The result is a bitmask + * in which individual signals can be checked by bitwise OR with values of + * the sp_signal enum. + * + * @param port Pointer to port structure. + * @param signal_mask Pointer to variable to receive result. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signal_mask); + +/** + * Put the port transmit line into the break state. + * + * @param port Pointer to port structure. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_start_break(struct sp_port *port); + +/** + * Take the port transmit line out of the break state. + * + * @param port Pointer to port structure. + * + * @return SP_OK upon success, a negative error code otherwise. + * + * @since 0.1.0 + */ +enum sp_return sp_end_break(struct sp_port *port); + +/** + * @} + * @defgroup Errors Obtaining error information + * @{ +*/ + +/** + * Get the error code for a failed operation. + * + * In order to obtain the correct result, this function should be called + * straight after the failure, before executing any other system operations. + * + * @return The system's numeric code for the error that caused the last + * operation to fail. + * + * @since 0.1.0 + */ +int sp_last_error_code(void); + +/** + * Get the error message for a failed operation. + * + * In order to obtain the correct result, this function should be called + * straight after the failure, before executing other system operations. + * + * @return The system's message for the error that caused the last + * operation to fail. This string may be allocated by the function, + * and should be freed after use by calling sp_free_error_message(). + * + * @since 0.1.0 + */ +char *sp_last_error_message(void); + +/** + * Free an error message returned by sp_last_error_message(). + * + * @since 0.1.0 + */ +void sp_free_error_message(char *message); + +/** + * Set the handler function for library debugging messages. + * + * Debugging messages are generated by the library during each operation, + * to help in diagnosing problems. The handler will be called for each + * message. The handler can be set to NULL to ignore all debug messages. + * + * The handler function should accept a format string and variable length + * argument list, in the same manner as e.g. printf(). + * + * The default handler is sp_default_debug_handler(). + * + * @since 0.1.0 + */ +void sp_set_debug_handler(void (*handler)(const char *format, ...)); + +/** + * Default handler function for library debugging messages. + * + * This function prints debug messages to the standard error stream if the + * environment variable LIBSERIALPORT_DEBUG is set. Otherwise, they are + * ignored. + * + * @since 0.1.0 + */ +void sp_default_debug_handler(const char *format, ...); + +/** @} */ + +/** + * @defgroup Versions Version number querying functions, definitions, and macros + * + * This set of API calls returns two different version numbers related + * to libserialport. The "package version" is the release version number of the + * libserialport tarball in the usual "major.minor.micro" format, e.g. "0.1.0". + * + * The "library version" is independent of that; it is the libtool version + * number in the "current:revision:age" format, e.g. "2:0:0". + * See http://www.gnu.org/software/libtool/manual/libtool.html#Libtool-versioning for details. + * + * Both version numbers (and/or individual components of them) can be + * retrieved via the API calls at runtime, and/or they can be checked at + * compile/preprocessor time using the respective macros. + * + * @{ + */ + +/* + * Package version macros (can be used for conditional compilation). + */ + +/** The libserialport package 'major' version number. */ +#define SP_PACKAGE_VERSION_MAJOR 0 + +/** The libserialport package 'minor' version number. */ +#define SP_PACKAGE_VERSION_MINOR 2 + +/** The libserialport package 'micro' version number. */ +#define SP_PACKAGE_VERSION_MICRO 0 + +/** The libserialport package version ("major.minor.micro") as string. */ +#define SP_PACKAGE_VERSION_STRING "0.2.0" + +/* + * Library/libtool version macros (can be used for conditional compilation). + */ + +/** The libserialport libtool 'current' version number. */ +#define SP_LIB_VERSION_CURRENT 0 + +/** The libserialport libtool 'revision' version number. */ +#define SP_LIB_VERSION_REVISION 0 + +/** The libserialport libtool 'age' version number. */ +#define SP_LIB_VERSION_AGE 0 + +/** The libserialport libtool version ("current:revision:age") as string. */ +#define SP_LIB_VERSION_STRING "0:0:0" + +/** + * Get the major libserialport package version number. + * + * @return The major package version number. + * + * @since 0.1.0 + */ +int sp_get_major_package_version(void); + +/** + * Get the minor libserialport package version number. + * + * @return The minor package version number. + * + * @since 0.1.0 + */ +int sp_get_minor_package_version(void); + +/** + * Get the micro libserialport package version number. + * + * @return The micro package version number. + * + * @since 0.1.0 + */ +int sp_get_micro_package_version(void); + +/** + * Get the libserialport package version number as a string. + * + * @return The package version number string. The returned string is + * static and thus should NOT be free'd by the caller. + * + * @since 0.1.0 + */ +const char *sp_get_package_version_string(void); + +/** + * Get the "current" part of the libserialport library version number. + * + * @return The "current" library version number. + * + * @since 0.1.0 + */ +int sp_get_current_lib_version(void); + +/** + * Get the "revision" part of the libserialport library version number. + * + * @return The "revision" library version number. + * + * @since 0.1.0 + */ +int sp_get_revision_lib_version(void); + +/** + * Get the "age" part of the libserialport library version number. + * + * @return The "age" library version number. + * + * @since 0.1.0 + */ +int sp_get_age_lib_version(void); + +/** + * Get the libserialport library version number as a string. + * + * @return The library version number string. The returned string is + * static and thus should NOT be free'd by the caller. + * + * @since 0.1.0 + */ +const char *sp_get_lib_version_string(void); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/vendor/github.com/mikepb/go-serial/libserialport_internal.h b/vendor/github.com/mikepb/go-serial/libserialport_internal.h new file mode 100644 index 0000000..28c3076 --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/libserialport_internal.h @@ -0,0 +1,229 @@ +/* + * This file is part of the libserialport project. + * + * Copyright (C) 2014 Martin Ling + * Copyright (C) 2014 Aurelien Jacobs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifdef __linux__ +#define _BSD_SOURCE // for timeradd, timersub, timercmp +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#include +#include +#include +#undef DEFINE_GUID +#define DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ + static const GUID name = { l,w1,w2,{ b1,b2,b3,b4,b5,b6,b7,b8 } } +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif +#ifdef __APPLE__ +#include +#include +#include +#include +#include +#endif +#ifdef __linux__ +#include +#ifndef __ANDROID__ +#include "linux/serial.h" +#endif +#include "linux_termios.h" + +/* TCGETX/TCSETX is not available everywhere. */ +#if defined(TCGETX) && defined(TCSETX) && defined(HAVE_TERMIOX) +#define USE_TERMIOX +#endif +#endif + +/* TIOCINQ/TIOCOUTQ is not available everywhere. */ +#if !defined(TIOCINQ) && defined(FIONREAD) +#define TIOCINQ FIONREAD +#endif +#if !defined(TIOCOUTQ) && defined(FIONWRITE) +#define TIOCOUTQ FIONWRITE +#endif + +/* Non-standard baudrates are not available everywhere. */ +#if (defined(HAVE_TERMIOS_SPEED) || defined(HAVE_TERMIOS2_SPEED)) && defined(HAVE_BOTHER) +#define USE_TERMIOS_SPEED +#endif + +struct sp_port { + char *name; + char *description; + enum sp_transport transport; + int usb_bus; + int usb_address; + int usb_vid; + int usb_pid; + char *usb_manufacturer; + char *usb_product; + char *usb_serial; + char *bluetooth_address; +#ifdef _WIN32 + char *usb_path; + HANDLE hdl; + COMMTIMEOUTS timeouts; + OVERLAPPED write_ovl; + OVERLAPPED read_ovl; + OVERLAPPED wait_ovl; + DWORD events; + BYTE pending_byte; + BOOL writing; +#else + int fd; +#endif +}; + +struct sp_port_config { + int baudrate; + int bits; + enum sp_parity parity; + int stopbits; + enum sp_rts rts; + enum sp_cts cts; + enum sp_dtr dtr; + enum sp_dsr dsr; + enum sp_xonxoff xon_xoff; +}; + +struct port_data { +#ifdef _WIN32 + DCB dcb; +#else + struct termios term; + int controlbits; + int termiox_supported; + int rts_flow; + int cts_flow; + int dtr_flow; + int dsr_flow; +#endif +}; + +#ifdef _WIN32 +typedef HANDLE event_handle; +#else +typedef int event_handle; +#endif + +/* Standard baud rates. */ +#ifdef _WIN32 +#define BAUD_TYPE DWORD +#define BAUD(n) {CBR_##n, n} +#else +#define BAUD_TYPE speed_t +#define BAUD(n) {B##n, n} +#endif + +struct std_baudrate { + BAUD_TYPE index; + int value; +}; + +extern const struct std_baudrate std_baudrates[]; + +#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) +#define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates) + +extern void (*sp_debug_handler)(const char *format, ...); + +/* Debug output macros. */ +#define DEBUG_FMT(fmt, ...) do { \ + if (sp_debug_handler) \ + sp_debug_handler(fmt ".\n", __VA_ARGS__); \ +} while (0) +#define DEBUG(msg) DEBUG_FMT(msg, NULL) +#define DEBUG_ERROR(err, msg) DEBUG_FMT("%s returning " #err ": " msg, __func__) +#define DEBUG_FAIL(msg) do { \ + char *errmsg = sp_last_error_message(); \ + DEBUG_FMT("%s returning SP_ERR_FAIL: " msg ": %s", __func__, errmsg); \ + sp_free_error_message(errmsg); \ +} while (0); +#define RETURN() do { \ + DEBUG_FMT("%s returning", __func__); \ + return; \ +} while(0) +#define RETURN_CODE(x) do { \ + DEBUG_FMT("%s returning " #x, __func__); \ + return x; \ +} while (0) +#define RETURN_CODEVAL(x) do { \ + switch (x) { \ + case SP_OK: RETURN_CODE(SP_OK); \ + case SP_ERR_ARG: RETURN_CODE(SP_ERR_ARG); \ + case SP_ERR_FAIL: RETURN_CODE(SP_ERR_FAIL); \ + case SP_ERR_MEM: RETURN_CODE(SP_ERR_MEM); \ + case SP_ERR_SUPP: RETURN_CODE(SP_ERR_SUPP); \ + } \ +} while (0) +#define RETURN_OK() RETURN_CODE(SP_OK); +#define RETURN_ERROR(err, msg) do { \ + DEBUG_ERROR(err, msg); \ + return err; \ +} while (0) +#define RETURN_FAIL(msg) do { \ + DEBUG_FAIL(msg); \ + return SP_ERR_FAIL; \ +} while (0) +#define RETURN_INT(x) do { \ + int _x = x; \ + DEBUG_FMT("%s returning %d", __func__, _x); \ + return _x; \ +} while (0) +#define RETURN_STRING(x) do { \ + char *_x = x; \ + DEBUG_FMT("%s returning %s", __func__, _x); \ + return _x; \ +} while (0) +#define RETURN_POINTER(x) do { \ + void *_x = x; \ + DEBUG_FMT("%s returning %p", __func__, _x); \ + return _x; \ +} while (0) +#define SET_ERROR(val, err, msg) do { DEBUG_ERROR(err, msg); val = err; } while (0) +#define SET_FAIL(val, msg) do { DEBUG_FAIL(msg); val = SP_ERR_FAIL; } while (0) +#define TRACE(fmt, ...) DEBUG_FMT("%s(" fmt ") called", __func__, __VA_ARGS__) +#define TRACE_VOID() DEBUG_FMT("%s() called", __func__) + +#define TRY(x) do { int ret = x; if (ret != SP_OK) RETURN_CODEVAL(ret); } while (0) + +SP_PRIV struct sp_port **list_append(struct sp_port **list, const char *portname); + +/* OS-specific Helper functions. */ +SP_PRIV enum sp_return get_port_details(struct sp_port *port); +SP_PRIV enum sp_return list_ports(struct sp_port ***list); diff --git a/vendor/github.com/mikepb/go-serial/linux.c b/vendor/github.com/mikepb/go-serial/linux.c new file mode 100644 index 0000000..204f0fe --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/linux.c @@ -0,0 +1,226 @@ +/* + * This file is part of the libserialport project. + * + * Copyright (C) 2014 Aurelien Jacobs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifdef __linux__ + +#include "libserialport.h" +#include "libserialport_internal.h" + +SP_PRIV enum sp_return get_port_details(struct sp_port *port) +{ + /* Description limited to 127 char, + anything longer would not be user friendly anyway */ + char description[128]; + int bus, address; + unsigned int vid, pid; + char manufacturer[128], product[128], serial[128]; + char baddr[32]; + const char dir_name[] = "/sys/class/tty/%s/device/%s%s"; + char sub_dir[32] = "", file_name[PATH_MAX]; + char *ptr, *dev = port->name + 5; + FILE *file; + int i, count; + + if (strncmp(port->name, "/dev/", 5)) + RETURN_ERROR(SP_ERR_ARG, "Device name not recognized."); + + snprintf(file_name, sizeof(file_name), "/sys/class/tty/%s", dev); + count = readlink(file_name, file_name, sizeof(file_name)); + if (count <= 0 || count >= (int) sizeof(file_name)-1) + RETURN_ERROR(SP_ERR_ARG, "Device not found."); + file_name[count] = 0; + if (strstr(file_name, "bluetooth")) + port->transport = SP_TRANSPORT_BLUETOOTH; + else if (strstr(file_name, "usb")) + port->transport = SP_TRANSPORT_USB; + + if (port->transport == SP_TRANSPORT_USB) { + for (i=0; i<5; i++) { + strcat(sub_dir, "../"); + + snprintf(file_name, sizeof(file_name), dir_name, dev, sub_dir, "busnum"); + if (!(file = fopen(file_name, "r"))) + continue; + count = fscanf(file, "%d", &bus); + fclose(file); + if (count != 1) + continue; + + snprintf(file_name, sizeof(file_name), dir_name, dev, sub_dir, "devnum"); + if (!(file = fopen(file_name, "r"))) + continue; + count = fscanf(file, "%d", &address); + fclose(file); + if (count != 1) + continue; + + snprintf(file_name, sizeof(file_name), dir_name, dev, sub_dir, "idVendor"); + if (!(file = fopen(file_name, "r"))) + continue; + count = fscanf(file, "%4x", &vid); + fclose(file); + if (count != 1) + continue; + + snprintf(file_name, sizeof(file_name), dir_name, dev, sub_dir, "idProduct"); + if (!(file = fopen(file_name, "r"))) + continue; + count = fscanf(file, "%4x", &pid); + fclose(file); + if (count != 1) + continue; + + port->usb_bus = bus; + port->usb_address = address; + port->usb_vid = vid; + port->usb_pid = pid; + + snprintf(file_name, sizeof(file_name), dir_name, dev, sub_dir, "product"); + if ((file = fopen(file_name, "r"))) { + if ((ptr = fgets(description, sizeof(description), file))) { + ptr = description + strlen(description) - 1; + if (ptr >= description && *ptr == '\n') + *ptr = 0; + port->description = strdup(description); + } + fclose(file); + } + if (!file || !ptr) + port->description = strdup(dev); + + snprintf(file_name, sizeof(file_name), dir_name, dev, sub_dir, "manufacturer"); + if ((file = fopen(file_name, "r"))) { + if ((ptr = fgets(manufacturer, sizeof(manufacturer), file))) { + ptr = manufacturer + strlen(manufacturer) - 1; + if (ptr >= manufacturer && *ptr == '\n') + *ptr = 0; + port->usb_manufacturer = strdup(manufacturer); + } + fclose(file); + } + + snprintf(file_name, sizeof(file_name), dir_name, dev, sub_dir, "product"); + if ((file = fopen(file_name, "r"))) { + if ((ptr = fgets(product, sizeof(product), file))) { + ptr = product + strlen(product) - 1; + if (ptr >= product && *ptr == '\n') + *ptr = 0; + port->usb_product = strdup(product); + } + fclose(file); + } + + snprintf(file_name, sizeof(file_name), dir_name, dev, sub_dir, "serial"); + if ((file = fopen(file_name, "r"))) { + if ((ptr = fgets(serial, sizeof(serial), file))) { + ptr = serial + strlen(serial) - 1; + if (ptr >= serial && *ptr == '\n') + *ptr = 0; + port->usb_serial = strdup(serial); + } + fclose(file); + } + + break; + } + } else { + port->description = strdup(dev); + + if (port->transport == SP_TRANSPORT_BLUETOOTH) { + snprintf(file_name, sizeof(file_name), dir_name, dev, "", "address"); + if ((file = fopen(file_name, "r"))) { + if ((ptr = fgets(baddr, sizeof(baddr), file))) { + ptr = baddr + strlen(baddr) - 1; + if (ptr >= baddr && *ptr == '\n') + *ptr = 0; + port->bluetooth_address = strdup(baddr); + } + fclose(file); + } + } + } + + RETURN_OK(); +} + +SP_PRIV enum sp_return list_ports(struct sp_port ***list) +{ + char name[PATH_MAX], target[PATH_MAX]; + struct dirent entry, *result; +#ifdef HAVE_SERIAL_STRUCT + struct serial_struct serial_info; + int ioctl_result; +#endif + char buf[sizeof(entry.d_name) + 16]; + int len, fd; + DIR *dir; + int ret = SP_OK; + + DEBUG("Enumerating tty devices"); + if (!(dir = opendir("/sys/class/tty"))) + RETURN_FAIL("could not open /sys/class/tty"); + + DEBUG("Iterating over results"); + while (!readdir_r(dir, &entry, &result) && result) { + snprintf(buf, sizeof(buf), "/sys/class/tty/%s", entry.d_name); + len = readlink(buf, target, sizeof(target)); + if (len <= 0 || len >= (int) sizeof(target)-1) + continue; + target[len] = 0; + if (strstr(target, "virtual")) + continue; + snprintf(name, sizeof(name), "/dev/%s", entry.d_name); + DEBUG_FMT("Found device %s", name); + if (strstr(target, "serial8250")) { + /* The serial8250 driver has a hardcoded number of ports. + * The only way to tell which actually exist on a given system + * is to try to open them and make an ioctl call. */ + DEBUG("serial8250 device, attempting to open"); + if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) { + DEBUG("open failed, skipping"); + continue; + } +#ifdef HAVE_SERIAL_STRUCT + ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info); +#endif + close(fd); +#ifdef HAVE_SERIAL_STRUCT + if (ioctl_result != 0) { + DEBUG("ioctl failed, skipping"); + continue; + } + if (serial_info.type == PORT_UNKNOWN) { + DEBUG("port type is unknown, skipping"); + continue; + } +#endif + } + DEBUG_FMT("Found port %s", name); + *list = list_append(*list, name); + if (!list) { + SET_ERROR(ret, SP_ERR_MEM, "list append failed"); + break; + } + } + closedir(dir); + + return ret; +} + +#endif diff --git a/vendor/github.com/mikepb/go-serial/linux_termios.c b/vendor/github.com/mikepb/go-serial/linux_termios.c new file mode 100644 index 0000000..b1e73b1 --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/linux_termios.c @@ -0,0 +1,132 @@ +/* + * This file is part of the libserialport project. + * + * Copyright (C) 2013 Martin Ling + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/* + * At the time of writing, glibc does not support the Linux kernel interfaces + * for setting non-standard baud rates and flow control. We therefore have to + * prepare the correct ioctls ourselves, for which we need the declarations in + * linux/termios.h. + * + * We can't include linux/termios.h in serialport.c however, because its + * contents conflict with the termios.h provided by glibc. So this file exists + * to isolate the bits of code which use the kernel termios declarations. + * + * The details vary by architecture. Some architectures have c_ispeed/c_ospeed + * in struct termios, accessed with TCSETS/TCGETS. Others have these fields in + * struct termios2, accessed with TCSETS2/TCGETS2. Some architectures have the + * TCSETX/TCGETX ioctls used with struct termiox, others do not. + */ + +#ifdef __linux__ + +#include +#include +#include "linux_termios.h" + +SP_PRIV unsigned long get_termios_get_ioctl(void) +{ +#ifdef HAVE_TERMIOS2 + return TCGETS2; +#else + return TCGETS; +#endif +} + +SP_PRIV unsigned long get_termios_set_ioctl(void) +{ +#ifdef HAVE_TERMIOS2 + return TCSETS2; +#else + return TCSETS; +#endif +} + +SP_PRIV size_t get_termios_size(void) +{ +#ifdef HAVE_TERMIOS2 + return sizeof(struct termios2); +#else + return sizeof(struct termios); +#endif +} + +#if (defined(HAVE_TERMIOS_SPEED) || defined(HAVE_TERMIOS2_SPEED)) && defined(HAVE_BOTHER) +SP_PRIV int get_termios_speed(void *data) +{ +#ifdef HAVE_TERMIOS2 + struct termios2 *term = (struct termios2 *) data; +#else + struct termios *term = (struct termios *) data; +#endif + if (term->c_ispeed != term->c_ospeed) + return -1; + else + return term->c_ispeed; +} + +SP_PRIV void set_termios_speed(void *data, int speed) +{ +#ifdef HAVE_TERMIOS2 + struct termios2 *term = (struct termios2 *) data; +#else + struct termios *term = (struct termios *) data; +#endif + term->c_cflag &= ~CBAUD; + term->c_cflag |= BOTHER; + term->c_ispeed = term->c_ospeed = speed; +} +#endif + +#ifdef HAVE_TERMIOX +SP_PRIV size_t get_termiox_size(void) +{ + return sizeof(struct termiox); +} + +SP_PRIV int get_termiox_flow(void *data, int *rts, int *cts, int *dtr, int *dsr) +{ + struct termiox *termx = (struct termiox *) data; + int flags = 0; + + *rts = (termx->x_cflag & RTSXOFF); + *cts = (termx->x_cflag & CTSXON); + *dtr = (termx->x_cflag & DTRXOFF); + *dsr = (termx->x_cflag & DSRXON); + + return flags; +} + +SP_PRIV void set_termiox_flow(void *data, int rts, int cts, int dtr, int dsr) +{ + struct termiox *termx = (struct termiox *) data; + + termx->x_cflag &= ~(RTSXOFF | CTSXON | DTRXOFF | DSRXON); + + if (rts) + termx->x_cflag |= RTSXOFF; + if (cts) + termx->x_cflag |= CTSXON; + if (dtr) + termx->x_cflag |= DTRXOFF; + if (dsr) + termx->x_cflag |= DSRXON; +} +#endif + +#endif diff --git a/vendor/github.com/mikepb/go-serial/linux_termios.h b/vendor/github.com/mikepb/go-serial/linux_termios.h new file mode 100644 index 0000000..ea8f9da --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/linux_termios.h @@ -0,0 +1,38 @@ +/* + * This file is part of the libserialport project. + * + * Copyright (C) 2013 Martin Ling + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifdef __linux__ + +#ifndef LIBSERIALPORT_LINUX_TERMIOS_H +#define LIBSERIALPORT_LINUX_TERMIOS_H + +#include + +SP_PRIV unsigned long get_termios_get_ioctl(void); +SP_PRIV unsigned long get_termios_set_ioctl(void); +SP_PRIV size_t get_termios_size(void); +SP_PRIV int get_termios_speed(void *data); +SP_PRIV void set_termios_speed(void *data, int speed); +SP_PRIV size_t get_termiox_size(void); +SP_PRIV int get_termiox_flow(void *data, int *rts, int *cts, int *dtr, int *dsr); +SP_PRIV void set_termiox_flow(void *data, int rts, int cts, int dtr, int dsr); + +#endif + +#endif diff --git a/vendor/github.com/mikepb/go-serial/listports/listports.go b/vendor/github.com/mikepb/go-serial/listports/listports.go new file mode 100644 index 0000000..1e3e596 --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/listports/listports.go @@ -0,0 +1,213 @@ +package main + +import ( + ".." + "log" + "time" +) + +func main() { + ports, err := serial.ListPorts() + if err != nil { + log.Panic(err) + } + + log.Printf("Found %d ports:\n", len(ports)) + + for _, info := range ports { + log.Println(info.Name()) + log.Println("\tName:", info.Name()) + log.Println("\tDescription:", info.Description()) + log.Println("\tTransport:", info.Transport()) + + if bus, addr, err := info.USBBusAddress(); err != nil { + log.Println("\tbus:", bus, "\taddr:", addr) + } else { + log.Println(err) + } + + if vid, pid, err := info.USBVIDPID(); err != nil { + log.Println("\tvid:", vid, "\tpid:", pid) + } else { + log.Println(err) + } + + log.Println("\tUSB Manufacturer:", info.USBManufacturer()) + log.Println("\tUSB Product:", info.USBProduct()) + log.Println("\tUSB Serial Number:", info.USBSerialNumber()) + log.Println("\tBluetooth Address:", info.BluetoothAddress()) + + port, err := info.Open() + if err != nil { + log.Println("\tOpen:", err) + continue + } + + log.Println("\tLocalAddr:", port.LocalAddr().String()) + log.Println("\tRemoteAddr:", port.RemoteAddr().String()) + + if bitrate, err := port.BitRate(); err != nil { + log.Println("\tBit Rate:", err) + } else { + log.Println("\tBit Rate:", bitrate) + } + + if databits, err := port.DataBits(); err != nil { + log.Println("\tData Bits:", err) + } else { + log.Println("\tData Bits:", databits) + } + + if parity, err := port.Parity(); err != nil { + log.Println("\tParity:", err) + } else { + log.Println("\tParity:", parity) + } + + if stopbits, err := port.StopBits(); err != nil { + log.Println("\tStop Bits:", err) + } else { + log.Println("\tStop Bits:", stopbits) + } + + if rts, err := port.RTS(); err != nil { + log.Println("\tRTS:", err) + } else { + log.Println("\tRTS:", rts) + } + + if cts, err := port.CTS(); err != nil { + log.Println("\tCTS:", err) + } else { + log.Println("\tCTS:", cts) + } + + if dtr, err := port.DTR(); err != nil { + log.Println("\tDTR:", err) + } else { + log.Println("\tDTR:", dtr) + } + + if dsr, err := port.DSR(); err != nil { + log.Println("\tDSR:", err) + } else { + log.Println("\tDSR:", dsr) + } + + if xon, err := port.XonXoff(); err != nil { + log.Println("\tXON/XOFF:", err) + } else { + log.Println("\tXON/XOFF:", xon) + } + + /* + if err := port.Apply(&serial.RawOptions); err != nil { + log.Println("\tApply Raw Config:", err) + } else { + log.Println("\tApply Raw Config: ok") + } + */ + + if b, err := port.InputWaiting(); err != nil { + log.Println("\tInput Waiting: ", err) + } else { + log.Println("\tInput Waiting: ", b) + } + + if b, err := port.OutputWaiting(); err != nil { + log.Println("\tOutput Waiting: ", err) + } else { + log.Println("\tOutput Waiting: ", b) + } + + if err := port.Sync(); err != nil { + log.Println("\tSync: ", err) + } + if err := port.Reset(); err != nil { + log.Println("\tReset: ", err) + } + if err := port.ResetInput(); err != nil { + log.Println("\tReset input: ", err) + } + if err := port.ResetOutput(); err != nil { + log.Println("\tReset output: ", err) + } + + buf := make([]byte, 1) + + if err := port.SetDeadline(time.Now()); err != nil { + log.Println("\tSetDeadline: ", err) + } else { + log.Printf("\tSet deadline") + } + + if c, err := port.Read(buf); err != nil { + log.Printf("\tRead immediate %d: %v", c, err) + if err != serial.ErrTimeout { + continue + } + } else { + log.Printf("\tRead immediate %d: %v", c, buf) + } + + if c, err := port.Write([]byte{0}); err != nil { + log.Println("\tWrite immediate:", err) + if err != serial.ErrTimeout { + continue + } + } else { + log.Printf("\tWrite immediate %d: %v", c, buf) + } + + if err := port.SetDeadline(time.Now().Add(time.Millisecond)); err != nil { + log.Println("\tSetDeadline: ", err) + } else { + log.Printf("\tSet deadline") + } + + if c, err := port.Read(buf); err != nil { + log.Printf("\tRead wait %d: %v", c, err) + } else { + log.Printf("\tRead wait %d: %v", c, buf) + } + + if err := port.SetDeadline(time.Now().Add(time.Millisecond)); err != nil { + log.Println("\tSetDeadline: ", err) + } else { + log.Printf("\tSet deadline") + } + + if c, err := port.Write([]byte{0}); err != nil { + log.Println("\tWrite wait:", err) + } else { + log.Printf("\tWrite wait %d: %v", c, buf) + } + + if err := port.SetReadDeadline(time.Time{}); err != nil { + log.Println("\tSetReadDeadline: ", err) + } else { + log.Printf("\tSet read deadline") + } + if err := port.SetWriteDeadline(time.Time{}); err != nil { + log.Println("\tSetWriteDeadline: ", err) + } else { + log.Printf("\tSet write deadline") + } + + if c, err := port.Read(buf); err != nil { + log.Printf("\tRead %d: %v", c, err) + } else { + log.Printf("\tRead %d: %v", c, buf) + } + + if c, err := port.Write([]byte{0}); err != nil { + log.Println("\tWrite:", err) + } else { + log.Printf("\tWrite %d: %v", c, buf) + } + + if err := port.Close(); err != nil { + log.Println(err) + } + } +} diff --git a/vendor/github.com/mikepb/go-serial/macosx.c b/vendor/github.com/mikepb/go-serial/macosx.c new file mode 100644 index 0000000..afd03c2 --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/macosx.c @@ -0,0 +1,229 @@ +/* + * This file is part of the libserialport project. + * + * Copyright (C) 2013-2014 Martin Ling + * Copyright (C) 2014 Aurelien Jacobs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifdef __APPLE__ + +#include "libserialport.h" +#include "libserialport_internal.h" + +SP_PRIV enum sp_return get_port_details(struct sp_port *port) +{ + /* Description limited to 127 char, + anything longer would not be user friendly anyway */ + char description[128]; + int bus, address, vid, pid = -1; + char manufacturer[128], product[128], serial[128]; + CFMutableDictionaryRef classes; + io_iterator_t iter; + io_object_t ioport, ioparent; + CFTypeRef cf_property, cf_bus, cf_address, cf_vendor, cf_product; + Boolean result; + char path[PATH_MAX], class[16]; + + DEBUG("Getting serial port list"); + if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) + RETURN_FAIL("IOServiceMatching() failed"); + + if (IOServiceGetMatchingServices(kIOMasterPortDefault, classes, + &iter) != KERN_SUCCESS) + RETURN_FAIL("IOServiceGetMatchingServices() failed"); + + DEBUG("Iterating over results"); + while ((ioport = IOIteratorNext(iter))) { + if (!(cf_property = IORegistryEntryCreateCFProperty(ioport, + CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0))) { + IOObjectRelease(ioport); + continue; + } + result = CFStringGetCString(cf_property, path, sizeof(path), + kCFStringEncodingASCII); + CFRelease(cf_property); + if (!result || strcmp(path, port->name)) { + IOObjectRelease(ioport); + continue; + } + DEBUG_FMT("Found port %s", path); + + IORegistryEntryGetParentEntry(ioport, kIOServicePlane, &ioparent); + if ((cf_property=IORegistryEntrySearchCFProperty(ioparent,kIOServicePlane, + CFSTR("IOProviderClass"), kCFAllocatorDefault, + kIORegistryIterateRecursively | kIORegistryIterateParents))) { + if (CFStringGetCString(cf_property, class, sizeof(class), + kCFStringEncodingASCII) && + strstr(class, "USB")) { + DEBUG("Found USB class device"); + port->transport = SP_TRANSPORT_USB; + } + CFRelease(cf_property); + } + IOObjectRelease(ioparent); + + if ((cf_property = IORegistryEntrySearchCFProperty(ioport,kIOServicePlane, + CFSTR("USB Interface Name"), kCFAllocatorDefault, + kIORegistryIterateRecursively | kIORegistryIterateParents)) || + (cf_property = IORegistryEntrySearchCFProperty(ioport,kIOServicePlane, + CFSTR("USB Product Name"), kCFAllocatorDefault, + kIORegistryIterateRecursively | kIORegistryIterateParents)) || + (cf_property = IORegistryEntrySearchCFProperty(ioport,kIOServicePlane, + CFSTR("Product Name"), kCFAllocatorDefault, + kIORegistryIterateRecursively | kIORegistryIterateParents)) || + (cf_property = IORegistryEntryCreateCFProperty(ioport, + CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0))) { + if (CFStringGetCString(cf_property, description, sizeof(description), + kCFStringEncodingASCII)) { + DEBUG_FMT("Found description %s", description); + port->description = strdup(description); + } + CFRelease(cf_property); + } else { + DEBUG("No description for this device"); + } + + cf_bus = IORegistryEntrySearchCFProperty(ioport, kIOServicePlane, + CFSTR("USBBusNumber"), + kCFAllocatorDefault, + kIORegistryIterateRecursively + | kIORegistryIterateParents); + cf_address = IORegistryEntrySearchCFProperty(ioport, kIOServicePlane, + CFSTR("USB Address"), + kCFAllocatorDefault, + kIORegistryIterateRecursively + | kIORegistryIterateParents); + if (cf_bus && cf_address && + CFNumberGetValue(cf_bus , kCFNumberIntType, &bus) && + CFNumberGetValue(cf_address, kCFNumberIntType, &address)) { + DEBUG_FMT("Found matching USB bus:address %03d:%03d", bus, address); + port->usb_bus = bus; + port->usb_address = address; + } + if (cf_bus ) CFRelease(cf_bus); + if (cf_address) CFRelease(cf_address); + + cf_vendor = IORegistryEntrySearchCFProperty(ioport, kIOServicePlane, + CFSTR("idVendor"), + kCFAllocatorDefault, + kIORegistryIterateRecursively + | kIORegistryIterateParents); + cf_product = IORegistryEntrySearchCFProperty(ioport, kIOServicePlane, + CFSTR("idProduct"), + kCFAllocatorDefault, + kIORegistryIterateRecursively + | kIORegistryIterateParents); + if (cf_vendor && cf_product && + CFNumberGetValue(cf_vendor , kCFNumberIntType, &vid) && + CFNumberGetValue(cf_product, kCFNumberIntType, &pid)) { + DEBUG_FMT("Found matching USB vid:pid %04X:%04X", vid, pid); + port->usb_vid = vid; + port->usb_pid = pid; + } + if (cf_vendor ) CFRelease(cf_vendor); + if (cf_product) CFRelease(cf_product); + + if ((cf_property = IORegistryEntrySearchCFProperty(ioport,kIOServicePlane, + CFSTR("USB Vendor Name"), kCFAllocatorDefault, + kIORegistryIterateRecursively | kIORegistryIterateParents))) { + if (CFStringGetCString(cf_property, manufacturer, sizeof(manufacturer), + kCFStringEncodingASCII)) { + DEBUG_FMT("Found manufacturer %s", manufacturer); + port->usb_manufacturer = strdup(manufacturer); + } + CFRelease(cf_property); + } + + if ((cf_property = IORegistryEntrySearchCFProperty(ioport,kIOServicePlane, + CFSTR("USB Product Name"), kCFAllocatorDefault, + kIORegistryIterateRecursively | kIORegistryIterateParents))) { + if (CFStringGetCString(cf_property, product, sizeof(product), + kCFStringEncodingASCII)) { + DEBUG_FMT("Found product name %s", product); + port->usb_product = strdup(product); + } + CFRelease(cf_property); + } + + if ((cf_property = IORegistryEntrySearchCFProperty(ioport,kIOServicePlane, + CFSTR("USB Serial Number"), kCFAllocatorDefault, + kIORegistryIterateRecursively | kIORegistryIterateParents))) { + if (CFStringGetCString(cf_property, serial, sizeof(serial), + kCFStringEncodingASCII)) { + DEBUG_FMT("Found serial number %s", serial); + port->usb_serial = strdup(serial); + } + CFRelease(cf_property); + } + + IOObjectRelease(ioport); + break; + } + IOObjectRelease(iter); + + RETURN_OK(); +} + +SP_PRIV enum sp_return list_ports(struct sp_port ***list) +{ + CFMutableDictionaryRef classes; + io_iterator_t iter; + char path[PATH_MAX]; + io_object_t port; + CFTypeRef cf_path; + Boolean result; + int ret = SP_OK; + + DEBUG("Creating matching dictionary"); + if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) { + SET_FAIL(ret, "IOServiceMatching() failed"); + goto out_done; + } + + DEBUG("Getting matching services"); + if (IOServiceGetMatchingServices(kIOMasterPortDefault, classes, + &iter) != KERN_SUCCESS) { + SET_FAIL(ret, "IOServiceGetMatchingServices() failed"); + goto out_done; + } + + DEBUG("Iterating over results"); + while ((port = IOIteratorNext(iter))) { + cf_path = IORegistryEntryCreateCFProperty(port, + CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0); + if (cf_path) { + result = CFStringGetCString(cf_path, path, sizeof(path), + kCFStringEncodingASCII); + CFRelease(cf_path); + if (result) { + DEBUG_FMT("Found port %s", path); + if (!(*list = list_append(*list, path))) { + SET_ERROR(ret, SP_ERR_MEM, "list append failed"); + IOObjectRelease(port); + goto out; + } + } + } + IOObjectRelease(port); + } +out: + IOObjectRelease(iter); +out_done: + + return ret; +} + +#endif diff --git a/vendor/github.com/mikepb/go-serial/serial.go b/vendor/github.com/mikepb/go-serial/serial.go new file mode 100644 index 0000000..3c4bdb5 --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/serial.go @@ -0,0 +1,1174 @@ +/* + +Package serial provides a binding to libserialport for serial port +functionality. Serial ports are commonly used with embedded systems, +such as the Arduino platform. + +Example Usage + + package main + + import ( + "github.com/mikepb/go-serial" + "log" + ) + + func main() { + options := serial.RawOptions + options.BitRate = 115200 + p, err := options.Open("/dev/tty") + if err != nil { + log.Panic(err) + } + + defer p.Close() + + buf := make([]byte, 1) + if c, err := p.Read(buf); err != nil { + log.Panic(err) + } else { + log.Println(buf) + } + } + +*/ +package serial + +/* +#cgo CFLAGS: -g -O2 -Wall -Wextra -DSP_PRIV= -DSP_API= +#cgo darwin LDFLAGS: -framework IOKit -framework CoreFoundation + +#include +#include +#include +#include "libserialport.h" + +void debug_handler(const char *fmt, ...) { + va_list args; + va_start(args, fmt); + vfprintf(stderr, fmt, args); + va_end(args); +} + +void setdebug(int enable) { + sp_set_debug_handler(enable ? debug_handler : NULL); +} + +*/ +import "C" + +import ( + "bytes" + "log" + "net" + "reflect" + "runtime" + "time" + "unsafe" +) + +// Debug flag +const Debug = false + +// Port access modes +const ( + MODE_READ = C.SP_MODE_READ // Open port for read access + MODE_WRITE = C.SP_MODE_WRITE // Open port for write access + MODE_READ_WRITE = C.SP_MODE_READ_WRITE // Open port for read and write access. +) + +// Port events. +const ( + EVENT_RX_READY = C.SP_EVENT_RX_READY // Data received and ready to read. + EVENT_TX_READY = C.SP_EVENT_TX_READY // Ready to transmit new data. + EVENT_ERROR = C.SP_EVENT_ERROR // Error occured. +) + +// Parity settings. +const ( + PARITY_INVALID = iota // Special value to indicate setting should be left alone. + PARITY_NONE // No parity. + PARITY_ODD // Odd parity. + PARITY_EVEN // Even parity. + PARITY_MARK // Mark parity. + PARITY_SPACE // Space parity. +) + +// RTS pin behaviour. +const ( + RTS_INVALID = iota // Special value to indicate setting should be left alone. + RTS_OFF // RTS off. + RTS_ON // RTS on. + RTS_FLOW_CONTROL // RTS used for flow control. +) + +// CTS pin behaviour. +const ( + CTS_INVALID = iota // Special value to indicate setting should be left alone. + CTS_IGNORE // CTS ignored. + CTS_FLOW_CONTROL // CTS used for flow control. +) + +// DTR pin behaviour. +const ( + DTR_INVALID = iota // Special value to indicate setting should be left alone. + DTR_OFF // DTR off. + DTR_ON // DTR on. + DTR_FLOW_CONTROL // DTR used for flow control. +) + +// DSR pin behaviour. +const ( + DSR_INVALID = iota // Special value to indicate setting should be left alone. + DSR_IGNORE // DSR ignored. + DSR_FLOW_CONTROL // DSR used for flow control. +) + +// XON/XOFF flow control behaviour. +const ( + XONXOFF_INVALID = iota // Special value to indicate setting should be left alone. + XONXOFF_DISABLED // XON/XOFF disabled. + XONXOFF_IN // XON/XOFF enabled for input only. + XONXOFF_OUT // XON/XOFF enabled for output only. + XONXOFF_INOUT // XON/XOFF enabled for input and output. +) + +// Standard flow control combinations. +const ( + _ = iota + FLOWCONTROL_NONE // No flow control. + FLOWCONTROL_XONXOFF // Software flow control using XON/XOFF characters. + FLOWCONTROL_RTSCTS // Hardware flow control using RTS/CTS signals. + FLOWCONTROL_DTRDSR // Hardware flow control using DTR/DSR signals. +) + +// Input signals +const ( + SIG_CTS = C.SP_SIG_CTS // Clear to send + SIG_DSR = C.SP_SIG_DSR // Data set ready + SIG_DCD = C.SP_SIG_DCD // Data carrier detect + SIG_RI = C.SP_SIG_RI // Ring indicator +) + +// Transport types. +const ( + TRANSPORT_NATIVE = C.SP_TRANSPORT_NATIVE // Native platform serial port. + TRANSPORT_USB = C.SP_TRANSPORT_USB // USB serial port adapter. + TRANSPORT_BLUETOOTH = C.SP_TRANSPORT_BLUETOOTH // Bluetooh serial port adapter. +) + +// Serial port info. +type Info struct { + p *C.struct_sp_port + opened bool +} + +// Serial port options. +type Options struct { + Mode int // read, write; default is read + BitRate int // number of bits per second (baudrate) + DataBits int // number of data bits (5, 6, 7, 8) + StopBits int // number of stop bits (1, 2) + Parity int // none, odd, even, mark, space + FlowControl int // none, xonxoff, rtscts, dtrdsr + + RTS int + CTS int + DTR int + DSR int +} + +// Serial port. +type Port struct { + Info + c *C.struct_sp_port_config + readDeadline time.Time + writeDeadline time.Time +} + +// Implementation of net.Addr +type Addr struct { + name string +} + +// Implementation of net.Error +type Error struct { + msg string + timeout bool + temporary bool +} + +var RawOptions = Options{ + DataBits: 8, + Parity: PARITY_NONE, + StopBits: 1, + FlowControl: FLOWCONTROL_NONE, +} + +var ErrInvalidArguments = &Error{msg: "Invalid arguments were passed to the function"} +var ErrSystem = &Error{msg: "A system error occured while executing the operation"} +var ErrMemoryAllocation = &Error{msg: "A memory allocation failed while executing the operation"} +var ErrUnsupportedOperation = &Error{msg: "The requested operation is not supported by this system or device"} +var ErrTimeout = &Error{msg: "Operation timed out", timeout: true} + +// Map error codes to errors. +func errmsg(err C.enum_sp_return) error { + switch err { + case C.SP_ERR_ARG: + return ErrInvalidArguments + case C.SP_ERR_FAIL: + return ErrSystem + case C.SP_ERR_MEM: + return ErrMemoryAllocation + case C.SP_ERR_SUPP: + return ErrUnsupportedOperation + } + return nil +} + +// Wrap a sp_port struct in a go Port struct and set finalizer for +// garbage collection. +func newInfo(p *C.struct_sp_port) (*Info, error) { + info := &Info{p: p} + runtime.SetFinalizer(info, (*Info).free) + return info, nil +} + +// Finalizer callback for garbage collection. +func (i *Info) free() { + if i.p != nil { + if i.opened { + C.sp_close(i.p) + } + C.sp_free_port(i.p) + } + i.opened = false + i.p = nil +} + +// Wrap a sp_port struct in a go Port struct and set finalizer for +// garbage collection. +func newPort(info *Info) (*Port, error) { + port := &Port{} + + // copy info + if info != nil { + if err := errmsg(C.sp_copy_port(info.p, &port.p)); err != nil { + return nil, err + } + } + + // set finalizers + runtime.SetFinalizer(port, (*Port).free) + + return port, nil +} + +// Finalizer callback for garbage collection. +func (p *Port) free() { + p.Info.free() + if p.c != nil { + C.sp_free_config(p.c) + } + p.c = nil +} + +// calculate milliseconds until deadline (rounded up) +func deadline2millis(deadline time.Time) int64 { + delta := deadline.Sub(time.Now()) + + duration := time.Duration(delta.Nanoseconds()) + duration += duration + time.Millisecond - time.Nanosecond + duration /= time.Millisecond + + millis := int64(duration) + + if Debug { + log.Printf("timeout: %d ns %d ms", delta, millis) + } + + return millis +} + +// Print libserialport debug messages to stderr. +func SetDebug(enable bool) { + if enable { + C.setdebug(1) + } else { + C.setdebug(0) + } +} + +// Get a port by name. +func PortByName(name string) (*Info, error) { + if p, err := portByName(name); err != nil { + return nil, err + } else { + return newInfo(p) + } +} +func portByName(name string) (*C.struct_sp_port, error) { + var p *C.struct_sp_port + + cname := C.CString(name) + defer C.free(unsafe.Pointer(cname)) + + if err := errmsg(C.sp_get_port_by_name(cname, &p)); err != nil { + return nil, err + } + + return p, nil +} + +// List the serial ports available on the system. +func ListPorts() ([]*Info, error) { + var p **C.struct_sp_port + + if err := C.sp_list_ports(&p); err != C.SP_OK { + return nil, errmsg(err) + } + defer C.sp_free_port_list(p) + + // Convert the C array into a Go slice + // See: https://code.google.com/p/go-wiki/wiki/cgo + pp := (*[1 << 15]*C.struct_sp_port)(unsafe.Pointer(p)) + + // count number of ports + c := 0 + for ; uintptr(unsafe.Pointer(pp[c])) != 0; c++ { + } + + // populate + ports := make([]*Info, c) + for j := 0; j < c; j++ { + var pc *C.struct_sp_port + if err := errmsg(C.sp_copy_port(pp[j], &pc)); err != nil { + return nil, err + } + if sp, err := newInfo(pc); err != nil { + return nil, err + } else { + ports[j] = sp + } + } + + return ports, nil +} + +// Get the name of a port. +func (i *Info) Name() string { + return C.GoString(C.sp_get_port_name(i.p)) +} + +// Get a description for a port, to present to end user. +func (i *Info) Description() string { + return C.GoString(C.sp_get_port_description(i.p)) +} + +// Get the transport type used by a port. +func (i *Info) Transport() int { + t := C.sp_get_port_transport(i.p) + return int(t) +} + +// Get the USB bus number and address on bus of a USB serial adapter port. +func (i *Info) USBBusAddress() (int, int, error) { + var bus, address C.int + if err := errmsg(C.sp_get_port_usb_bus_address(i.p, &bus, &address)); err != nil { + return 0, 0, err + } + return int(bus), int(address), nil +} + +// Get the USB Vendor ID and Product ID of a USB serial adapter port. +func (i *Info) USBVIDPID() (int, int, error) { + var vid, pid C.int + if err := errmsg(C.sp_get_port_usb_vid_pid(i.p, &vid, &pid)); err != nil { + return 0, 0, err + } + return int(vid), int(pid), nil +} + +// Get the USB manufacturer string of a USB serial adapter port. +func (i *Info) USBManufacturer() string { + cdesc := C.sp_get_port_usb_manufacturer(i.p) + return C.GoString(cdesc) +} + +// Get the USB product string of a USB serial adapter port. +func (i *Info) USBProduct() string { + cdesc := C.sp_get_port_usb_product(i.p) + return C.GoString(cdesc) +} + +// Get the USB serial number string of a USB serial adapter port. +func (i *Info) USBSerialNumber() string { + cdesc := C.sp_get_port_usb_serial(i.p) + return C.GoString(cdesc) +} + +// Get the MAC address of a Bluetooth serial adapter port. +func (i *Info) BluetoothAddress() string { + cdesc := C.sp_get_port_bluetooth_address(i.p) + return C.GoString(cdesc) +} + +// Open the port for reading and default options. +func (i *Info) Open() (*Port, error) { + return i.OpenPort(&Options{Mode: MODE_READ}) +} + +// Open the port with the specified options. +func (i *Info) OpenPort(options *Options) (*Port, error) { + // create port + port, err := newPort(i) + if err != nil { + return nil, err + } + + // open port + mode := MODE_READ + if options.Mode != 0 { + mode = options.Mode + } + if err = port.open(mode); err != nil { + return nil, err + } + + // apply options + if err = port.Apply(options); err != nil { + port.Close() + return nil, err + } + + return port, nil +} + +func (i *Info) createPortAndInvalidateInfo() (*Port, error) { + port, err := newPort(nil) + if err != nil { + return nil, err + } + + port.p = i.p + port.opened = i.opened + + i.p = nil + i.opened = false + + return port, nil +} + +// Open a port at the given name using the options object. +func (o *Options) Open(name string) (port *Port, err error) { + if info, err := PortByName(name); err != nil { + return nil, err + } else { + return info.OpenPort(o) + } +} + +// Open a port at the given info using the options object. +func (o *Options) OpenAt(info *Info) (port *Port, err error) { + return info.OpenPort(o) +} + +// Open a port for reading. +func Open(name string) (port *Port, err error) { + // get the port by name + if info, err := PortByName(name); err != nil { + return nil, err + } else if p, err := info.createPortAndInvalidateInfo(); p != nil { + return nil, err + } else { + port = p + } + + // open port with read mode + if err = port.open(MODE_READ); err != nil { + return nil, err + } + + return +} + +func (p *Port) open(mode int) error { + if p.opened { + panic("already opened") + } + err := errmsg(C.sp_open(p.p, C.enum_sp_mode(mode))) + p.opened = err == nil + return p.getConf() +} + +// Close the serial port. +func (p *Port) Close() error { + if !p.opened { + panic("already closed") + } + err := errmsg(C.sp_close(p.p)) + p.opened = false + return err +} + +func (p *Port) getConf() error { + if p.c == nil { + if err := errmsg(C.sp_new_config(&p.c)); err != nil { + return err + } + } + return errmsg(C.sp_get_config(p.p, p.c)) +} + +// Apply port options. +func (p *Port) Apply(o *Options) (err error) { + // get port config + var conf *C.struct_sp_port_config + if err = errmsg(C.sp_new_config(&conf)); err != nil { + return + } + defer C.sp_free_config(conf) + + // set bit rate + if o.BitRate != 0 { + err = errmsg(C.sp_set_config_baudrate(conf, C.int(o.BitRate))) + if err != nil { + return + } + } + + // set data bits + if o.DataBits != 0 { + err = errmsg(C.sp_set_config_bits(conf, C.int(o.DataBits))) + if err != nil { + return + } + } + + // set stop bits + if o.StopBits != 0 { + err = errmsg(C.sp_set_config_stopbits(conf, C.int(o.StopBits))) + if err != nil { + return + } + } + + // set parity + if o.Parity != 0 { + cparity := parity2c(o.Parity) + if err = errmsg(C.sp_set_config_parity(conf, cparity)); err != nil { + return + } + } + + // set flow control + if o.FlowControl != 0 { + cfc, err := flow2c(o.FlowControl) + if err != nil { + return err + } + if err = errmsg(C.sp_set_config_flowcontrol(conf, cfc)); err != nil { + return err + } + } + + // set RTS + if o.RTS != 0 { + crts := rts2c(o.RTS) + if err = errmsg(C.sp_set_config_rts(conf, crts)); err != nil { + return + } + } + + // set CTS + if o.CTS != 0 { + ccts := cts2c(o.CTS) + if err = errmsg(C.sp_set_config_cts(conf, ccts)); err != nil { + return + } + } + + // set DTR + if o.DTR != 0 { + cdtr := dtr2c(o.DTR) + if err = errmsg(C.sp_set_config_dtr(conf, cdtr)); err != nil { + return + } + } + + // set DSR + if o.DSR != 0 { + cdsr := dsr2c(o.DSR) + if err = errmsg(C.sp_set_config_dsr(conf, cdsr)); err != nil { + return + } + } + + // apply config + if err = errmsg(C.sp_set_config(p.p, conf)); err != nil { + return + } + + // update local config + return p.getConf() +} + +// Get the baud rate from a port configuration. The port must be +// opened for this operation. +func (p *Port) BitRate() (int, error) { + var bitrate C.int + if err := errmsg(C.sp_get_config_baudrate(p.c, &bitrate)); err != nil { + return 0, err + } + return int(bitrate), nil +} + +// Set the baud rate for the serial port. The port must be opened for +// this operation. Call p.ApplyConfig() to apply the change. +func (p *Port) SetBitRate(bitrate int) error { + if err := errmsg(C.sp_set_baudrate(p.p, C.int(bitrate))); err != nil { + return err + } + return p.getConf() +} + +// Get the data bits from a port configuration. The port must be +// opened for this operation. +func (p *Port) DataBits() (int, error) { + var bits C.int + if err := errmsg(C.sp_get_config_bits(p.c, &bits)); err != nil { + return 0, err + } + return int(bits), nil +} + +// Set the number of data bits for the serial port. The port must be +// opened for this operation. Call p.ApplyConfig() to apply the +// change. +func (p *Port) SetDataBits(bits int) error { + if err := errmsg(C.sp_set_config_bits(p.c, C.int(bits))); err != nil { + return err + } + return p.getConf() +} + +// Get the stop bits from a port configuration. The port must be +// opened for this operation. +func (p *Port) StopBits() (int, error) { + var stopbits C.int + if err := errmsg(C.sp_get_config_stopbits(p.c, &stopbits)); err != nil { + return 0, err + } + return int(stopbits), nil +} + +// Set the stop bits for the serial port. The port must be opened for +// this operation. Call p.ApplyConfig() to apply the change. +func (p *Port) SetStopBits(stopbits int) error { + if err := errmsg(C.sp_set_config_stopbits(p.c, C.int(stopbits))); err != nil { + return err + } + return p.getConf() +} + +// Get the parity setting from a port configuration. The port must be +// opened for this operation. +func (p *Port) Parity() (int, error) { + cparity := C.enum_sp_parity(C.SP_PARITY_INVALID) + if err := errmsg(C.sp_get_config_parity(p.c, &cparity)); err != nil { + return 0, err + } + return c2parity(cparity), nil +} + +// Set the parity setting for the serial port. The port must be opened +// for this operation. Call p.ApplyConfig() to apply the change. +func (p *Port) SetParity(parity int) error { + cparity := parity2c(parity) + if err := errmsg(C.sp_set_config_parity(p.c, cparity)); err != nil { + return err + } + return p.getConf() +} + +func c2parity(cparity C.enum_sp_parity) int { + switch cparity { + case C.SP_PARITY_NONE: + return PARITY_NONE + case C.SP_PARITY_ODD: + return PARITY_ODD + case C.SP_PARITY_EVEN: + return PARITY_EVEN + case C.SP_PARITY_MARK: + return PARITY_MARK + case C.SP_PARITY_SPACE: + return PARITY_SPACE + default: + return PARITY_INVALID + } +} + +func parity2c(parity int) C.enum_sp_parity { + switch parity { + case PARITY_NONE: + return C.SP_PARITY_NONE + case PARITY_ODD: + return C.SP_PARITY_ODD + case PARITY_EVEN: + return C.SP_PARITY_EVEN + case PARITY_MARK: + return C.SP_PARITY_MARK + case PARITY_SPACE: + return C.SP_PARITY_SPACE + default: + return C.SP_PARITY_INVALID + } +} + +// Get the RTS pin behaviour from a port configuration. The port must +// be opened for this operation. +func (p *Port) RTS() (int, error) { + rts := C.enum_sp_rts(C.SP_RTS_INVALID) + if err := errmsg(C.sp_get_config_rts(p.c, &rts)); err != nil { + return 0, err + } + return c2rts(rts), nil +} + +// Set the RTS pin behaviour in a port configuration. The port must be +// opened for this operation. Call p.ApplyConfig() to apply the +// change. +func (p *Port) SetRTS(rts int) error { + crts := rts2c(rts) + if err := errmsg(C.sp_set_config_rts(p.c, crts)); err != nil { + return err + } + return p.getConf() +} + +func c2rts(rts C.enum_sp_rts) int { + switch rts { + case C.SP_RTS_OFF: + return RTS_OFF + case C.SP_RTS_ON: + return RTS_ON + case C.SP_RTS_FLOW_CONTROL: + return RTS_FLOW_CONTROL + default: + return RTS_INVALID + } +} + +func rts2c(rts int) C.enum_sp_rts { + switch rts { + case RTS_OFF: + return C.SP_RTS_OFF + case RTS_ON: + return C.SP_RTS_ON + case RTS_FLOW_CONTROL: + return C.SP_RTS_FLOW_CONTROL + default: + return C.SP_RTS_INVALID + } +} + +// Get the CTS pin behaviour from a port configuration. The port must +// be opened for this operation. +func (p *Port) CTS() (int, error) { + cts := C.enum_sp_cts(C.SP_CTS_INVALID) + if err := errmsg(C.sp_get_config_cts(p.c, &cts)); err != nil { + return 0, err + } + return c2cts(cts), nil +} + +// Set the CTS pin behaviour in a port configuration. The port must be +// opened for this operation. Call p.ApplyConfig() to apply the +// change. +func (p *Port) SetCTS(cts int) error { + ccts := cts2c(cts) + if err := errmsg(C.sp_set_config_cts(p.c, ccts)); err != nil { + return err + } + return p.getConf() +} + +func c2cts(cts C.enum_sp_cts) int { + switch cts { + case C.SP_CTS_IGNORE: + return CTS_IGNORE + case C.SP_CTS_FLOW_CONTROL: + return CTS_FLOW_CONTROL + default: + return CTS_INVALID + } +} + +func cts2c(cts int) C.enum_sp_cts { + switch cts { + case CTS_IGNORE: + return C.SP_CTS_IGNORE + case CTS_FLOW_CONTROL: + return C.SP_CTS_FLOW_CONTROL + default: + return C.SP_CTS_INVALID + } +} + +// Get the DTR pin behaviour from a port configuration. The port must +// be opened for this operation. +func (p *Port) DTR() (int, error) { + dtr := C.enum_sp_dtr(C.SP_DTR_INVALID) + if err := errmsg(C.sp_get_config_dtr(p.c, &dtr)); err != nil { + return 0, err + } + return c2dtr(dtr), nil +} + +// Set the DTR pin behaviour in a port configuration. The port must be +// opened for this operation. Call p.ApplyConfig() to apply the +// change. +func (p *Port) SetDTR(dtr int) error { + cdtr := dtr2c(dtr) + if err := errmsg(C.sp_set_config_dtr(p.c, cdtr)); err != nil { + return err + } + return p.getConf() +} + +func c2dtr(dtr C.enum_sp_dtr) int { + switch dtr { + case C.SP_DTR_OFF: + return DTR_OFF + case C.SP_DTR_ON: + return DTR_ON + case C.SP_DTR_FLOW_CONTROL: + return DTR_FLOW_CONTROL + default: + return DTR_INVALID + } +} + +func dtr2c(dtr int) C.enum_sp_dtr { + switch dtr { + case DTR_OFF: + return C.SP_DTR_OFF + case DTR_ON: + return C.SP_DTR_ON + case DTR_FLOW_CONTROL: + return C.SP_DTR_FLOW_CONTROL + default: + return C.SP_DTR_INVALID + } +} + +// Get the DSR pin behaviour from a port configuration. The port must +// be opened for this operation. +func (p *Port) DSR() (int, error) { + dsr := C.enum_sp_dsr(C.SP_DSR_INVALID) + if err := errmsg(C.sp_get_config_dsr(p.c, &dsr)); err != nil { + return 0, err + } + return c2dsr(dsr), nil +} + +// Set the DSR pin behaviour in a port configuration. The port must be +// opened for this operation. Call p.ApplyConfig() to apply the +// change. +func (p *Port) SetDSR(dsr int) error { + cdsr := dsr2c(dsr) + if err := errmsg(C.sp_set_config_dsr(p.c, cdsr)); err != nil { + return err + } + return p.getConf() +} + +func c2dsr(dsr C.enum_sp_dsr) int { + switch dsr { + case C.SP_DSR_IGNORE: + return DSR_IGNORE + case C.SP_DSR_FLOW_CONTROL: + return DSR_FLOW_CONTROL + default: + return DSR_INVALID + } +} + +func dsr2c(dsr int) C.enum_sp_dsr { + switch dsr { + case DSR_IGNORE: + return C.SP_DSR_IGNORE + case DSR_FLOW_CONTROL: + return C.SP_DSR_FLOW_CONTROL + default: + return C.SP_DSR_INVALID + } +} + +// Get the XON/XOFF configuration from a port configuration. The port +// must be opened for this operation. +func (p *Port) XonXoff() (int, error) { + xon := C.enum_sp_xonxoff(C.SP_XONXOFF_INVALID) + if err := errmsg(C.sp_get_config_xon_xoff(p.c, &xon)); err != nil { + return 0, err + } + return c2xon(xon), nil +} + +// Set the XON/XOFF configuration in a port configuration. The port +// must be opened for this operation. Call p.ApplyConfig() to apply +// the change. +func (p *Port) SetXonXoff(xon int) error { + cxon := xon2c(xon) + if err := errmsg(C.sp_set_config_xon_xoff(p.c, cxon)); err != nil { + return err + } + return p.getConf() +} + +func c2xon(xon C.enum_sp_xonxoff) int { + switch xon { + case C.SP_XONXOFF_DISABLED: + return XONXOFF_DISABLED + case C.SP_XONXOFF_IN: + return XONXOFF_IN + case C.SP_XONXOFF_OUT: + return XONXOFF_OUT + default: + return XONXOFF_INVALID + } +} + +func xon2c(xon int) C.enum_sp_xonxoff { + switch xon { + case XONXOFF_DISABLED: + return C.SP_XONXOFF_DISABLED + case XONXOFF_IN: + return C.SP_XONXOFF_IN + case XONXOFF_OUT: + return C.SP_XONXOFF_OUT + default: + return C.SP_XONXOFF_INVALID + } +} + +// Set the flow control type in a port configuration. The port must be +// opened for this operation. Call p.ApplyConfig() to apply the +// change. +func (p *Port) SetFlowControl(fc int) error { + cfc, err := flow2c(fc) + if err != nil { + return err + } + + if err := errmsg(C.sp_set_config_flowcontrol(p.c, cfc)); err != nil { + return err + } + + return p.getConf() +} + +func flow2c(fc int) (cfc C.enum_sp_flowcontrol, err error) { + switch fc { + case FLOWCONTROL_NONE: + cfc = C.SP_FLOWCONTROL_NONE + case FLOWCONTROL_XONXOFF: + cfc = C.SP_FLOWCONTROL_XONXOFF + case FLOWCONTROL_RTSCTS: + cfc = C.SP_FLOWCONTROL_RTSCTS + case FLOWCONTROL_DTRDSR: + cfc = C.SP_FLOWCONTROL_DTRDSR + default: + err = ErrInvalidArguments + } + return +} + +// Implementation of io.Reader interface. +func (p *Port) Read(b []byte) (int, error) { + var c int32 + var start time.Time + + if Debug { + start = time.Now() + } + + buf, size := unsafe.Pointer(&b[0]), C.size_t(len(b)) + + if p.readDeadline.IsZero() { + + // no deadline + c = C.sp_blocking_read(p.p, buf, size, 0) + + } else if millis := deadline2millis(p.readDeadline); millis <= 0 { + + // call nonblocking read + c = C.sp_nonblocking_read(p.p, buf, size) + + } else { + + // call blocking read + c = C.sp_blocking_read(p.p, buf, size, C.uint(millis)) + + } + + if Debug { + log.Printf("read time: %d ns", time.Since(start).Nanoseconds()) + } + + n := int(c) + + // check for error + if n < 0 { + return 0, errmsg(c) + } else if n != len(b) { + return n, ErrTimeout + } + + // update slice length + reflect.ValueOf(&b).Elem().SetLen(int(c)) + + return n, nil +} + +// Implementation of io.Writer interface. +func (p *Port) Write(b []byte) (int, error) { + var c int32 + var start time.Time + + if Debug { + start = time.Now() + } + + buf, size := unsafe.Pointer(&b[0]), C.size_t(len(b)) + + if p.writeDeadline.IsZero() { + + // no deadline + c = C.sp_blocking_write(p.p, buf, size, 0) + + } else if millis := deadline2millis(p.writeDeadline); millis <= 0 { + + // call nonblocking write + c = C.sp_nonblocking_write(p.p, buf, size) + + } else { + + // call blocking write + c = C.sp_blocking_write(p.p, buf, size, C.uint(millis)) + + } + + if Debug { + log.Printf("write time: %d ns", time.Since(start).Nanoseconds()) + } + + n := int(c) + + // check for error + if n < 0 { + return 0, errmsg(c) + } else if n != len(b) { + return n, ErrTimeout + } + + return n, nil +} + +// WriteString is like Write, but writes the contents of string s +// rather than a slice of bytes. +func (p *Port) WriteString(s string) (int, error) { + return p.Write(bytes.NewBufferString(s).Bytes()) +} + +// Implementation of net.Conn.LocalAddr +func (p *Port) LocalAddr() net.Addr { + return &Addr{name: p.Name()} +} + +// Implementation of net.Conn.RemoteAddr +func (p *Port) RemoteAddr() net.Addr { + return &Addr{name: p.Name()} +} + +// Implementation of net.Conn.SetDeadline +func (p *Port) SetDeadline(t time.Time) error { + p.readDeadline = t + p.writeDeadline = t + return nil +} + +// Implementation of net.Conn.SetReadDeadline +func (p *Port) SetReadDeadline(t time.Time) error { + p.readDeadline = t + return nil +} + +// Implementation of net.Conn.SetWriteDeadline +func (p *Port) SetWriteDeadline(t time.Time) error { + p.writeDeadline = t + return nil +} + +// Gets the number of bytes waiting in the input buffer. +func (p *Port) InputWaiting() (int, error) { + c := C.sp_input_waiting(p.p) + if c < 0 { + return 0, errmsg(c) + } + return int(c), nil +} + +// Gets the number of bytes waiting in the output buffer. +func (p *Port) OutputWaiting() (int, error) { + c := C.sp_output_waiting(p.p) + if c < 0 { + return 0, errmsg(c) + } + return int(c), nil +} + +// Wait for buffered data to be transmitted. +func (p *Port) Sync() error { + return errmsg(C.sp_drain(p.p)) +} + +// Discard buffered data. +func (p *Port) Reset() error { + return errmsg(C.sp_flush(p.p, C.SP_BUF_BOTH)) +} + +// Discard buffered input data. +func (p *Port) ResetInput() error { + return errmsg(C.sp_flush(p.p, C.SP_BUF_INPUT)) +} + +// Discard buffered output data. +func (p *Port) ResetOutput() error { + return errmsg(C.sp_flush(p.p, C.SP_BUF_OUTPUT)) +} + +// Implementation of net.Addr.Network() +func (a *Addr) Network() string { + return "serial" +} + +// Implementation of net.Addr.String() +func (a *Addr) String() string { + return a.name +} + +// Implementation of error.Error() +func (e *Error) Error() string { + return e.msg +} + +// Implementation of net.Error.Timeout() +func (e *Error) Timeout() bool { + return e.timeout +} + +// Implementation of net.Error.Temporary() +func (e *Error) Temporary() bool { + return e.temporary +} diff --git a/vendor/github.com/mikepb/go-serial/serialport.c b/vendor/github.com/mikepb/go-serial/serialport.c new file mode 100644 index 0000000..2ec2c2f --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/serialport.c @@ -0,0 +1,2320 @@ +/* + * This file is part of the libserialport project. + * + * Copyright (C) 2010-2012 Bert Vermeulen + * Copyright (C) 2010-2012 Uwe Hermann + * Copyright (C) 2013 Martin Ling + * Copyright (C) 2013 Matthias Heidbrink + * Copyright (C) 2014 Aurelien Jacobs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include "libserialport.h" +#include "libserialport_internal.h" + +const struct std_baudrate std_baudrates[] = { +#ifdef _WIN32 + /* + * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to + * have documented CBR_* macros. + */ + BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800), + BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600), + BAUD(115200), BAUD(128000), BAUD(256000), +#else + BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200), + BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800), + BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200), + BAUD(230400), +#if !defined(__APPLE__) && !defined(__OpenBSD__) + BAUD(460800), +#endif +#endif +}; + +void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler; + +static enum sp_return get_config(struct sp_port *port, struct port_data *data, + struct sp_port_config *config); + +static enum sp_return set_config(struct sp_port *port, struct port_data *data, + const struct sp_port_config *config); + +SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr) +{ + struct sp_port *port; +#ifndef NO_PORT_METADATA + enum sp_return ret; +#endif + int len; + + TRACE("%s, %p", portname, port_ptr); + + if (!port_ptr) + RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); + + *port_ptr = NULL; + + if (!portname) + RETURN_ERROR(SP_ERR_ARG, "Null port name"); + + DEBUG_FMT("Building structure for port %s", portname); + + if (!(port = malloc(sizeof(struct sp_port)))) + RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed"); + + len = strlen(portname) + 1; + + if (!(port->name = malloc(len))) { + free(port); + RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed"); + } + + memcpy(port->name, portname, len); + +#ifdef _WIN32 + port->usb_path = NULL; + port->hdl = INVALID_HANDLE_VALUE; +#else + port->fd = -1; +#endif + + port->description = NULL; + port->transport = SP_TRANSPORT_NATIVE; + port->usb_bus = -1; + port->usb_address = -1; + port->usb_vid = -1; + port->usb_pid = -1; + port->usb_manufacturer = NULL; + port->usb_product = NULL; + port->usb_serial = NULL; + port->bluetooth_address = NULL; + +#ifndef NO_PORT_METADATA + if ((ret = get_port_details(port)) != SP_OK) { + sp_free_port(port); + return ret; + } +#endif + + *port_ptr = port; + + RETURN_OK(); +} + +SP_API char *sp_get_port_name(const struct sp_port *port) +{ + TRACE("%p", port); + + if (!port) + return NULL; + + RETURN_STRING(port->name); +} + +SP_API char *sp_get_port_description(struct sp_port *port) +{ + TRACE("%p", port); + + if (!port || !port->description) + return NULL; + + RETURN_STRING(port->description); +} + +SP_API enum sp_transport sp_get_port_transport(struct sp_port *port) +{ + TRACE("%p", port); + + if (!port) + RETURN_ERROR(SP_ERR_ARG, "Null port"); + + RETURN_INT(port->transport); +} + +SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port, + int *usb_bus,int *usb_address) +{ + TRACE("%p", port); + + if (!port) + RETURN_ERROR(SP_ERR_ARG, "Null port"); + if (port->transport != SP_TRANSPORT_USB) + RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport"); + if (port->usb_bus < 0 || port->usb_address < 0) + RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available"); + + if (usb_bus) *usb_bus = port->usb_bus; + if (usb_address) *usb_address = port->usb_address; + + RETURN_OK(); +} + +SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port, + int *usb_vid, int *usb_pid) +{ + TRACE("%p", port); + + if (!port) + RETURN_ERROR(SP_ERR_ARG, "Null port"); + if (port->transport != SP_TRANSPORT_USB) + RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport"); + if (port->usb_vid < 0 || port->usb_pid < 0) + RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available"); + + if (usb_vid) *usb_vid = port->usb_vid; + if (usb_pid) *usb_pid = port->usb_pid; + + RETURN_OK(); +} + +SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port) +{ + TRACE("%p", port); + + if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer) + return NULL; + + RETURN_STRING(port->usb_manufacturer); +} + +SP_API char *sp_get_port_usb_product(const struct sp_port *port) +{ + TRACE("%p", port); + + if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product) + return NULL; + + RETURN_STRING(port->usb_product); +} + +SP_API char *sp_get_port_usb_serial(const struct sp_port *port) +{ + TRACE("%p", port); + + if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial) + return NULL; + + RETURN_STRING(port->usb_serial); +} + +SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port) +{ + TRACE("%p", port); + + if (!port || port->transport != SP_TRANSPORT_BLUETOOTH + || !port->bluetooth_address) + return NULL; + + RETURN_STRING(port->bluetooth_address); +} + +SP_API enum sp_return sp_get_port_handle(const struct sp_port *port, + void *result_ptr) +{ + TRACE("%p, %p", port, result_ptr); + + if (!port) + RETURN_ERROR(SP_ERR_ARG, "Null port"); + +#ifdef _WIN32 + HANDLE *handle_ptr = result_ptr; + *handle_ptr = port->hdl; +#else + int *fd_ptr = result_ptr; + *fd_ptr = port->fd; +#endif + + RETURN_OK(); +} + +SP_API enum sp_return sp_copy_port(const struct sp_port *port, + struct sp_port **copy_ptr) +{ + TRACE("%p, %p", port, copy_ptr); + + if (!copy_ptr) + RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); + + *copy_ptr = NULL; + + if (!port) + RETURN_ERROR(SP_ERR_ARG, "Null port"); + + if (!port->name) + RETURN_ERROR(SP_ERR_ARG, "Null port name"); + + DEBUG("Copying port structure"); + + RETURN_INT(sp_get_port_by_name(port->name, copy_ptr)); +} + +SP_API void sp_free_port(struct sp_port *port) +{ + TRACE("%p", port); + + if (!port) { + DEBUG("Null port"); + RETURN(); + } + + DEBUG("Freeing port structure"); + + if (port->name) + free(port->name); + if (port->description) + free(port->description); + if (port->usb_manufacturer) + free(port->usb_manufacturer); + if (port->usb_product) + free(port->usb_product); + if (port->usb_serial) + free(port->usb_serial); + if (port->bluetooth_address) + free(port->bluetooth_address); +#ifdef _WIN32 + if (port->usb_path) + free(port->usb_path); +#endif + + free(port); + + RETURN(); +} + +SP_PRIV struct sp_port **list_append(struct sp_port **list, + const char *portname) +{ + void *tmp; + unsigned int count; + + for (count = 0; list[count]; count++); + if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2)))) + goto fail; + list = tmp; + if (sp_get_port_by_name(portname, &list[count]) != SP_OK) + goto fail; + list[count + 1] = NULL; + return list; + +fail: + sp_free_port_list(list); + return NULL; +} + +SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr) +{ + struct sp_port **list; + int ret; + + TRACE("%p", list_ptr); + + if (!list_ptr) + RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); + + DEBUG("Enumerating ports"); + + if (!(list = malloc(sizeof(struct sp_port **)))) + RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed"); + + list[0] = NULL; + +#ifdef NO_ENUMERATION + ret = SP_ERR_SUPP; +#else + ret = list_ports(&list); +#endif + + switch (ret) { + case SP_OK: + *list_ptr = list; + RETURN_OK(); + case SP_ERR_SUPP: + DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform"); + default: + if (list) + sp_free_port_list(list); + *list_ptr = NULL; + return ret; + } +} + +SP_API void sp_free_port_list(struct sp_port **list) +{ + unsigned int i; + + TRACE("%p", list); + + if (!list) { + DEBUG("Null list"); + RETURN(); + } + + DEBUG("Freeing port list"); + + for (i = 0; list[i]; i++) + sp_free_port(list[i]); + free(list); + + RETURN(); +} + +#define CHECK_PORT() do { \ + if (port == NULL) \ + RETURN_ERROR(SP_ERR_ARG, "Null port"); \ + if (port->name == NULL) \ + RETURN_ERROR(SP_ERR_ARG, "Null port name"); \ +} while (0) +#ifdef _WIN32 +#define CHECK_PORT_HANDLE() do { \ + if (port->hdl == INVALID_HANDLE_VALUE) \ + RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \ +} while (0) +#else +#define CHECK_PORT_HANDLE() do { \ + if (port->fd < 0) \ + RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \ +} while (0) +#endif +#define CHECK_OPEN_PORT() do { \ + CHECK_PORT(); \ + CHECK_PORT_HANDLE(); \ +} while (0) + +SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags) +{ + struct port_data data; + struct sp_port_config config; + enum sp_return ret; + + TRACE("%p, 0x%x", port, flags); + + CHECK_PORT(); + + if (flags > SP_MODE_READ_WRITE) + RETURN_ERROR(SP_ERR_ARG, "Invalid flags"); + + DEBUG_FMT("Opening port %s", port->name); + +#ifdef _WIN32 + DWORD desired_access = 0, flags_and_attributes = 0, errors; + char *escaped_port_name; + COMSTAT status; + + /* Prefix port name with '\\.\' to work with ports above COM9. */ + if (!(escaped_port_name = malloc(strlen(port->name) + 5))) + RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed"); + sprintf(escaped_port_name, "\\\\.\\%s", port->name); + + /* Map 'flags' to the OS-specific settings. */ + flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED; + if (flags & SP_MODE_READ) + desired_access |= GENERIC_READ; + if (flags & SP_MODE_WRITE) + desired_access |= GENERIC_WRITE; + + port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0, + OPEN_EXISTING, flags_and_attributes, 0); + + free(escaped_port_name); + + if (port->hdl == INVALID_HANDLE_VALUE) + RETURN_FAIL("port CreateFile() failed"); + + /* All timeouts initially disabled. */ + port->timeouts.ReadIntervalTimeout = 0; + port->timeouts.ReadTotalTimeoutMultiplier = 0; + port->timeouts.ReadTotalTimeoutConstant = 0; + port->timeouts.WriteTotalTimeoutMultiplier = 0; + port->timeouts.WriteTotalTimeoutConstant = 0; + + if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) { + sp_close(port); + RETURN_FAIL("SetCommTimeouts() failed"); + } + + /* Prepare OVERLAPPED structures. */ +#define INIT_OVERLAPPED(ovl) do { \ + memset(&port->ovl, 0, sizeof(port->ovl)); \ + port->ovl.hEvent = INVALID_HANDLE_VALUE; \ + if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \ + == INVALID_HANDLE_VALUE) { \ + sp_close(port); \ + RETURN_FAIL(#ovl "CreateEvent() failed"); \ + } \ +} while (0) + + INIT_OVERLAPPED(read_ovl); + INIT_OVERLAPPED(write_ovl); + INIT_OVERLAPPED(wait_ovl); + + /* Set event mask for RX and error events. */ + if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) { + sp_close(port); + RETURN_FAIL("SetCommMask() failed"); + } + + /* Start background operation for RX and error events. */ + if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) { + if (GetLastError() != ERROR_IO_PENDING) { + sp_close(port); + RETURN_FAIL("WaitCommEvent() failed"); + } + } + + port->writing = FALSE; + +#else + int flags_local = O_NONBLOCK | O_NOCTTY; + + /* Map 'flags' to the OS-specific settings. */ + if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE) + flags_local |= O_RDWR; + else if (flags & SP_MODE_READ) + flags_local |= O_RDONLY; + else if (flags & SP_MODE_WRITE) + flags_local |= O_WRONLY; + + if ((port->fd = open(port->name, flags_local)) < 0) + RETURN_FAIL("open() failed"); +#endif + + ret = get_config(port, &data, &config); + + if (ret < 0) { + sp_close(port); + RETURN_CODEVAL(ret); + } + + /* Set sane port settings. */ +#ifdef _WIN32 + data.dcb.fBinary = TRUE; + data.dcb.fDsrSensitivity = FALSE; + data.dcb.fErrorChar = FALSE; + data.dcb.fNull = FALSE; + data.dcb.fAbortOnError = TRUE; +#else + /* Turn off all fancy termios tricks, give us a raw channel. */ + data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL); +#ifdef IUCLC + data.term.c_iflag &= ~IUCLC; +#endif + data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET); +#ifdef OLCUC + data.term.c_oflag &= ~OLCUC; +#endif +#ifdef NLDLY + data.term.c_oflag &= ~NLDLY; +#endif +#ifdef CRDLY + data.term.c_oflag &= ~CRDLY; +#endif +#ifdef TABDLY + data.term.c_oflag &= ~TABDLY; +#endif +#ifdef BSDLY + data.term.c_oflag &= ~BSDLY; +#endif +#ifdef VTDLY + data.term.c_oflag &= ~VTDLY; +#endif +#ifdef FFDLY + data.term.c_oflag &= ~FFDLY; +#endif +#ifdef OFILL + data.term.c_oflag &= ~OFILL; +#endif + data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN); + data.term.c_cc[VMIN] = 0; + data.term.c_cc[VTIME] = 0; + + /* Ignore modem status lines; enable receiver; leave control lines alone on close. */ + data.term.c_cflag |= (CLOCAL | CREAD | HUPCL); +#endif + +#ifdef _WIN32 + if (ClearCommError(port->hdl, &errors, &status) == 0) + RETURN_FAIL("ClearCommError() failed"); +#endif + + ret = set_config(port, &data, &config); + + if (ret < 0) { + sp_close(port); + RETURN_CODEVAL(ret); + } + + RETURN_OK(); +} + +SP_API enum sp_return sp_close(struct sp_port *port) +{ + TRACE("%p", port); + + CHECK_OPEN_PORT(); + + DEBUG_FMT("Closing port %s", port->name); + +#ifdef _WIN32 + /* Returns non-zero upon success, 0 upon failure. */ + if (CloseHandle(port->hdl) == 0) + RETURN_FAIL("port CloseHandle() failed"); + port->hdl = INVALID_HANDLE_VALUE; + + /* Close event handles for overlapped structures. */ +#define CLOSE_OVERLAPPED(ovl) do { \ + if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \ + CloseHandle(port->ovl.hEvent) == 0) \ + RETURN_FAIL(# ovl "event CloseHandle() failed"); \ +} while (0) + CLOSE_OVERLAPPED(read_ovl); + CLOSE_OVERLAPPED(write_ovl); + CLOSE_OVERLAPPED(wait_ovl); + +#else + /* Returns 0 upon success, -1 upon failure. */ + if (close(port->fd) == -1) + RETURN_FAIL("close() failed"); + port->fd = -1; +#endif + + RETURN_OK(); +} + +SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers) +{ + TRACE("%p, 0x%x", port, buffers); + + CHECK_OPEN_PORT(); + + if (buffers > SP_BUF_BOTH) + RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection"); + + const char *buffer_names[] = {"no", "input", "output", "both"}; + + DEBUG_FMT("Flushing %s buffers on port %s", + buffer_names[buffers], port->name); + +#ifdef _WIN32 + DWORD flags = 0; + if (buffers & SP_BUF_INPUT) + flags |= PURGE_RXCLEAR; + if (buffers & SP_BUF_OUTPUT) + flags |= PURGE_TXCLEAR; + + /* Returns non-zero upon success, 0 upon failure. */ + if (PurgeComm(port->hdl, flags) == 0) + RETURN_FAIL("PurgeComm() failed"); +#else + int flags = 0; + if (buffers == SP_BUF_BOTH) + flags = TCIOFLUSH; + else if (buffers == SP_BUF_INPUT) + flags = TCIFLUSH; + else if (buffers == SP_BUF_OUTPUT) + flags = TCOFLUSH; + + /* Returns 0 upon success, -1 upon failure. */ + if (tcflush(port->fd, flags) < 0) + RETURN_FAIL("tcflush() failed"); +#endif + RETURN_OK(); +} + +SP_API enum sp_return sp_drain(struct sp_port *port) +{ + TRACE("%p", port); + + CHECK_OPEN_PORT(); + + DEBUG_FMT("Draining port %s", port->name); + +#ifdef _WIN32 + /* Returns non-zero upon success, 0 upon failure. */ + if (FlushFileBuffers(port->hdl) == 0) + RETURN_FAIL("FlushFileBuffers() failed"); + RETURN_OK(); +#else + int result; + while (1) { +#ifdef __ANDROID__ + int arg = 1; + result = ioctl(port->fd, TCSBRK, &arg); +#else + result = tcdrain(port->fd); +#endif + if (result < 0) { + if (errno == EINTR) { + DEBUG("tcdrain() was interrupted"); + continue; + } else { + RETURN_FAIL("tcdrain() failed"); + } + } else { + RETURN_OK(); + } + } +#endif +} + +SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf, + size_t count, unsigned int timeout) +{ + TRACE("%p, %p, %d, %d", port, buf, count, timeout); + + CHECK_OPEN_PORT(); + + if (!buf) + RETURN_ERROR(SP_ERR_ARG, "Null buffer"); + + if (timeout) + DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms", + count, port->name, timeout); + else + DEBUG_FMT("Writing %d bytes to port %s, no timeout", + count, port->name); + + if (count == 0) + RETURN_INT(0); + +#ifdef _WIN32 + DWORD bytes_written = 0; + BOOL result; + + /* Wait for previous non-blocking write to complete, if any. */ + if (port->writing) { + DEBUG("Waiting for previous write to complete"); + result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE); + port->writing = 0; + if (!result) + RETURN_FAIL("Previous write failed to complete"); + DEBUG("Previous write completed"); + } + + /* Set timeout. */ + port->timeouts.WriteTotalTimeoutConstant = timeout; + if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) + RETURN_FAIL("SetCommTimeouts() failed"); + + /* Start write. */ + if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) { + if (GetLastError() == ERROR_IO_PENDING) { + DEBUG("Waiting for write to complete"); + GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE); + DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count); + RETURN_INT(bytes_written); + } else { + RETURN_FAIL("WriteFile() failed"); + } + } else { + DEBUG("Write completed immediately"); + RETURN_INT(count); + } +#else + size_t bytes_written = 0; + unsigned char *ptr = (unsigned char *) buf; + struct timeval start, delta, now, end = {0, 0}; + fd_set fds; + int result; + + if (timeout) { + /* Get time at start of operation. */ + gettimeofday(&start, NULL); + /* Define duration of timeout. */ + delta.tv_sec = timeout / 1000; + delta.tv_usec = (timeout % 1000) * 1000; + /* Calculate time at which we should give up. */ + timeradd(&start, &delta, &end); + } + + /* Loop until we have written the requested number of bytes. */ + while (bytes_written < count) + { + /* Wait until space is available. */ + FD_ZERO(&fds); + FD_SET(port->fd, &fds); + if (timeout) { + gettimeofday(&now, NULL); + if (timercmp(&now, &end, >)) { + DEBUG("write timed out"); + RETURN_INT(bytes_written); + } + timersub(&end, &now, &delta); + } + result = select(port->fd + 1, NULL, &fds, NULL, timeout ? &delta : NULL); + if (result < 0) { + if (errno == EINTR) { + DEBUG("select() call was interrupted, repeating"); + continue; + } else { + RETURN_FAIL("select() failed"); + } + } else if (result == 0) { + DEBUG("write timed out"); + RETURN_INT(bytes_written); + } + + /* Do write. */ + result = write(port->fd, ptr, count - bytes_written); + + if (result < 0) { + if (errno == EAGAIN) + /* This shouldn't happen because we did a select() first, but handle anyway. */ + continue; + else + /* This is an actual failure. */ + RETURN_FAIL("write() failed"); + } + + bytes_written += result; + ptr += result; + } + + RETURN_INT(bytes_written); +#endif +} + +SP_API enum sp_return sp_nonblocking_write(struct sp_port *port, + const void *buf, size_t count) +{ + TRACE("%p, %p, %d", port, buf, count); + + CHECK_OPEN_PORT(); + + if (!buf) + RETURN_ERROR(SP_ERR_ARG, "Null buffer"); + + DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name); + + if (count == 0) + RETURN_INT(0); + +#ifdef _WIN32 + DWORD written = 0; + BYTE *ptr = (BYTE *) buf; + + /* Check whether previous write is complete. */ + if (port->writing) { + if (HasOverlappedIoCompleted(&port->write_ovl)) { + DEBUG("Previous write completed"); + port->writing = 0; + } else { + DEBUG("Previous write not complete"); + /* Can't take a new write until the previous one finishes. */ + RETURN_INT(0); + } + } + + /* Set timeout. */ + port->timeouts.WriteTotalTimeoutConstant = 0; + if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) + RETURN_FAIL("SetCommTimeouts() failed"); + + /* Keep writing data until the OS has to actually start an async IO for it. + * At that point we know the buffer is full. */ + while (written < count) + { + /* Copy first byte of user buffer. */ + port->pending_byte = *ptr++; + + /* Start asynchronous write. */ + if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) { + if (GetLastError() == ERROR_IO_PENDING) { + if (HasOverlappedIoCompleted(&port->write_ovl)) { + DEBUG("Asynchronous write completed immediately"); + port->writing = 0; + written++; + continue; + } else { + DEBUG("Asynchronous write running"); + port->writing = 1; + RETURN_INT(++written); + } + } else { + /* Actual failure of some kind. */ + RETURN_FAIL("WriteFile() failed"); + } + } else { + DEBUG("Single byte written immediately"); + written++; + } + } + + DEBUG("All bytes written immediately"); + + RETURN_INT(written); +#else + /* Returns the number of bytes written, or -1 upon failure. */ + ssize_t written = write(port->fd, buf, count); + + if (written < 0) + RETURN_FAIL("write() failed"); + else + RETURN_INT(written); +#endif +} + +SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf, + size_t count, unsigned int timeout) +{ + TRACE("%p, %p, %d, %d", port, buf, count, timeout); + + CHECK_OPEN_PORT(); + + if (!buf) + RETURN_ERROR(SP_ERR_ARG, "Null buffer"); + + if (timeout) + DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms", + count, port->name, timeout); + else + DEBUG_FMT("Reading %d bytes from port %s, no timeout", + count, port->name); + + if (count == 0) + RETURN_INT(0); + +#ifdef _WIN32 + DWORD bytes_read = 0; + + /* Set timeout. */ + port->timeouts.ReadIntervalTimeout = 0; + port->timeouts.ReadTotalTimeoutConstant = timeout; + if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) + RETURN_FAIL("SetCommTimeouts() failed"); + + /* Start read. */ + if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) { + if (GetLastError() == ERROR_IO_PENDING) { + DEBUG("Waiting for read to complete"); + GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE); + DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count); + } else { + RETURN_FAIL("ReadFile() failed"); + } + } else { + DEBUG("Read completed immediately"); + bytes_read = count; + } + + /* Start background operation for subsequent events. */ + if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) { + if (GetLastError() != ERROR_IO_PENDING) + RETURN_FAIL("WaitCommEvent() failed"); + } + + RETURN_INT(bytes_read); + +#else + size_t bytes_read = 0; + unsigned char *ptr = (unsigned char *) buf; + struct timeval start, delta, now, end = {0, 0}; + fd_set fds; + int result; + + if (timeout) { + /* Get time at start of operation. */ + gettimeofday(&start, NULL); + /* Define duration of timeout. */ + delta.tv_sec = timeout / 1000; + delta.tv_usec = (timeout % 1000) * 1000; + /* Calculate time at which we should give up. */ + timeradd(&start, &delta, &end); + } + + /* Loop until we have the requested number of bytes. */ + while (bytes_read < count) + { + /* Wait until data is available. */ + FD_ZERO(&fds); + FD_SET(port->fd, &fds); + if (timeout) { + gettimeofday(&now, NULL); + if (timercmp(&now, &end, >)) + /* Timeout has expired. */ + RETURN_INT(bytes_read); + timersub(&end, &now, &delta); + } + result = select(port->fd + 1, &fds, NULL, NULL, timeout ? &delta : NULL); + if (result < 0) { + if (errno == EINTR) { + DEBUG("select() call was interrupted, repeating"); + continue; + } else { + RETURN_FAIL("select() failed"); + } + } else if (result == 0) { + DEBUG("read timed out"); + RETURN_INT(bytes_read); + } + + /* Do read. */ + result = read(port->fd, ptr, count - bytes_read); + + if (result < 0) { + if (errno == EAGAIN) + /* This shouldn't happen because we did a select() first, but handle anyway. */ + continue; + else + /* This is an actual failure. */ + RETURN_FAIL("read() failed"); + } + + bytes_read += result; + ptr += result; + } + + RETURN_INT(bytes_read); +#endif +} + +SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf, + size_t count) +{ + TRACE("%p, %p, %d", port, buf, count); + + CHECK_OPEN_PORT(); + + if (!buf) + RETURN_ERROR(SP_ERR_ARG, "Null buffer"); + + DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name); + +#ifdef _WIN32 + DWORD bytes_read; + + /* Set timeout. */ + port->timeouts.ReadIntervalTimeout = MAXDWORD; + port->timeouts.ReadTotalTimeoutConstant = 0; + if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) + RETURN_FAIL("SetCommTimeouts() failed"); + + /* Do read. */ + if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0) + RETURN_FAIL("ReadFile() failed"); + + /* Get number of bytes read. */ + if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0) + RETURN_FAIL("GetOverlappedResult() failed"); + + if (bytes_read > 0) { + /* Start background operation for subsequent events. */ + if (WaitCommEvent(port->hdl, &port->events, &port->wait_ovl) == 0) { + if (GetLastError() != ERROR_IO_PENDING) + RETURN_FAIL("WaitCommEvent() failed"); + } + } + + RETURN_INT(bytes_read); +#else + ssize_t bytes_read; + + /* Returns the number of bytes read, or -1 upon failure. */ + if ((bytes_read = read(port->fd, buf, count)) < 0) { + if (errno == EAGAIN) + /* No bytes available. */ + bytes_read = 0; + else + /* This is an actual failure. */ + RETURN_FAIL("read() failed"); + } + RETURN_INT(bytes_read); +#endif +} + +SP_API enum sp_return sp_input_waiting(struct sp_port *port) +{ + TRACE("%p", port); + + CHECK_OPEN_PORT(); + + DEBUG_FMT("Checking input bytes waiting on port %s", port->name); + +#ifdef _WIN32 + DWORD errors; + COMSTAT comstat; + + if (ClearCommError(port->hdl, &errors, &comstat) == 0) + RETURN_FAIL("ClearCommError() failed"); + RETURN_INT(comstat.cbInQue); +#else + int bytes_waiting; + if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0) + RETURN_FAIL("TIOCINQ ioctl failed"); + RETURN_INT(bytes_waiting); +#endif +} + +SP_API enum sp_return sp_output_waiting(struct sp_port *port) +{ + TRACE("%p", port); + + CHECK_OPEN_PORT(); + + DEBUG_FMT("Checking output bytes waiting on port %s", port->name); + +#ifdef _WIN32 + DWORD errors; + COMSTAT comstat; + + if (ClearCommError(port->hdl, &errors, &comstat) == 0) + RETURN_FAIL("ClearCommError() failed"); + RETURN_INT(comstat.cbOutQue); +#else + int bytes_waiting; + if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0) + RETURN_FAIL("TIOCOUTQ ioctl failed"); + RETURN_INT(bytes_waiting); +#endif +} + +SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr) +{ + struct sp_event_set *result; + + TRACE("%p", result_ptr); + + if (!result_ptr) + RETURN_ERROR(SP_ERR_ARG, "Null result"); + + *result_ptr = NULL; + + if (!(result = malloc(sizeof(struct sp_event_set)))) + RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed"); + + memset(result, 0, sizeof(struct sp_event_set)); + + *result_ptr = result; + + RETURN_OK(); +} + +static enum sp_return add_handle(struct sp_event_set *event_set, + event_handle handle, enum sp_event mask) +{ + void *new_handles; + enum sp_event *new_masks; + + TRACE("%p, %d, %d", event_set, handle, mask); + + if (!(new_handles = realloc(event_set->handles, + sizeof(event_handle) * (event_set->count + 1)))) + RETURN_ERROR(SP_ERR_MEM, "handle array realloc() failed"); + + if (!(new_masks = realloc(event_set->masks, + sizeof(enum sp_event) * (event_set->count + 1)))) + RETURN_ERROR(SP_ERR_MEM, "mask array realloc() failed"); + + event_set->handles = new_handles; + event_set->masks = new_masks; + + ((event_handle *) event_set->handles)[event_set->count] = handle; + event_set->masks[event_set->count] = mask; + + event_set->count++; + + RETURN_OK(); +} + +SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set, + const struct sp_port *port, enum sp_event mask) +{ + TRACE("%p, %p, %d", event_set, port, mask); + + if (!event_set) + RETURN_ERROR(SP_ERR_ARG, "Null event set"); + + if (!port) + RETURN_ERROR(SP_ERR_ARG, "Null port"); + + if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR)) + RETURN_ERROR(SP_ERR_ARG, "Invalid event mask"); + + if (!mask) + RETURN_OK(); + +#ifdef _WIN32 + enum sp_event handle_mask; + if ((handle_mask = mask & SP_EVENT_TX_READY)) + TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask)); + if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR))) + TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask)); +#else + TRY(add_handle(event_set, port->fd, mask)); +#endif + + RETURN_OK(); +} + +SP_API void sp_free_event_set(struct sp_event_set *event_set) +{ + TRACE("%p", event_set); + + if (!event_set) { + DEBUG("Null event set"); + RETURN(); + } + + DEBUG("Freeing event set"); + + if (event_set->handles) + free(event_set->handles); + if (event_set->masks) + free(event_set->masks); + + free(event_set); + + RETURN(); +} + +SP_API enum sp_return sp_wait(struct sp_event_set *event_set, + unsigned int timeout) +{ + TRACE("%p, %d", event_set, timeout); + + if (!event_set) + RETURN_ERROR(SP_ERR_ARG, "Null event set"); + +#ifdef _WIN32 + if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE, + timeout ? timeout : INFINITE) == WAIT_FAILED) + RETURN_FAIL("WaitForMultipleObjects() failed"); + + RETURN_OK(); +#else + struct timeval start, delta, now, end = {0, 0}; + int result, timeout_remaining; + struct pollfd *pollfds; + unsigned int i; + + if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count))) + RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed"); + + for (i = 0; i < event_set->count; i++) { + pollfds[i].fd = ((int *) event_set->handles)[i]; + pollfds[i].events = 0; + pollfds[i].revents = 0; + if (event_set->masks[i] & SP_EVENT_RX_READY) + pollfds[i].events |= POLLIN; + if (event_set->masks[i] & SP_EVENT_TX_READY) + pollfds[i].events |= POLLOUT; + if (event_set->masks[i] & SP_EVENT_ERROR) + pollfds[i].events |= POLLERR; + } + + if (timeout) { + /* Get time at start of operation. */ + gettimeofday(&start, NULL); + /* Define duration of timeout. */ + delta.tv_sec = timeout / 1000; + delta.tv_usec = (timeout % 1000) * 1000; + /* Calculate time at which we should give up. */ + timeradd(&start, &delta, &end); + } + + /* Loop until an event occurs. */ + while (1) + { + if (timeout) { + gettimeofday(&now, NULL); + if (timercmp(&now, &end, >)) { + DEBUG("wait timed out"); + break; + } + timersub(&end, &now, &delta); + timeout_remaining = delta.tv_sec * 1000 + delta.tv_usec / 1000; + } + + result = poll(pollfds, event_set->count, timeout ? timeout_remaining : -1); + + if (result < 0) { + if (errno == EINTR) { + DEBUG("poll() call was interrupted, repeating"); + continue; + } else { + free(pollfds); + RETURN_FAIL("poll() failed"); + } + } else if (result == 0) { + DEBUG("poll() timed out"); + break; + } else { + DEBUG("poll() completed"); + break; + } + } + + free(pollfds); + RETURN_OK(); +#endif +} + +#ifdef USE_TERMIOS_SPEED +static enum sp_return get_baudrate(int fd, int *baudrate) +{ + void *data; + + TRACE("%d, %p", fd, baudrate); + + DEBUG("Getting baud rate"); + + if (!(data = malloc(get_termios_size()))) + RETURN_ERROR(SP_ERR_MEM, "termios malloc failed"); + + if (ioctl(fd, get_termios_get_ioctl(), data) < 0) { + free(data); + RETURN_FAIL("getting termios failed"); + } + + *baudrate = get_termios_speed(data); + + free(data); + + RETURN_OK(); +} + +static enum sp_return set_baudrate(int fd, int baudrate) +{ + void *data; + + TRACE("%d, %d", fd, baudrate); + + DEBUG("Getting baud rate"); + + if (!(data = malloc(get_termios_size()))) + RETURN_ERROR(SP_ERR_MEM, "termios malloc failed"); + + if (ioctl(fd, get_termios_get_ioctl(), data) < 0) { + free(data); + RETURN_FAIL("getting termios failed"); + } + + DEBUG("Setting baud rate"); + + set_termios_speed(data, baudrate); + + if (ioctl(fd, get_termios_set_ioctl(), data) < 0) { + free(data); + RETURN_FAIL("setting termios failed"); + } + + free(data); + + RETURN_OK(); +} +#endif /* USE_TERMIOS_SPEED */ + +#ifdef USE_TERMIOX +static enum sp_return get_flow(int fd, struct port_data *data) +{ + void *termx; + + TRACE("%d, %p", fd, data); + + DEBUG("Getting advanced flow control"); + + if (!(termx = malloc(get_termiox_size()))) + RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed"); + + if (ioctl(fd, TCGETX, termx) < 0) { + free(termx); + RETURN_FAIL("getting termiox failed"); + } + + get_termiox_flow(termx, &data->rts_flow, &data->cts_flow, + &data->dtr_flow, &data->dsr_flow); + + free(termx); + + RETURN_OK(); +} + +static enum sp_return set_flow(int fd, struct port_data *data) +{ + void *termx; + + TRACE("%d, %p", fd, data); + + DEBUG("Getting advanced flow control"); + + if (!(termx = malloc(get_termiox_size()))) + RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed"); + + if (ioctl(fd, TCGETX, termx) < 0) { + free(termx); + RETURN_FAIL("getting termiox failed"); + } + + DEBUG("Setting advanced flow control"); + + set_termiox_flow(termx, data->rts_flow, data->cts_flow, + data->dtr_flow, data->dsr_flow); + + if (ioctl(fd, TCSETX, termx) < 0) { + free(termx); + RETURN_FAIL("setting termiox failed"); + } + + free(termx); + + RETURN_OK(); +} +#endif /* USE_TERMIOX */ + +static enum sp_return get_config(struct sp_port *port, struct port_data *data, + struct sp_port_config *config) +{ + unsigned int i; + + TRACE("%p, %p, %p", port, data, config); + + DEBUG_FMT("Getting configuration for port %s", port->name); + +#ifdef _WIN32 + if (!GetCommState(port->hdl, &data->dcb)) + RETURN_FAIL("GetCommState() failed"); + + for (i = 0; i < NUM_STD_BAUDRATES; i++) { + if (data->dcb.BaudRate == std_baudrates[i].index) { + config->baudrate = std_baudrates[i].value; + break; + } + } + + if (i == NUM_STD_BAUDRATES) + /* BaudRate field can be either an index or a custom baud rate. */ + config->baudrate = data->dcb.BaudRate; + + config->bits = data->dcb.ByteSize; + + if (data->dcb.fParity) + switch (data->dcb.Parity) { + case NOPARITY: + config->parity = SP_PARITY_NONE; + break; + case ODDPARITY: + config->parity = SP_PARITY_ODD; + break; + case EVENPARITY: + config->parity = SP_PARITY_EVEN; + break; + case MARKPARITY: + config->parity = SP_PARITY_MARK; + break; + case SPACEPARITY: + config->parity = SP_PARITY_SPACE; + break; + default: + config->parity = -1; + } + else + config->parity = SP_PARITY_NONE; + + switch (data->dcb.StopBits) { + case ONESTOPBIT: + config->stopbits = 1; + break; + case TWOSTOPBITS: + config->stopbits = 2; + break; + default: + config->stopbits = -1; + } + + switch (data->dcb.fRtsControl) { + case RTS_CONTROL_DISABLE: + config->rts = SP_RTS_OFF; + break; + case RTS_CONTROL_ENABLE: + config->rts = SP_RTS_ON; + break; + case RTS_CONTROL_HANDSHAKE: + config->rts = SP_RTS_FLOW_CONTROL; + break; + default: + config->rts = -1; + } + + config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE; + + switch (data->dcb.fDtrControl) { + case DTR_CONTROL_DISABLE: + config->dtr = SP_DTR_OFF; + break; + case DTR_CONTROL_ENABLE: + config->dtr = SP_DTR_ON; + break; + case DTR_CONTROL_HANDSHAKE: + config->dtr = SP_DTR_FLOW_CONTROL; + break; + default: + config->dtr = -1; + } + + config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE; + + if (data->dcb.fInX) { + if (data->dcb.fOutX) + config->xon_xoff = SP_XONXOFF_INOUT; + else + config->xon_xoff = SP_XONXOFF_IN; + } else { + if (data->dcb.fOutX) + config->xon_xoff = SP_XONXOFF_OUT; + else + config->xon_xoff = SP_XONXOFF_DISABLED; + } + +#else // !_WIN32 + + if (tcgetattr(port->fd, &data->term) < 0) + RETURN_FAIL("tcgetattr() failed"); + + if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0) + RETURN_FAIL("TIOCMGET ioctl failed"); + +#ifdef USE_TERMIOX + int ret = get_flow(port->fd, data); + + if (ret == SP_ERR_FAIL && errno == EINVAL) + data->termiox_supported = 0; + else if (ret < 0) + RETURN_CODEVAL(ret); + else + data->termiox_supported = 1; +#else + data->termiox_supported = 0; +#endif + + for (i = 0; i < NUM_STD_BAUDRATES; i++) { + if (cfgetispeed(&data->term) == std_baudrates[i].index) { + config->baudrate = std_baudrates[i].value; + break; + } + } + + if (i == NUM_STD_BAUDRATES) { +#ifdef __APPLE__ + config->baudrate = (int)data->term.c_ispeed; +#elif defined(USE_TERMIOS_SPEED) + TRY(get_baudrate(port->fd, &config->baudrate)); +#else + config->baudrate = -1; +#endif + } + + switch (data->term.c_cflag & CSIZE) { + case CS8: + config->bits = 8; + break; + case CS7: + config->bits = 7; + break; + case CS6: + config->bits = 6; + break; + case CS5: + config->bits = 5; + break; + default: + config->bits = -1; + } + + if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR)) + config->parity = SP_PARITY_NONE; + else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR)) + config->parity = -1; +#ifdef CMSPAR + else if (data->term.c_cflag & CMSPAR) + config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE; +#endif + else + config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN; + + config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1; + + if (data->term.c_cflag & CRTSCTS) { + config->rts = SP_RTS_FLOW_CONTROL; + config->cts = SP_CTS_FLOW_CONTROL; + } else { + if (data->termiox_supported && data->rts_flow) + config->rts = SP_RTS_FLOW_CONTROL; + else + config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF; + + config->cts = (data->termiox_supported && data->cts_flow) ? + SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE; + } + + if (data->termiox_supported && data->dtr_flow) + config->dtr = SP_DTR_FLOW_CONTROL; + else + config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF; + + config->dsr = (data->termiox_supported && data->dsr_flow) ? + SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE; + + if (data->term.c_iflag & IXOFF) { + if (data->term.c_iflag & IXON) + config->xon_xoff = SP_XONXOFF_INOUT; + else + config->xon_xoff = SP_XONXOFF_IN; + } else { + if (data->term.c_iflag & IXON) + config->xon_xoff = SP_XONXOFF_OUT; + else + config->xon_xoff = SP_XONXOFF_DISABLED; + } +#endif + + RETURN_OK(); +} + +static enum sp_return set_config(struct sp_port *port, struct port_data *data, + const struct sp_port_config *config) +{ + unsigned int i; +#ifdef __APPLE__ + BAUD_TYPE baud_nonstd; + + baud_nonstd = B0; +#endif +#ifdef USE_TERMIOS_SPEED + int baud_nonstd = 0; +#endif + + TRACE("%p, %p, %p", port, data, config); + + DEBUG_FMT("Setting configuration for port %s", port->name); + +#ifdef _WIN32 + if (config->baudrate >= 0) { + for (i = 0; i < NUM_STD_BAUDRATES; i++) { + if (config->baudrate == std_baudrates[i].value) { + data->dcb.BaudRate = std_baudrates[i].index; + break; + } + } + + if (i == NUM_STD_BAUDRATES) + data->dcb.BaudRate = config->baudrate; + } + + if (config->bits >= 0) + data->dcb.ByteSize = config->bits; + + if (config->parity >= 0) { + switch (config->parity) { + case SP_PARITY_NONE: + data->dcb.Parity = NOPARITY; + break; + case SP_PARITY_ODD: + data->dcb.Parity = ODDPARITY; + break; + case SP_PARITY_EVEN: + data->dcb.Parity = EVENPARITY; + break; + case SP_PARITY_MARK: + data->dcb.Parity = MARKPARITY; + break; + case SP_PARITY_SPACE: + data->dcb.Parity = SPACEPARITY; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting"); + } + } + + if (config->stopbits >= 0) { + switch (config->stopbits) { + /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */ + case 1: + data->dcb.StopBits = ONESTOPBIT; + break; + case 2: + data->dcb.StopBits = TWOSTOPBITS; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting"); + } + } + + if (config->rts >= 0) { + switch (config->rts) { + case SP_RTS_OFF: + data->dcb.fRtsControl = RTS_CONTROL_DISABLE; + break; + case SP_RTS_ON: + data->dcb.fRtsControl = RTS_CONTROL_ENABLE; + break; + case SP_RTS_FLOW_CONTROL: + data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting"); + } + } + + if (config->cts >= 0) { + switch (config->cts) { + case SP_CTS_IGNORE: + data->dcb.fOutxCtsFlow = FALSE; + break; + case SP_CTS_FLOW_CONTROL: + data->dcb.fOutxCtsFlow = TRUE; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting"); + } + } + + if (config->dtr >= 0) { + switch (config->dtr) { + case SP_DTR_OFF: + data->dcb.fDtrControl = DTR_CONTROL_DISABLE; + break; + case SP_DTR_ON: + data->dcb.fDtrControl = DTR_CONTROL_ENABLE; + break; + case SP_DTR_FLOW_CONTROL: + data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting"); + } + } + + if (config->dsr >= 0) { + switch (config->dsr) { + case SP_DSR_IGNORE: + data->dcb.fOutxDsrFlow = FALSE; + break; + case SP_DSR_FLOW_CONTROL: + data->dcb.fOutxDsrFlow = TRUE; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting"); + } + } + + if (config->xon_xoff >= 0) { + switch (config->xon_xoff) { + case SP_XONXOFF_DISABLED: + data->dcb.fInX = FALSE; + data->dcb.fOutX = FALSE; + break; + case SP_XONXOFF_IN: + data->dcb.fInX = TRUE; + data->dcb.fOutX = FALSE; + break; + case SP_XONXOFF_OUT: + data->dcb.fInX = FALSE; + data->dcb.fOutX = TRUE; + break; + case SP_XONXOFF_INOUT: + data->dcb.fInX = TRUE; + data->dcb.fOutX = TRUE; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting"); + } + } + + if (!SetCommState(port->hdl, &data->dcb)) + RETURN_FAIL("SetCommState() failed"); + +#else /* !_WIN32 */ + + int controlbits; + + if (config->baudrate >= 0) { + for (i = 0; i < NUM_STD_BAUDRATES; i++) { + if (config->baudrate == std_baudrates[i].value) { + if (cfsetospeed(&data->term, std_baudrates[i].index) < 0) + RETURN_FAIL("cfsetospeed() failed"); + + if (cfsetispeed(&data->term, std_baudrates[i].index) < 0) + RETURN_FAIL("cfsetispeed() failed"); + break; + } + } + + /* Non-standard baud rate */ + if (i == NUM_STD_BAUDRATES) { +#ifdef __APPLE__ + /* Set "dummy" baud rate. */ + if (cfsetspeed(&data->term, B9600) < 0) + RETURN_FAIL("cfsetspeed() failed"); + baud_nonstd = config->baudrate; +#elif defined(USE_TERMIOS_SPEED) + baud_nonstd = 1; +#else + RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported"); +#endif + } + } + + if (config->bits >= 0) { + data->term.c_cflag &= ~CSIZE; + switch (config->bits) { + case 8: + data->term.c_cflag |= CS8; + break; + case 7: + data->term.c_cflag |= CS7; + break; + case 6: + data->term.c_cflag |= CS6; + break; + case 5: + data->term.c_cflag |= CS5; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting"); + } + } + + if (config->parity >= 0) { + data->term.c_iflag &= ~IGNPAR; + data->term.c_cflag &= ~(PARENB | PARODD); +#ifdef CMSPAR + data->term.c_cflag &= ~CMSPAR; +#endif + switch (config->parity) { + case SP_PARITY_NONE: + data->term.c_iflag |= IGNPAR; + break; + case SP_PARITY_EVEN: + data->term.c_cflag |= PARENB; + break; + case SP_PARITY_ODD: + data->term.c_cflag |= PARENB | PARODD; + break; +#ifdef CMSPAR + case SP_PARITY_MARK: + data->term.c_cflag |= PARENB | PARODD; + data->term.c_cflag |= CMSPAR; + break; + case SP_PARITY_SPACE: + data->term.c_cflag |= PARENB; + data->term.c_cflag |= CMSPAR; + break; +#else + case SP_PARITY_MARK: + case SP_PARITY_SPACE: + RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported"); +#endif + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting"); + } + } + + if (config->stopbits >= 0) { + data->term.c_cflag &= ~CSTOPB; + switch (config->stopbits) { + case 1: + data->term.c_cflag &= ~CSTOPB; + break; + case 2: + data->term.c_cflag |= CSTOPB; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting"); + } + } + + if (config->rts >= 0 || config->cts >= 0) { + if (data->termiox_supported) { + data->rts_flow = data->cts_flow = 0; + switch (config->rts) { + case SP_RTS_OFF: + case SP_RTS_ON: + controlbits = TIOCM_RTS; + if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0) + RETURN_FAIL("Setting RTS signal level failed"); + break; + case SP_RTS_FLOW_CONTROL: + data->rts_flow = 1; + break; + default: + break; + } + if (config->cts == SP_CTS_FLOW_CONTROL) + data->cts_flow = 1; + + if (data->rts_flow && data->cts_flow) + data->term.c_iflag |= CRTSCTS; + else + data->term.c_iflag &= ~CRTSCTS; + } else { + /* Asymmetric use of RTS/CTS not supported. */ + if (data->term.c_iflag & CRTSCTS) { + /* Flow control can only be disabled for both RTS & CTS together. */ + if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) { + if (config->cts != SP_CTS_IGNORE) + RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together"); + } + if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) { + if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL) + RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together"); + } + } else { + /* Flow control can only be enabled for both RTS & CTS together. */ + if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) || + ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL))) + RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together"); + } + + if (config->rts >= 0) { + if (config->rts == SP_RTS_FLOW_CONTROL) { + data->term.c_iflag |= CRTSCTS; + } else { + controlbits = TIOCM_RTS; + if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, + &controlbits) < 0) + RETURN_FAIL("Setting RTS signal level failed"); + } + } + } + } + + if (config->dtr >= 0 || config->dsr >= 0) { + if (data->termiox_supported) { + data->dtr_flow = data->dsr_flow = 0; + switch (config->dtr) { + case SP_DTR_OFF: + case SP_DTR_ON: + controlbits = TIOCM_DTR; + if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0) + RETURN_FAIL("Setting DTR signal level failed"); + break; + case SP_DTR_FLOW_CONTROL: + data->dtr_flow = 1; + break; + default: + break; + } + if (config->dsr == SP_DSR_FLOW_CONTROL) + data->dsr_flow = 1; + } else { + /* DTR/DSR flow control not supported. */ + if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL) + RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported"); + + if (config->dtr >= 0) { + controlbits = TIOCM_DTR; + if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, + &controlbits) < 0) + RETURN_FAIL("Setting DTR signal level failed"); + } + } + } + + if (config->xon_xoff >= 0) { + data->term.c_iflag &= ~(IXON | IXOFF | IXANY); + switch (config->xon_xoff) { + case SP_XONXOFF_DISABLED: + break; + case SP_XONXOFF_IN: + data->term.c_iflag |= IXOFF; + break; + case SP_XONXOFF_OUT: + data->term.c_iflag |= IXON | IXANY; + break; + case SP_XONXOFF_INOUT: + data->term.c_iflag |= IXON | IXOFF | IXANY; + break; + default: + RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting"); + } + } + + if (tcsetattr(port->fd, TCSANOW, &data->term) < 0) + RETURN_FAIL("tcsetattr() failed"); + +#ifdef __APPLE__ + if (baud_nonstd != B0) { + if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1) + RETURN_FAIL("IOSSIOSPEED ioctl failed"); + /* Set baud rates in data->term to correct, but incompatible + * with tcsetattr() value, same as delivered by tcgetattr(). */ + if (cfsetspeed(&data->term, baud_nonstd) < 0) + RETURN_FAIL("cfsetspeed() failed"); + } +#elif defined(__linux__) +#ifdef USE_TERMIOS_SPEED + if (baud_nonstd) + TRY(set_baudrate(port->fd, config->baudrate)); +#endif +#ifdef USE_TERMIOX + if (data->termiox_supported) + TRY(set_flow(port->fd, data)); +#endif +#endif + +#endif /* !_WIN32 */ + + RETURN_OK(); +} + +SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr) +{ + struct sp_port_config *config; + + TRACE("%p", config_ptr); + + if (!config_ptr) + RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); + + *config_ptr = NULL; + + if (!(config = malloc(sizeof(struct sp_port_config)))) + RETURN_ERROR(SP_ERR_MEM, "config malloc failed"); + + config->baudrate = -1; + config->bits = -1; + config->parity = -1; + config->stopbits = -1; + config->rts = -1; + config->cts = -1; + config->dtr = -1; + config->dsr = -1; + + *config_ptr = config; + + RETURN_OK(); +} + +SP_API void sp_free_config(struct sp_port_config *config) +{ + TRACE("%p", config); + + if (!config) + DEBUG("Null config"); + else + free(config); + + RETURN(); +} + +SP_API enum sp_return sp_get_config(struct sp_port *port, + struct sp_port_config *config) +{ + struct port_data data; + + TRACE("%p, %p", port, config); + + CHECK_OPEN_PORT(); + + if (!config) + RETURN_ERROR(SP_ERR_ARG, "Null config"); + + TRY(get_config(port, &data, config)); + + RETURN_OK(); +} + +SP_API enum sp_return sp_set_config(struct sp_port *port, + const struct sp_port_config *config) +{ + struct port_data data; + struct sp_port_config prev_config; + + TRACE("%p, %p", port, config); + + CHECK_OPEN_PORT(); + + if (!config) + RETURN_ERROR(SP_ERR_ARG, "Null config"); + + TRY(get_config(port, &data, &prev_config)); + TRY(set_config(port, &data, config)); + + RETURN_OK(); +} + +#define CREATE_ACCESSORS(x, type) \ +SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \ + struct port_data data; \ + struct sp_port_config config; \ + TRACE("%p, %d", port, x); \ + CHECK_OPEN_PORT(); \ + TRY(get_config(port, &data, &config)); \ + config.x = x; \ + TRY(set_config(port, &data, &config)); \ + RETURN_OK(); \ +} \ +SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \ + type *x) { \ + TRACE("%p, %p", config, x); \ + if (!config) \ + RETURN_ERROR(SP_ERR_ARG, "Null config"); \ + *x = config->x; \ + RETURN_OK(); \ +} \ +SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \ + type x) { \ + TRACE("%p, %d", config, x); \ + if (!config) \ + RETURN_ERROR(SP_ERR_ARG, "Null config"); \ + config->x = x; \ + RETURN_OK(); \ +} + +CREATE_ACCESSORS(baudrate, int) +CREATE_ACCESSORS(bits, int) +CREATE_ACCESSORS(parity, enum sp_parity) +CREATE_ACCESSORS(stopbits, int) +CREATE_ACCESSORS(rts, enum sp_rts) +CREATE_ACCESSORS(cts, enum sp_cts) +CREATE_ACCESSORS(dtr, enum sp_dtr) +CREATE_ACCESSORS(dsr, enum sp_dsr) +CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff) + +SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, + enum sp_flowcontrol flowcontrol) +{ + if (!config) + RETURN_ERROR(SP_ERR_ARG, "Null configuration"); + + if (flowcontrol > SP_FLOWCONTROL_DTRDSR) + RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting"); + + if (flowcontrol == SP_FLOWCONTROL_XONXOFF) + config->xon_xoff = SP_XONXOFF_INOUT; + else + config->xon_xoff = SP_XONXOFF_DISABLED; + + if (flowcontrol == SP_FLOWCONTROL_RTSCTS) { + config->rts = SP_RTS_FLOW_CONTROL; + config->cts = SP_CTS_FLOW_CONTROL; + } else { + if (config->rts == SP_RTS_FLOW_CONTROL) + config->rts = SP_RTS_ON; + config->cts = SP_CTS_IGNORE; + } + + if (flowcontrol == SP_FLOWCONTROL_DTRDSR) { + config->dtr = SP_DTR_FLOW_CONTROL; + config->dsr = SP_DSR_FLOW_CONTROL; + } else { + if (config->dtr == SP_DTR_FLOW_CONTROL) + config->dtr = SP_DTR_ON; + config->dsr = SP_DSR_IGNORE; + } + + RETURN_OK(); +} + +SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port, + enum sp_flowcontrol flowcontrol) +{ + struct port_data data; + struct sp_port_config config; + + TRACE("%p, %d", port, flowcontrol); + + CHECK_OPEN_PORT(); + + TRY(get_config(port, &data, &config)); + + TRY(sp_set_config_flowcontrol(&config, flowcontrol)); + + TRY(set_config(port, &data, &config)); + + RETURN_OK(); +} + +SP_API enum sp_return sp_get_signals(struct sp_port *port, + enum sp_signal *signals) +{ + TRACE("%p, %p", port, signals); + + CHECK_OPEN_PORT(); + + if (!signals) + RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); + + DEBUG_FMT("Getting control signals for port %s", port->name); + + *signals = 0; +#ifdef _WIN32 + DWORD bits; + if (GetCommModemStatus(port->hdl, &bits) == 0) + RETURN_FAIL("GetCommModemStatus() failed"); + if (bits & MS_CTS_ON) + *signals |= SP_SIG_CTS; + if (bits & MS_DSR_ON) + *signals |= SP_SIG_DSR; + if (bits & MS_RLSD_ON) + *signals |= SP_SIG_DCD; + if (bits & MS_RING_ON) + *signals |= SP_SIG_RI; +#else + int bits; + if (ioctl(port->fd, TIOCMGET, &bits) < 0) + RETURN_FAIL("TIOCMGET ioctl failed"); + if (bits & TIOCM_CTS) + *signals |= SP_SIG_CTS; + if (bits & TIOCM_DSR) + *signals |= SP_SIG_DSR; + if (bits & TIOCM_CAR) + *signals |= SP_SIG_DCD; + if (bits & TIOCM_RNG) + *signals |= SP_SIG_RI; +#endif + RETURN_OK(); +} + +SP_API enum sp_return sp_start_break(struct sp_port *port) +{ + TRACE("%p", port); + + CHECK_OPEN_PORT(); +#ifdef _WIN32 + if (SetCommBreak(port->hdl) == 0) + RETURN_FAIL("SetCommBreak() failed"); +#else + if (ioctl(port->fd, TIOCSBRK, 1) < 0) + RETURN_FAIL("TIOCSBRK ioctl failed"); +#endif + + RETURN_OK(); +} + +SP_API enum sp_return sp_end_break(struct sp_port *port) +{ + TRACE("%p", port); + + CHECK_OPEN_PORT(); +#ifdef _WIN32 + if (ClearCommBreak(port->hdl) == 0) + RETURN_FAIL("ClearCommBreak() failed"); +#else + if (ioctl(port->fd, TIOCCBRK, 1) < 0) + RETURN_FAIL("TIOCCBRK ioctl failed"); +#endif + + RETURN_OK(); +} + +SP_API int sp_last_error_code(void) +{ + TRACE_VOID(); +#ifdef _WIN32 + RETURN_INT(GetLastError()); +#else + RETURN_INT(errno); +#endif +} + +SP_API char *sp_last_error_message(void) +{ + TRACE_VOID(); + +#ifdef _WIN32 + LPVOID message; + DWORD error = GetLastError(); + + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &message, + 0, NULL ); + + RETURN_STRING(message); +#else + RETURN_STRING(strerror(errno)); +#endif +} + +SP_API void sp_free_error_message(char *message) +{ + TRACE("%s", message); + +#ifdef _WIN32 + LocalFree(message); +#else + (void)message; +#endif + + RETURN(); +} + +SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...)) +{ + TRACE("%p", handler); + + sp_debug_handler = handler; + + RETURN(); +} + +SP_API void sp_default_debug_handler(const char *format, ...) +{ + va_list args; + va_start(args, format); + if (getenv("LIBSERIALPORT_DEBUG")) { + fputs("sp: ", stderr); + vfprintf(stderr, format, args); + } + va_end(args); +} + +SP_API int sp_get_major_package_version(void) +{ + return SP_PACKAGE_VERSION_MAJOR; +} + +SP_API int sp_get_minor_package_version(void) +{ + return SP_PACKAGE_VERSION_MINOR; +} + +SP_API int sp_get_micro_package_version(void) +{ + return SP_PACKAGE_VERSION_MICRO; +} + +SP_API const char *sp_get_package_version_string(void) +{ + return SP_PACKAGE_VERSION_STRING; +} + +SP_API int sp_get_current_lib_version(void) +{ + return SP_LIB_VERSION_CURRENT; +} + +SP_API int sp_get_revision_lib_version(void) +{ + return SP_LIB_VERSION_REVISION; +} + +SP_API int sp_get_age_lib_version(void) +{ + return SP_LIB_VERSION_AGE; +} + +SP_API const char *sp_get_lib_version_string(void) +{ + return SP_LIB_VERSION_STRING; +} + +/** @} */ diff --git a/vendor/github.com/mikepb/go-serial/windows.c b/vendor/github.com/mikepb/go-serial/windows.c new file mode 100644 index 0000000..b611a74 --- /dev/null +++ b/vendor/github.com/mikepb/go-serial/windows.c @@ -0,0 +1,542 @@ +/* + * This file is part of the libserialport project. + * + * Copyright (C) 2013-2014 Martin Ling + * Copyright (C) 2014 Aurelien Jacobs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifdef _WIN32 + +#include "libserialport.h" +#include "libserialport_internal.h" + +/* USB path is a string of at most 8 decimal numbers < 128 separated by dots */ +#define MAX_USB_PATH (8*3 + 7*1 + 1) + +static void enumerate_hub(struct sp_port *port, char *hub_name, + char *parent_path); + +static char *wc_to_utf8(PWCHAR wc_buffer, ULONG size) +{ + WCHAR wc_str[size/sizeof(WCHAR)+1]; + char *utf8_str; + + /* zero terminate the wide char string */ + memcpy(wc_str, wc_buffer, size); + wc_str[sizeof(wc_str)-1] = 0; + + /* compute the size of the utf8 converted string */ + if (!(size = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1, + NULL, 0, NULL, NULL))) + return NULL; + + /* allocate utf8 output buffer */ + if (!(utf8_str = malloc(size))) + return NULL; + + /* actually converted to utf8 */ + if (!WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wc_str, -1, + utf8_str, size, NULL, NULL)) { + free(utf8_str); + return NULL; + } + + return utf8_str; +} + +static char *get_root_hub_name(HANDLE host_controller) +{ + USB_ROOT_HUB_NAME root_hub_name; + PUSB_ROOT_HUB_NAME root_hub_name_wc; + char *root_hub_name_utf8; + ULONG size = 0; + + /* compute the size of the root hub name string */ + if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME, 0, 0, + &root_hub_name, sizeof(root_hub_name), &size, NULL)) + return NULL; + + /* allocate wide char root hub name string */ + size = root_hub_name.ActualLength; + if (!(root_hub_name_wc = malloc(size))) + return NULL; + + /* actually get the root hub name string */ + if (!DeviceIoControl(host_controller, IOCTL_USB_GET_ROOT_HUB_NAME, + NULL, 0, root_hub_name_wc, size, &size, NULL)) { + free(root_hub_name_wc); + return NULL; + } + + /* convert the root hub name string to utf8 */ + root_hub_name_utf8 = wc_to_utf8(root_hub_name_wc->RootHubName, size); + free(root_hub_name_wc); + return root_hub_name_utf8; +} + +static char *get_external_hub_name(HANDLE hub, ULONG connection_index) +{ + USB_NODE_CONNECTION_NAME ext_hub_name; + PUSB_NODE_CONNECTION_NAME ext_hub_name_wc; + char *ext_hub_name_utf8; + ULONG size; + + /* compute the size of the external hub name string */ + ext_hub_name.ConnectionIndex = connection_index; + if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME, + &ext_hub_name, sizeof(ext_hub_name), + &ext_hub_name, sizeof(ext_hub_name), &size, NULL)) + return NULL; + + /* allocate wide char external hub name string */ + size = ext_hub_name.ActualLength; + if (size <= sizeof(ext_hub_name) + || !(ext_hub_name_wc = malloc(size))) + return NULL; + + /* get the name of the external hub attached to the specified port */ + ext_hub_name_wc->ConnectionIndex = connection_index; + if (!DeviceIoControl(hub, IOCTL_USB_GET_NODE_CONNECTION_NAME, + ext_hub_name_wc, size, + ext_hub_name_wc, size, &size, NULL)) { + free(ext_hub_name_wc); + return NULL; + } + + /* convert the external hub name string to utf8 */ + ext_hub_name_utf8 = wc_to_utf8(ext_hub_name_wc->NodeName, size); + free(ext_hub_name_wc); + return ext_hub_name_utf8; +} + +static char *get_string_descriptor(HANDLE hub_device, ULONG connection_index, + UCHAR descriptor_index) +{ + char desc_req_buf[sizeof(USB_DESCRIPTOR_REQUEST) + + MAXIMUM_USB_STRING_LENGTH] = { 0 }; + PUSB_DESCRIPTOR_REQUEST desc_req = (void *) desc_req_buf; + PUSB_STRING_DESCRIPTOR desc = (void *) (desc_req + 1); + ULONG size = sizeof(desc_req_buf); + + desc_req->ConnectionIndex = connection_index; + desc_req->SetupPacket.wValue = (USB_STRING_DESCRIPTOR_TYPE << 8) + | descriptor_index; + desc_req->SetupPacket.wIndex = 0; + desc_req->SetupPacket.wLength = size - sizeof(*desc_req); + + if (!DeviceIoControl(hub_device, + IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, + desc_req, size, desc_req, size, &size, NULL) + || size < 2 + || desc->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE + || desc->bLength != size - sizeof(*desc_req) + || desc->bLength % 2) + return NULL; + + return wc_to_utf8(desc->bString, desc->bLength); +} + +static void enumerate_hub_ports(struct sp_port *port, HANDLE hub_device, + ULONG nb_ports, char *parent_path) +{ + char path[MAX_USB_PATH]; + ULONG index = 0; + + for (index = 1; index <= nb_ports; index++) { + PUSB_NODE_CONNECTION_INFORMATION_EX connection_info_ex; + ULONG size = sizeof(*connection_info_ex) + 30*sizeof(USB_PIPE_INFO); + + if (!(connection_info_ex = malloc(size))) + break; + + connection_info_ex->ConnectionIndex = index; + if (!DeviceIoControl(hub_device, + IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, + connection_info_ex, size, + connection_info_ex, size, &size, NULL)) { + /* try to get CONNECTION_INFORMATION if CONNECTION_INFORMATION_EX + did not work */ + PUSB_NODE_CONNECTION_INFORMATION connection_info; + + size = sizeof(*connection_info) + 30*sizeof(USB_PIPE_INFO); + if (!(connection_info = malloc(size))) { + free(connection_info_ex); + continue; + } + connection_info->ConnectionIndex = index; + if (!DeviceIoControl(hub_device, + IOCTL_USB_GET_NODE_CONNECTION_INFORMATION, + connection_info, size, + connection_info, size, &size, NULL)) { + free(connection_info); + free(connection_info_ex); + continue; + } + + connection_info_ex->ConnectionIndex = connection_info->ConnectionIndex; + connection_info_ex->DeviceDescriptor = connection_info->DeviceDescriptor; + connection_info_ex->DeviceIsHub = connection_info->DeviceIsHub; + connection_info_ex->DeviceAddress = connection_info->DeviceAddress; + free(connection_info); + } + + if (connection_info_ex->DeviceIsHub) { + /* recursively enumerate external hub */ + PCHAR ext_hub_name; + if ((ext_hub_name = get_external_hub_name(hub_device, index))) { + snprintf(path, sizeof(path), "%s%ld.", + parent_path, connection_info_ex->ConnectionIndex); + enumerate_hub(port, ext_hub_name, path); + } + free(connection_info_ex); + } else { + snprintf(path, sizeof(path), "%s%ld", + parent_path, connection_info_ex->ConnectionIndex); + + /* check if this device is the one we search for */ + if (strcmp(path, port->usb_path)) { + free(connection_info_ex); + continue; + } + + /* finally grab detailed informations regarding the device */ + port->usb_address = connection_info_ex->DeviceAddress + 1; + port->usb_vid = connection_info_ex->DeviceDescriptor.idVendor; + port->usb_pid = connection_info_ex->DeviceDescriptor.idProduct; + + if (connection_info_ex->DeviceDescriptor.iManufacturer) + port->usb_manufacturer = get_string_descriptor(hub_device,index, + connection_info_ex->DeviceDescriptor.iManufacturer); + if (connection_info_ex->DeviceDescriptor.iProduct) + port->usb_product = get_string_descriptor(hub_device, index, + connection_info_ex->DeviceDescriptor.iProduct); + if (connection_info_ex->DeviceDescriptor.iSerialNumber) + port->usb_serial = get_string_descriptor(hub_device, index, + connection_info_ex->DeviceDescriptor.iSerialNumber); + + free(connection_info_ex); + break; + } + } +} + +static void enumerate_hub(struct sp_port *port, char *hub_name, + char *parent_path) +{ + USB_NODE_INFORMATION hub_info; + HANDLE hub_device; + ULONG size = sizeof(hub_info); + char *device_name; + + /* open the hub with its full name */ + if (!(device_name = malloc(strlen("\\\\.\\") + strlen(hub_name) + 1))) + return; + strcpy(device_name, "\\\\.\\"); + strcat(device_name, hub_name); + hub_device = CreateFile(device_name, GENERIC_WRITE, FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, 0, NULL); + free(device_name); + if (hub_device == INVALID_HANDLE_VALUE) + return; + + /* get the number of ports of the hub */ + if (DeviceIoControl(hub_device, IOCTL_USB_GET_NODE_INFORMATION, + &hub_info, size, &hub_info, size, &size, NULL)) + /* enumerate the ports of the hub */ + enumerate_hub_ports(port, hub_device, + hub_info.u.HubInformation.HubDescriptor.bNumberOfPorts, parent_path); + + CloseHandle(hub_device); +} + +static void enumerate_host_controller(struct sp_port *port, + HANDLE host_controller_device) +{ + char *root_hub_name; + + if ((root_hub_name = get_root_hub_name(host_controller_device))) { + enumerate_hub(port, root_hub_name, ""); + free(root_hub_name); + } +} + +static void get_usb_details(struct sp_port *port, DEVINST dev_inst_match) +{ + HDEVINFO device_info; + SP_DEVINFO_DATA device_info_data; + ULONG i, size = 0; + + device_info = SetupDiGetClassDevs(&GUID_CLASS_USB_HOST_CONTROLLER,NULL,NULL, + DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); + device_info_data.cbSize = sizeof(device_info_data); + + for (i=0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) { + SP_DEVICE_INTERFACE_DATA device_interface_data; + PSP_DEVICE_INTERFACE_DETAIL_DATA device_detail_data; + DEVINST dev_inst = dev_inst_match; + HANDLE host_controller_device; + + device_interface_data.cbSize = sizeof(device_interface_data); + if (!SetupDiEnumDeviceInterfaces(device_info, 0, + &GUID_CLASS_USB_HOST_CONTROLLER, + i, &device_interface_data)) + continue; + + if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data, + NULL, 0, &size, NULL) + && GetLastError() != ERROR_INSUFFICIENT_BUFFER) + continue; + + if (!(device_detail_data = malloc(size))) + continue; + device_detail_data->cbSize = sizeof(*device_detail_data); + if (!SetupDiGetDeviceInterfaceDetail(device_info,&device_interface_data, + device_detail_data, size, &size, + NULL)) { + free(device_detail_data); + continue; + } + + while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS + && dev_inst != device_info_data.DevInst) { } + if (dev_inst != device_info_data.DevInst) { + free(device_detail_data); + continue; + } + + port->usb_bus = i + 1; + + host_controller_device = CreateFile(device_detail_data->DevicePath, + GENERIC_WRITE, FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, 0, NULL); + if (host_controller_device != INVALID_HANDLE_VALUE) { + enumerate_host_controller(port, host_controller_device); + CloseHandle(host_controller_device); + } + free(device_detail_data); + } + + SetupDiDestroyDeviceInfoList(device_info); + return; +} + +SP_PRIV enum sp_return get_port_details(struct sp_port *port) +{ + /* Description limited to 127 char, + anything longer would not be user friendly anyway */ + char description[128]; + SP_DEVINFO_DATA device_info_data = { .cbSize = sizeof(device_info_data) }; + HDEVINFO device_info; + int i; + + device_info = SetupDiGetClassDevs(NULL, 0, 0, + DIGCF_PRESENT | DIGCF_ALLCLASSES); + if (device_info == INVALID_HANDLE_VALUE) + RETURN_FAIL("SetupDiGetClassDevs() failed"); + + for (i=0; SetupDiEnumDeviceInfo(device_info, i, &device_info_data); i++) { + HKEY device_key; + DEVINST dev_inst; + char value[8], class[16]; + DWORD size, type; + CONFIGRET cr; + + /* check if this is the device we are looking for */ + device_key = SetupDiOpenDevRegKey(device_info, &device_info_data, + DICS_FLAG_GLOBAL, 0, + DIREG_DEV, KEY_QUERY_VALUE); + if (device_key == INVALID_HANDLE_VALUE) + continue; + size = sizeof(value); + if (RegQueryValueExA(device_key, "PortName", NULL, &type, (LPBYTE)value, + &size) != ERROR_SUCCESS || type != REG_SZ) { + RegCloseKey(device_key); + continue; + } + RegCloseKey(device_key); + value[sizeof(value)-1] = 0; + if (strcmp(value, port->name)) + continue; + + /* check port transport type */ + dev_inst = device_info_data.DevInst; + size = sizeof(class); + cr = CR_FAILURE; + while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS && + (cr = CM_Get_DevNode_Registry_PropertyA(dev_inst, + CM_DRP_CLASS, 0, class, &size, 0)) != CR_SUCCESS) { } + if (cr == CR_SUCCESS) { + if (!strcmp(class, "USB")) + port->transport = SP_TRANSPORT_USB; + } + + /* get port description (friendly name) */ + dev_inst = device_info_data.DevInst; + size = sizeof(description); + while ((cr = CM_Get_DevNode_Registry_PropertyA(dev_inst, + CM_DRP_FRIENDLYNAME, 0, description, &size, 0)) != CR_SUCCESS + && CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS) { } + if (cr == CR_SUCCESS) + port->description = strdup(description); + + /* get more informations for USB connected ports */ + if (port->transport == SP_TRANSPORT_USB) { + char usb_path[MAX_USB_PATH] = "", tmp[MAX_USB_PATH]; + char device_id[MAX_DEVICE_ID_LEN]; + + /* recurse over parents to build the USB device path */ + dev_inst = device_info_data.DevInst; + do { + /* verify that this layer of the tree is USB related */ + if (CM_Get_Device_IDA(dev_inst, device_id, + sizeof(device_id), 0) != CR_SUCCESS + || strncmp(device_id, "USB\\", 4)) + continue; + + /* discard one layer for composite devices */ + char compat_ids[512], *p = compat_ids; + size = sizeof(compat_ids); + if (CM_Get_DevNode_Registry_PropertyA(dev_inst, + CM_DRP_COMPATIBLEIDS, 0, + &compat_ids, + &size, 0) == CR_SUCCESS) { + while (*p) { + if (!strncmp(p, "USB\\COMPOSITE", 13)) + break; + p += strlen(p) + 1; + } + if (*p) + continue; + } + + /* stop the recursion when reaching the USB root */ + if (!strncmp(device_id, "USB\\ROOT", 8)) + break; + + /* prepend the address of current USB layer to the USB path */ + DWORD address; + size = sizeof(address); + if (CM_Get_DevNode_Registry_PropertyA(dev_inst, CM_DRP_ADDRESS, + 0, &address, &size, 0) == CR_SUCCESS) { + strcpy(tmp, usb_path); + snprintf(usb_path, sizeof(usb_path), "%d%s%s", + (int)address, *tmp ? "." : "", tmp); + } + } while (CM_Get_Parent(&dev_inst, dev_inst, 0) == CR_SUCCESS); + + port->usb_path = strdup(usb_path); + + /* wake up the USB device to be able to read string descriptor */ + char *escaped_port_name; + HANDLE handle; + if (!(escaped_port_name = malloc(strlen(port->name) + 5))) + RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed"); + sprintf(escaped_port_name, "\\\\.\\%s", port->name); + handle = CreateFile(escaped_port_name, GENERIC_READ, 0, 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, 0); + free(escaped_port_name); + CloseHandle(handle); + + /* retrieve USB device details from the device descriptor */ + get_usb_details(port, device_info_data.DevInst); + } + break; + } + + SetupDiDestroyDeviceInfoList(device_info); + + RETURN_OK(); +} + +SP_PRIV enum sp_return list_ports(struct sp_port ***list) +{ + HKEY key; + TCHAR *value, *data; + DWORD max_value_len, max_data_size, max_data_len; + DWORD value_len, data_size, data_len; + DWORD type, index = 0; + char *name; + int name_len; + int ret = SP_OK; + + DEBUG("Opening registry key"); + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"), + 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) { + SET_FAIL(ret, "RegOpenKeyEx() failed"); + goto out_done; + } + DEBUG("Querying registry key value and data sizes"); + if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) { + SET_FAIL(ret, "RegQueryInfoKey() failed"); + goto out_close; + } + max_data_len = max_data_size / sizeof(TCHAR); + if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR)))) { + SET_ERROR(ret, SP_ERR_MEM, "registry value malloc failed"); + goto out_close; + } + if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR)))) { + SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed"); + goto out_free_value; + } + DEBUG("Iterating over values"); + while ( + value_len = max_value_len + 1, + data_size = max_data_size, + RegEnumValue(key, index, value, &value_len, + NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS) + { + if (type == REG_SZ) { + data_len = data_size / sizeof(TCHAR); + data[data_len] = '\0'; +#ifdef UNICODE + name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL); +#else + name_len = data_len + 1; +#endif + if (!(name = malloc(name_len))) { + SET_ERROR(ret, SP_ERR_MEM, "registry port name malloc failed"); + goto out; + } +#ifdef UNICODE + WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL); +#else + strcpy(name, data); +#endif + DEBUG_FMT("Found port %s", name); + if (!(*list = list_append(*list, name))) { + SET_ERROR(ret, SP_ERR_MEM, "list append failed"); + free(name); + goto out; + } + free(name); + } + index++; + } +out: + free(data); +out_free_value: + free(value); +out_close: + RegCloseKey(key); +out_done: + + return ret; +} + +#endif