Skip to content

Instantly share code, notes, and snippets.

@saper-2
Last active February 21, 2026 23:38
Show Gist options
  • Select an option

  • Save saper-2/42d8c3ea638263d3af00e48448a5c160 to your computer and use it in GitHub Desktop.

Select an option

Save saper-2/42d8c3ea638263d3af00e48448a5c160 to your computer and use it in GitHub Desktop.
cp2112-headers-dll
/*++
VER_LEGALCOPYRIGHT_STR
Module Name:
silabs_defs.h
Abstract:
A top-level, across-all-repos, collection of some "useful" defines/enums
Environment:
User or kernel mode
--*/
//
#if (_MSC_VER > 1000)
#pragma once
#endif
#ifndef HOST_COMMON_INCLUDE_SILABS_DEFS_H_INCLUDED_BVHHTNCO7E
#define HOST_COMMON_INCLUDE_SILABS_DEFS_H_INCLUDED_BVHHTNCO7E
/// @addtogroup silabs_defs
///
/// Defines common to all Silicon Labs USB Birdge devices (GUIDs, VIDs, PIDs and Part Numbers)
///
/// @{
#include "silabs_sal.h"
#ifdef _WIN32
#if ! defined(__cplusplus)
#define bool BOOLEAN
#endif // ! defined(__cplusplus)
#else
typedef unsigned char BYTE;
#endif
#ifndef _WIN32
#define UNREFERENCED_PARAMETER(p) (void)(p)
#endif
#if defined(DEFINE_GUID)
/// @defgroup GUID_DEVINTERFACE_SILABS_GUIDS
/// @{
DEFINE_GUID(GUID_DEVINTERFACE_SILABS_CP210x,
0xa2a39220, 0x39f4, 0x4b88, 0xae, 0xcb, 0x3d, 0x86, 0xa3, 0x5d, 0xc7, 0x48);
/// CP213x Device GUID (must match WinUSB Driver INF file's interface GUID)
/// {F81D8403-3C27-45FF-98B7-3D00F19169CE}
DEFINE_GUID(GUID_DEVINTERFACE_SILABS_CP213x,
0xf81d8403, 0x3c27, 0x45ff, 0x98, 0xb7, 0x3d, 0x00, 0xf1, 0x91, 0x69, 0xce);
/// CP2615 Device GUID
/// {26C6CE68-9013-4B40-B72A-298EB2BDD269}
DEFINE_GUID(GUID_DEVINTERFACE_SILABS_CP2615,
0x26C6CE68, 0x9013, 0x4B40, 0xB7, 0x2A, 0x29, 0x8E, 0xB2, 0xBD, 0xD2, 0x69);
/// USBXpress
/// {3C5E1462-5695-4e18-876B-F3F3D08AAF18}
DEFINE_GUID(GUID_DEVINTERFACE_SILABS_USBXPRESS_BRIDGE,
0x3c5e1462, 0x5695, 0x4e18, 0x87, 0x6b, 0xf3, 0xf3, 0xd0, 0x8a, 0xaf, 0x18);
/// @}
#endif // DEFINE_GUID
#define SILABS_TEST_FILL 0xa5 ///< 10100101 A "fill" pattern, typically only used in Debug situations
/// Company Vendor ID (VID)
typedef enum _SILABS_VID {
SILABS_VID_10C4 = ((unsigned short)(0xFFFF & 0x10C4)) ///< Decimal 4292; VID aquired via Cygnal.
, SILABS_VID_1BA4 = ((unsigned short)(0xFFFF & 0x1BA4)) ///< Decimal 7076; VID aquired via Ember.
, SILABS_VID_2544 = ((unsigned short)(0xFFFF & 0x2544)) ///< Decimal 9540; VID aquired via Energy Micro.
} SILABS_VID, *PSILABS_VID;
_Check_return_
_Success_(return == TRUE)
__inline static bool IsValidSILABS_VID ( _In_ const SILABS_VID _v ) { return (SILABS_VID_10C4 == _v); }
/// Device Product IDs (PIDs)
typedef enum _SILABS_PID {
SILABS_PID_UNKNOWN = ((unsigned short)(0xFFFF & 0x0000))
, SILABS_PID_CP210SINGLEPORT = ((unsigned short)(0xFFFF & 0xEA60)) ///< Single port CP210x device/s
, SILABS_PID_CP210SINGLEPORTII = ((unsigned short)(0xFFFF & 0xEA63)) ///< Single port CP210x device/s (Windows Update PID)
, SILABS_PID_CP2101 = SILABS_PID_CP210SINGLEPORT ///< CP2101
, SILABS_PID_CP2102 = SILABS_PID_CP210SINGLEPORT ///< CP2102
, SILABS_PID_CP2102N = SILABS_PID_CP210SINGLEPORT ///< CP2102N
, SILABS_PID_CP2103 = SILABS_PID_CP210SINGLEPORT ///< CP2103
, SILABS_PID_CP2104 = SILABS_PID_CP210SINGLEPORT ///< CP2104
, SILABS_PID_CP210DUALPORT = ((unsigned short)(0xFFFF & 0xEA70)) ///< Dual port CP210x device/s
, SILABS_PID_CP210DUALPORTII = ((unsigned short)(0xFFFF & 0xEA7A)) ///< Dual port CP210x device/s (Windows Update PID)
, SILABS_PID_CP2105 = SILABS_PID_CP210DUALPORT ///< CP2105
, SILABS_PID_CP2105II = SILABS_PID_CP210DUALPORTII ///< CP2105 (Windows Update PID)
, SILABS_PID_CP210QUADPORT = ((unsigned short)(0xFFFF & 0xEA71)) ///< Quad port CP210x device/s
, SILABS_PID_CP210QUADPORTII = ((unsigned short)(0xFFFF & 0xEA7B)) ///< Quad port CP210x device/s (Windows Update PID)
, SILABS_PID_CP2108 = SILABS_PID_CP210QUADPORT ///< CP2108
, SILABS_PID_CP2108II = SILABS_PID_CP210QUADPORTII ///< CP2108 (Windows Update PID)
, SILABS_PID_CP2109 = SILABS_PID_CP210SINGLEPORT ///< CP2109
, SILABS_PID_CP2110 = ((unsigned short)(0xFFFF & 0xEA80)) ///< CP2110
, SILABS_PID_CP2111 = SILABS_PID_CP2110 ///< CP2111
, SILABS_PID_CP2112 = ((unsigned short)(0xFFFF & 0xEA90)) ///< CP2112
, SILABS_PID_CP2114 = ((unsigned short)(0xFFFF & 0xEAB0)) ///< CP2114
, SILABS_PID_CP2130 = ((unsigned short)(0xFFFF & 0x87A0)) ///< CP2130
, SILABS_PID_CP2615 = ((unsigned short)(0xFFFF & 0xEAC1)) ///< CP2615
, SILABS_PID_DIRECTACCESS = ((unsigned short)(0xFFFF & 0xEA61)) ///< Direct Access
, SILABS_PID_USBXPress = SILABS_PID_DIRECTACCESS ///< Direct Access (nee USBXPress) @deprecated SILABS_PID_USBXPress
} SILABS_PID, *PSILABS_PID;
_Check_return_
_Success_(return == TRUE)
__inline static bool IsValidSILABS_PID(_In_ const SILABS_PID _p) {
#pragma warning ( push )
#pragma warning ( disable : 6287 ) // warning C6287: redundant code: the left and right sub-expressions are identical
return ((SILABS_PID_CP210SINGLEPORT == _p) || (SILABS_PID_CP210SINGLEPORTII == _p)
|| (SILABS_PID_CP210DUALPORT == _p) || (SILABS_PID_CP210DUALPORTII == _p)
|| (SILABS_PID_CP210QUADPORT == _p) || (SILABS_PID_CP210QUADPORTII == _p)
|| (SILABS_PID_CP2101 == _p) || (SILABS_PID_CP2102 == _p) || (SILABS_PID_CP2102N == _p) || (SILABS_PID_CP2103 == _p)
|| (SILABS_PID_CP2104 == _p)
|| (SILABS_PID_CP2105 == _p) || (SILABS_PID_CP2105II == _p)
|| (SILABS_PID_CP2108 == _p) || (SILABS_PID_CP2108II == _p)
|| (SILABS_PID_CP2109 == _p)
|| (SILABS_PID_CP2110 == _p) || (SILABS_PID_CP2111 == _p) || (SILABS_PID_CP2112 == _p) || (SILABS_PID_CP2114 == _p)
|| (SILABS_PID_CP2130 == _p)
|| (SILABS_PID_CP2615 == _p)
|| (SILABS_PID_DIRECTACCESS == _p));
#pragma warning ( pop )
}
_Check_return_
_Success_(return == TRUE)
__inline static bool IsValidCP210X_PID(_In_ const SILABS_PID _p) {
#pragma warning ( push )
#pragma warning ( disable : 6287 ) // warning C6287: redundant code: the left and right sub-expressions are identical
return ((SILABS_PID_CP210SINGLEPORT == _p) || (SILABS_PID_CP210SINGLEPORTII == _p)
|| (SILABS_PID_CP210DUALPORT == _p) || (SILABS_PID_CP210DUALPORTII == _p)
|| (SILABS_PID_CP210QUADPORT == _p) || (SILABS_PID_CP210QUADPORTII == _p)
|| (SILABS_PID_CP2101 == _p) || (SILABS_PID_CP2102 == _p) || (SILABS_PID_CP2102N == _p) || (SILABS_PID_CP2103 == _p)
|| (SILABS_PID_CP2104 == _p)
|| (SILABS_PID_CP2105 == _p) || (SILABS_PID_CP2105II == _p)
|| (SILABS_PID_CP2108 == _p) || (SILABS_PID_CP2108II == _p)
|| (SILABS_PID_CP2109 == _p));
#pragma warning ( pop )
}
/// Device Part Numbers
typedef enum _SILABS_PARTNUM_CPXXXX {
CP210x_PARTNUM_UNKNOWN = ((BYTE)(0xFF & 0x00)) ///<
, CP210x_PARTNUM_CP2101 = ((BYTE)(0xFF & 0x01)) ///< CP2101
, CP210x_PARTNUM_CP2102 = ((BYTE)(0xFF & 0x02)) ///< CP2102
, CP210x_PARTNUM_CP2103 = ((BYTE)(0xFF & 0x03)) ///< CP2103
, CP210x_PARTNUM_CP2104 = ((BYTE)(0xFF & 0x04)) ///< CP2104
, CP210x_PARTNUM_CP2105 = ((BYTE)(0xFF & 0x05)) ///< CP2105
, CP210x_PARTNUM_CP2108 = ((BYTE)(0xFF & 0x08)) ///< CP2108
, CP210x_PARTNUM_CP2109 = ((BYTE)(0xFF & 0x09)) ///< CP2109
, SILABS_PARTNUM_CP2110 = ((BYTE)(0xFF & 0x0A)) ///< CP2110 HID_UART_PART_CP2110
, HID_UART_PART_CP2110 = SILABS_PARTNUM_CP2110
, CP210x_PARTNUM_CP2112 = ((BYTE)(0xFF & 0x0C)) ///< CP2112 HID_SMBUS_PART_CP2112
, HID_SMBUS_PART_CP2112 = CP210x_PARTNUM_CP2112
, SILABS_PARTNUM_CP2114 = ((BYTE)(0xFF & 0x0E)) ///< CP2114 HID_UART_PART_CP2114
, HID_UART_PART_CP2114 = SILABS_PARTNUM_CP2114
, CP210x_PARTNUM_CP2102N_QFN28 = ((BYTE)(0xFF & 0x20)) ///< CP2102N QFN28
, CP210x_PARTNUM_CP2102N_QFN24 = ((BYTE)(0xFF & 0x21)) ///< CP2102N QFN24
, CP210x_PARTNUM_CP2102N_QFN20 = ((BYTE)(0xFF & 0x22)) ///< CP2102N QFN20
, CP210x_PARTNUM_USBXPRESS_F3XX = ((BYTE)(0xFF & 0x80)) ///< USBXPRESS_F3XX
, CP210x_PARTNUM_USBXPRESS_EFM8 = ((BYTE)(0xFF & 0x80)) ///< USBXPRESS_EFM8
, CP210x_PARTNUM_USBXPRESS_EFM32 = ((BYTE)(0xFF & 0x81)) ///< USBXPRESS_EFM32
} SILABS_PARTNUM_CPXXXX, *PSILABS_PARTNUM_CPXXXX;
#define CP210X_PARTNUM SILABS_PARTNUM_CPXXXX ///< @deprecated, use @ref SILABS_PARTNUM_CPXXXX
_Check_return_
_Success_(return == TRUE)
__inline static bool IsValidCP210X_PARTNUM(_In_ const SILABS_PARTNUM_CPXXXX _v) {
return (((CP210x_PARTNUM_CP2101 <= _v) && (_v <= CP210x_PARTNUM_CP2105)) || (CP210x_PARTNUM_CP2108 == _v) || (CP210x_PARTNUM_CP2109 == _v) || (CP210x_PARTNUM_CP2112 == _v) || ((CP210x_PARTNUM_CP2102N_QFN28 <= _v) && (_v <= CP210x_PARTNUM_CP2102N_QFN20)) || (CP210x_PARTNUM_USBXPRESS_F3XX == _v));
}
_Check_return_
_Success_(return == TRUE)
__inline static bool IsCP2102N_PARTNUM(_In_ const SILABS_PARTNUM_CPXXXX _v) {
return ((CP210x_PARTNUM_CP2102N_QFN28 == _v) || (CP210x_PARTNUM_CP2102N_QFN24 == _v) || (CP210x_PARTNUM_CP2102N_QFN20 == _v));
}
_Check_return_
_Success_(return == TRUE)
__inline static bool IsOTPCP210X_PARTNUM(_In_ const SILABS_PARTNUM_CPXXXX _v) {
return ((CP210x_PARTNUM_CP2104 == _v) || (CP210x_PARTNUM_CP2105 == _v) || (CP210x_PARTNUM_CP2109 == _v));
}
_Check_return_
_Success_(return == TRUE)
__inline static bool IsOTP(_In_ const SILABS_PID _p, _In_ const SILABS_PARTNUM_CPXXXX _v) {
return IsValidCP210X_PID(_p) ? IsOTPCP210X_PARTNUM(_v) : ((SILABS_PID_CP2110 == _v) || (SILABS_PID_CP2112 == _v) || (SILABS_PID_CP2114 == _v) || (SILABS_PID_CP2130 == _v));
}
_Check_return_
_Success_(return == TRUE)
__inline static bool IsWriteReadLatchPartNum(_In_ const SILABS_PARTNUM_CPXXXX _v) {
return (IsCP2102N_PARTNUM(_v) || (CP210x_PARTNUM_CP2103 == _v) || (CP210x_PARTNUM_CP2104 == _v) || (CP210x_PARTNUM_CP2105 == _v) || (CP210x_PARTNUM_CP2108 == _v));
}
_Check_return_
_Success_(return == TRUE)
__inline static bool IsMultiInterfacePartNum(_In_ const SILABS_PARTNUM_CPXXXX _v) {
return ((CP210x_PARTNUM_CP2105 == _v) || (CP210x_PARTNUM_CP2108 == _v));
}
/// API Status return codes
/// @enum SILABS_STATUS
typedef enum _SILABS_STATUS {
SILABS_STATUS_SUCCESS = ((BYTE)(0xFF & 0x00)) ///< no error
, SILABS_STATUS_TBD = ((BYTE)(0xFF & 0x01)) ///< tbd
, SILABS_STATUS_INVALID_PARAMETER = ((BYTE)(0xFF & 0x02)) ///< a parameter was not valid
, SILABS_STATUS_INVALID_HANDLE = ((BYTE)(0xFF & 0x03)) ///< an handle parameter was not valid
, SILABS_STATUS_DEVICE_NOT_FOUND = ((BYTE)(0xFF & 0x04)) ///< the specified device was not found
, SILABS_STATUS_DEVICE_TBD = ((BYTE)(0xFF & 0x05)) ///< the specified device is tbd
, SILABS_STATUS_DEVICE_ALREADY_OPENED = ((BYTE)(0xFF & 0x06)) ///< the specified device is already (exclusively) opened
, SILABS_STATUS_DEVICE_ERROR = ((BYTE)(0xFF & 0x07)) ///< general/underetmined device-side error
, SILABS_STATUS_DEVICE_ERROR_STATE = ((BYTE)(0xFF & 0x08)) ///< device-side in wrong state to perform operation
, SILABS_STATUS_DEVICE_ERROR_TIMEOUT = ((BYTE)(0xFF & 0x09)) ///< device-side timed out the operation
, SILABS_STATUS_FUNCTION_NOT_SUPPORTED = ((BYTE)(0xFF & 0x0F)) ///< the specified function is not supported
, SILABS_STATUS_MEMORY_ALLOC_ERROR = ((BYTE)(0xFF & 0x44)) ///< an attempt to dynamically allocate memory failed
, SILABS_STATUS_SYSTEM_ERROR = ((BYTE)(0xFF & 0x74)) ///< an unexpected, unrecoverable error happened while interacting with the operating system
, SILABS_STATUS_UNKNOWN_ERROR = ((BYTE)(0xFF & 0xFF)) ///< an otherwise unclassified error occurred
} SILABS_STATUS, *PSILABS_STATUS;
_Check_return_
_Success_(return == TRUE)
__inline static bool IsValidSILABS_STATUS(_In_ const SILABS_STATUS _s) {
return (((SILABS_STATUS_SUCCESS <= _s) && (_s <= SILABS_STATUS_DEVICE_ERROR_TIMEOUT))
|| (SILABS_STATUS_FUNCTION_NOT_SUPPORTED == _s)
|| (SILABS_STATUS_MEMORY_ALLOC_ERROR == _s)
|| (SILABS_STATUS_SYSTEM_ERROR == _s)
|| (SILABS_STATUS_UNKNOWN_ERROR == _s));
}
_Check_return_
_Success_(return == TRUE)
__inline static bool IsSuccessSILABS_STATUS(_In_ const SILABS_STATUS _s) { return SILABS_STATUS_SUCCESS == _s; }
/// @}
#endif // !defined(HOST_COMMON_INCLUDE_SILABS_DEFS_H_INCLUDED_BVHHTNCO7E)
/*++
VER_LEGALCOPYRIGHT_STR
Module Name:
silabs_sal.h
Abstract:
A top-level, across all repos, authoritative, Master include file for
older IDEs that do not support the SAL-annotations that our API Header files use.
Environment:
User mode
--*/
//
#if (_MSC_VER > 1000)
#pragma once
#endif
#ifndef HOST_COMMON_INCLUDE_SILABS_SAL_H_INCLUDED_VASIQW4TVT
#define HOST_COMMON_INCLUDE_SILABS_SAL_H_INCLUDED_VASIQW4TVT
#if ! defined(_Check_return_)
#define _Check_return_
#endif // ! defined(_Check_return_)
#if ! defined(_Ret_range_)
#define _Ret_range_(lb,ub)
#endif // ! defined(_Ret_range_)
#if ! defined(_Success_)
#define _Success_(expr)
#endif // ! defined(_Success_)
#if ! defined(_In_)
#define _In_
#endif // ! defined(_In_)
#if ! defined(_In_opt_)
#define _In_opt_
#endif // ! defined(_In_opt_)
#if ! defined(_Out_)
#define _Out_
#endif // ! defined(_Out_)
#if ! defined(_In_range_)
#define _In_range_(lb,ub)
#endif // ! defined(_In_range_)
#if ! defined(_Out_range_)
#define _Out_range_(lb,ub)
#endif // ! defined(_Out_range_)
#if ! defined(_In_reads_bytes_)
#define _In_reads_bytes_(n)
#endif // ! defined(_In_reads_bytes_)
#if ! defined(_Out_writes_bytes_)
#define _Out_writes_bytes_(n)
#endif // ! defined(_Out_writes_bytes_)
#if ! defined(_Out_writes_bytes_opt_)
#define _Out_writes_bytes_opt_(n)
#endif // ! defined(_Out_writes_bytes_opt_)
#if ! defined(_Inout_updates_bytes_opt_)
#define _Inout_updates_bytes_opt_(n)
#endif // ! defined(_Inout_updates_bytes_opt_)
#if ! defined(_Printf_format_string_)
#define _Printf_format_string_
#endif // ! defined(_Printf_format_string_)
#if ! defined(_Use_decl_annotations_)
#define _Use_decl_annotations_
#endif // ! defined(_Use_decl_annotations_)
#if ! defined(_Acquires_lock_)
#define _Acquires_lock_(arg)
#endif // ! defined(_Acquires_lock_)
#if ! defined(_Releases_lock_)
#define _Releases_lock_(arg)
#endif // !defined(_Releases_lock_)
#if ! defined(_Pre_defensive_)
#define _Pre_defensive_
#endif
#if ! defined(_Struct_size_bytes_)
#define _Struct_size_bytes_(n)
#endif
#if ! defined(_Null_terminated_)
#define _Null_terminated_
#endif
#if ! defined(_Out_writes_z_)
#define _Out_writes_z_(arg)
#endif
#endif // !defined(HOST_COMMON_INCLUDE_SILABS_SAL_H_INCLUDED_VASIQW4TVT)
/*++
VER_LEGALCOPYRIGHT_STR
Module Name:
silabs_version.h
Abstract:
A top-level, authoritative, definition of some common across-all-repos/products items
Versioning based on http://semver.org/ three-field version number, but extended to Microsoft's
four-field version number. Semver's MAJOR.MINOR.PATCH extended to MAJOR.MINOR.PATCH.BUILD. Such that
1.MAJOR version when you make incompatible API changes,
2.MINOR version when you add functionality in a backwards-compatible manner,
3.PATCH version when you make backwards-compatible bug fixes, and
4.BUILD is Jenkins's BUILD_NUMBER.
Notice too, that this file contains the "Product"-level version. Each build artifact within the
"product" will have it's own, independent, "File"-level version number.
Beyond a Version number, this file contains attributes that go into a Windows .RC VERSION resource (such as
company name, copyright verbiage, etc.)
Environment:
User or kernel mode
--*/
//
#ifndef HOST_COMMON_INCLUDE_SILABS_VERSION_H_INCLUDED_I1WFULXDGP
#define HOST_COMMON_INCLUDE_SILABS_VERSION_H_INCLUDED_I1WFULXDGP
#pragma comment( user, "Compiled on " __DATE__ " at " __TIME__ )
#define VER_COMPANYNAME_LEGAL_STR "Silicon Laboratories Inc."
#define VER_COMPANYNAME_SHORT_STR "Silicon Labs"
#define VER_COMPANYNAME_ABBR_STR "SiLabs"
#define VER_LEGALCOPYRIGHT_STR "Copyright © 2019 " VER_COMPANYNAME_LEGAL_STR ", All Rights Reserved."
#define VER_PRODUCTNAME_STR VER_COMPANYNAME_SHORT_STR " USBXpress Software"
// Stringize an int
#define XSTRINGIFY2(x) #x
#define STRINGIFY(x) XSTRINGIFY2(x)
#define STR(x) XSTRINGIFY2(x) // obsolete, don't use STR() any more
// Jenkins will pass in the BUILD_NUMBER. If not, use 0.
// Some futzing necessary to detect BUILD_NUMBER= which makes BUILD_NUMBER defined but to have no value, which breaks.
#if ! defined(BUILD_NUMBER) || (7-BUILD_NUMBER-7 == 14)
#undef BUILD_NUMBER // undefine it, lest it be defined as no value (otherwise the next line throws a warning about a redefine)
#define BUILD_NUMBER (0)
#endif
#define VER_PRODUCTVERSION_MAJOR 6
#define VER_PRODUCTVERSION_MINOR 7
#define VER_PRODUCTVERSION_PATCH 7
#define VER_PRODUCTVERSION_BUILD BUILD_NUMBER
#define VER_PRODUCTVERSION VER_PRODUCTVERSION_MAJOR,VER_PRODUCTVERSION_MINOR,VER_PRODUCTVERSION_PATCH,VER_PRODUCTVERSION_BUILD
#define VER_PRODUCTVERSION_STR STRINGIFY(VER_PRODUCTVERSION_MAJOR) "." STRINGIFY(VER_PRODUCTVERSION_MINOR) "." STRINGIFY(VER_PRODUCTVERSION_PATCH) "." STRINGIFY(VER_PRODUCTVERSION_BUILD)
#define RELEASE_TAG VER_PRODUCTVERSION_STR
// Pointedly UNdefine Internal- and Original-filename so that it MUST be defined in
// respective files' .rc files.
// Original File Name - "Original name of the file, not including a path" -- MSDN
// Internal File Name - "original filename, without extension" -- MSDN
// For example, Original file name is "fubar.exe", giving an Internal file name of "fubar".
#undef VER_ORIGINALFILENAME_STR
#undef VER_INTERNALFILENAME_STR
// Pointedly UNdefine the FileVersion so that it MUST be defined in
// respective files' .rc files.
#undef VER_FILEVERSION
#undef VER_FILEVERSION_STR
#endif // !defined(HOST_COMMON_INCLUDE_SILABS_VERSION_H_INCLUDED_I1WFULXDGP)
/////////////////////////////////////////////////////////////////////////////
// SLABCP2112.h
// For SLABHIDtoSMBus.dll
// and Silicon Labs CP2112 HID to SMBus
/////////////////////////////////////////////////////////////////////////////
#ifndef HOST_LIB_SLABHIDSMBUS_INCLUDE_SLABCP2112_H_INCLUDED_QU4N7WC20W
#define HOST_LIB_SLABHIDSMBUS_INCLUDE_SLABCP2112_H_INCLUDED_QU4N7WC20W
/// @addtogroup slabhidsmbus CP2112 SMBus over HID interface Library
///
/// @{
/////////////////////////////////////////////////////////////////////////////
// Includes
/////////////////////////////////////////////////////////////////////////////
#include "Types.h"
#include "silabs_defs.h"
#include "silabs_sal.h"
/////////////////////////////////////////////////////////////////////////////
// Tool-chain-dependent hacks
/////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the HID_TO_SMBUS_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// HID_TO_SMBUS_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#if defined(HID_TO_SMBUS_EXPORTS)
#define HID_TO_SMBUS_API
#else
#define HID_TO_SMBUS_API __declspec(dllimport)
#pragma comment(lib, "SLABHIDtoSMBus.lib")
#endif // defined(HID_TO_SMBUS_EXPORTS)
#else // !_WIN32
#define HID_TO_SMBUS_API
#define WINAPI
#endif // !_WIN32
/////////////////////////////////////////////////////////////////////////////
// Return Code Definitions
/////////////////////////////////////////////////////////////////////////////
// HID_SMBUS_STATUS
#if defined(NOT_YET)
typedef enum _HID_SMBUS_STATUS {
HID_SMBUS_SUCCESS = SILABS_STATUS_SUCCESS ///< @ref SILABS_STATUS no error
, HID_SMBUS_DEVICE_NOT_FOUND = 0x01 ///< the specified device was not found
, HID_SMBUS_INVALID_HANDLE = 0x02 ///< an handle parameter was not valid
, HID_SMBUS_INVALID_DEVICE_OBJECT = 0x03
, HID_SMBUS_INVALID_PARAMETER = 0x04 ///< a parameter was not valid
, HID_SMBUS_INVALID_REQUEST_LENGTH = 0x05
, HID_SMBUS_DEVICE_ALREADY_OPENED = SILABS_STATUS_DEVICE_ALREADY_OPENED ///< the specified device is already (exclusively) opened
, HID_SMBUS_READ_ERROR = 0x10
, HID_SMBUS_WRITE_ERROR = 0x11
, HID_SMBUS_READ_TIMED_OUT = 0x12
, HID_SMBUS_WRITE_TIMED_OUT = 0x13
, HID_SMBUS_DEVICE_IO_FAILED = 0x14
, HID_SMBUS_DEVICE_ACCESS_ERROR = 0x15
, HID_SMBUS_DEVICE_NOT_SUPPORTED = 0x16
, HID_SMBUS_UNKNOWN_ERROR = SILABS_STATUS_UNKNOWN_ERROR ///< an otherwise unclassified error occurred
} HID_SMBUS_STATUS, *PHID_SMBUS_STATUS;
#else // defined(NOT_YET)
typedef int HID_SMBUS_STATUS;
// HID_SMBUS_STATUS Return Codes
/// @defgroup HID_SMBUS_STATUSReturnCodes HID_SMBUS_STATUS Return Codes definitions
/// @{
#define HID_SMBUS_SUCCESS SILABS_STATUS_SUCCESS ///< Success
#define HID_SMBUS_DEVICE_NOT_FOUND 0x01 ///< the specified device was not found
#define HID_SMBUS_INVALID_HANDLE 0x02 ///< an handle parameter was not valid
#define HID_SMBUS_INVALID_DEVICE_OBJECT 0x03 ///< the device object pointer does not match the address of a valid HID - to - UART device
#define HID_SMBUS_INVALID_PARAMETER 0x04 ///< a parameter was not valid
#define HID_SMBUS_INVALID_REQUEST_LENGTH 0x05 ///< the specified number of bytes to read or write is invalid.
#define HID_SMBUS_DEVICE_ALREADY_OPENED SILABS_STATUS_DEVICE_ALREADY_OPENED ///< the specified device is already (exclusively) opened
#define HID_SMBUS_READ_ERROR 0x10 ///< the read was not successful and did not time out.
#define HID_SMBUS_WRITE_ERROR 0x11 ///< the write was not successful.
#define HID_SMBUS_READ_TIMED_OUT 0x12 ///< a read failed to return the number of bytes requested before the read timeout elapsed.
#define HID_SMBUS_WRITE_TIMED_OUT 0x13 ///< a write failed to complete sending the number of bytes requested before the write timeout elapsed.
#define HID_SMBUS_DEVICE_IO_FAILED 0x14 ///< host was unable to get or set a feature report.
#define HID_SMBUS_DEVICE_ACCESS_ERROR 0x15 ///< the device or device property could not be accessed.Either the device is not opened, already opened when trying to open, or an error occurred when trying to get HID information.
#define HID_SMBUS_DEVICE_NOT_SUPPORTED 0x16 ///< the current device does not support the corresponding action
#define HID_SMBUS_UNKNOWN_ERROR SILABS_STATUS_UNKNOWN_ERROR ///< This value should never be returned.
/// @}
#endif // defined(NOT_YET)
// HID_SMBUS_TRANSFER_S0
typedef BYTE HID_SMBUS_S0;
/// @defgroup HID_SMBUS_S0 HID_SMBUS_S0 definitions
/// @{
#define HID_SMBUS_S0_IDLE 0x00 ///< No transfers are currently active on the bus.
#define HID_SMBUS_S0_BUSY 0x01 ///< A read or write transfer is in progress.
#define HID_SMBUS_S0_COMPLETE 0x02 ///< A read or write transfer completed without error and without retry.
#define HID_SMBUS_S0_ERROR 0x03 ///< A read or write transfer completed with an error.
/// @}
// HID_SMBUS_TRANSFER_S1
typedef BYTE HID_SMBUS_S1;
// HID_SMBUS_TRANSFER_S0 = HID_SMBUS_S0_BUSY
/// @defgroup HID_SMBUS_S1_BUSY HID_SMBUS_S1_BUSY definitions
/// @{
#define HID_SMBUS_S1_BUSY_ADDRESS_ACKED 0x00 ///< The slave address was acknowledged.
#define HID_SMBUS_S1_BUSY_ADDRESS_NACKED 0x01 ///< The slave address has not been acknowledged.
#define HID_SMBUS_S1_BUSY_READING 0x02 ///< Read data phase in progress.
#define HID_SMBUS_S1_BUSY_WRITING 0x03 ///< Write data phase in progress.
/// @}
// HID_SMBUS_TRANSFER_S0 = HID_SMBUS_S0_ERROR
/// @defgroup HID_SMBUS_S1_ERRORS HID_SMBUS_S1_ERROR definitions
/// @{
#define HID_SMBUS_S1_ERROR_TIMEOUT_NACK 0x00 ///< Tranfer timeout: SMBus slave address was NACKed
#define HID_SMBUS_S1_ERROR_TIMEOUT_BUS_NOT_FREE 0x01 ///< Tranfser timeout: SMBus not free (or SCL low timeout occurred)
#define HID_SMBUS_S1_ERROR_ARB_LOST 0x02 ///< Bus arbitration was lost
#define HID_SMBUS_S1_ERROR_READ_INCOMPLETE 0x03 ///< Read was incomplete
#define HID_SMBUS_S1_ERROR_WRITE_INCOMPLETE 0x04 ///< Write was incomplete
#define HID_SMBUS_S1_ERROR_SUCCESS_AFTER_RETRY 0x05 ///< Transfer completed after numRetries number of retries
/// @}
/////////////////////////////////////////////////////////////////////////////
// String Definitions
/////////////////////////////////////////////////////////////////////////////
// Product String Types
/// @ref HidSmbus_GetString() and @ref HidSmbus_GetOpenedString() options values
typedef enum _HID_SMBUS_GETSTRING {
HID_SMBUS_GET_VID_STR = 0x01 ///< Vendor ID string
, HID_SMBUS_GET_PID_STR = 0x02 ///< Product ID string
, HID_SMBUS_GET_PATH_STR = 0x03 ///< Path string
, HID_SMBUS_GET_SERIAL_STR = 0x04 ///< Serial Number string
, HID_SMBUS_GET_MANUFACTURER_STR = 0x05 ///< Manufacturer string
, HID_SMBUS_GET_PRODUCT_STR = 0x06 ///< Product string
} HID_SMBUS_GETSTRING, *PHID_SMBUS_GETSTRING;
_Check_return_
_Success_(return == TRUE)
__inline static bool IsValidHID_SMBUS_GETSTRING(_In_ const HID_SMBUS_GETSTRING _s) { return (HID_SMBUS_GET_VID_STR == _s) || (HID_SMBUS_GET_PID_STR == _s) || (HID_SMBUS_GET_PATH_STR == _s) || (HID_SMBUS_GET_SERIAL_STR == _s) || (HID_SMBUS_GET_MANUFACTURER_STR == _s) || (HID_SMBUS_GET_PRODUCT_STR == _s); }
// String Lengths
#define HID_SMBUS_DEVICE_STRLEN 260
// HID_SMBUS_DEVICE_STR
typedef char HID_SMBUS_DEVICE_STR[HID_SMBUS_DEVICE_STRLEN];
/////////////////////////////////////////////////////////////////////////////
// SMBUS Definitions
/////////////////////////////////////////////////////////////////////////////
// SMbus Configuration Limits
/// @defgroup SMbusConfigurationLimits SMbus Configuration Limits definitions
/// @{
#define HID_SMBUS_MIN_BIT_RATE 1
#define HID_SMBUS_MIN_TIMEOUT 0
#define HID_SMBUS_MAX_TIMEOUT 1000
#define HID_SMBUS_MAX_RETRIES 1000
#define HID_SMBUS_MIN_ADDRESS 0x02
#define HID_SMBUS_MAX_ADDRESS 0xFE
/// @}
// Read/Write Limits
/// @defgroup ReadWriteLimits Read/Write Limits definitions
/// @{
#define HID_SMBUS_MIN_READ_REQUEST_SIZE 1
#define HID_SMBUS_MAX_READ_REQUEST_SIZE 512
#define HID_SMBUS_MIN_TARGET_ADDRESS_SIZE 1
#define HID_SMBUS_MAX_TARGET_ADDRESS_SIZE 16
#define HID_SMBUS_MAX_READ_RESPONSE_SIZE 61
#define HID_SMBUS_MIN_WRITE_REQUEST_SIZE 1
#define HID_SMBUS_MAX_WRITE_REQUEST_SIZE 61
/// @}
/////////////////////////////////////////////////////////////////////////////
// GPIO Definitions
/////////////////////////////////////////////////////////////////////////////
// GPIO Pin Direction Bit Value
/// @defgroup GPIOPinDirectionBitValue GPIO Pin Direction Bit Value definitions
/// @{
#define HID_SMBUS_DIRECTION_INPUT 0 ///<
#define HID_SMBUS_DIRECTION_OUTPUT 1 ///<
/// @}
// GPIO Pin Mode Bit Value
/// @defgroup GPIOPinModeBitValue GPIO Pin Mode Bit Value definitions
/// @{
#define HID_SMBUS_MODE_OPEN_DRAIN 0 ///< Open-Drain
#define HID_SMBUS_MODE_PUSH_PULL 1 ///< Push-Pull
/// @}
// GPIO Function Bitmask
/// @defgroup GPIOFunctionBitmask GPIO Function Bitmask definitions
/// @{
#define HID_SMBUS_MASK_FUNCTION_GPIO_7_CLK 0x01 ///< Enables or disables the clock output function of GPIO.7
#define HID_SMBUS_MASK_FUNCTION_GPIO_0_TXT 0x02 ///< Enables or disables the TX toggle function of GPIO.0
#define HID_SMBUS_MASK_FUNCTION_GPIO_1_RXT 0x04 ///< Enables or disables the RX toggle function of GPIO.1
/// @}
// GPIO Function Bit Value
/// @defgroup GPIOFunctionBitValue GPIO Function Bit Value definitions
/// @{
#define HID_SMBUS_GPIO_FUNCTION 0 ///< GPIO function as configured using direction and mode.
#define HID_SMBUS_SPECIAL_FUNCTION 1 ///< Special function: GPIO.0 - TX Toggle (push - pull output) GPIO.1 - RX Toggle (push - pull output) GPIO.7 - Clock Output (push - pull output)
/// @}
// GPIO Pin Bitmask
/// @defgroup GPIOPinBitmask GPIO Pin Bitmask definitions
/// @{
#define HID_SMBUS_MASK_GPIO_0 0x01
#define HID_SMBUS_MASK_GPIO_1 0x02
#define HID_SMBUS_MASK_GPIO_2 0x04
#define HID_SMBUS_MASK_GPIO_3 0x08
#define HID_SMBUS_MASK_GPIO_4 0x10
#define HID_SMBUS_MASK_GPIO_5 0x20
#define HID_SMBUS_MASK_GPIO_6 0x40
#define HID_SMBUS_MASK_GPIO_7 0x80
/// @}
/////////////////////////////////////////////////////////////////////////////
// Part Number Definitions
/////////////////////////////////////////////////////////////////////////////
// Part Numbers
#define HID_SMBUS_PART_CP2112 CP210x_PARTNUM_CP2112
/////////////////////////////////////////////////////////////////////////////
// User Customization Definitions
/////////////////////////////////////////////////////////////////////////////
// User-Customizable Field Lock Bitmasks
/// @ref HidSmbus_SetLock() and @ref HidSmbus_GetLock() options values
typedef enum _HID_SMBUS_LOCKBITS {
HID_SMBUS_LOCK_VID = ((BYTE)(0xFF & 0x01)) ///< VID
, HID_SMBUS_LOCK_PID = ((BYTE)(0xFF & 0x02)) ///< PID
, HID_SMBUS_LOCK_POWER = ((BYTE)(0xFF & 0x04)) ///< Power
, HID_SMBUS_LOCK_POWER_MODE = ((BYTE)(0xFF & 0x08)) ///< Power Mode
, HID_SMBUS_LOCK_RELEASE_VERSION = ((BYTE)(0xFF & 0x10)) ///< Release Version
, HID_SMBUS_LOCK_MFG_STR = ((BYTE)(0xFF & 0x20)) ///< Manufacturing String
, HID_SMBUS_LOCK_PRODUCT_STR = ((BYTE)(0xFF & 0x40)) ///< Product String
, HID_SMBUS_LOCK_SERIAL_STR = ((BYTE)(0xFF & 0x80)) ///< Serial String
} HID_SMBUS_LOCKBITS, *PHID_SMBUS_LOCKBITS;
_Check_return_
_Success_(return == TRUE)
__inline static bool IsValidHID_SMBUS_HID_SMBUS_LOCKBITS(_In_ const HID_SMBUS_LOCKBITS _s)
{
return (HID_SMBUS_LOCK_VID == _s) || (HID_SMBUS_LOCK_PID == _s)
|| (HID_SMBUS_LOCK_POWER == _s) || (HID_SMBUS_LOCK_POWER_MODE == _s)
|| (HID_SMBUS_LOCK_RELEASE_VERSION == _s)
|| (HID_SMBUS_LOCK_MFG_STR == _s) || (HID_SMBUS_LOCK_PRODUCT_STR == _s) || (HID_SMBUS_LOCK_SERIAL_STR == _s);
}
// Field Lock Bit Values
/// @defgroup FieldLockBitValues Field Lock Bit Values definitions
/// @{
#define HID_SMBUS_LOCK_UNLOCKED 1 ///< Field can be customized. If the bit is set to 1, the corresponding field HAS NOT been customized
#define HID_SMBUS_LOCK_LOCKED 0 ///< Field has already been customized, or has been locked. If the bit is set to 0, the corresponding field HAS been customized or locked, and can no longer be changed for this device
/// @}
// Power Max Value (500 mA)
#define HID_SMBUS_BUS_POWER_MAX 0xFA ///< maximum power of 500mA, represented as a milliamps/2, I.e. 250 IFF bus-powered
// Power Modes
/// @defgroup PowerModes Power Modes definitions
/// @{
#define HID_SMBUS_BUS_POWER 0x00 ///< Device is bus powered
#define HID_SMBUS_SELF_POWER_VREG_DIS 0x01 ///< Device is self powered (voltage regulator disabled)
#define HID_SMBUS_SELF_POWER_VREG_EN 0x02 ///< Device is self powered (voltage regulator enabled)
/// @}
// USB Config Bitmasks
/// @defgroup USBConfigBitmasks USB Config Bitmasks definitions
/// @{
#define HID_SMBUS_SET_VID 0x01 ///< VID
#define HID_SMBUS_SET_PID 0x02 ///< PID
#define HID_SMBUS_SET_POWER 0x04 ///< Power
#define HID_SMBUS_SET_POWER_MODE 0x08 ///< Power Mode
#define HID_SMBUS_SET_RELEASE_VERSION 0x10 ///< Release Version
/// @}
// USB Config Bit Values
/// @defgroup USBConfigBitValues USB Config Bit Values definitions
/// @{
#define HID_SMBUS_SET_IGNORE 0
#define HID_SMBUS_SET_PROGRAM 1
/// @}
// String Lengths
/// @defgroup CP2112StringLengths String Lengths definitions
/// @{
#define HID_SMBUS_CP2112_MFG_STRLEN 30
#define HID_SMBUS_CP2112_PRODUCT_STRLEN 30
#define HID_SMBUS_CP2112_SERIAL_STRLEN 30
/// @}
// HID_SMBUS_MFG_STR
typedef char HID_SMBUS_CP2112_MFG_STR[HID_SMBUS_CP2112_MFG_STRLEN];
// HID_SMBUS_PRODUCT_STR
typedef char HID_SMBUS_CP2112_PRODUCT_STR[HID_SMBUS_CP2112_PRODUCT_STRLEN];
// HID_SMBUS_SERIAL_STR
typedef char HID_SMBUS_CP2112_SERIAL_STR[HID_SMBUS_CP2112_SERIAL_STRLEN];
/////////////////////////////////////////////////////////////////////////////
// Typedefs
/////////////////////////////////////////////////////////////////////////////
typedef void* HID_SMBUS_DEVICE;
/////////////////////////////////////////////////////////////////////////////
// Exported Library Functions
/////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// HidSmbus_GetNumDevices
/// @brief Determines the number of devices connected to the system with matching VID/PID
///
/// @param[out] lpdwNumDevices a pointer to a DWORD/4-byte location to hold the returned device count
/// @param[in] vid is the 2-byte Vendor ID value, filter device results by this Vendor ID.
/// @param[in] pid is the 2-byte Product ID value, filter device results by this Product ID.
///
/// @note If both vid and pid are set to 0x0000, then HID devices will not be filtered by VID/PID.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- lpdwNumDevices was not specified, or is an unexpected value
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetNumDevices(_Out_writes_bytes_(sizeof(DWORD)) _Pre_defensive_ DWORD* lpdwNumDevices, _In_ _Pre_defensive_ const WORD vid, _In_ _Pre_defensive_ const WORD pid);
// HidSmbus_GetString
/// @brief This function returns a null-terminated vendor ID string, product ID string, serial number string, device path
/// string, manufacturer string, or product string for the device specified by an index passed in deviceNum.
///
/// @detail The index for the first device is 0 and the last device is the value returned by @ref HidUart_GetNumDevices() - 1.
///
/// @param[in] deviceNum Index of the device for which the string is desired.
/// @param[in] vid is the 2-byte Vendor ID value, filter device results by this Vendor ID.
/// @param[in] pid is the 2-byte Product ID value, filter device results by this Product ID.
/// @param[out] deviceString - Variable of type @ref HID_SMBUS_DEVICE_STR which will contain a NULL terminated
/// ASCII device string on return. The string is 260 bytes on Windows and 512 bytes on macos and Linux.
/// @param[in] options - Determines if deviceString contains a vendor ID string, product ID string, serial number string,
/// device path string, manufacturer string, or product string. See @ref HID_SMBUS_GETSTRING
///
/// @note If both @ref vid and @ref pid are set to 0x0000, then HID devices will not be filtered by VID/PID.
///
/// @note BUG: This is an string-UNSAFE function, not defensive against a "too small" buffer provided as the @ref deviceString parameter.
///
/// @note Intended for use pre- @ref HidSmbus_Open() or post- @ref HidSmbus_Close(). Fails with #HID_SMBUS_DEVICE_ALREADY_OPENED otherwise.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- deviceString was not specified, and/or options is an unexpected value
/// @retval #HID_SMBUS_DEVICE_NOT_FOUND -- the specified device was not found
/// @retval #HID_SMBUS_DEVICE_ALREADY_OPENED -- the specified device is already (exclusively) opened
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetString(_In_ _Pre_defensive_ const DWORD deviceNum, _In_ _Pre_defensive_ const WORD vid, _In_ _Pre_defensive_ const WORD pid, _Out_ _Pre_defensive_ char* deviceString, _In_ _Pre_defensive_ const HID_SMBUS_GETSTRING options);
// HidSmbus_GetOpenedString
/// @brief This function returns a null-terminated vendor ID string, product ID string, serial number string, device path
/// string, manufacturer string, or product string for the device specified by device.
///
/// @param[in] device is the Device object pointer as returned by @ref HidSmbus_Open().
/// @param[out] deviceString - Variable of type @ref HID_SMBUS_DEVICE_STR which will contain a NULL terminated
/// ASCII device string on return. The string is 260 bytes on Windows and 512 bytes on macos
/// and Linux.
/// @param[in] options - Determines if deviceString contains a vendor ID string, product ID string, serial number string,
/// device path string, manufacturer string, or product string. See @ref HID_SMBUS_GETSTRING
///
/// @note BUG: This is an string-UNSAFE function, not defensive against a "too small" buffer provided as the @ref deviceString parameter.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- deviceString was not specified, and/or options is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetOpenedString(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, char* deviceString, _In_ _Pre_defensive_ const HID_SMBUS_GETSTRING options);
// HidSmbus_GetIndexedString
/// @brief This function returns a null-terminated USB string descriptor for the device specified by an index
/// passed in deviceNum. (Windows/Linux only)
///
/// @param[in] deviceNum Index of the device for which the string is desired.
/// @param[in] vid is the 2-byte Vendor ID value, filter device results by this Vendor ID.
/// @param[in] pid is the 2-byte Product ID value, filter device results by this Product ID.
/// @param[in] stringIndex - Specifies the device-specific index of the USB string descriptor to return.
/// @param[out] deviceString - Variable of type @ref HID_SMBUS_DEVICE_STR which will contain a NULL terminated
/// device descriptor string on return. The string is 260 bytes on Windows and 512 bytes on Linux.
///
/// @note If both vid and pid are set to 0x0000, then HID devices will not be filtered by VID/PID.
///
/// @note BUG: This is an string-UNSAFE function, not defensive against a "too small" buffer provided as the @ref deviceString parameter.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- deviceString was not specified, and/or options is an unexpected value
/// @retval #HID_SMBUS_DEVICE_NOT_FOUND -- the specified device was not found
/// @retval #HID_SMBUS_DEVICE_ALREADY_OPENED -- the specified device is already (exclusively) opened
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetIndexedString(_In_ _Pre_defensive_ const DWORD deviceNum, _In_ _Pre_defensive_ const WORD vid, _In_ _Pre_defensive_ const WORD pid, _In_ _Pre_defensive_ const DWORD stringIndex, char* deviceString);
// HidSmbus_GetOpenedIndexedString
/// @brief This function returns a null-terminated USB string descriptor for the device specified by device. (Windows/Linux only)
///
/// @param[in] device is the Device object pointer as returned by @ref HidSmbus_Open().
/// @param[in] stringIndex - Specifies the device-specific index of the USB string descriptor to return.
/// @param[out] deviceString - Variable of type @ref HID_SMBUS_DEVICE_STR which will contain a NULL terminated
/// device descriptor string on return. The string is 260 bytes on Windows and 512 bytes on Linux.
///
/// @note BUG: This is an string-UNSAFE function, not defensive against a "too small" buffer provided as the @ref deviceString parameter.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- deviceString is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetOpenedIndexedString(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _In_ _Pre_defensive_ const DWORD stringIndex, char* deviceString);
// HidSmbus_GetAttributes
/// @brief This function returns the device vendor ID, product ID, and device release number for the device specified
/// by an index passed in deviceNum.
///
/// @param[in] deviceNum Index of the device for which the string is desired.
/// @param[in] vid is the 2-byte Vendor ID value, filter device results by this Vendor ID.
/// @param[in] pid is the 2-byte Product ID value, filter device results by this Product ID.
/// @param[out] deviceVid - returns the 2-byte Vendor ID value from the device.
/// @param[out] devicePid - returns the 2-byte Product ID value from the device.
/// @param[out] pDeviceReleaseNumber points at a 2-byte buffer into which the USB device bcdVersion, or device release number, value will be written
///
/// @note If both vid and pid are zero (0x0000), devices will NOT be filtered by vid/pid.
///
/// @note A successfully returned pDeviceReleaseNumber is in binary-coded decimal (BCD).
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- -- deviceVid, devicePid and/or pDeviceReleaseNumber is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetAttributes(_In_ _Pre_defensive_ const DWORD deviceNum, _In_ _Pre_defensive_ const WORD vid, _In_ _Pre_defensive_ const WORD pid, _Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* deviceVid, _Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* devicePid, _Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* deviceReleaseNumber);
// HidSmbus_GetOpenedAttributes
/// @brief This function returns the device vendor ID, product ID, and device release number for the opened device.
///
/// @param[in] device is the Device object pointer as returned by @ref HidSmbus_Open().
/// @param[out] pDeviceVid - returns the 2-byte Vendor ID value from the device.
/// @param[out] pDevicePid - returns the 2-byte Product ID value from the device.
/// @param[out] pDeviceReleaseNumber points at a 2-byte buffer into which the USB device bcdVersion, or device release number, value will be written
///
/// @note A successfully returned @ref pDeviceReleaseNumber is in binary-coded decimal (BCD).
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- deviceString was not specified, and/or options is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetOpenedAttributes(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* deviceVid, _Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* devicePid, _Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* deviceReleaseNumber);
// HidSmbus_Open
/// @brief Opens a device using a device number between 0 and @ref HidSmbus_GetNumDevices() - 1, enables the
/// UART, and returns a device object pointer which will be used for subsequent accesses.
///
/// @param[out] pdevice - Returns a pointer to a HID-to-SMBUS device object for subsequent accesses to the device.
/// @param[in] deviceNum - Zero-based device index, between 0 and (@ref HidSmbus_GetNumDevices() - 1).
/// @param[in] vid is the 2-byte Vendor ID value, filter device results by this Vendor ID.
/// @param[in] pid is the 2-byte Product ID value, filter device results by this Product ID.
///
/// @note If both @ref vid and @ref pid are zero (0x0000), devices will NOT be filtered by @ref vid/@ref pid.
///
/// @note Be careful when opening a device. Any HID device may be opened by this library. However, if the
/// device is not actually a CP211x, use of this library will cause undesirable results. The best course of
/// action would be to designate a unique VID/PID for CP211x devices only. The application should then
/// filter devices using this VID/PID.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_DEVICE_NOT_FOUND -- deviceNum is an unexpected value
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- Could not access device (i.e. already opened?)
/// @retval #HID_SMBUS_DEVICE_NOT_SUPPORTED -- Per device's PartNum only support CP2110 and CP2114 devices
/// @retval #HID_SMBUS_INVALID_PARAMETER -- pdevice is an unexpected value
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_Open(_Out_writes_bytes_(sizeof(HID_SMBUS_DEVICE*)) _Pre_defensive_ HID_SMBUS_DEVICE* pdevice, _In_ _Pre_defensive_ const DWORD deviceNum, _In_ _Pre_defensive_ const WORD vid, _In_ _Pre_defensive_ const WORD pid);
// HidSmbus_Close
/// @brief Closes an opened device using the device object pointer provided by @ref HidUart_Open().
///
/// @param[in] device is the Device object pointer as returned by @ref HidSmbus_Open().
///
/// @note The device parameter is invalid after calling @ref HidSmbus_Close(). Set device to NULL after calling @ref HidSmbus_Close().
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- device is not a valid, recognized Device object
/// @retval #HID_SMBUS_INVALID_HANDLE -- failed, the device specified by device does not have a valid handle
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_Close(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device);
// HidSmbus_IsOpened
/// @brief Returns the device opened status.
///
/// @param[in] device is the Device object pointer as returned by @ref HidSmbus_Open().
/// @param[out] pbIsOpened points to a buffer into which a Boolean flag where TRUE means the device object pointer is valid and the device has been opened using @ref HidSmbus_Open(), and FALSE means it has not will be written
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- device is not a valid, recognized Device object
/// @retval #HID_SMBUS_INVALID_PARAMETER -- pbIsOpened is an unexpected value
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_IsOpened(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _Out_writes_bytes_(sizeof(BOOL)) _Pre_defensive_ BOOL* bIsOpened);
// HidSmbus_ReadRequest
/// @brief intiates a read transfer to the specified slave device address.
///
/// Read and write timeouts as well as transfer retries can be set using @ref HidSmbus_SetSmbusConfig().
///
/// HidSmbus_ReadRequest() initiates a read transfer. SMBus is a half-duplex bus, which means that
/// only one read, address read, or write transfer can be active at a time.The device will attempt to read
/// up to transferRetries number of times and for readTimeout milliseconds before timing out.
/// See HidSmbus_SetSmbusConfig() for more information on configuring read timeouts. If the autoReadRespond
/// setting is enabled, then call @ref HidSmbus_GetReadResponse() to return the results of the read transfer.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] slaveAddress the address of the slave device to read from. This value must be between
/// 0x02–0xFE. The least significant bit is the read / write bit for the SMBus transaction and must be 0.
/// @param[in] numBytesToRead is the number of bytes to read from the device (1–512).
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- slaveAddress and/or numBytesToRead is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_ReadRequest(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _In_range_(0x02,0xFE) _Pre_defensive_ const BYTE slaveAddress, _In_range_(1, 512) _Pre_defensive_ const WORD numBytesToRead);
// HidSmbus_AddressReadRequest
/// @brief intiates a read transfer to the specified slave device address and specifies the address
/// to read from on the device. Read and write timeouts as well as transfer retries can be set using
/// @ref HidSmbus_SetSmbusConfig()
///
/// HidSmbus_AddressReadRequest() initiates a read transfer. SMBus is a half-duplex bus which
/// means that only one read, address read, or write transfer can be active at a time. The device will attempt
/// to read up to transferRetries number of times and for readTimeout milliseconds before timing
/// out. See @ref HidSmbus_SetSmbusConfig() for more information on configuring read timeouts. If the
/// autoReadRespond setting is enabled, then call @ref HidSmbus_GetReadResponse() to return the results of
/// the read transfer. The device will transmit the target address on the bus after the slave device has
/// acknowledged its address. This function is designed to read from EEPROMs with an SMBus interface.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] slaveAddress the address of the slave device to read from. This value must be between
/// 0x02–0xFE. The least significant bit is the read / write bit for the SMBus transaction and must be 0.
/// @param[in] numBytesToRead is the number of bytes to read from the device (1–512).
/// @param[in] targetAddressSize is the size of the target address in bytes (1-16).
/// @param[in] targetAddress is the address to read from the slave device.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- slaveAddress and/or numBytesToRead and/or targetAddressSize and/or targetAddress is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_AddressReadRequest(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _In_range_(0x02, 0xFE) _Pre_defensive_ const BYTE slaveAddress, _In_range_(1, 512) _Pre_defensive_ const WORD numBytesToRead, _In_range_(1, 16) _Pre_defensive_ const BYTE targetAddressSize, BYTE targetAddress[16]);
// HidSmbus_ForceReadResponse
/// @brief cause the device to send a read response to the host after a read transfer has been issued.
///
/// HidSmbus_ForceReadResponse() should only be called if autoReadRespond is disabled using
/// @ref HidSmbus_SetSmbusConfig(). This allows the user to read data in a polled mode. Call
/// @ref HidSmbus_ReadRequest() or @ref HidSmbus_AddressReadRequest() first. Next, call @ref HidSmbus_TransferStatusRequest()
/// and @ref HidSmbus_TransferStatusResponse() to check if the device has received data. Next, call HidSmbus_ForceReadResponse().
/// Finally, call @ref HidSmbus_GetReadResponse() repeatedly until all read
/// data is returned.
///
/// @note Typically, this procedure is not necessary as users should enable the autoReadRespond setting.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] numBytesToRead is the number of bytes to read from the device (1–512).
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- numBytesToRead is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_ForceReadResponse(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _In_range_(1, 512) _Pre_defensive_ const WORD numBytesToRead);
// HidSmbus_GetReadResponse
/// @brief returns the read response to a read request. Read and write timeouts as well as transfer
/// retries can be set using HidSmbus_SetSmbusConfig()
///
/// HidSmbus_GetReadResponse() waits for up to readTimeout milliseconds for the device to send a
/// read response interrupt report to the host. This function should be called repeatedly until all read data
/// has been received or an error occurs. Call @ref HidSmbus_ReadRequest() or @ref HidSmbus_AddressReadRequest()
/// followed by HidSmbus_GetReadResponse() to read data when autoReadResponse is enabled
/// using @ref HidSmbus_SetSmbusConfig(). HidSmbus_GetReadResponse() will wait for up to
/// responseTimeout milliseconds before returning @ref HID_SMBUS_READ_TIMED_OUT.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] status points at a 1-byte buffer into which the status of the read request will be copied and returned. See @ref HID_SMBUS_S0.
/// @param[out] buffer - returns up to 61 read data bytes.
/// @param[in] bufferSize—is the size of buffer and must be at least 61 bytes.
/// @param[out] numBytesRead—returns the number of valid data bytes returned in buffer.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- status and/or buffer and/or buffersize and/or numBytesRead is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetReadResponse(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_Out_writes_bytes_(sizeof(HID_SMBUS_S0)) _Pre_defensive_ HID_SMBUS_S0* status,
_Out_writes_bytes_(sizeof(bufferSize)) _Pre_defensive_ BYTE* buffer,
_In_ _Pre_defensive_ const BYTE bufferSize,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* numBytesRead
);
// HidSmbus_WriteRequest
/// @brief writes the specified number of bytes from the supplied buffer to the specified slave device
/// and returns immediately after sending the request to the CP2112.
///
/// Read and write timeouts can be set using @ref HidSmbus_SetTimeouts().
///
/// Call @ref HidSmbus_TransferStatusRequest() / @ref HidSmbus_GetTransferStatusResponse() to wait for
/// the write transfer to complete before issuing another transfer request. The device waits for up to
/// transferRetries number of retries and writeTimeout number of milliseconds before timing out.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] slaveAddress the address of the slave device to write to. This value must be between
/// 0x02–0xFE. The least significant bit is the read / write bit for the SMBus transaction and must be 0.
/// @param[in] buffer—is the address of a buffer to be sent to the device.
/// @param[in] numBytesToWrite is the number of bytes to write to the device (1–61). This value must be less
/// than or equal to the size of buffer.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- slaveAddress and/or buffer and/or numBytesToWrite is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_WriteRequest(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_In_range_(0x02, 0xFE) _Pre_defensive_ const BYTE slaveAddress,
_In_reads_bytes_(numBytesToWrite) _Pre_defensive_ BYTE* buffer,
_In_range_(1, 61) _Pre_defensive_ const BYTE numBytesToWrite
);
// HidSmbus_TransferStatusRequest
/// @brief requests the status of the current read or write transfer.
///
/// Call HidSmbus_TransferStatusRequest() followed by @ref HidSmbus_GetTransferStatusResponse()
/// to get the status of the current read or write transfer.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_TransferStatusRequest(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device);
// HidSmbus_GetTransferStatusResponse
/// @brief returns the status of the current read or write transfer.
///
/// Call @ref HidSmbus_TransferStatusRequest() followed by HidSmbus_GetTransferStatusResponse()
/// to get the status of the current read or write transfer. HidSmbus_GetTransferStatusResponse() will
/// wait for up to responseTimeout milliseconds before returning @ref HID_SMBUS_READ_TIMED_OUT.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] status points at a 1-byte buffer into which the status of the read or write request will be copied and returned. See @ref HID_SMBUS_S0.
/// @param[out] detailedStatus points at a 1-byte buffer into which the extended status of the read or write request will be copied and returned. See @ref HID_SMBUS_S1.
/// @param[out] numRetries points at a 2-byte buffer into which the tbd will be copied and returned.
/// @param[out] bytesRead points at a 2-byte buffer into which the tbd will be copied and returned.
///
/// When status of @ref HID_SMBUS_S0_IDLE is returned, for detailedStatus see @ref TBD.
/// When status of @ref HID_SMBUS_S0_BUSY is returned, for detailedStatus see @ref HID_SMBUS_S1_BUSY.
/// When status of @ref HID_SMBUS_S0_ERROR is returned, for detailedStatus see @ref HID_SMBUS_S1_ERRORS.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- status and/or detailedStatus and/or numRetries and/or bytesRead is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetTransferStatusResponse(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_Out_writes_bytes_(sizeof(HID_SMBUS_S0)) _Pre_defensive_ HID_SMBUS_S0* status,
_Out_writes_bytes_(sizeof(HID_SMBUS_S1)) _Pre_defensive_ HID_SMBUS_S1* detailedStatus,
_Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* numRetries,
_Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* bytesRead
);
// HidSmbus_CancelTransfer
/// @brief cancels the current read or write transfer.
///
/// This function will clear any read responses received.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_CancelTransfer(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device);
// HidSmbus_CancelIo
/// @brief This function cancels any pending HID reads and writes (Windows Only).
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_CancelIo(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device);
// HidSmbus_SetTimeouts
/// @brief Sets the response timeouts.
///
/// Response timeouts are used by @ref HidSmbus_GetReadResponse() and @ref HidSmbus_GetTransferStatusResponse().
/// The default value for response timeouts is 1000ms, but timeouts can be set to wait for any number of
/// milliseconds between 1 and 0xFFFFFFFF. Specifying a response timeout of 0, will wait indefinitely.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] responseTimeout is the 4-byte response timeout.
///
/// @note If timeouts are set to a large value and no data is received, the application may appear unresponsive.
/// It is recommended to set timeouts appropriately before using the device. Typically, users will want to
/// specify a response timeout that is greater than the read and write timeouts.
///
/// @note Timeouts are maintained for each device but are not persistent across @ref HidSmbus_Open()/@ref HidSmbus_Close().
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_SetTimeouts(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _In_ _Pre_defensive_ const DWORD responseTimeout);
// HidSmbus_GetTimeouts
/// @brief returns the current response timeouts specified in milliseconds.
///
/// A response timeout value of 0 indicates an infinite timeout.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] responseTimeout points at a 4-byte buffer into which the response timeout will be copied and returned.
///
/// @note Timeouts are maintained for each device but are not persistent across @ref HidSmbus_Open()/@ref HidSmbus_Close().
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- responseTimeout is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetTimeouts(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _Out_writes_bytes_(sizeof(DWORD)) _Pre_defensive_ DWORD* responseTimeout);
// HidSmbus_SetSmbusConfig
/// @brief sets the SMBus bit rate, address, and transfer settings such as timeouts and retries.
///
/// Refer to the device data sheet for a list of supported configuration settings.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] bitRate is the 4-byte bit rate for SMBus communication. The default is 100 kHz. This value must be non-zero.
/// @param[in] address is the 1-byte device’s slave address (0x02–0xFE) address. The device will only acknowledge
/// this address. The default is 0x02. The least significant bit is the read/write bit for the SMBus
/// transaction and must be 0.
/// @param[in] autoReadRespond is the 4-byte boolean value that controls the read response behavior of the device. If enabled, the device will
/// automatically send read response interrupt reports to the device after initiating a read transfer. If
/// disabled, the user must call @ref HidSmbus_ForceReadResponse() before read response interrupt reports
/// will be sent to the host. The default is FALSE(0).
/// @param[in] writeTimeout is the 2-byte time limit in milliseconds (0–1000) before the device will automatically
/// cancel a write transfer. A value of 0 indicates an infinite timeout. In this case, a write transfer will
/// wait indefinitely for a write to complete or until @ref HidSmbus_CancelTransfer() is called. The default
/// is 0.
/// @param[in] readTimeout is the 2-byte time limit in milliseconds (0 - 1000) before the device will automatically
/// cancel a read transfer. A value of 0 indicates an infinite timeout. In this case, a read transfer will
/// wait indefinitely for a read to complete or until @ref HidSmbus_CancelTransfer() is called. The default
/// is 0.
/// @param[in] sclLowTimeout is the 4-byte timeout that will reset the SMBus if the SCL line is held low for more than
/// 25ms. If enabled and an SCL Low Timeout occurs, the status byte of the Transfer Status Response
/// command will be set appropriately. The default is FALSE(0).
/// @param[in] transferRetries is the 2-byte number of times to retry (0 - 1000) a failed read or write transfer. A
/// value of 0 indicates an infinite number of retries until the specified read or write timeout has
/// elapsed. The default is 0.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- bitRate and/or address and/or autoReadRespond and/or writeTimeout and/or readTimeout and/or sclLowTimeout and/or transferRetries is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_SetSmbusConfig(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_In_ _Pre_defensive_ const DWORD bitRate,
_In_range_(HID_SMBUS_MIN_ADDRESS, HID_SMBUS_MAX_ADDRESS) _Pre_defensive_ const BYTE address,
_In_ _Pre_defensive_ const BOOL autoReadRespond,
_In_range_(HID_SMBUS_MIN_TIMEOUT, HID_SMBUS_MAX_TIMEOUT) _Pre_defensive_ const WORD writeTimeout,
_In_range_(HID_SMBUS_MIN_TIMEOUT, HID_SMBUS_MAX_TIMEOUT) _Pre_defensive_ const WORD readTimeout,
_In_ _Pre_defensive_ const BOOL sclLowTimeout,
_In_range_(0, HID_SMBUS_MAX_RETRIES) _Pre_defensive_ const WORD transferRetries
);
// HidSmbus_GetSmbusConfig
/// @brief gets the SMBus bit rate, address, and transfer settings such as timeouts and retries.
///
/// Refer to the device data sheet for a list of supported configuration settings.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] bitRate returns the 4-byte bit rate for SMBus communication. The default is 100 kHz. This value must be non-zero.
/// @param[out] address returns the 1-byte device’s slave address (0x02–0xFE) address. The device will only acknowledge
/// this address. The default is 0x02. The least significant bit is the read/write bit for the SMBus
/// transaction and must be 0.
/// @param[out] autoReadRespond returns the 4-byte boolean value that controls the read response behavior of the device. If enabled, the device will
/// automatically send read response interrupt reports to the device after initiating a read transfer. If
/// disabled, the user must call @ref HidSmbus_ForceReadResponse() before read response interrupt reports
/// will be sent to the host. The default is FALSE(0).
/// @param[out] writeTimeout returns the 2-byte time limit in milliseconds (0–1000) before the device will automatically
/// cancel a write transfer. A value of 0 indicates an infinite timeout. In this case, a write transfer will
/// wait indefinitely for a write to complete or until @ref HidSmbus_CancelTransfer() is called. The default
/// is 0.
/// @param[out] readTimeout returns the 2-byte time limit in milliseconds (0 - 1000) before the device will automatically
/// cancel a read transfer. A value of 0 indicates an infinite timeout. In this case, a read transfer will
/// wait indefinitely for a read to complete or until @ref HidSmbus_CancelTransfer() is called. The default
/// is 0.
/// @param[out] sclLowTimeout returns the 4-byte timeout that will reset the SMBus if the SCL line is held low for more than
/// 25ms. If enabled and an SCL Low Timeout occurs, the status byte of the Transfer Status Response
/// command will be set appropriately. The default is FALSE(0).
/// @param[out] transferRetries returns the 2-byte number of times to retry (0 - 1000) a failed read or write transfer. A
/// value of 0 indicates an infinite number of retries until the specified read or write timeout has
/// elapsed. The default is 0.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- bitRate and/or address and/or autoReadRespond and/or writeTimeout and/or readTimeout and/or sclLowTimeout and/or transferRetries is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetSmbusConfig(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_Out_writes_bytes_(sizeof(DWORD)) _Pre_defensive_ DWORD* bitRate,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* address,
_Out_writes_bytes_(sizeof(BOOL)) _Pre_defensive_ BOOL* autoReadRespond,
_Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* writeTimeout,
_Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* readTimeout,
_Out_writes_bytes_(sizeof(BOOL)) _Pre_defensive_ BOOL* sclLowtimeout,
_Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* transferRetries
);
// HidSmbus_Reset
/// @brief initiates a full device reset. All configuration settings will be reset to their default values
/// after the device re-enumerates.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
///
/// @note Resetting the device will make the device handle stale. Users must close the device using the old
/// handle before proceeding to reconnect to the device. See more information on surprise removal.
/// See @ref HidSmbus_SetSmbusConfig() and @ref HidSmbus_SetGpioConfig() for default configuration settings.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_Reset(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device);
// HidSmbus_SetGpioConfig
/// @brief configures the GPIO pins’ directions and modes.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] direction is the 1-byte bitmask that specifies each GPIO pin’s direction. See @ref GPIOPinDirectionBitValue.
/// @param[in] mode is the 1-byte bitmask that specifies each GPIO pin’s mode. See @ref GPIOPinModeBitValue.
/// @param[in] function is the 1-byte bitmask that specifies the special behavior of GPIO.0, GPIO.1, and GPIO.7. See @ref GPIOFunctionBitmask.
/// @param[in] clkDiv is the 1-byte clock output divider value used for GPIO.7 when configured in clock output
/// mode. The frequency is equal to 48 MHz / (2 x clkDiv) when clkDiv is between 1 and 255 and
/// equal to 48 MHz when clkDiv is 0.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- direction and/or mode and/or function and/or clkDiv is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_SetGpioConfig(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_In_ _Pre_defensive_ const BYTE direction,
_In_ _Pre_defensive_ const BYTE mode,
_In_ _Pre_defensive_ const BYTE function,
_In_ _Pre_defensive_ const BYTE clkDiv
);
// HidSmbus_GetGpioConfig
/// @brief returns the GPIO pins’ directions and modes.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] direction returns the 1-byte bitmask that specifies each GPIO pin’s direction. See @ref GPIOPinDirectionBitValue.
/// @param[out] mode returns the 1-byte bitmask that specifies each GPIO pin’s mode. See @ref GPIOPinModeBitValue.
/// @param[out] function returns the 1-byte bitmask that specifies the special behavior of GPIO.0, GPIO.1, and GPIO.7. See @ref GPIOFunctionBitmask.
/// @param[out] clkDiv returns the 1-byte clock output divider value used for GPIO.7 when configured in clock output
/// mode. The frequency is equal to 48 MHz / (2 x clkDiv) when clkDiv is between 1 and 255 and
/// equal to 48 MHz when clkDiv is 0.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- direction and/or mode and/or function and/or clkDiv is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetGpioConfig(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* direction,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* mode,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* function,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* clkDiv
);
// HidSmbus_ReadLatch
/// @brief returns the current GPIO latch value.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] latchValue points at a buffer into which the current GPIO latch value will be copied and returned
///
/// If a pin is configured as an input, then the latchValue bit represents the logical voltage level received
/// on the pin. If a pin is configured as an output, then the latchValue bit represents the logical
/// voltage level driven on the pin.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- latchValue is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_ReadLatch(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* latchValue);
// HidSmbus_WriteLatch
/// @brief sets the current GPIO latch value for the specified bits.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] options is the 1-byte output value to drive on GPIO pins configured as outputs. See @ref GPIOPinBitmask.
/// @param[in] options is the 1-byte bitmask specifying which bits to modify.
///
/// @note Only GPIO pins configured as outputs with their corresponding latchMask bits set can be written to.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- deviceString was not specified, and/or options is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_WriteLatch(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_In_ _Pre_defensive_ const BYTE latchValue,
_In_ _Pre_defensive_ const BYTE latchMask
);
// HidSmbus_GetPartNumber
/// @brief retrieves the part number and version of the CP2112 device.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] partNumber points at a byte-sized buffer into which the Part Number value will be written. See @ref HID_SMBUS_PART_CP2112.
/// @param[out] version points at a byte-sized buffer into which the part's Version value will be written
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, another @ref HID_SMBUS_STATUS if there is an error:
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- device is invalid
/// @retval #HID_SMBUS_INVALID_PARAMETER -- partNumber or version is an unexpected value
/// @retval #HID_SMBUS_DEVICE_IO_FAILED -- the device failed to respond to I/O in any expected manner
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetPartNumber(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* partNumber,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* version
);
// HidSmbus_GetLibraryVersion
/// @brief Reads and returns the HID USB-to-SMBus Interface Library version
///
/// @param[out] major points at a byte-sized buffer into which the major number part of the DLL Version will be written
/// @param[out] minor points at a byte-sized buffer into which the minor number part of the DLL Version will be written
/// @param[out] bIsRelease points at a BOOL-sized buffer into which a True/False indication of whether the DLL is a Release-build or not (Debug-build) will be written
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, another @ref HID_SMBUS_STATUS if there is an error:
/// @retval #HID_SMBUS_INVALID_PARAMETER -- major or minor or bIsRelease is an unexpected value
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetLibraryVersion(_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* major, _Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* minor, _Out_writes_bytes_(sizeof(BOOL)) _Pre_defensive_ BOOL* bIsRelease);
// HidSmbus_GetHidLibraryVersion
/// @brief Reads and returns the version of the HID Device Interface Library that is currently in use.
///
/// @param major points at a byte-sized buffer into which the major number part of the Firmware Version will be written
/// @param minor points at a byte-sized buffer into which the minor number part of the Firmware Version will be written
/// @param bIsRelease points at a BOOL-sized buffer into which a True/False indication of whether the Firmware is a Release-build or not (Debug-build) will be written
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, another @ref HID_SMBUS_STATUS if there is an error:
/// @retval #HID_SMBUS_INVALID_PARAMETER -- major or minor or bIsRelease is an unexpected value
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- the device failed to respond to I/O in any expected manner
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetHidLibraryVersion(_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* major, _Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* minor, _Out_writes_bytes_(sizeof(BOOL)) _Pre_defensive_ BOOL* bIsRelease);
// HidSmbus_GetHidGuid
/// @brief Return the GUID for HIDClass devices ("return the HID GUID") (Windows only)
///
/// The HID GUID can be used to register for surprise removal notifications. See @ref MSDNURL.
///
/// @param[out] pHIDGuid points at a caller-allocated GUID buffer into which the HID GUID value will be written
///
/// @note BUG: This is an buffer-UNSAFE function, not defensive against a "too small" buffer provided as the pHIDGuid parameter.
/// @deprecated please use @ref HidUart_GetHidGuidSafe()
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- pHIDGuid is an unexpected value
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetHidGuid(_Out_ void* pHIDGuid);
// TODO: Enstone: Implement HidSmbus_GetHidGuidSafe(_Out_ GUID *pHIDGuid);
/////////////////////////////////////////////////////////////////////////////
// Exported Library Functions - Device Customization
/////////////////////////////////////////////////////////////////////////////
// HidSmbus_SetLock
/// @brief permanently locks/disables device customization.
///
/// @param[in] device is an open handle to the device as returned from @ref HidSmbus_Open()
/// @param[in] lock is a 1-byte bitmask specifying which fields can be customized/programmed and which fields
/// are already customized. See @ref HID_SMBUS_LOCKBITS and @ref FieldLockBitValues.
///
/// @note When this function is successfully called, the specified fields are fully locked and cannot be further
/// customized. The user customization functions can be called and may return HID_SMBUS_SUCCESS
/// even though the device was not programmed. Call @ref HidSmbus_GetLock() to verify
/// that customization was successful. Each field is stored in one time programmable memory(OTP) and
/// can only be customized once. After a field is customized, the corresponding lock bits are set to 0.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- lock was not specified, and/or is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_SetLock(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _In_ _Pre_defensive_ const BYTE lock);
// HidSmbus_GetLock
/// @brief Get and return the device customization lock status
///
/// @param[in] device is an open handle to the device as returned from @ref HidSmbus_Open()
/// @param[out] lock points at a 1-byte buffer into which the @ref #HID_SMBUS_LOCKBITS bitmask specifying which fields are locked will be copied and returned
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- lock was not specified, and/or is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetLock(_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device, _Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* lock);
// HidSmbus_SetUsbConfig
/// @brief This function allows one-time customization of the USB configuration, which includes vendor ID,
/// product ID, power, power mode, and release version settings.Each field can be independently programmed
/// one time via the mask field.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] vid is the 2-byte Vendor ID value.
/// @param[in] pid is the 2-byte Product ID value.
/// @param[in] power is the 1-byte power value which specifies the current requested by the device IFF the device is configured to be bus powered. See @ref HID_SMBUS_BUS_POWER_MAX.
/// @param[in] powerMode is the 1-byte Power Mode value to configure the device as bus powered or self powered. See @ref PowerModes.
/// @param[in] releaseVersion is the 2-byte user-programmable Major.Minor Release Version value.
/// @param[in] mask is the 1-byte bitmask value specifying which fields to customize. See @ref USBConfigBitmasks.
///
/// @note releaseVersion version is not the same as the device release number described in the USB device descriptor.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- power and/or powerMode is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_SetUsbConfig(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_In_ _Pre_defensive_ const WORD vid,
_In_ _Pre_defensive_ const WORD pid,
_In_range_(0, HID_SMBUS_BUS_POWER_MAX) _Pre_defensive_ const BYTE power,
_In_ _Pre_defensive_ const BYTE powerMode,
_In_ _Pre_defensive_ const WORD releaseVersion,
_In_ _Pre_defensive_ const BYTE mask
);
// HidSmbus_GetUsbConfig
/// @brief retrieves USB configuration, which includes vendor ID, product ID, power, power mode,
/// release version, and flush buffers settings.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] pVid points to a 1-byte buffer into which the Vendor ID is written and returned.
/// @param[out] pPid points to a 1-byte buffer into which the Product ID is written and returned.
/// @param[out] pPower points to a 1-byte buffer into which the power value which specifies the current requested by the device IFF the device is configured to be bus powered is written and returned. See @ref HID_SMBUS_BUS_POWER_MAX.
/// @param[out] pPowerMode points to a 1-byte buffer into which the Power Mode value to configure the device as bus powered or self powered is written and returned. See @ref PowerModes.
/// @param[out] pReleaseVersion points to a 1-byte buffer into which the Major.Minor Release Version value is written and returned.
/// @param[out] pFlushBuffers is the 2-byte Flush Buffers value is written and returned. See @ref USBConfigBitmasks.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- vid and/or pid and/or power and/or powerMode and/or releaseVersion is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetUsbConfig(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* vid,
_Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* pid,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* power,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* powerMode,
_Out_writes_bytes_(sizeof(WORD)) _Pre_defensive_ WORD* releaseVersion
);
// HidSmbus_SetManufacturingString
/// @brief Allows one-time customization of the USB manufacturing string.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] manufacturingString is a variable of type HID_SMBUS_CP2112_MFG_STR, a 30-byte character
/// buffer containing the ASCII manufacturing string.
/// @param[in] strlen is the 1-byte length of manufacturingString in bytes.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- manufacturingString and/or strlen is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_SetManufacturingString(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_In_reads_bytes_(strlen) _Pre_defensive_ char* manufacturingString,
_In_range_(0, HID_SMBUS_CP2112_MFG_STRLEN) _Pre_defensive_ const BYTE strlen
);
// HidSmbus_GetManufacturingString
/// @brief retrieves the USB manufacturing string.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] manufacturingString is a variable of type HID_SMBUS_CP2112_MFG_STR, a 30-byte character
/// buffer that will contain the ASCII manufacturing string.
/// @param[out] strlen returns the length of the string in bytes.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- manufacturingString and/or strlen is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetManufacturingString(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
char* manufacturingString,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* strlen
);
// HidSmbus_SetProductString
/// @brief allows one-time customization of the USB product string.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] productString is a variable of type HID_SMBUS_CP2112_PRODUCT_STR, a 30-byte character
/// buffer containing the ASCII product string.
/// @param[in] strlen is the length of productString in bytes. The maximum string length is 30 bytes.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- productString and/or strlen is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_SetProductString(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_In_reads_bytes_(strlen) _Pre_defensive_ char* productString,
_In_range_(0, HID_SMBUS_CP2112_PRODUCT_STRLEN) _Pre_defensive_ const BYTE strlen
);
// HidSmbus_GetProductString
/// @brief retrieves the USB product string.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] productString is a variable of type HID_SMBUS_CP2112_PRODUCT_STR, a 30-byte character
/// buffer that will contain the ASCII product string.
/// @param[out] strlen returns the length of the string in bytes.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- productString and/or strlen is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetProductString(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
char* productString,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* strlen
);
// HidSmbus_SetSerialString
/// @brief allows one-time customization of the USB serial string.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[in] serialString is a variable of type HID_SMBUS_CP2112_SERIAL_STR, a 30-byte character buffer
/// containing the ASCII serial string.
/// @param[in] strlen is the length of serialString in bytes. The maximum string length is 30 bytes.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- serialString and/or strlen is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_SetSerialString(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
_In_reads_bytes_(strlen) _Pre_defensive_ char* serialString,
_In_range_(0, HID_SMBUS_CP2112_SERIAL_STRLEN) _Pre_defensive_ const BYTE strlen
);
// HidSmbus_GetSerialString
/// @brief retrieves the USB product string.
///
/// @param[in] device is an open handle to the device as returned by @ref HidSmbus_Open().
/// @param[out] serialString is a variable of type HID_SMBUS_CP2112_SERIAL_STR, a 30-byte character buffer
/// that will contain the ASCII product string.
/// @param[out] strlen returns the length of the string in bytes.
///
/// @returns Returns #HID_SMBUS_SUCCESS on success, or another @ref HID_SMBUS_STATUS Return value if there is an error.
/// @retval #HID_SMBUS_SUCCESS -- success
/// @retval #HID_SMBUS_INVALID_PARAMETER -- serialString and/or strlen is an unexpected value
/// @retval #HID_SMBUS_INVALID_DEVICE_OBJECT -- the specified device is invalid
/// @retval #HID_SMBUS_DEVICE_ACCESS_ERROR -- tbd
_Check_return_
_Ret_range_(HID_SMBUS_SUCCESS, HID_SMBUS_UNKNOWN_ERROR)
_Success_(HID_SMBUS_SUCCESS)
HID_TO_SMBUS_API HID_SMBUS_STATUS WINAPI
HidSmbus_GetSerialString(
_In_ _Pre_defensive_ const HID_SMBUS_DEVICE device,
char* serialString,
_Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ BYTE* strlen
);
#ifdef __cplusplus
}
#endif // __cplusplus
/// @}
#endif // HOST_LIB_SLABHIDSMBUS_INCLUDE_SLABCP2112_H_INCLUDED_QU4N7WC20W
////////////////////////////////////////////////////////////////////////////////
// SLABHIDDevice.h
////////////////////////////////////////////////////////////////////////////////
#ifndef HOST_LIB_SLABHIDDEVICE_INCLUDE_SLABHIDDEVICE_H_INCLUDED_MJWYLEYUPA
#define HOST_LIB_SLABHIDDEVICE_INCLUDE_SLABHIDDEVICE_H_INCLUDED_MJWYLEYUPA
/// @addtogroup slabhiddevice CP211x HID-based interface Library
///
/// The Silicon Labs CP211x USB-to-HID bridges are devices that communicate over
/// the Universal Serial Bus (USB) to perform Universal Asynchronous Receiver / Transmitter
/// (UART) data transfers. These devices have many programmable options that can
/// be configured via USB. These devices also often include flexible GPIO functions that
/// can be configured and accessed via USB during runtime. Silicon Labs provides libraries
/// that can be used to configure these devices and access their GPIOs.
///
/// Two interface library files can be used to interface with CP211x devices, CP210xManufacturing.DLL and .LIB, which is responsible for reading and writing
/// the device settings, and CP210xRuntime.DLL and .LIB, which is responsible for interfacing with the device's GPIOs. The APIs for CP210xManufacturing are
/// described below.
///
/// This document supercedes, obsoletes and takes precedences over AN532.
///
/// The CP211x SLABHIDDevice Host API is provided as a means to facilitate production of customized CP211x devices. This API allows access to the
/// CP211x device for retrieving and setting the VID, PID, product string, serial number, self - power attribute, maximum power consumption,
/// and device version.
///
/// The CP211x SLABHIDDevice Host API is provided in the form of a Windows Dynamic Link Library (DLL), SLABHIDDevice.DLL and as a Windows
/// static link library (SLABHIDDevice.static.LIB). The host interface
/// library communicates with the bridge controller device via the provided device driver and the operating system's USB stack.
///
/// Custom applications can use the CP211x SLABHIDDevice API implemented in SLABHIDDevice.DLL. To use functions implemented in SLABHIDDevice.DLL link SLABHIDDevice.LIB
/// include SLABHIDDevice.h into any source code files that call any functions implemented in SLABHIDDevice.DLL and include the PATH to the location of SLABHIDDevice.DLL
/// in your custom application Visual Studio .VCXPROJ Profile File's Properties->Linker->General->Additional Library Directories property.
///
/// Typically, the user initiates communication with the target CP211x device by making a call to @ref HidDevice_GetNumHidDevices(). This call
/// returns the number of CP211x target devices. This number is used as a range when calling @ref HidDevice_GetHidString() to build a list
/// of devices connected to the host machine.
/// A handle to the device must first be opened by a call to @ref HidDevice_Open() using an index determined from the call to @ref HidDevice_GetNumHidDevices().
/// The handle will be used for all subsequent accesses. When I/O operations are complete, the device handle is closed by a call to
/// @ref HidDevice_Close().
///
/// @{
/////////////////////////////////////////////////////////////////////////////
// Includes
/////////////////////////////////////////////////////////////////////////////
#include "silabs_defs.h"
#include "silabs_sal.h"
#ifdef _WIN32
#include <windows.h>
#else // !_WIN32
#endif // !_WIN32
#include "Types.h"
#ifdef _WIN32
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the CP210xDLL_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// CP210xDLL_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef SLAB_HID_DEVICE_EXPORTS
#define SLAB_HID_DEVICE_API
#elif defined(SLAB_HID_DEVICE_BUILD_SOURCE)
#define SLAB_HID_DEVICE_API
#else
#if defined(SILABS_STATIC_LINK)
#define SLAB_HID_DEVICE_API extern
#pragma comment (lib, "SLABHIDDevice.static.lib")
#else // defined(SILABS_STATIC_LINK)
#define SLAB_HID_DEVICE_API __declspec(dllimport)
#pragma comment (lib, "SLABHIDDevice.lib")
#endif // defined(SILABS_STATIC_LINK)
#endif
#else // !_WIN32
#define SLAB_HID_DEVICE_API
#define WINAPI
#endif // !_WIN32
/////////////////////////////////////////////////////////////////////////////
// Definitions
/////////////////////////////////////////////////////////////////////////////
/// API Status return codes
#define USE_LEGACY_SLAB_HID_DEVICE_STATUS
#if !defined(USE_LEGACY_SLAB_HID_DEVICE_STATUS) // TODO: Enstone: These defines are a exact duplicate values of HID_DEVICE_STATUS enums in HIDDevice.h.
typedef enum _SLAB_HID_DEVICE_STATUS {
HID_DEVICE_SUCCESS = SILABS_STATUS_SUCCESS ///< @ref SILABS_STATUS no error
, HID_DEVICE_NOT_FOUND = 0x01 ///< the specified device was not found
, HID_DEVICE_NOT_OPENED = 0x02
, HID_DEVICE_ALREADY_OPENED = 0x03
, HID_DEVICE_TRANSFER_TIMEOUT = 0x04
, HID_DEVICE_TRANSFER_FAILED = 0x05
, HID_DEVICE_CANNOT_GET_HID_INFO = 0x06
, HID_DEVICE_HANDLE_ERROR = 0x07
, HID_DEVICE_INVALID_BUFFER_SIZE = 0x08
, HID_DEVICE_SYSTEM_CODE = 0x09
, HID_DEVICE_UNSUPPORTED_FUNCTION = 0x0A
, HID_DEVICE_UNKNOWN_ERROR = SILABS_STATUS_UNKNOWN_ERROR
} SLAB_HID_DEVICE_STATUS, *PSLAB_HID_DEVICE_STATUS;
#else // defined(NOT_YET)
/// @defgroup SLAB_HID_DEVICE_STATUS HID Device Status Codes
/// @{
typedef BYTE SLAB_HID_DEVICE_STATUS; ///< SLAB HID Device Status Codes
#define HID_DEVICE_SUCCESS SILABS_STATUS_SUCCESS ///< @ref SILABS_STATUS no error
#define HID_DEVICE_NOT_FOUND 0x01 ///< Indicates that the specified device index was invalid or the device does not exist or is inaccessible.
#define HID_DEVICE_NOT_OPENED 0x02 ///< Indicates that the device must be opened prior to calling the function.
#define HID_DEVICE_ALREADY_OPENED 0x03 ///< Indicates that the device is already opened and cannot be re-opened.
#define HID_DEVICE_TRANSFER_TIMEOUT 0x04 ///< Indicates that a get or set report function returned due to a timeout. @ref HidDevice_GetInputReport_Interrupt() and/or @ref HidDevice_GetInputReport_Interrupt_WithTimeout() returned with less bytes than requested.
#define HID_DEVICE_TRANSFER_FAILED 0x05 ///< The host failed to communicate with the device or function parameters are incorrect.
#define HID_DEVICE_CANNOT_GET_HID_INFO 0x06 ///< Cannot retrieve device path or hidStringType is invalid.
#define HID_DEVICE_HANDLE_ERROR 0x07 ///< HID CreateFile() handle is invalid.
#define HID_DEVICE_INVALID_BUFFER_SIZE 0x08 ///< Specified buffer is not large enough to return requested data.
#define HID_DEVICE_SYSTEM_CODE 0x09 ///< Indicates that a system error occurred. Call Windows GetLastError() to retrieve the system error code.
#define HID_DEVICE_UNSUPPORTED_FUNCTION 0x0A ///< The function is only supported on certain (newer?) Windows versions.
#define HID_DEVICE_INVALID_PARAMETER 0x0B ///< Specified (typically non-buffer related) parameter is wrong or unexpected
#define HID_DEVICE_UNKNOWN_ERROR SILABS_STATUS_UNKNOWN_ERROR ///< This is the default return code value. This value should never be returned.
/// @}
#endif // defined(NOT_YET)
/// Max number of USB Devices allowed
#define MAX_USB_DEVICES 64
/// @defgroup SLABHIDDEVICE_MAX_REPORT_REQUESTS Max number of reports that can be requested at time
/// @{
#define MAX_REPORT_REQUEST_XP 512 ///< Maximum number of input report buffers for Windows XP and later.
#define MAX_REPORT_REQUEST_2K 200 ///< Maximum number of input report buffers for Windows 2000.
#define DEFAULT_REPORT_INPUT_BUFFERS 0 ///< Use OS-dependent HID driver default.
/// @}
/// String Types // TODO: Enstone: These defines are a exact duplicate values of HID_DEVICE_STRING_ID enums in HIDDevice.h.
#define HID_VID_STRING 0x01 ///< VID string, derived from @ref HID_PATH_STRING
#define HID_PID_STRING 0x02 ///< PID string, derived from @ref HID_PATH_STRING
#define HID_PATH_STRING 0x03 ///< Full Path string
#define HID_SERIAL_STRING 0x04 ///< iSerial Number string retrieved from device
#define HID_MANUFACTURER_STRING 0x05 ///< Manufacturer Description string retrieved from device
#define HID_PRODUCT_STRING 0x06 ///< Product Description string retrieved from device
/// @defgroup SLABHIDDEVICE_MAX_STRING_LENGTHS String Lengths in ASCII character lengths not including NULL-terminator
/// @{
#define MAX_VID_LENGTH 5 ///< Maximum Length of VID string
#define MAX_PID_LENGTH 5 ///< Maximum Length of PID string
#define MAX_PATH_LENGTH 260 ///< Maximum Length of Path string
#define MAX_SERIAL_STRING_LENGTH 256 ///< Maximum Length of Serial Number string
#define MAX_MANUFACTURER_STRING_LENGTH 256 ///< Maximum Length of Manufacturer string
#define MAX_PRODUCT_STRING_LENGTH 256 ///< Maximum Length of Product string
#define MAX_INDEXED_STRING_LENGTH 256 ///< Maximum Length of a USB String Descriptor string, in characters, not including null-terminator
#define MAX_STRING_LENGTH 260 ///< maximum length of any string, in characters
/// @}
/////////////////////////////////////////////////////////////////////////////
// Typedefs
/////////////////////////////////////////////////////////////////////////////
typedef void* HID_DEVICE; ///< an opaque handle object
/////////////////////////////////////////////////////////////////////////////
// Exported Functions
/////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/// @brief Determines the number of devices connected to the system with matching VID/PID
///
/// @detail This function returns the number of connected devices. This does not imply that a device is
/// available for use. Users must call @ref HidDevice_GetNumHidDevices() before calling any function that
/// takes a device index as a parameter in order to build an up - to - date device list. If a device is
/// installed or removed after calling @ref HidDevice_GetNumHidDevices(), then the device list will be out
/// of date, and the results may be unpredictable. Currently, @ref HidDevice_GetHidString(),
/// @ref HidDevice_GetHidIndexedString(), @ref HidDevice_GetHidAttributes(), and @ref HidDevice_Open() all
/// take a device index parameter.
///
/// @param[in] Vid - Filter device results by the 2-byte Vendor ID value.
/// @param[in] Pid - Filter device results by the 2-byte Product ID value.
///
/// @note If both @ref Vid and @ref Pid are zero (0x0000), devices will NOT be filtered by @ref Vid/@ref Pid.
///
/// @returns Returns the number of devices connected to the system which have VID/PID of @ref Vid/@ref Pid.
/// A return value of 0 indicates that no devices are available. Otherwise returns the number of
/// connected devices. When referring to a device by dwDeviceIndex, the index may range from 0 to
/// (@ref HidDevice_GetNumHidDevices() – 1).
_Check_return_
_Ret_range_(0, MAX_USB_DEVICES-1)
SLAB_HID_DEVICE_API DWORD WINAPI
HidDevice_GetNumHidDevices(_In_ _Pre_defensive_ const WORD Vid, _In_ _Pre_defensive_ const WORD Pid);
/// @brief Gets a "Product string"
///
/// @detail This function returns an ASCII NULL-terminated Vendor ID string, Product ID string, serial number string, manufacturer string,
/// product description string, or full
/// path string for the device specified by an index passed in the @ref dwDeviceIndex parameter. The index of the
/// first device is 0, and the index of the last device is the value(NumDevices) returned by @ref HidDevice_GetNumHidDevices() - 1.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_VID_STRING "Vendor ID" string is derived from the "full path" string.
/// deviceString must point to a buffer at least @ref MAX_VID_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_PID_STRING "Product ID" string is derived from the "full path" string.
/// deviceString must point to a buffer at least @ref MAX_PID_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_PATH_STRING "full path" string is the "device interface path" or "Device Path". This path can be passed to Win32 functions such as CreateFile().
/// deviceString must point to a buffer at least @ref MAX_PATH_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_SERIAL_STRING "Serial Number" string is the Serial Number string from the specified Hid device's USB Device Descriptor's iSerialNumber Serial Number String Descriptor.
/// deviceString must point to a buffer at least @ref MAX_SERIAL_STRING_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_MANUFACTURER_STRING "Manufacturer Description" string is the Manufacturer string from the specified Hid device's USB Device Descriptor's iManufacturer Manufacturer String Descriptor.
/// deviceString must point to a buffer at least @ref MAX_MANUFACTURER_STRING_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_PRODUCT_STRING "Product" string is the product string from the specified Hid device's USB Device Descriptor's iProduct Product String Descriptor.
/// deviceString must point to a buffer at least @ref MAX_PRODUCT_STRING_LENGTH bytes long.
///
/// Returned strings are UCS-1?/ASCII and NULL-terminated. (verified)
///
///
/// @param[in] dwDeviceIndex is the desired device's index into the device list used to determine @ref HidDevice_GetNumHidDevices()
/// @param[in] Vid - Filter device results by the 2-byte Vendor ID value.
/// @param[in] Pid - Filter device results by the 2-byte Product ID value.
/// @param[in] WhichHidStringToReturn is the indication of which string to return, one of @ref SLAB_HID_DEVICE_STRING_ID
/// @param[out] deviceString points at a buffer into which the string will be copied and returned
/// @param[in] deviceStringLengthInBytes is the size, in bytes/octets, of the buffer into which the the string will be copied and returned I.e. sizeof deviceString buffer
///
/// @note If both @ref Vid and @ref Pid are zero (0x0000), devices will NOT be filtered by @ref Vid/@ref Pid.
///
/// @note Once a device is opened dwDeviceIndex is no longer valid, and @ref HidDevice_GetString() must be used rather than @ref HidDevice_GetHidString()
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_NOT_FOUND -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- failed, @ref deviceStringLengthInBytes indicated a buffer that is too small
/// @retval #HID_DEVICE_ALREADY_OPENED -- failed to open the device, it is already exclusively open elsewhere
/// @retval #HID_DEVICE_SYSTEM_CODE -- failed
/// @retval #HID_DEVICE_CANNOT_GET_HID_INFO -- failed
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetHidString(_In_ _Pre_defensive_ const DWORD dwDeviceIndex, _In_ _Pre_defensive_ const WORD Vid, _In_ _Pre_defensive_ const WORD Pid, _In_ _Pre_defensive_ const BYTE WhichHidStringToReturn, char* deviceString, _In_ _Pre_defensive_ const DWORD deviceStringLengthInBytes);
/// @brief Gets an indexed string from the device
///
/// Returned strings are UCS-1?/ASCII and NULL-terminated. (verified)
///
/// @param[in] dwDeviceIndex is the desired device's index into the device list used to determine @ref HidDevice_GetNumHidDevices()
/// @param[in] Vid - Filter device results by the 2-byte Vendor ID value.
/// @param[in] Pid - Filter device results by the 2-byte Product ID value.
/// @param[in] stringIndex is the one-based index of which USB String Descriptor string to return.
/// @param[out] deviceString points at a buffer into which the string will be copied and returned
/// @param[in] deviceStringLengthInBytes is the size, in bytes/octets, of the buffer into which the the string will be copied and returned I.e. sizeof deviceString buffer
///
/// @note If both Vid and Pid are zero (0x0000), devices will NOT be filtered by Vid/Pid.
///
/// @note String descriptors are referenced by their one-based index number. Specifically, a stringIndex
/// of 0 successfully does NOT return the list of supported languages.
///
/// @note Once a device is opened dwDeviceIndex is no longer valid, and @ref HidDevice_GetIndexedString() must be used rather than @ref HidDevice_GetHidIndexedString()
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_NOT_FOUND -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- failed, @ref deviceStringLengthInBytes indicated a buffer that is too small
/// @retval #HID_DEVICE_ALREADY_OPENED -- failed to open the device, it is already exclusively open elsewhere
/// @retval #HID_DEVICE_SYSTEM_CODE -- failed, including when @ref stringIndex is "too high" (I.e. there aren't this many strings on the device to index)
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetHidIndexedString(_In_ _Pre_defensive_ const DWORD dwDeviceIndex, _In_ _Pre_defensive_ const WORD Vid, _In_ _Pre_defensive_ const WORD Pid, _In_ _Pre_defensive_ const DWORD stringIndex, char* deviceString, _In_ _Pre_defensive_ const DWORD deviceStringLengthInBytes);
/// @brief Reads and returns the Vendor ID, Product ID and device Release Number
///
/// @detail This function returns the USB vendor ID, product ID, and device release number for the device
/// specified by dwDeviceIndex.
///
/// @param[in] dwDeviceIndex is the desired device's index into the device list used to determine @ref HidDevice_GetNumHidDevices()
/// @param[in] Vid - Filter device results by the 2-byte Vendor ID value.
/// @param[in] Pid - Filter device results by the 2-byte Product ID value.
/// @param[out] pDeviceVid points at a 2-byte buffer into which the USB device vendor ID value will be written
/// @param[out] pDevicePid points at a 2-byte buffer into which the USB device product ID value will be written
/// @param[out] pDeviceReleaseNumber points at a 2-byte buffer into which the USB device bcdVersion, or device release number, value will be written
///
/// @note If both @ref Vid and @ref Pid are zero (0x0000), devices will NOT be filtered by @ref Vid/@ref Pid.
///
/// @note A successfully returned @ref pDeviceReleaseNumber is in binary-coded decimal (BCD).
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_PARAMETER -- pDeviceVid, pDevicePid and/or pDeviceReleaseNumber is an unexpected value
/// @retval #HID_DEVICE_NOT_FOUND -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_ALREADY_OPENED -- failed to open the device, it is already exclusively open elsewhere
/// @retval #HID_DEVICE_SYSTEM_CODE -- failed, see Windows GetLastError()
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetHidAttributes(_In_ _Pre_defensive_ const DWORD dwDeviceIndex, _In_ _Pre_defensive_ const WORD Vid, _In_ _Pre_defensive_ const WORD Pid, _Out_writes_bytes_(2) _Pre_defensive_ WORD* pDeviceVid, _Out_writes_bytes_(2) _Pre_defensive_ WORD* pDevicePid, _Out_writes_bytes_(2) _Pre_defensive_ WORD* pDeviceReleaseNumber);
/// @brief Return the GUID for HIDClass devices ("return the HID GUID")
///
/// @param[out] pHIDGuid points at a caller-allocated GUID buffer into which the HID GUID value will be written
///
/// @returns None.
SLAB_HID_DEVICE_API void WINAPI
HidDevice_GetHidGuid(_Out_ void *pHIDGuid);
/// @brief tbd
///
/// @param[out] pMajor points at a 1-byte buffer into which the library major version number value will be written
/// @param[out] pMinor points at a 1-byte buffer into which the library minor version number value will be written
/// @param[out] pbIsReleaseBuild points at a 4-byte buffer into which a non-zero/TRUE value will be written IFF the library was built as Release mode, else into which a zero/0 value will be written if the library was built as Debug mode.
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- pMajor, pMinor and/or pbIsReleaseBuild is an unexpected value
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetHidLibraryVersion(_Out_writes_bytes_(1) _Pre_defensive_ BYTE* pMajor, _Out_writes_bytes_(1) _Pre_defensive_ BYTE* pMinor, _Out_writes_bytes_(4) BOOL* pbIsReleaseBuild);
/// @brief tbd
///
/// @detail For Windows 2000, the maximum number of queued input reports is 200/@ref MAX_REPORT_REQUEST_2K.
/// For Windows XP and later, the maximum number of queued input reports is 512/@ref MAX_REPORT_REQUEST_XP.
/// For Windows XP and later, the OS default number of queued input reports is 32.
/// In most cases, call this function with numInputBuffers set to @ref MAX_REPORT_REQUEST_XP to
/// achieve the best input report throughput.
/// If numInputBuffers is set to a value higher than the OS maximum, then the OS maximum value will
/// be used.
/// It is very common to list all connected devices by serial string. After calling
/// @ref HidDevice_GetNumHidDevices(), call @ref HidDevice_GetHidString() to get each device's serial string,
/// making sure to check the return code. Since @ref HidDevice_GetHidString() may fail (indicating that the
/// device is unavailable) it is not appropriate to simply add each device's serial string to a list and use
/// the list index to open. Similarly, a device index may have changed since the last time the device
/// list was updated. In this case, the user should select a device solely by serial string and query all
/// devices for a matching serial string.
/// This function allocates the dynamic report buffers, sets timeouts to their default values, and clears
/// the report queue.
///
/// @param[out] device is a pointer to an @ref HID_DEVICE opaque object location to hold the returned open handle to the device
/// @param[in] dwDeviceIndex is the desired device's index into the device list used to determine @ref HidDevice_GetNumHidDevices()
/// @param[in] Vid is the 2-byte Vendor ID value.
/// @param[in] Pid is the 2-byte Product ID value.
/// @param[in] numInputBuffers is the number of input report buffers to queue in the HID class driver.
///
/// @note If both @ref Vid and @ref Pid are zero (0x0000), devices will NOT be filtered by @ref Vid/@ref Pid.
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_PARAMETER -- device is an unexpected value
/// @retval #HID_DEVICE_NOT_FOUND -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_ALREADY_OPENED -- failed to open the device, it is already exclusively open elsewhere
/// @retval #HID_DEVICE_SYSTEM_CODE -- failed
/// @retval #HID_DEVICE_CANNOT_GET_HID_INFO -- failed
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_Open(_Out_ HID_DEVICE* device, _In_ _Pre_defensive_ const DWORD dwDeviceIndex, _In_ _Pre_defensive_ const WORD Vid, _In_ _Pre_defensive_ const WORD Pid, _In_ _Pre_defensive_ const DWORD numInputBuffers);
/// @brief This function returns the device opened state.
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open(), or not
///
/// @returns Returns TRUE if a device is opened. Returns FALSE if the device is invalid or if a device is not opened.
_Ret_range_(FALSE, TRUE)
_Success_(return)
SLAB_HID_DEVICE_API BOOL WINAPI
HidDevice_IsOpened(_In_ _Pre_defensive_ const HID_DEVICE device);
/// @brief This function returns the HID handle for the currently-opened device.
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
///
/// @returns Returns a Windows HANDLE created by Windows CreateFile() in @ref HidDevice_Open(). Returns
/// INVALID_HANDLE_VALUE if a device is not open or if there was an error opening a device.
_Check_return_
SLAB_HID_DEVICE_API HANDLE WINAPI
HidDevice_GetHandle(_In_ _Pre_defensive_ const HID_DEVICE device);
/// @brief Gets a "Product string"
///
/// @detail This function returns an ASCII NULL-terminated Vendor ID string, Product ID string, serial number string, manufacturer string,
/// product description string, or full
/// path string for the device specified by @ref device parameter.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_VID_STRING "Vendor ID" string is derived from the "full path" string.
/// deviceString must point to a buffer at least @ref MAX_VID_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_PID_STRING "Product ID" string is derived from the "full path" string.
/// deviceString must point to a buffer at least @ref MAX_PID_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_PATH_STRING "full path" string is the "device interface path" or "Device Path". This path can be passed to Win32 functions such as CreateFile().
/// deviceString must point to a buffer at least @ref MAX_PATH_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_SERIAL_STRING "Serial Number" string is the Serial Number string from the specified Hid device's USB Device Descriptor's iSerialNumber Serial Number String Descriptor.
/// deviceString must point to a buffer at least @ref MAX_SERIAL_STRING_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_MANUFACTURER_STRING "Manufacturer Description" string is the Manufacturer string from the specified Hid device's USB Device Descriptor's iManufacturer Manufacturer String Descriptor.
/// deviceString must point to a buffer at least @ref MAX_MANUFACTURER_STRING_LENGTH bytes long.
///
/// The @ref SLAB_HID_DEVICE_STRING_ID_PRODUCT_STRING "Product" string is the product string from the specified Hid device's USB Device Descriptor's iProduct Product String Descriptor.
/// deviceString must point to a buffer at least @ref MAX_PRODUCT_STRING_LENGTH bytes long.
///
/// Returned strings are UCS-1?/ASCII and NULL-terminated. (verified)
///
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] WhichHidStringToReturn is the indication of which string to return, one of @ref SLAB_HID_DEVICE_STRING_ID
/// @param[out] deviceString points at a buffer into which the string will be copied and returned
/// @param[in] deviceStringLengthInBytes is the size, in bytes/octets, of the buffer into which the the string will be copied and returned I.e. sizeof deviceString buffer
///
/// @note Once a device is opened dwDeviceIndex is no longer valid, and @ref HidDevice_GetString() must be used rather than @ref HidDevice_GetHidString()
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_NOT_FOUND -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- failed, @ref deviceStringLengthInBytes indicated a buffer that is too small
/// @retval #HID_DEVICE_SYSTEM_CODE -- failed
/// @retval #HID_DEVICE_CANNOT_GET_HID_INFO -- failed_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetString(_In_ _Pre_defensive_ const HID_DEVICE device, _In_ _Pre_defensive_ const BYTE WhichHidStringToReturn, char* deviceString, _In_ _Pre_defensive_ const DWORD deviceStringLengthInBytes);
/// @brief Gets an indexed string from the device
///
/// Returned strings are UCS-1?/ASCII and NULL-terminated. (verified)
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] stringIndex is the one-based index of which USB String Descriptor string to return.
/// @param[out] deviceString points at a buffer into which the string will be copied and returned
/// @param[in] deviceStringLengthInBytes is the size, in bytes/octets, of the buffer into which the the string will be copied and returned I.e. sizeof deviceString buffer
///
/// @note String descriptors are referenced by their one-based index number. Specifically, a @ref stringIndex
/// of 0 successfully does NOT return the list of supported languages.
///
/// @note Once a device is opened dwDeviceIndex is no longer valid, and @ref HidDevice_GetIndexedString() must be used rather than @ref HidDevice_GetHidIndexedString()
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- failed, @ref deviceStringLengthInBytes indicated a buffer that is too small
/// @retval #HID_DEVICE_SYSTEM_CODE -- failed, including when @ref stringIndex is "too high" (I.e. there aren't this many strings on the device to index)
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetIndexedString(_In_ _Pre_defensive_ const HID_DEVICE device, _In_ _Pre_defensive_ const DWORD stringIndex, char* deviceString, _In_ _Pre_defensive_ const DWORD deviceStringLengthInBytes);
/// @brief Reads and returns the Vendor ID, Product ID and device Release Number
///
/// @detail This function returns the USB vendor ID, product ID, and device release number for the device
/// specified by device.
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[out] pDeviceVid points at a 2-byte buffer into which the USB device vendor ID value will be written
/// @param[out] pDevicePid points at a 2-byte buffer into which the USB device product ID value will be written
/// @param[out] pDeviceReleaseNumber points at a 2-byte buffer into which the USB device bcdVersion, or device release number, value will be written
///
/// @note A successfully returned @ref pDeviceReleaseNumber is in binary-coded decimal (BCD).
///
/// @note Once a device is opened dwDeviceIndex is no longer valid, and @ref HidDevice_GetAttributes() must be used rather than @ref HidDevice_GetHidAttributes()
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_PARAMETER -- pDeviceVid, pDevicePid and/or pDeviceReleaseNumber is an unexpected value
/// @retval #HID_DEVICE_SYSTEM_CODE -- failed, system error see Windows' GetLastError()
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetAttributes(_In_ _Pre_defensive_ const HID_DEVICE device, _Out_writes_bytes_(2) _Pre_defensive_ WORD* pDeviceVid, _Out_writes_bytes_(2) _Pre_defensive_ WORD* pDevicePid, _Out_writes_bytes_(2) _Pre_defensive_ WORD* pDeviceReleaseNumber);
/// @brief This function sends an HID feature report from the host to the device over the control endpoint.
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] ReportBuffer is a byte array containing a feature report. The first byte specifies the report ID.
/// @param[in] ReportBufferLengthInBytes - The size of ReportBuffer in bytes I.e. the size of the feature report including the report ID.
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- ReportBuffer and/or ReportBufferLengthInBytes is an unexpected value
/// @retval #HID_DEVICE_NOT_OPENED -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_TRANSFER_FAILED -- failed, interaction with the device failed
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_SetFeatureReport_Control(_In_ _Pre_defensive_ const HID_DEVICE device, _In_reads_bytes_(ReportBufferLengthInBytes) _Pre_defensive_ BYTE* ReportBuffer, _In_ _Pre_defensive_ const DWORD ReportBufferLengthInBytes);
/// @brief This function receives an HID feature report from the host to the device over the control endpoint.
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] ReportBuffer - The buffer into which the feature report should be placed. The first byte of the buffer should be set to the report ID of the desired report.
/// @param[in] ReportBufferLengthInBytes - The size of ReportBuffer in bytes
///
/// The user must call this
/// function with the first byte in @ref ReportBuffer set to the report ID of the report to receive. @ref ReportBuffer must be
/// large enough to hold the feature report including report ID and, in most cases, should be
/// allocated with a size equal to @ref HidDevice_GetFeatureReportBufferLength().
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- ReportBuffer and/or ReportBufferLengthInBytes is an unexpected value
/// @retval #HID_DEVICE_NOT_OPENED -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_TRANSFER_FAILED -- failed, interaction with the device failed
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetFeatureReport_Control(_In_ _Pre_defensive_ const HID_DEVICE device, _Out_writes_bytes_(ReportBufferLengthInBytes) _Pre_defensive_ BYTE* ReportBuffer, _In_ _Pre_defensive_ const DWORD ReportBufferLengthInBytes);
/// @brief This function sends an HID output report from the host to the device over the interrupt endpoint.
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] ReportBuffer - A byte array containing an output report. The first byte specifies the report ID.
/// @param[in] ReportBufferLengthInBytes - The size of ReportBuffer in bytes
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- ReportBuffer and/or ReportBufferLengthInBytes is an unexpected value
/// @retval #HID_DEVICE_NOT_OPENED -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_TRANSFER_FAILED -- failed, interaction with the device failed
/// @retval #HID_DEVICE_TRANSFER_TIMEOUT -- failed, interaction with the device timed out
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_SetOutputReport_Interrupt(_In_ _Pre_defensive_ const HID_DEVICE device, _In_reads_bytes_(ReportBufferLengthInBytes) _Pre_defensive_ BYTE* ReportBuffer, _In_ _Pre_defensive_ const DWORD ReportBufferLengthInBytes);
/// @brief This function receives an HID input report from the host to the device over the interrupt endpoint.
///
/// Each input report returned in buffer is stored on boundaries set by the maximum input report buffer
/// size. For example, if the maximum input report buffer size as returned by
/// @ref HidDevice_GetInputReportBufferLength() is 64 and @ref HidDevice_GetInputReport_Interrupt() returns
/// 2 input reports, then bytesReturned will return with 128 bytes. The first input report starts at
/// buffer[0], and the second input report starts at buffer[64] regardless of the actual size of the report.
/// To retrieve the maximum number of input reports possible, call @ref HidDevice_GetInputReport_Interrupt()
/// with bufferSize set to(@ref HidDevice_GetInputReportBufferLength() * @ref HidDevice_GetMaxReportRequest())
/// and numReports set to @ref HidDevice_GetMaxReportRequest().
///
/// To get input report interrupt with timeouts see @ref HidDevice_GetInputReport_Interrupt_WithTimeout().
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] ReportBuffer - The buffer into which the tbd report should be placed.The first byte of the buffer should be set to the report ID of the desired report
/// @param[in] ReportBufferLengthInBytes - The size of ReportBuffer in bytes
/// @param[in] numReports - The maximum number of input reports to return
/// @param[out] bytesReturned points at a 1-byte buffer into which the number of bytes returned in @ref ReportBuffer will be written
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- ReportBuffer and/or ReportBufferLengthInBytes is an unexpected value
/// @retval #HID_DEVICE_NOT_OPENED -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_TRANSFER_FAILED -- failed, interaction with the device failed
/// @retval #HID_DEVICE_TRANSFER_TIMEOUT -- failed, interaction with the device timed out
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetInputReport_Interrupt(_In_ _Pre_defensive_ const HID_DEVICE device, _Out_writes_bytes_(ReportBufferLengthInBytes) _Pre_defensive_ BYTE* ReportBuffer, _In_ _Pre_defensive_ const DWORD ReportBufferLengthInBytes, _In_ _Pre_defensive_ const DWORD numReports, _Out_writes_bytes_(sizeof(DWORD)) _Pre_defensive_ DWORD* bytesReturned);
/// @brief This function receives an HID input report from the host to the device over the interrupt endpoint.
///
/// Set input report interrupt timeouts by settings getReportTimeout in @ref HidDevice_SetTimeouts().
///
/// Each input report returned in buffer is stored on boundaries set by the maximum input report buffer
/// size. For example, if the maximum input report buffer size as returned by
/// @ref HidDevice_GetInputReportBufferLength() is 64 and @ref HidDevice_GetInputReport_Interrupt() returns
/// 2 input reports, then bytesReturned will return with 128 bytes. The first input report starts at
/// buffer[0], and the second input report starts at buffer[64] regardless of the actual size of the report.
/// To retrieve the maximum number of input reports possible, call @ref HidDevice_GetInputReport_Interrupt()
/// with bufferSize set to(@ref HidDevice_GetInputReportBufferLength() * @ref HidDevice_GetMaxReportRequest())
/// and numReports set to @ref HidDevice_GetMaxReportRequest().
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] ReportBuffer - The buffer into which the tbd report should be placed.The first byte of the buffer should be set to the report ID of the desired report
/// @param[in] ReportBufferLengthInBytes - The size of ReportBuffer in bytes
/// @param[in] numReports - The maximum number of input reports to return
/// @param[out] bytesReturned points at a 1-byte buffer into which the number of bytes returned in @ref ReportBuffer will be written
/// @param[i] TimeoutMSec is the timeout in Milliseconds
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- ReportBuffer and/or ReportBufferLengthInBytes is an unexpected value
/// @retval #HID_DEVICE_NOT_OPENED -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_TRANSFER_FAILED -- failed, interaction with the device failed
/// @retval #HID_DEVICE_TRANSFER_TIMEOUT -- failed, interaction with the device timed out
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetInputReport_Interrupt_WithTimeout(_In_ _Pre_defensive_ const HID_DEVICE device, _Out_writes_bytes_(ReportBufferLengthInBytes) _Pre_defensive_ BYTE* ReportBuffer, _In_ _Pre_defensive_ const DWORD ReportBufferLengthInBytes, _In_ _Pre_defensive_ const DWORD numReports, _Out_writes_bytes_(sizeof(BYTE)) _Pre_defensive_ DWORD* bytesReturned, _In_ _Pre_defensive_ const DWORD TimeoutMSec);
/// @brief Sends an HID output report from the host to the device over the control endpoint
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] ReportBuffer - A byte array containing an output report. The first byte specifies the report ID.
/// @param[in] ReportBufferLengthInBytes - The size of ReportBuffer in bytes
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- ReportBuffer and/or ReportBufferLengthInBytes is an unexpected value
/// @retval #HID_DEVICE_NOT_OPENED -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_UNSUPPORTED_FUNCTION -- failed, this function is not supported on older Windows versions (Windows 2000)
/// @retval #HID_DEVICE_TRANSFER_FAILED -- failed, interaction with the device failed
/// @retval #HID_DEVICE_TRANSFER_TIMEOUT -- failed, interaction with the device timed out
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_SetOutputReport_Control(_In_ _Pre_defensive_ const HID_DEVICE device, _In_reads_bytes_(ReportBufferLengthInBytes) _Pre_defensive_ BYTE* ReportBuffer, _In_ _Pre_defensive_ const DWORD ReportBufferLengthInBytes);
/// @brief Receives an HID input report from the device to the host over the control endpoint
///
/// The user must call this
/// function with the first byte in @ref ReportBuffer set to the report ID of the report to receive. @ref ReportBuffer must be
/// large enough to hold the input report including report ID and, in most cases, should be
/// allocated with a size equal to @ref HidDevice_GetInputReportBufferLength().
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] ReportBuffer - The buffer into which the tbd report should be placed. The first byte of the buffer should be set to the report ID of the desired report
/// @param[in] ReportBufferLengthInBytes - The size of ReportBuffer in bytes
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_INVALID_BUFFER_SIZE -- ReportBuffer and/or ReportBufferLengthInBytes is an unexpected value
/// @retval #HID_DEVICE_NOT_OPENED -- failed, the device specified by the dwDeviceIndex and filtered on by Vid and Pid, was not found
/// @retval #HID_DEVICE_UNSUPPORTED_FUNCTION -- failed, this function is not supported on older Windows versions (Windows 2000)
/// @retval #HID_DEVICE_TRANSFER_FAILED -- failed, interaction with the device failed
/// @retval #HID_DEVICE_TRANSFER_TIMEOUT -- failed, interaction with the device timed out
_Check_return_
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_GetInputReport_Control(_In_ _Pre_defensive_ const HID_DEVICE device, _Out_writes_bytes_(ReportBufferLengthInBytes) _Pre_defensive_ BYTE* ReportBuffer, _In_ _Pre_defensive_ const DWORD ReportBufferLengthInBytes);
/// @brief Returns the maximum input report size including the report ID
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
///
/// @returns A return value of zero indicates that the specified device cannot be found. A non-zero value
/// specifies the maximum input report size including the report ID. This function should be called to
/// determine the appropriate buffer size for @ref HidDevice_GetInputReport_Interrupt() and
/// @ref HidDevice_GetInputReport_Control().
SLAB_HID_DEVICE_API WORD WINAPI
HidDevice_GetInputReportBufferLength(_In_ _Pre_defensive_ const HID_DEVICE device);
/// @brief Returns the maximum output report size including the report ID
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
///
/// @returns A return value of zero indicates that the specified device cannot be found. A non-zero value
/// specifies the maximum output report size, including the report ID.
SLAB_HID_DEVICE_API WORD WINAPI
HidDevice_GetOutputReportBufferLength(_In_ _Pre_defensive_ const HID_DEVICE device);
/// @brief Returns the maximum feature report size, including the report ID
///
/// @detail This function should be called to determine the appropriate buffer size for @ref HidDevice_GetFeatureReport_Control().
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
///
/// @returns A return value of zero indicates that the specified device cannot be found. A non-zero value
/// specifies the maximum feature report size, including the report ID.
SLAB_HID_DEVICE_API WORD WINAPI
HidDevice_GetFeatureReportBufferLength(_In_ _Pre_defensive_ const HID_DEVICE device);
/// @brief Returns the maximum number of input reports that can be queued in the HID driver
///
/// @detail This function should be called to determine the appropriate buffer size for @ref HidDevice_GetInputReport_Interrupt().
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
///
/// @returns A return value of zero indicates that the specified device cannot be found. A non-zero return value
/// specifies the maximum number of reports in the HID driver input report queue.
SLAB_HID_DEVICE_API DWORD WINAPI
HidDevice_GetMaxReportRequest(_In_ _Pre_defensive_ const HID_DEVICE device);
/// @brief Deletes all pending input reports in the HID driver queue and the HID library
///
/// This function first cancels pending overlapped input report reads (CancelIo()). Next, it flushes the
/// HID driver input report queue. Finally, it flushes the library's internal input report queue.
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
///
/// @returns Returns TRUE if the function completed successfully.
/// Returns FALSE if the function failed or if the device does not exist.
/// @retval TRUE -- success
/// @retval FALSE -- the function failed or the device does not exist.
_Check_return_
_Ret_range_(FALSE, TRUE)
_Success_(return)
SLAB_HID_DEVICE_API BOOL WINAPI
HidDevice_FlushBuffers(_In_ _Pre_defensive_ const HID_DEVICE device);
/// @brief Cancels all pending input and output operations issued by the calling thread
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
///
/// @returns Returns TRUE if the function completed successfully.
/// Returns FALSE if the function failed or if the device does not exist.
/// @retval TRUE -- success
/// @retval FALSE -- the function failed or the device does not exist.
_Check_return_
_Ret_range_(FALSE, TRUE)
_Success_(return)
SLAB_HID_DEVICE_API BOOL WINAPI
HidDevice_CancelIo(_In_ _Pre_defensive_ const HID_DEVICE device);
/// @brief Returns the input and output report timeouts over the interrupt endpoint
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[out] pGetReportTimeoutInMilliSeconds points at a 4-byte buffer into which the GetInputReport timeout value will be written
/// @param[out] pSetReportTimeoutInMilliSeconds points at a 4-byte buffer into which the SetOutputReport timeout value will be written
///
/// @ref pGetReportTimeoutInMilliSeconds is the read timeout for @ref HidDevice_GetInputReport_Interrupt_WithTimeout() in
/// milliseconds. This timeout specifies the number of milliseconds that must elapse before
/// @ref HidDevice_GetInputReport_Interrupt_WithTimeout() will return with fewer bytes than requested with an
/// @ref HID_DEVICE_TRANSFER_TIMEOUT error. A timeout of 0 ms will return immediately with
/// any available data.
///
/// @ref pSetReportTimeoutInMilliSeconds is the write timeout for HidDevice_SetOutputReport_Interrupt() in
/// milliseconds.This timeout specifies the number of milliseconds that must elapse for an output report
/// before @ref HidDevice_SetOutputReport_Interrupt() returns with an @ref HID_DEVICE_TRANSFER_TIMEOUT
/// error.
///
/// @note Read and write timeouts are maintained for each device but are not persistent across
/// @ref HidDevice_Open() / @ref HidDevice_Close().Allow for sufficient write timeouts to make sure that an
/// output report can be transmitted successfully.
///
/// The default get report and set report timeouts are both 1000 ms.
///
/// @returns Returns no return value.
SLAB_HID_DEVICE_API void WINAPI
HidDevice_GetTimeouts(_In_ _Pre_defensive_ const HID_DEVICE device, _Out_writes_bytes_(4) _Pre_defensive_ DWORD* pGetReportTimeoutInMilliSeconds, _Out_writes_bytes_(4) _Pre_defensive_ DWORD* pSetReportTimeoutInMilliSeconds);
/// @brief Sets the input and output report timeouts over the interrupt endpoint
///
/// @detail Timeouts are used for @ref HidDevice_GetInputReport_Interrupt() and @ref HidDevice_SetOutputReport_Interrupt().
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
/// @param[in] getReportTimeoutInMilliSeconds - Sets the timeout used in @ref HidDevice_GetInputReport_Interrupt() in
/// milliseconds. This timeout specifies the number of milliseconds that must elapse before
/// @ref HidDevice_GetInputReport_Interrupt() will return fewer bytes than requested with an
/// #HID_DEVICE_TRANSFER_TIMEOUT error. A timeout of 0 ms will return immediately with
/// any available data.
/// @param[in] setReportTimeoutInMilliSeconds - Sets the timeout used in @ref HidDevice_SetOutputReport_Interrupt() in
/// milliseconds.This timeout specifies the number of milliseconds that must elapse during an
/// output report before @ref HidDevice_SetOutputReport_Interrupt() will return with an
/// #HID_DEVICE_TRANSFER_TIMEOUT error.
///
/// @note If get report timeouts are set to a large value and no data is received, the application may appear
/// unresponsive.Therefore, it is recommended to set timeouts to an appropriate value before reading
/// from the device.
/// The default value for get report and set report timeouts is 1000 ms and can be set to any number
/// of milliseconds from 0 to 0xFFFFFFFF.
///
/// @returns Returns no return value.
SLAB_HID_DEVICE_API void WINAPI
HidDevice_SetTimeouts(_In_ _Pre_defensive_ const HID_DEVICE device, _In_ _Pre_defensive_ const DWORD getReportTimeoutInMilliSeconds, _In_ _Pre_defensive_ const DWORD setReportTimeoutInMilliSeconds);
/// @brief Closes an open handle to the device
///
/// This function deletes the internal library input report buffer and cancels any pending input report
/// reads via::CancelIo(). This function is responsible for deallocating the HID class object allocated
/// in @ref HidDevice_Open().
///
/// @param[in] device is an open handle to the device as returned by @ref HidDevice_Open()
///
/// @returns Returns #HID_DEVICE_SUCCESS on success, or another @ref SLAB_HID_DEVICE_STATUS Return value if there is an error.
/// @retval #HID_DEVICE_SUCCESS -- success
/// @retval #HID_DEVICE_HANDLE_ERROR -- failed, the device specified by device does not have a valid handle
/// @retval #HID_DEVICE_NOT_FOUND -- failed, the device specified by device was not found
/// @retval #HID_DEVICE_NOT_OPENED -- failed, the device specified by device is not open
_Ret_range_(HID_DEVICE_SUCCESS, HID_DEVICE_UNKNOWN_ERROR)
_Success_(HID_DEVICE_SUCCESS == return)
SLAB_HID_DEVICE_API SLAB_HID_DEVICE_STATUS WINAPI
HidDevice_Close(_In_ _Pre_defensive_ const HID_DEVICE device);
#ifdef __cplusplus
}
#endif // __cplusplus
/// @}
#endif // HOST_LIB_SLABHIDDEVICE_INCLUDE_SLABHIDDEVICE_H_INCLUDED_MJWYLEYUPA

#!/usr/bin/env python2
################################################################################
## Copyright (c) 2015 by Silicon Laboratories Inc. All rights reserved.
## The program contained in this listing is proprietary to Silicon Laboratories,
## headquartered in Austin, Texas, U.S.A. and is subject to worldwide copyright
## protection, including protection under the United States Copyright Act of 1976
## as an unpublished work, pursuant to Section 104 and Section 408 of Title XVII
## of the United States code. Unauthorized copying, adaptation, distribution,
## use, or display is prohibited by this law.
################################################################################
# Python 3.4
import ctypes
import sys
#-------------------------------------------------------------------------------
if sys.platform == 'win32':
g_DLL = ctypes.windll.LoadLibrary("./SLABHIDDevice.dll")
elif sys.platform.startswith('linux'):
g_DLL = ctypes.cdll.LoadLibrary("./libslabhiddevice.so.1.0")
elif sys.platform == 'darwin':
g_DLL = ctypes.cdll.LoadLibrary("libSLABHIDDevice.dylib")
fnc = getattr(g_DLL, "HidDevice_GetNumHidDevices")
fnc.restype = ctypes.c_ulong
fnc = getattr(g_DLL, "HidDevice_GetHidString")
fnc.restype = ctypes.c_ubyte
fnc = getattr(g_DLL, "HidDevice_Open")
fnc.restype = ctypes.c_ubyte
fnc = getattr(g_DLL, "HidDevice_Close")
fnc.restype = ctypes.c_ubyte
fnc = getattr(g_DLL, "HidDevice_SetFeatureReport_Control")
fnc.restype = ctypes.c_ubyte
fnc = getattr(g_DLL, "HidDevice_GetFeatureReport_Control")
fnc.restype = ctypes.c_ubyte
fnc = getattr(g_DLL, "HidDevice_GetTimeouts")
fnc.restype = None
fnc = getattr(g_DLL, "HidDevice_SetTimeouts")
fnc.restype = None
fnc = getattr(g_DLL, "HidDevice_GetMaxReportRequest")
fnc.restype = ctypes.c_ulong
fnc = getattr(g_DLL, "HidDevice_GetInputReportBufferLength")
fnc.restype = ctypes.c_ushort
fnc = getattr(g_DLL, "HidDevice_GetOutputReportBufferLength")
fnc.restype = ctypes.c_ushort
fnc = getattr(g_DLL, "HidDevice_GetFeatureReportBufferLength")
fnc.restype = ctypes.c_ushort
fnc = getattr(g_DLL, "HidDevice_GetInputReport_Interrupt")
fnc.restype = ctypes.c_ubyte
fnc = getattr(g_DLL, "HidDevice_SetOutputReport_Interrupt")
fnc.restype = ctypes.c_ubyte
fnc = getattr(g_DLL, "HidDevice_GetInputReport_Control")
fnc.restype = ctypes.c_ubyte
fnc = getattr(g_DLL, "HidDevice_SetOutputReport_Control")
fnc.restype = ctypes.c_ubyte
#-------------------------------------------------------------------------------
# Functions yet to be wrapped
"""
BYTE HidDevice_GetHidIndexedString(DWORD deviceIndex, WORD vid, WORD pid, DWORD stringIndex, char* deviceString, DWORD deviceStringLength);
BYTE HidDevice_GetHidAttributes(DWORD deviceIndex, WORD vid, WORD pid, WORD* deviceVid, WORD* devicePid, WORD* deviceReleaseNumber);
void HidDevice_GetHidGuid(void* hidGuid);
BYTE HidDevice_GetHidLibraryVersion(BYTE* major, BYTE* minor, BOOL* release);
BOOL HidDevice_IsOpened(HID_DEVICE device);
HANDLE HidDevice_GetHandle(HID_DEVICE device);
BYTE HidDevice_GetString(HID_DEVICE device, BYTE hidStringType, char* deviceString, DWORD deviceStringLength);
BYTE HidDevice_GetIndexedString(HID_DEVICE device, DWORD stringIndex, char* deviceString, DWORD deviceStringLength);
BYTE HidDevice_GetAttributes(HID_DEVICE device, WORD* deviceVid, WORD* devicePid, WORD* deviceReleaseNumber);
BOOL HidDevice_FlushBuffers(HID_DEVICE device);
BOOL HidDevice_CancelIo(HID_DEVICE device);
"""
#-------------------------------------------------------------------------------
# Constant definitions copied from the public DLL header
MAX_STRING_LENGTH = 260
# String Types
HID_VID_STRING = 0x01
HID_PID_STRING = 0x02
HID_PATH_STRING = 0x03
HID_SERIAL_STRING = 0x04
HID_MANUFACTURER_STRING = 0x05
HID_PRODUCT_STRING = 0x06
# Return Codes
HID_DEVICE_SUCCESS = 0x00
#-------------------------------------------------------------------------------
# This class trivially wraps SLABHIDDevice.dll. Class methods have same names as DLL functions.
# The parameters are the same unless the DLL declaration is given in a comment above wrapper to show difference.
# Also, the device file handle is stored in the object, so wrappers don't have it as the first parameter.
#
# See Function prototypes in SLABHIDDevice.h and HID_DeviceInterface_Specification.doc for functional description.
class SLABHIDDevice:
def __init__(self):
self.hDev = ctypes.c_void_p(0)
def HidDevice_GetNumHidDevices(self, vid, pid):
return g_DLL.HidDevice_GetNumHidDevices(vid, pid)
def HidDevice_GetHidString(self, deviceIndex, vid, pid, hidStringType, deviceString, deviceStringLength):
err = g_DLL.HidDevice_GetHidString( deviceIndex, vid, pid, hidStringType, deviceString, deviceStringLength)
if err != HID_DEVICE_SUCCESS :
print("HidDevice_GetHidString type %d err %x" % (hidStringType, err))
return err
def HidDevice_Open(self, deviceIndex, vid, pid, numInputBuffers):
err = g_DLL.HidDevice_Open( ctypes.byref(self.hDev), deviceIndex, vid, pid, numInputBuffers)
if err != HID_DEVICE_SUCCESS :
print("HidDevice_Open err %x" % err)
return err
def HidDevice_Close(self):
err = g_DLL.HidDevice_Close( self.hDev)
if err != HID_DEVICE_SUCCESS :
print("HidDevice_Close err %x" % err)
return err
def HidDevice_SetFeatureReport_Control(self, buffer, bufferSize):
err = g_DLL.HidDevice_SetFeatureReport_Control(self.hDev, buffer, bufferSize)
if err != HID_DEVICE_SUCCESS :
print("HidDevice_SetFeatureReport_Control err %x" % err)
return err
def HidDevice_GetFeatureReport_Control(self, buffer, bufferSize):
err = g_DLL.HidDevice_GetFeatureReport_Control(self.hDev, buffer, bufferSize)
if err != HID_DEVICE_SUCCESS :
print("HidDevice_GetFeatureReport_Control err %x" % err)
return err
def HidDevice_GetTimeouts(self, getReportTimeout, setReportTimeout):
g_DLL.HidDevice_GetTimeouts(self.hDev, ctypes.byref(getReportTimeout), ctypes.byref(setReportTimeout))
def HidDevice_SetTimeouts(self, getReportTimeout, setReportTimeout):
g_DLL.HidDevice_SetTimeouts(self.hDev, getReportTimeout, setReportTimeout)
def HidDevice_GetMaxReportRequest(self):
return g_DLL.HidDevice_GetMaxReportRequest(self.hDev)
def HidDevice_GetInputReportBufferLength(self):
return g_DLL.HidDevice_GetInputReportBufferLength(self.hDev)
def HidDevice_GetOutputReportBufferLength(self):
return g_DLL.HidDevice_GetOutputReportBufferLength(self.hDev)
def HidDevice_GetFeatureReportBufferLength(self):
return g_DLL.HidDevice_GetFeatureReportBufferLength(self.hDev)
def HidDevice_GetInputReport_Interrupt(self, buffer, bufferSize, numReports, bytesReturned):
err = g_DLL.HidDevice_GetInputReport_Interrupt(self.hDev, buffer, bufferSize, numReports, ctypes.byref(bytesReturned))
if err != HID_DEVICE_SUCCESS :
print("HidDevice_GetInputReport_Interrupt err %x" % err)
return err
def HidDevice_SetOutputReport_Interrupt(self, buffer, bufferSize):
err = g_DLL.HidDevice_SetOutputReport_Interrupt(self.hDev, buffer, bufferSize)
if err != HID_DEVICE_SUCCESS :
print("HidDevice_SetOutputReport_Interrupt err %x" % err)
return err
def HidDevice_SetOutputReport_Control(self, buffer, bufferSize):
err = g_DLL.HidDevice_SetOutputReport_Control(self.hDev, buffer, bufferSize)
if err != HID_DEVICE_SUCCESS :
print("HidDevice_SetOutputReport_Control err %x" % err)
return err
def HidDevice_GetInputReport_Control(self, buffer, bufferSize):
err = g_DLL.HidDevice_GetInputReport_Control(self.hDev, buffer, bufferSize)
if err != HID_DEVICE_SUCCESS :
print("HidDevice_GetInputReport_Control err %x" % err)
return err
def StrToUshort(s):
retval = int(s, 16) # this too can raise ValueError
if retval > 0xffff:
raise ValueError
if retval < 0:
raise ValueError
return retval
#------------------------------------------------------
# Open device #DevIndex and dump info about it
def TestHID( device, vid, pid, DevIndex):
buf = ctypes.create_string_buffer(MAX_STRING_LENGTH)
if device.HidDevice_GetHidString(DevIndex, vid, pid, HID_VID_STRING, buf, MAX_STRING_LENGTH) != HID_DEVICE_SUCCESS:
return -1
print("HID_VID_STRING: %s" % buf.value.decode())
if device.HidDevice_GetHidString(DevIndex, vid, pid, HID_PID_STRING, buf, MAX_STRING_LENGTH) != HID_DEVICE_SUCCESS:
return -1
print("HID_PID_STRING: %s" % buf.value.decode())
if sys.platform == 'win32':
if device.HidDevice_GetHidString(DevIndex, vid, pid, HID_PATH_STRING, buf, MAX_STRING_LENGTH) != HID_DEVICE_SUCCESS:
return -1
print("HID_PATH_STRING: %s" % buf.value.decode())
if device.HidDevice_GetHidString(DevIndex, vid, pid, HID_SERIAL_STRING, buf, MAX_STRING_LENGTH) != HID_DEVICE_SUCCESS:
return -1
print("HID_SERIAL_STRING: %s" % buf.value.decode())
if device.HidDevice_GetHidString(DevIndex, vid, pid, HID_MANUFACTURER_STRING, buf, MAX_STRING_LENGTH) != HID_DEVICE_SUCCESS:
return -1
print("HID_MANUFACTURER_STRING: %s" % buf.value.decode())
if device.HidDevice_GetHidString(DevIndex, vid, pid, HID_PRODUCT_STRING, buf, MAX_STRING_LENGTH) != HID_DEVICE_SUCCESS:
return -1
print("HID_PRODUCT_STRING: %s" % buf.value.decode())
if device.HidDevice_Open(DevIndex, vid, pid, 16) != HID_DEVICE_SUCCESS:
return -1
MaxReportRequest = device.HidDevice_GetMaxReportRequest()
print("MaxReportRequest: %d" % MaxReportRequest)
InputReportBufferLength = device.HidDevice_GetInputReportBufferLength()
print("InputReportBufferLength: %d" % InputReportBufferLength)
OutputReportBufferLength = device.HidDevice_GetOutputReportBufferLength()
print("OutputReportBufferLength: %d" % OutputReportBufferLength)
FeatureReportBufferLength = device.HidDevice_GetFeatureReportBufferLength()
print("FeatureReportBufferLength: %d" % FeatureReportBufferLength)
getReportTimeout = ctypes.c_ulong(0)
setReportTimeout = ctypes.c_ulong(0)
device.HidDevice_GetTimeouts(getReportTimeout, setReportTimeout)
print("getReportTimeout: %d setReportTimeout: %d" % (getReportTimeout.value, setReportTimeout.value))
if device.HidDevice_Close() != HID_DEVICE_SUCCESS:
return -1
return 0
API_Test_StatusNoDevFound = -2
def Test(vid, pid):
rc = -1
lib = SLABHIDDevice()
try:
SuccessCnt = 0
NumDevices = lib.HidDevice_GetNumHidDevices(vid, pid)
for i in range(0, NumDevices):
if TestHID( lib, vid, pid, i) == 0:
SuccessCnt = SuccessCnt + 1
if NumDevices == 0:
print("SLABHIDDevice: no devices found vid %04x pid %04x" % (vid, pid))
rc = API_Test_StatusNoDevFound
elif NumDevices == SuccessCnt:
rc = 0
except:
print("SLABHIDDevice: Unhandled exception")
finally:
return rc
#------------------------------------------------------
# Does no harm, just gets/dumps info about all devices
# Its purpose is to call all non-destructive wrappers as unit-testing.
#
def TestAll():
import sys
errorlevel = 1
if len(sys.argv) != 1 :
# Read 16-bit hex VID and PID from command line if specified, then test that device only
if len(sys.argv) != 3 :
print("error: invalid command line arguments: %s" % str(sys.argv))
sys.exit(1)
vid = 0
pid = 0
try:
vid = StrToUshort(sys.argv[1])
pid = StrToUshort(sys.argv[2])
except ValueError:
print("error: invalid command line arguments: %s" % str(sys.argv))
sys.exit(1)
rc = Test(vid, pid)
if rc == 0:
errorlevel = 0
else:
# Test all CP2110, CP2112 and CP2114 found
NotFoundCnt = 0
rc = Test(0x10c4, 0xea80) # CP2110
if rc == API_Test_StatusNoDevFound:
NotFoundCnt = NotFoundCnt + 1
rc = 0
if rc == 0:
rc = Test(0x10c4, 0xea90) # CP2112
if rc == API_Test_StatusNoDevFound:
NotFoundCnt = NotFoundCnt + 1
rc = 0
if rc == 0:
rc = Test(0x10c4, 0xeab0) # CP2114
if rc == API_Test_StatusNoDevFound:
NotFoundCnt = NotFoundCnt + 1
rc = 0
if rc == 0:
errorlevel = 0
if 0 != errorlevel: print("FAIL\n")
sys.exit(errorlevel)
#------------------------------------------------------
# This main does no harm, just gets/dumps info about all devicea
# Its purpose is to call all non-destructive wrappers as unit-testing.
#
if __name__ == "__main__":
TestAll()
#!/usr/bin/env python2
## Copyright (c) 2013 by Silicon Laboratories.
## All rights reserved. This program and the accompanying materials
## are made available under the terms of the Silicon Laboratories End User
## License Agreement which accompanies this distribution, and is available at
## http://developer.silabs.com/legal/version/v10/License_Agreement_v10.htm
## Original content and implementation provided by Silicon Laboratories.
"""
Python wrapper for Silabs CP2112 library (SLABHIDtoSMBus.dll).
Documentation for the library is provided by CP2112_API_Specification.pdf.
"""
import ctypes as ct
import sys
__version__ = "0.0.2"
__date__ = "27 Aug 2013"
__all__ = ['HID_SMBUS', 'HID_SMBUS_S0', 'HID_SMBUS_S1', 'HID_SMBUS_STATUS_DESC',
'HidSmbusDevice', 'HidSmbusError', 'IsOpened',
'GetNumDevices', 'GetAttributes', 'GetString',
'GetLibraryVersion', 'GetHidLibraryVersion', 'TestAll']
#==============================================================================
# Constants
#==============================================================================
class HID_SMBUS:
VID = 0x10C4
PID = 0xEA90
VID_STR = 0x01
PID_STR = 0x02
PATH_STR = 0x03
SERIAL_STR = 0x04
MANUFACTURER_STR = 0x05
PRODUCT_STR = 0x06
class HID_SMBUS_S0:
IDLE = 0x00
BUSY = 0x01
COMPLETE = 0x02
ERROR = 0x03
class HID_SMBUS_S1:
BUSY_ADDRESS_ACKED = 0x00
BUSY_ADDRESS_NACKED = 0x01
BUSY_READING = 0x02
BUSY_WRITING = 0x03
ERROR_TIMEOUT_NACK = 0x00
ERROR_TIMEOUT_BUS_NOT_FREE = 0x01
ERROR_ARB_LOST = 0x02
ERROR_READ_INCOMPLETE = 0x03
ERROR_WRITE_INCOMPLETE = 0x04
ERROR_SUCCESS_AFTER_RETRY = 0x05
#==============================================================================
# Error Handling
#==============================================================================
HID_SMBUS_DEVICE_NOT_FOUND = 0x01
HID_SMBUS_STATUS_DESC = {
0x00 : "HID_SMBUS_SUCCESS",
0x01 : "HID_SMBUS_DEVICE_NOT_FOUND",
0x02 : "HID_SMBUS_INVALID_HANDLE",
0x03 : "HID_SMBUS_INVALID_DEVICE_OBJECT",
0x04 : "HID_SMBUS_INVALID_PARAMETER",
0x05 : "HID_SMBUS_INVALID_REQUEST_LENGTH",
0x10 : "HID_SMBUS_READ_ERROR",
0x11 : "HID_SMBUS_WRITE_ERROR",
0x12 : "HID_SMBUS_READ_TIMED_OUT",
0x13 : "HID_SMBUS_WRITE_TIMED_OUT",
0x14 : "HID_SMBUS_DEVICE_IO_FAILED",
0x15 : "HID_SMBUS_DEVICE_ACCESS_ERROR",
0x16 : "HID_SMBUS_DEVICE_NOT_SUPPORTED",
0xFF : "HID_SMBUS_UNKNOWN_ERROR",
}
class HidSmbusError(Exception):
def __init__(self, status):
self.status = status
try:
self.name = HID_SMBUS_STATUS_DESC[status]
except:
self.name = "HID_UART_STATUS_UNKNOWN: " + hex(status)
def __str__(self):
return self.name
def hidsmb_errcheck(result, func, args):
if result != 0:
raise HidSmbusError(result)
#==============================================================================
# CP2112 HIDtoSMBus DLL
#==============================================================================
if sys.platform == 'win32':
_DLL = ct.windll.LoadLibrary("./SLABHIDtoSMBus.dll")
elif sys.platform.startswith('linux'):
_DLL_prev = ct.CDLL("./libslabhiddevice.so.1.0", mode=ct.RTLD_GLOBAL)
_DLL = ct.cdll.LoadLibrary("./libslabhidtosmbus.so.1.0")
elif sys.platform == 'darwin':
_DLL = ct.cdll.LoadLibrary("libSLABHIDtoSMBus.dylib")
# for win_function in ["HidSmbus_GetHidGuid",
# "HidSmbus_GetIndexedString", "HidSmbus_GetOpenedIndexedString"]:
# fnc = getattr(_DLL, win_function)
# fnc.restype = ct.c_int
# fnc.errcheck = hidsmb_errcheck
for hidsmb_function in ["HidSmbus_GetNumDevices",
"HidSmbus_GetAttributes", "HidSmbus_GetString",
"HidSmbus_GetLibraryVersion", "HidSmbus_GetHidLibraryVersion",
"HidSmbus_Open", "HidSmbus_Close",
"HidSmbus_IsOpened", "HidSmbus_GetPartNumber",
"HidSmbus_GetOpenedAttributes", "HidSmbus_GetOpenedString",
"HidSmbus_ReadRequest", "HidSmbus_AddressReadRequest",
"HidSmbus_ForceReadResponse", "HidSmbus_WriteRequest",
"HidSmbus_TransferStatusRequest", "HidSmbus_GetTransferStatusResponse",
"HidSmbus_CancelTransfer", "HidSmbus_CancelIo", "HidSmbus_Reset",
"HidSmbus_SetTimeouts", "HidSmbus_GetTimeouts",
"HidSmbus_SetSmbusConfig", "HidSmbus_GetSmbusConfig",
"HidSmbus_SetGpioConfig", "HidSmbus_GetGpioConfig",
"HidSmbus_ReadLatch", "HidSmbus_WriteLatch"]:
fnc = getattr(_DLL, hidsmb_function)
fnc.restype = ct.c_int
fnc.errcheck = hidsmb_errcheck
#==============================================================================
# Library Functions
#==============================================================================
# Methods Not Implemented
# HidSmbus_GetIndexedString(DWORD deviceNum, WORD vid, WORD pid, DWORD stringIndex, char* deviceString);
# HidSmbus_GetHidGuid(void* guid);
# HidSmbus_GetNumDevices(DWORD* numDevices, WORD vid, WORD pid);
def GetNumDevices(vid=HID_SMBUS.VID, pid=HID_SMBUS.PID):
"""Returns the number of devices connected to the host with matching VID/PID."""
ndev = ct.c_ulong()
_DLL.HidSmbus_GetNumDevices(ct.byref(ndev), vid, pid)
return ndev.value
# HidSmbus_GetAttributes(DWORD deviceNum, WORD vid, WORD pid, WORD* deviceVid, WORD* devicePid, WORD* deviceReleaseNumber);
def GetAttributes(index=0, vid=HID_SMBUS.VID, pid=HID_SMBUS.PID):
"""Returns VID, PID and release number for the indexed device with matching VID/PID."""
dev_vid = ct.c_ushort()
dev_pid = ct.c_ushort()
dev_rel = ct.c_ushort()
_DLL.HidSmbus_GetAttributes(index, vid, pid, ct.byref(dev_vid), ct.byref(dev_pid), ct.byref(dev_rel))
return (dev_vid.value, dev_pid.value, dev_rel.value)
# HidSmbus_GetString(DWORD deviceNum, WORD vid, WORD pid, char* deviceString, DWORD options);
def GetString(index=0, vid=HID_SMBUS.VID, pid=HID_SMBUS.PID, opt=HID_SMBUS.SERIAL_STR):
"""Returns the selected string for the indexed device with matching VID/PID."""
buf = ct.create_string_buffer(512)
_DLL.HidSmbus_GetString(index, vid, pid, buf, opt)
return buf.value.decode()
# HidSmbus_GetLibraryVersion(BYTE* major, BYTE* minor, BOOL* release);
def GetLibraryVersion():
"""Returns the SLABHIDtoSMBus library version number as a string."""
major = ct.c_byte()
minor = ct.c_byte()
release = ct.c_long()
_DLL.HidSmbus_GetLibraryVersion(ct.byref(major), ct.byref(minor), ct.byref(release))
return "{}.{}.{}".format(major.value, minor.value, release.value)
# HidSmbus_GetHidLibraryVersion(BYTE* major, BYTE* minor, BOOL* release);
def GetHidLibraryVersion():
"""Returns the SLABHIDDevice library version number as a string."""
major = ct.c_byte()
minor = ct.c_byte()
release = ct.c_long()
_DLL.HidSmbus_GetHidLibraryVersion(ct.byref(major), ct.byref(minor), ct.byref(release))
return "{}.{}.{}".format(major.value, minor.value, release.value)
def IsOpened(index=0, vid=HID_SMBUS.VID, pid=HID_SMBUS.PID):
"""Checks if the indexed device with matching VID/PID is already open."""
status = 0
try:
GetAttributes(index, vid, pid)
except HidSmbusError as e:
status = e.status
# 0x15 : "HID_SMBUS_DEVICE_ACCESS_ERROR"
return bool(status == 0x15)
#==============================================================================
# HidSmb Class
#==============================================================================
# Methods Not Implemented:
# HidSmbus_GetOpenedIndexedString(HID_SMBUS_DEVICE device, DWORD stringIndex, char* deviceString);
#
# HidSmbus_SetLock(HID_SMBUS_DEVICE device, BYTE lock);
# HidSmbus_GetLock(HID_SMBUS_DEVICE device, BYTE* lock);
# HidSmbus_SetUsbConfig(HID_SMBUS_DEVICE device, WORD vid, WORD pid, BYTE power, BYTE powerMode, WORD releaseVersion, BYTE mask);
# HidSmbus_GetUsbConfig(HID_SMBUS_DEVICE device, WORD* vid, WORD* pid, BYTE* power, BYTE* powerMode, WORD* releaseVersion);
# HidSmbus_SetManufacturingString(HID_SMBUS_DEVICE device, char* manufacturingString, BYTE strlen);
# HidSmbus_GetManufacturingString(HID_SMBUS_DEVICE device, char* manufacturingString, BYTE* strlen);
# HidSmbus_SetProductString(HID_SMBUS_DEVICE device, char* productString, BYTE strlen);
# HidSmbus_GetProductString(HID_SMBUS_DEVICE device, char* productString, BYTE* strlen);
# HidSmbus_SetSerialString(HID_SMBUS_DEVICE device, char* serialString, BYTE strlen);
# HidSmbus_GetSerialString(HID_SMBUS_DEVICE device, char* serialString, BYTE* strlen);
class HidSmbusDevice:
"""
HidSmbusDevice instances are used to work with a specific CP2112 device.
For help on the wrapped functions, refer to CP2112_API_Specification.pdf.
"""
def __init__(self):
self.handle = ct.c_void_p(0)
self._S0 = ct.c_byte(0)
self._S1 = ct.c_byte(0)
GetNumDevices()
@property
def S0(self):
return self._S0.value
@property
def S1(self):
return self._S1.value
# HidSmbus_Open(HID_SMBUS_DEVICE* device, DWORD deviceNum, WORD vid, WORD pid);
def Open(self, index=0, vid=HID_SMBUS.VID, pid=HID_SMBUS.PID):
_DLL.HidSmbus_Open(ct.byref(self.handle), index, vid, pid)
# HidSmbus_Close(HID_SMBUS_DEVICE device);
def Close(self):
if self.handle:
_DLL.HidSmbus_Close(self.handle)
self.handle.value = 0
# HidSmbus_IsOpened(HID_SMBUS_DEVICE device, BOOL* opened);
def IsOpened(self):
opened = ct.c_long(0)
if self.handle:
_DLL.HidSmbus_IsOpened(self.handle, ct.byref(opened))
return bool(opened.value)
# HidSmbus_GetOpenedAttributes(HID_SMBUS_DEVICE device, WORD* deviceVid, WORD* devicePid, WORD* deviceReleaseNumber);
def GetAttributes(self):
vid = ct.c_ushort(0)
pid = ct.c_ushort(0)
rel = ct.c_ushort(0)
_DLL.HidSmbus_GetOpenedAttributes(self.handle, ct.byref(vid), ct.byref(pid), ct.byref(rel))
return (vid.value, pid.value, rel.value)
# HidSmbus_GetPartNumber(HID_SMBUS_DEVICE device, BYTE* partNumber, BYTE* version);
def GetPartNumber(self):
pno = ct.c_byte(0)
ver = ct.c_byte(0)
_DLL.HidSmbus_GetPartNumber(self.handle, ct.byref(pno), ct.byref(ver))
return (pno.value, ver.value)
# HidSmbus_GetOpenedString(HID_SMBUS_DEVICE device, char* deviceString, DWORD options);
def GetString(self, opt=HID_SMBUS.SERIAL_STR):
buf = ct.create_string_buffer(512)
_DLL.HidSmbus_GetOpenedString(self.handle, buf, opt)
return buf.value.decode()
# HidSmbus_CancelTransfer(HID_SMBUS_DEVICE device);
def CancelTransfer(self):
_DLL.HidSmbus_CancelTransfer(self.handle)
# HidSmbus_CancelIo(HID_SMBUS_DEVICE device);
def CancelIo(self):
_DLL.HidSmbus_CancelIo(self.handle)
# HidSmbus_Reset(HID_SMBUS_DEVICE device);
def Reset(self):
_DLL.HidSmbus_Reset(self.handle)
_DLL.HidSmbus_Close(self.handle)
self.handle.value = 0
# HidSmbus_ReadRequest(HID_SMBUS_DEVICE device, BYTE slaveAddress, WORD numBytesToRead);
def ReadRequest(self, address=2, count=64):
_DLL.HidSmbus_ReadRequest(self.handle, address, count)
# HidSmbus_AddressReadRequest(HID_SMBUS_DEVICE device, BYTE slaveAddress, WORD numBytesToRead, BYTE targetAddressSize, BYTE targetAddress[16]);
def AddressReadRequest(self, address=2, count=64, offset_size=2, offset=b'\x00\x00'):
buf = ct.create_string_buffer(bytes(offset), size=16)
_DLL.HidSmbus_AddressReadRequest(self.handle, address, count, offset_size, buf)
# HidSmbus_ForceReadResponse(HID_SMBUS_DEVICE device, WORD numBytesToRead);
def ForceReadResponse(self, count=64):
_DLL.HidSmbus_ForceReadResponse(self.handle, count)
# HidSmbus_GetReadResponse(HID_SMBUS_DEVICE device, HID_SMBUS_S0* status, BYTE* buffer, BYTE bufferSize, BYTE* numBytesRead);
def GetReadResponse(self, address=2, count=64):
buf = ct.create_string_buffer(count)
n = ct.c_ulong(0)
try:
_DLL.HidSmbus_GetReadResponse(self.handle, ct.byref(self._S0), buf, count, ct.byref(n))
except HidSmbusError as e:
# Ignore timeout, return the data that was read
if e.status != 0x12:
raise
return buf.value
# HidSmbus_WriteRequest(HID_SMBUS_DEVICE device, BYTE slaveAddress, BYTE* buffer, BYTE numBytesToWrite);
def WriteRequest(self, address, buffer, count=None):
if count is None:
count = len(buffer)
_DLL.HidSmbus_WriteRequest(self.handle, address, bytes(buffer), count)
# HidSmbus_TransferStatusRequest(HID_SMBUS_DEVICE device);
def TransferStatusRequest(self):
_DLL.HidSmbus_TransferStatusRequest(self.handle)
# HidSmbus_GetTransferStatusResponse(HID_SMBUS_DEVICE device, HID_SMBUS_S0* status, HID_SMBUS_S1* detailedStatus, WORD* numRetries, WORD* bytesRead);
def GetTransferStatusResponse(self):
tries = ct.c_ushort(0)
count = ct.c_ushort(0)
_DLL.HidSmbus_GetTransferStatusResponse(self.handle, ct.byref(self._S0), ct.byref(self._S1), ct.byref(tries), ct.byref(count))
return (self._S0.value, self._S1.value, tries.value, count.value)
# HidSmbus_SetTimeouts(HID_SMBUS_DEVICE device, DWORD responseTimeout);
def SetTimeouts(self, timeout=1000):
_DLL.HidSmbus_SetTimeouts(self.handle, timeout)
# HidSmbus_GetTimeouts(HID_SMBUS_DEVICE device, DWORD* responseTimeout);
def GetTimeouts(self):
timeout = ct.c_ulong(0)
_DLL.HidSmbus_GetTimeouts(self.handle, ct.byref(timeout))
return timeout.value
# HidSmbus_SetSmbusConfig(HID_SMBUS_DEVICE device, DWORD bitRate, BYTE address, BOOL autoReadRespond, WORD writeTimeout, WORD readTimeout, BOOL sclLowTimeout, WORD transferRetries);
def SetSmbusConfig(self, bitRate=100000, address=2, autoReadRespond=False, writeTimeout=0, readTimeout=0, sclLowTimeout=False, transferRetries=0):
_DLL.HidSmbus_SetSmbusConfig(self.handle,
bitRate, address, autoReadRespond, writeTimeout, readTimeout, sclLowTimeout, transferRetries)
# HidSmbus_GetSmbusConfig(HID_SMBUS_DEVICE device, DWORD* bitRate, BYTE* address, BOOL* autoReadRespond, WORD* writeTimeout, WORD* readTimeout, BOOL* sclLowtimeout, WORD* transferRetries);
def GetSmbusConfig(self):
rate = ct.c_ulong()
addr = ct.c_byte()
auto = ct.c_bool()
wto = ct.c_ushort()
rto = ct.c_ushort()
scl = ct.c_bool()
retry = ct.c_ushort()
_DLL.HidSmbus_GetSmbusConfig(self.handle,
ct.byref(rate), ct.byref(addr), ct.byref(auto), ct.byref(wto),
ct.byref(rto), ct.byref(scl), ct.byref(retry))
return (rate.value, addr.value, auto.value, wto.value, rto.value, scl.value, retry.value)
# HidSmbus_SetGpioConfig(HID_SMBUS_DEVICE device, BYTE direction, BYTE mode, BYTE function, BYTE clkDiv);
def SetGpioConfig(self, direction=0, mode=0, function=0, clkDiv=0):
_DLL.HidSmbus_SetGpioConfig(self.handle, direction, mode, function, clkDiv)
# HidSmbus_GetGpioConfig(HID_SMBUS_DEVICE device, BYTE* direction, BYTE* mode, BYTE* function, BYTE* clkDiv);
def GetGpioConfig(self):
dir = ct.c_byte()
mode = ct.c_byte()
fnc = ct.c_byte()
div = ct.c_byte()
_DLL.HidSmbus_GetGpioConfig(self.handle, ct.byref(dir), ct.byref(mode), ct.byref(fnc), ct.byref(div))
return (dir.value, mode.value, fnc.value, div.value)
# HidSmbus_ReadLatch(HID_SMBUS_DEVICE device, BYTE* latchValue);
def ReadLatch(self):
latch = ct.c_ushort()
_DLL.HidSmbus_ReadLatch(self.handle, ct.byref(latch))
return latch.value
# HidSmbus_WriteLatch(HID_SMBUS_DEVICE device, BYTE latchValue, BYTE latchMask);
def WriteLatch(self, latch, mask=0xFF):
_DLL.HidSmbus_WriteLatch(self.handle, latch, mask)
def PRINTV(*arg):
# print(arg)
pass
def Test( DevIndex):
PRINTV("--- device #%d" % DevIndex)
PRINTV("SLABHIDtoSMBus:", GetLibraryVersion())
PRINTV(" SLABHIDDevice:", GetHidLibraryVersion())
rc = -1
try:
smb = HidSmbusDevice()
smb.Open(DevIndex)
PRINTV('')
PRINTV(" VID:", smb.GetString(HID_SMBUS.VID_STR))
PRINTV(" PID:", smb.GetString(HID_SMBUS.PID_STR))
if sys.platform == 'win32':
PRINTV("DevPath:", smb.GetString(HID_SMBUS.PATH_STR))
PRINTV(" S/N:", smb.GetString(HID_SMBUS.SERIAL_STR))
PRINTV("Product:", smb.GetString(HID_SMBUS.PRODUCT_STR))
PRINTV("Company:", smb.GetString(HID_SMBUS.MANUFACTURER_STR))
PRINTV('')
PRINTV("GetAttributes() =", smb.GetAttributes())
PRINTV("GetPartNumber() =", smb.GetPartNumber())
PRINTV("GetString() =", smb.GetString())
PRINTV("GetTimeouts() =", smb.GetTimeouts())
PRINTV("GetSmbusConfig() =", smb.GetSmbusConfig())
PRINTV("GetGpioConfig() =", smb.GetGpioConfig())
PRINTV("ReadLatch() =", hex(smb.ReadLatch()))
smb.TransferStatusRequest()
PRINTV("GetTransferStatusResponse() =", smb.GetTransferStatusResponse())
rc = 0
except HidSmbusError as e:
print("Device Error:", e, "-", hex(e.status))
finally:
smb.Close()
return rc
def TestInvalDevIndex( NumDevices):
rc = 0
try:
smb = HidSmbusDevice()
smb.Open(NumDevices)
rc = -1
except HidSmbusError as e:
if e.status != HID_SMBUS_DEVICE_NOT_FOUND :
print("TestInvalDevIndex: Unexpected error:", e, "-", hex(e.status))
rc = -1
finally:
return rc
def TestAll():
errorlevel = 1
try:
NumDevices = GetNumDevices()
if TestInvalDevIndex( NumDevices) == 0:
SuccessCnt = 0
for i in range(0, NumDevices):
if Test( i) == 0:
SuccessCnt = SuccessCnt + 1
if NumDevices == SuccessCnt:
errorlevel = 0 # let shell know that test PASSED
except:
print("API_Test: Unhandled exception")
finally:
if errorlevel:
print("FAIL\n")
else:
print("PASS\n")
sys.exit(errorlevel)
if __name__ == "__main__":
TestAll()
////////////////////////////////////////////////////////////////////////////////
// Types.h
////////////////////////////////////////////////////////////////////////////////
#ifndef HOST_COMMON_INCLUDE_TYPES_H_INCLUDED_37C49TY24C
#define HOST_COMMON_INCLUDE_TYPES_H_INCLUDED_37C49TY24C
#if defined(_WIN32)
#include <windows.h>
#else
#include <stdint.h>
////////////////////////////////////////////////////////////////////////////////
// Typedefs
////////////////////////////////////////////////////////////////////////////////
typedef int BOOL;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned int UINT;
#if defined(__APPLE__)
typedef unsigned long DWORD;
typedef unsigned long long ULONGLONG;
#else
typedef unsigned int DWORD;
typedef unsigned int ULONG;
#define ULONGLONG int64_t
#endif
typedef char *LPSTR;
typedef const char *LPCSTR;
typedef BOOL *LPBOOL;
typedef BYTE *LPBYTE;
typedef WORD *LPWORD;
typedef UINT *LPUINT;
typedef DWORD *LPDWORD;
typedef void *LPVOID;
typedef void *HANDLE;
typedef HANDLE *LPHANDLE;
typedef HANDLE * PHANDLE;
typedef void * LPGUID;
////////////////////////////////////////////////////////////////////////////////
// Definitions
////////////////////////////////////////////////////////////////////////////////
#define INFINITE 0xFFFFFFFF
#if !defined(FALSE)
#define FALSE (0)
#endif
#if !defined(TRUE)
#define TRUE (1) // TODO: or !FALSE?
#endif
#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)>(b)?(a):(b))
// TODO: Delete these. Use host_common/silabs_utils.h::SILABS_MAKEWORD(), SILABS_LOBYTE() & SILABS_HIBYTE()
#define MAKEWORD(a, b) ((WORD)(((BYTE)(a)) | ((WORD)((BYTE)(b))) << 8))
#define LOWORD(l) ((WORD)(l))
#define HIWORD(l) ((WORD)(((DWORD)(l) >> 16) & 0xFFFF))
#define LOBYTE(w) ((BYTE)(w))
#define HIBYTE(w) ((BYTE)(((WORD)(w) >> 8) & 0xFF))
#endif // defined(_WIN32)
#endif // HOST_COMMON_INCLUDE_TYPES_H_INCLUDED_37C49TY24C

Comments are disabled for this gist.