@shubham0x13/ffbeast-wheel-webhid-api 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +47 -38
  2. package/dist/index.d.ts +216 -173
  3. package/dist/index.js +665 -439
  4. package/package.json +20 -29
package/dist/index.js CHANGED
@@ -1,16 +1,10 @@
1
- import { EventEmitter } from "eventemitter3";
2
1
 
3
- //#region src/constants.ts
4
- /** USB Vendor ID for FFBeast devices. */
2
+ import { EventEmitter } from "eventemitter3";
3
+ // src/constants.ts
4
+ /** USB Vendor ID for FFBeast devices. */
5
5
  const VID = 1115;
6
6
  /** USB Product ID for FFBeast wheel controllers. */
7
7
  const PID = 22999;
8
- /** Size of HID reports in bytes. */
9
- const REPORT_SIZE = 64;
10
- /** HID usage page for interface 0. */
11
- const INTERFACE_0_USAGE_PAGE = 65394;
12
- /** HID usage for interface 0. */
13
- const INTERFACE_0_USAGE = 161;
14
8
  /**
15
9
  * Maximum raw position value from the device.
16
10
  * @remarks Used for converting raw position to degrees.
@@ -21,205 +15,175 @@ const RAW_POSITION_MAX = 1e4;
21
15
  * @remarks Used for normalizing torque to [-100, 100] range.
22
16
  */
23
17
  const RAW_TORQUE_MAX = 1e4;
24
-
25
- //#endregion
26
- //#region src/enums.ts
27
- let ExtensionMode = /* @__PURE__ */ function(ExtensionMode$1) {
28
- ExtensionMode$1[ExtensionMode$1["None"] = 0] = "None";
29
- ExtensionMode$1[ExtensionMode$1["Custom"] = 1] = "Custom";
30
- return ExtensionMode$1;
31
- }({});
32
- let PinMode = /* @__PURE__ */ function(PinMode$1) {
33
- PinMode$1[PinMode$1["None"] = 0] = "None";
34
- PinMode$1[PinMode$1["Gpio"] = 1] = "Gpio";
35
- PinMode$1[PinMode$1["Analog"] = 2] = "Analog";
36
- PinMode$1[PinMode$1["SpiCs"] = 3] = "SpiCs";
37
- PinMode$1[PinMode$1["SpiSck"] = 4] = "SpiSck";
38
- PinMode$1[PinMode$1["SpiMiso"] = 5] = "SpiMiso";
39
- PinMode$1[PinMode$1["EnableEffects"] = 6] = "EnableEffects";
40
- PinMode$1[PinMode$1["CenterReset"] = 7] = "CenterReset";
41
- PinMode$1[PinMode$1["BrakingPwm"] = 8] = "BrakingPwm";
42
- PinMode$1[PinMode$1["EffectLed"] = 9] = "EffectLed";
43
- PinMode$1[PinMode$1["Reboot"] = 10] = "Reboot";
44
- return PinMode$1;
45
- }({});
46
- let ButtonMode = /* @__PURE__ */ function(ButtonMode$1) {
47
- ButtonMode$1[ButtonMode$1["None"] = 0] = "None";
48
- ButtonMode$1[ButtonMode$1["Normal"] = 1] = "Normal";
49
- ButtonMode$1[ButtonMode$1["Inverted"] = 2] = "Inverted";
50
- ButtonMode$1[ButtonMode$1["Pulse"] = 3] = "Pulse";
51
- ButtonMode$1[ButtonMode$1["PulseInverted"] = 4] = "PulseInverted";
52
- return ButtonMode$1;
53
- }({});
54
- let AmplifierGain = /* @__PURE__ */ function(AmplifierGain$1) {
55
- AmplifierGain$1[AmplifierGain$1["Gain80"] = 0] = "Gain80";
56
- AmplifierGain$1[AmplifierGain$1["Gain40"] = 1] = "Gain40";
57
- AmplifierGain$1[AmplifierGain$1["Gain20"] = 2] = "Gain20";
58
- AmplifierGain$1[AmplifierGain$1["Gain10"] = 3] = "Gain10";
59
- return AmplifierGain$1;
18
+ // src/conversions.ts
19
+ /**
20
+ * Converts raw position value to degrees.
21
+ *
22
+ * @param rawPosition - The raw position value from the device.
23
+ * @param motionRange - The motion range configured on the device, in degrees
24
+ * (see {@link EffectSettings.motionRange}).
25
+ * @returns The position in degrees.
26
+ */
27
+ function convertPositionToDegrees(rawPosition, motionRange) {
28
+ return rawPosition * motionRange / (2 * RAW_POSITION_MAX);
29
+ }
30
+ /**
31
+ * Normalizes raw torque value to a [-100, 100] range.
32
+ *
33
+ * @param rawTorque - The raw torque value from the device.
34
+ * @returns The normalized torque value between -100 and 100.
35
+ */
36
+ function normalizeTorque(rawTorque) {
37
+ return rawTorque * 100 / RAW_TORQUE_MAX;
38
+ }
39
+ // src/enums.ts
40
+ /** GPIO extension mode (`ExtensionModeEnum` in the reference header). */
41
+ let ExtensionMode = /* @__PURE__ */ function(ExtensionMode) {
42
+ ExtensionMode[ExtensionMode["None"] = 0] = "None";
43
+ ExtensionMode[ExtensionMode["Custom"] = 1] = "Custom";
44
+ return ExtensionMode;
60
45
  }({});
61
- let SpiMode = /* @__PURE__ */ function(SpiMode$1) {
62
- SpiMode$1[SpiMode$1["Mode0"] = 0] = "Mode0";
63
- SpiMode$1[SpiMode$1["Mode1"] = 1] = "Mode1";
64
- SpiMode$1[SpiMode$1["Mode2"] = 2] = "Mode2";
65
- SpiMode$1[SpiMode$1["Mode3"] = 3] = "Mode3";
66
- return SpiMode$1;
46
+ /** Function assigned to a GPIO extension pin (`PinModeEnum`). */
47
+ let PinMode = /* @__PURE__ */ function(PinMode) {
48
+ PinMode[PinMode["None"] = 0] = "None";
49
+ PinMode[PinMode["Gpio"] = 1] = "Gpio";
50
+ PinMode[PinMode["Analog"] = 2] = "Analog";
51
+ PinMode[PinMode["SpiCs"] = 3] = "SpiCs";
52
+ PinMode[PinMode["SpiSck"] = 4] = "SpiSck";
53
+ PinMode[PinMode["SpiMiso"] = 5] = "SpiMiso";
54
+ PinMode[PinMode["EnableEffects"] = 6] = "EnableEffects";
55
+ PinMode[PinMode["CenterReset"] = 7] = "CenterReset";
56
+ PinMode[PinMode["BrakingPwm"] = 8] = "BrakingPwm";
57
+ PinMode[PinMode["EffectLed"] = 9] = "EffectLed";
58
+ PinMode[PinMode["Reboot"] = 10] = "Reboot";
59
+ return PinMode;
67
60
  }({});
68
- let SpiLatchMode = /* @__PURE__ */ function(SpiLatchMode$1) {
69
- SpiLatchMode$1[SpiLatchMode$1["LatchUp"] = 0] = "LatchUp";
70
- SpiLatchMode$1[SpiLatchMode$1["LatchDown"] = 1] = "LatchDown";
71
- return SpiLatchMode$1;
61
+ /** How a button input is interpreted (`ButtonModeEnum`). */
62
+ let ButtonMode = /* @__PURE__ */ function(ButtonMode) {
63
+ ButtonMode[ButtonMode["None"] = 0] = "None";
64
+ ButtonMode[ButtonMode["Normal"] = 1] = "Normal";
65
+ ButtonMode[ButtonMode["Inverted"] = 2] = "Inverted";
66
+ /** Not implemented by the firmware, according to the reference header. */
67
+ ButtonMode[ButtonMode["Pulse"] = 3] = "Pulse";
68
+ /** Not implemented by the firmware, according to the reference header. */
69
+ ButtonMode[ButtonMode["PulseInverted"] = 4] = "PulseInverted";
70
+ return ButtonMode;
72
71
  }({});
73
- let ReportData = /* @__PURE__ */ function(ReportData$1) {
74
- ReportData$1[ReportData$1["CommandReboot"] = 1] = "CommandReboot";
75
- ReportData$1[ReportData$1["CommandSaveSettings"] = 2] = "CommandSaveSettings";
76
- ReportData$1[ReportData$1["CommandDfuMode"] = 3] = "CommandDfuMode";
77
- ReportData$1[ReportData$1["DataOverrideData"] = 16] = "DataOverrideData";
78
- ReportData$1[ReportData$1["DataFirmwareActivationData"] = 19] = "DataFirmwareActivationData";
79
- ReportData$1[ReportData$1["DataSettingsFieldData"] = 20] = "DataSettingsFieldData";
80
- ReportData$1[ReportData$1["CommandResetCenter"] = 4] = "CommandResetCenter";
81
- return ReportData$1;
72
+ /** Amplifier gain setting (`AmplifierGainEnum`). */
73
+ let AmplifierGain = /* @__PURE__ */ function(AmplifierGain) {
74
+ AmplifierGain[AmplifierGain["Gain80"] = 0] = "Gain80";
75
+ AmplifierGain[AmplifierGain["Gain40"] = 1] = "Gain40";
76
+ AmplifierGain[AmplifierGain["Gain20"] = 2] = "Gain20";
77
+ AmplifierGain[AmplifierGain["Gain10"] = 3] = "Gain10";
78
+ return AmplifierGain;
82
79
  }({});
83
- let ReportType = /* @__PURE__ */ function(ReportType$1) {
84
- ReportType$1[ReportType$1["JoystickInput"] = 1] = "JoystickInput";
85
- ReportType$1[ReportType$1["CreateNewEffect"] = 17] = "CreateNewEffect";
86
- ReportType$1[ReportType$1["PIDBlockLoad"] = 18] = "PIDBlockLoad";
87
- ReportType$1[ReportType$1["PIDPool"] = 19] = "PIDPool";
88
- ReportType$1[ReportType$1["SetEffect"] = 17] = "SetEffect";
89
- ReportType$1[ReportType$1["SetEnvelope"] = 18] = "SetEnvelope";
90
- ReportType$1[ReportType$1["SetCondition"] = 19] = "SetCondition";
91
- ReportType$1[ReportType$1["SetPeriodic"] = 20] = "SetPeriodic";
92
- ReportType$1[ReportType$1["SetConstantForce"] = 21] = "SetConstantForce";
93
- ReportType$1[ReportType$1["SetRampForce"] = 22] = "SetRampForce";
94
- ReportType$1[ReportType$1["EffectOperation"] = 26] = "EffectOperation";
95
- ReportType$1[ReportType$1["PIDState"] = 18] = "PIDState";
96
- ReportType$1[ReportType$1["PIDBlockFree"] = 27] = "PIDBlockFree";
97
- ReportType$1[ReportType$1["PIDDeviceControl"] = 28] = "PIDDeviceControl";
98
- ReportType$1[ReportType$1["DeviceGain"] = 29] = "DeviceGain";
99
- ReportType$1[ReportType$1["HardwareSettingsFeature"] = 33] = "HardwareSettingsFeature";
100
- ReportType$1[ReportType$1["EffectSettingsFeature"] = 34] = "EffectSettingsFeature";
101
- ReportType$1[ReportType$1["FirmwareLicenseFeature"] = 37] = "FirmwareLicenseFeature";
102
- ReportType$1[ReportType$1["GpioSettingsFeature"] = 161] = "GpioSettingsFeature";
103
- ReportType$1[ReportType$1["AdcSettingsFeature"] = 162] = "AdcSettingsFeature";
104
- ReportType$1[ReportType$1["GenericInputOutput"] = 163] = "GenericInputOutput";
105
- return ReportType$1;
80
+ /** SPI mode used to read the GPIO extension (`SpiModeEnum`). */
81
+ let SpiMode = /* @__PURE__ */ function(SpiMode) {
82
+ /**
83
+ * The first bit is output as soon as CS activates. Sequence: read, clock up,
84
+ * delay, clock down, delay.
85
+ */
86
+ SpiMode[SpiMode["Mode0"] = 0] = "Mode0";
87
+ /**
88
+ * The first bit is output on the first clock edge after CS activates.
89
+ * Sequence: clock up, delay, read, clock down, delay.
90
+ */
91
+ SpiMode[SpiMode["Mode1"] = 1] = "Mode1";
92
+ /**
93
+ * The first bit is output as soon as CS activates. Sequence: read, clock
94
+ * down, delay, clock up, delay.
95
+ */
96
+ SpiMode[SpiMode["Mode2"] = 2] = "Mode2";
97
+ /**
98
+ * The first bit is output on the first clock edge after CS activates.
99
+ * Sequence: clock down, delay, read, clock up, delay.
100
+ */
101
+ SpiMode[SpiMode["Mode3"] = 3] = "Mode3";
102
+ return SpiMode;
106
103
  }({});
107
- let SettingField = /* @__PURE__ */ function(SettingField$1) {
108
- SettingField$1[SettingField$1["DirectXConstantDirection"] = 0] = "DirectXConstantDirection";
109
- SettingField$1[SettingField$1["DirectXSpringStrength"] = 1] = "DirectXSpringStrength";
110
- SettingField$1[SettingField$1["DirectXConstantStrength"] = 2] = "DirectXConstantStrength";
111
- SettingField$1[SettingField$1["DirectXPeriodicStrength"] = 3] = "DirectXPeriodicStrength";
112
- SettingField$1[SettingField$1["TotalEffectStrength"] = 4] = "TotalEffectStrength";
113
- SettingField$1[SettingField$1["MotionRange"] = 5] = "MotionRange";
114
- SettingField$1[SettingField$1["SoftStopStrength"] = 6] = "SoftStopStrength";
115
- SettingField$1[SettingField$1["SoftStopRange"] = 7] = "SoftStopRange";
116
- SettingField$1[SettingField$1["StaticDampeningStrength"] = 8] = "StaticDampeningStrength";
117
- SettingField$1[SettingField$1["SoftStopDampeningStrength"] = 9] = "SoftStopDampeningStrength";
118
- SettingField$1[SettingField$1["ForceEnabled"] = 11] = "ForceEnabled";
119
- SettingField$1[SettingField$1["DebugTorque"] = 12] = "DebugTorque";
120
- SettingField$1[SettingField$1["AmplifierGain"] = 13] = "AmplifierGain";
121
- SettingField$1[SettingField$1["CalibrationMagnitude"] = 15] = "CalibrationMagnitude";
122
- SettingField$1[SettingField$1["CalibrationSpeed"] = 16] = "CalibrationSpeed";
123
- SettingField$1[SettingField$1["PowerLimit"] = 17] = "PowerLimit";
124
- SettingField$1[SettingField$1["BrakingLimit"] = 18] = "BrakingLimit";
125
- SettingField$1[SettingField$1["PositionSmoothing"] = 19] = "PositionSmoothing";
126
- SettingField$1[SettingField$1["SpeedBufferSize"] = 20] = "SpeedBufferSize";
127
- SettingField$1[SettingField$1["EncoderDirection"] = 21] = "EncoderDirection";
128
- SettingField$1[SettingField$1["ForceDirection"] = 22] = "ForceDirection";
129
- SettingField$1[SettingField$1["PolePairs"] = 23] = "PolePairs";
130
- SettingField$1[SettingField$1["EncoderCPR"] = 24] = "EncoderCPR";
131
- SettingField$1[SettingField$1["PGain"] = 25] = "PGain";
132
- SettingField$1[SettingField$1["IGain"] = 26] = "IGain";
133
- SettingField$1[SettingField$1["ExtensionMode"] = 27] = "ExtensionMode";
134
- SettingField$1[SettingField$1["PinMode"] = 28] = "PinMode";
135
- SettingField$1[SettingField$1["ButtonMode"] = 29] = "ButtonMode";
136
- SettingField$1[SettingField$1["SpiMode"] = 30] = "SpiMode";
137
- SettingField$1[SettingField$1["SpiLatchMode"] = 31] = "SpiLatchMode";
138
- SettingField$1[SettingField$1["SpiLatchDelay"] = 32] = "SpiLatchDelay";
139
- SettingField$1[SettingField$1["SpiClkPulseLength"] = 33] = "SpiClkPulseLength";
140
- SettingField$1[SettingField$1["AdcMinDeadZone"] = 34] = "AdcMinDeadZone";
141
- SettingField$1[SettingField$1["AdcMaxDeadZone"] = 35] = "AdcMaxDeadZone";
142
- SettingField$1[SettingField$1["AdcToButtonLow"] = 36] = "AdcToButtonLow";
143
- SettingField$1[SettingField$1["AdcToButtonHigh"] = 37] = "AdcToButtonHigh";
144
- SettingField$1[SettingField$1["AdcSmoothing"] = 38] = "AdcSmoothing";
145
- SettingField$1[SettingField$1["AdcInvert"] = 39] = "AdcInvert";
146
- SettingField$1[SettingField$1["ResetCenterOnZ0"] = 41] = "ResetCenterOnZ0";
147
- SettingField$1[SettingField$1["IntegratedSpringStrength"] = 43] = "IntegratedSpringStrength";
148
- return SettingField$1;
104
+ /**
105
+ * Edge of the chip-select signal that triggers the SPI latch
106
+ * (`SpiLatchModeEnum`).
107
+ */
108
+ let SpiLatchMode = /* @__PURE__ */ function(SpiLatchMode) {
109
+ /** nCS goes up to trigger the SPI latch. */
110
+ SpiLatchMode[SpiLatchMode["LatchUp"] = 0] = "LatchUp";
111
+ /** nCS goes down to trigger the SPI latch. */
112
+ SpiLatchMode[SpiLatchMode["LatchDown"] = 1] = "LatchDown";
113
+ return SpiLatchMode;
149
114
  }({});
150
115
  /**
151
- * Binary field type identifiers for parsing HID reports.
152
- * @internal
116
+ * Identifiers of the settings written with {@link WheelApi.sendSetting}
117
+ * (`SettingsFieldEnum`).
153
118
  */
154
- let FieldType = /* @__PURE__ */ function(FieldType$1) {
155
- FieldType$1[FieldType$1["Int8"] = 0] = "Int8";
156
- FieldType$1[FieldType$1["Uint8"] = 1] = "Uint8";
157
- FieldType$1[FieldType$1["Int16"] = 2] = "Int16";
158
- FieldType$1[FieldType$1["Uint16"] = 3] = "Uint16";
159
- FieldType$1[FieldType$1["Int32"] = 4] = "Int32";
160
- FieldType$1[FieldType$1["Uint32"] = 5] = "Uint32";
161
- FieldType$1[FieldType$1["Float32"] = 6] = "Float32";
162
- return FieldType$1;
119
+ let SettingField = /* @__PURE__ */ function(SettingField) {
120
+ SettingField[SettingField["DirectXConstantDirection"] = 0] = "DirectXConstantDirection";
121
+ SettingField[SettingField["DirectXSpringStrength"] = 1] = "DirectXSpringStrength";
122
+ SettingField[SettingField["DirectXConstantStrength"] = 2] = "DirectXConstantStrength";
123
+ SettingField[SettingField["DirectXPeriodicStrength"] = 3] = "DirectXPeriodicStrength";
124
+ SettingField[SettingField["TotalEffectStrength"] = 4] = "TotalEffectStrength";
125
+ SettingField[SettingField["MotionRange"] = 5] = "MotionRange";
126
+ SettingField[SettingField["SoftStopStrength"] = 6] = "SoftStopStrength";
127
+ SettingField[SettingField["SoftStopRange"] = 7] = "SoftStopRange";
128
+ SettingField[SettingField["StaticDampeningStrength"] = 8] = "StaticDampeningStrength";
129
+ SettingField[SettingField["SoftStopDampeningStrength"] = 9] = "SoftStopDampeningStrength";
130
+ /** Supported by firmware RC.26.1.1; ignored by RC.24.1.4. */
131
+ SettingField[SettingField["DynamicDampeningStrength"] = 10] = "DynamicDampeningStrength";
132
+ /** Applies after {@link WheelApi.saveAndReboot}. */
133
+ SettingField[SettingField["ForceEnabled"] = 11] = "ForceEnabled";
134
+ SettingField[SettingField["DebugTorque"] = 12] = "DebugTorque";
135
+ /** Applies after {@link WheelApi.saveAndReboot}. */
136
+ SettingField[SettingField["AmplifierGain"] = 13] = "AmplifierGain";
137
+ SettingField[SettingField["CalibrationMagnitude"] = 15] = "CalibrationMagnitude";
138
+ SettingField[SettingField["CalibrationSpeed"] = 16] = "CalibrationSpeed";
139
+ SettingField[SettingField["PowerLimit"] = 17] = "PowerLimit";
140
+ SettingField[SettingField["BrakingLimit"] = 18] = "BrakingLimit";
141
+ SettingField[SettingField["PositionSmoothing"] = 19] = "PositionSmoothing";
142
+ SettingField[SettingField["SpeedBufferSize"] = 20] = "SpeedBufferSize";
143
+ SettingField[SettingField["EncoderDirection"] = 21] = "EncoderDirection";
144
+ SettingField[SettingField["ForceDirection"] = 22] = "ForceDirection";
145
+ SettingField[SettingField["PolePairs"] = 23] = "PolePairs";
146
+ SettingField[SettingField["EncoderCPR"] = 24] = "EncoderCPR";
147
+ SettingField[SettingField["PGain"] = 25] = "PGain";
148
+ SettingField[SettingField["IGain"] = 26] = "IGain";
149
+ SettingField[SettingField["ExtensionMode"] = 27] = "ExtensionMode";
150
+ /** Applies after {@link WheelApi.saveAndReboot}. */
151
+ SettingField[SettingField["PinMode"] = 28] = "PinMode";
152
+ SettingField[SettingField["ButtonMode"] = 29] = "ButtonMode";
153
+ SettingField[SettingField["SpiMode"] = 30] = "SpiMode";
154
+ SettingField[SettingField["SpiLatchMode"] = 31] = "SpiLatchMode";
155
+ SettingField[SettingField["SpiLatchDelay"] = 32] = "SpiLatchDelay";
156
+ SettingField[SettingField["SpiClkPulseLength"] = 33] = "SpiClkPulseLength";
157
+ SettingField[SettingField["AdcMinDeadZone"] = 34] = "AdcMinDeadZone";
158
+ SettingField[SettingField["AdcMaxDeadZone"] = 35] = "AdcMaxDeadZone";
159
+ SettingField[SettingField["AdcToButtonLow"] = 36] = "AdcToButtonLow";
160
+ SettingField[SettingField["AdcToButtonHigh"] = 37] = "AdcToButtonHigh";
161
+ SettingField[SettingField["AdcSmoothing"] = 38] = "AdcSmoothing";
162
+ SettingField[SettingField["AdcInvert"] = 39] = "AdcInvert";
163
+ /**
164
+ * Sets pin Z0 (`pinMode[8]`) to {@link PinMode.CenterReset} for a non-zero
165
+ * value, or {@link PinMode.None} for zero. The index is ignored. Applies
166
+ * after {@link WheelApi.saveAndReboot}.
167
+ */
168
+ SettingField[SettingField["ResetCenterOnZ0"] = 41] = "ResetCenterOnZ0";
169
+ SettingField[SettingField["IntegratedSpringStrength"] = 43] = "IntegratedSpringStrength";
170
+ return SettingField;
163
171
  }({});
172
+ // src/internal/binary.ts
164
173
  /**
165
- * Maps {@link SettingField} values to their corresponding {@link FieldType}.
166
- *
167
- * @remarks
168
- * This mapping is based on the struct definitions in the original C++ `wheel_api.h`.
174
+ * Helpers for reading and writing packed binary report data.
169
175
  *
170
176
  * @internal
177
+ * @module
171
178
  */
172
- const FIELD_TYPE_MAP = {
173
- [SettingField.MotionRange]: FieldType.Uint16,
174
- [SettingField.StaticDampeningStrength]: FieldType.Uint16,
175
- [SettingField.SoftStopDampeningStrength]: FieldType.Uint16,
176
- [SettingField.TotalEffectStrength]: FieldType.Uint8,
177
- [SettingField.IntegratedSpringStrength]: FieldType.Uint8,
178
- [SettingField.SoftStopRange]: FieldType.Uint8,
179
- [SettingField.SoftStopStrength]: FieldType.Uint8,
180
- [SettingField.DirectXConstantDirection]: FieldType.Int8,
181
- [SettingField.DirectXSpringStrength]: FieldType.Uint8,
182
- [SettingField.DirectXConstantStrength]: FieldType.Uint8,
183
- [SettingField.DirectXPeriodicStrength]: FieldType.Uint8,
184
- [SettingField.EncoderCPR]: FieldType.Uint16,
185
- [SettingField.IGain]: FieldType.Uint16,
186
- [SettingField.PGain]: FieldType.Uint8,
187
- [SettingField.ForceEnabled]: FieldType.Uint8,
188
- [SettingField.DebugTorque]: FieldType.Uint8,
189
- [SettingField.AmplifierGain]: FieldType.Uint8,
190
- [SettingField.CalibrationMagnitude]: FieldType.Uint8,
191
- [SettingField.CalibrationSpeed]: FieldType.Uint8,
192
- [SettingField.PowerLimit]: FieldType.Uint8,
193
- [SettingField.BrakingLimit]: FieldType.Uint8,
194
- [SettingField.PositionSmoothing]: FieldType.Uint8,
195
- [SettingField.SpeedBufferSize]: FieldType.Uint8,
196
- [SettingField.EncoderDirection]: FieldType.Int8,
197
- [SettingField.ForceDirection]: FieldType.Int8,
198
- [SettingField.PolePairs]: FieldType.Uint8,
199
- [SettingField.ExtensionMode]: FieldType.Uint8,
200
- [SettingField.PinMode]: FieldType.Uint8,
201
- [SettingField.ButtonMode]: FieldType.Uint8,
202
- [SettingField.SpiMode]: FieldType.Uint8,
203
- [SettingField.SpiLatchMode]: FieldType.Uint8,
204
- [SettingField.SpiLatchDelay]: FieldType.Uint8,
205
- [SettingField.SpiClkPulseLength]: FieldType.Uint8,
206
- [SettingField.AdcSmoothing]: FieldType.Uint8,
207
- [SettingField.AdcToButtonLow]: FieldType.Uint8,
208
- [SettingField.AdcToButtonHigh]: FieldType.Uint8,
209
- [SettingField.AdcInvert]: FieldType.Uint8,
210
- [SettingField.AdcMinDeadZone]: FieldType.Uint16,
211
- [SettingField.AdcMaxDeadZone]: FieldType.Uint16,
212
- [SettingField.ResetCenterOnZ0]: FieldType.Uint8
213
- };
214
-
215
- //#endregion
216
- //#region src/utils.ts
217
179
  /**
218
180
  * Helper to read packed C-structs sequentially.
219
181
  * Eliminates the need to manually track byte offsets.
220
182
  * @internal
221
183
  */
222
184
  var StructReader = class {
185
+ view;
186
+ offset;
223
187
  constructor(view, offset = 0) {
224
188
  this.view = view;
225
189
  this.offset = offset;
@@ -249,34 +213,308 @@ var StructReader = class {
249
213
  return Array.from({ length: len }, fn);
250
214
  }
251
215
  };
216
+ function clamp(val, min, max) {
217
+ return Math.max(min, Math.min(val, max));
218
+ }
252
219
  /**
253
- * Converts raw position value to degrees.
220
+ * Throws a `RangeError` unless `value` is finite. `DataView` setters would
221
+ * silently write `NaN` as 0.
254
222
  *
255
- * @param rawPosition - The raw position value from the device.
256
- * @param motionRange - The configured motion range in degrees.
257
- * @returns The position in degrees.
223
+ * @internal
258
224
  */
259
- function convertPositionToDegrees(rawPosition, motionRange = 900) {
260
- return rawPosition * motionRange / (2 * RAW_POSITION_MAX);
225
+ function assertFinite(value, name) {
226
+ if (!Number.isFinite(value)) throw new RangeError(`${name} must be a finite number, received ${String(value)}`);
261
227
  }
262
228
  /**
263
- * Normalizes raw torque value to a [-100, 100] range.
229
+ * Rounds `value` and clamps it to `[min, max]`. `DataView` integer setters
230
+ * would truncate fractions instead.
264
231
  *
265
- * @param rawTorque - The raw torque value from the device.
266
- * @returns The normalized torque value between -100 and 100.
232
+ * @throws RangeError if `value` is not finite.
233
+ * @internal
267
234
  */
268
- function normalizeTorque(rawTorque) {
269
- return rawTorque * 100 / RAW_TORQUE_MAX;
235
+ function toClampedInt(value, min, max, name) {
236
+ assertFinite(value, name);
237
+ return clamp(Math.round(value), min, max);
270
238
  }
271
- function isTargetDevice(device) {
272
- return device.vendorId === VID && device.productId === PID && device.collections.some((c) => c.usagePage === INTERFACE_0_USAGE_PAGE && c.usage === INTERFACE_0_USAGE);
239
+ /** HID usage page for interface 0. */
240
+ const INTERFACE_0_USAGE_PAGE = 65394;
241
+ /**
242
+ * Wire type of each {@link SettingField}, from the reference `wheel_api.h`
243
+ * structs and the FFBeast protocol page (`DynamicDampeningStrength`).
244
+ */
245
+ const FIELD_TYPE_MAP = {
246
+ [5]: 3,
247
+ [8]: 3,
248
+ [9]: 3,
249
+ [10]: 3,
250
+ [4]: 1,
251
+ [43]: 1,
252
+ [7]: 1,
253
+ [6]: 1,
254
+ [0]: 0,
255
+ [1]: 1,
256
+ [2]: 1,
257
+ [3]: 1,
258
+ [24]: 3,
259
+ [26]: 3,
260
+ [25]: 1,
261
+ [11]: 1,
262
+ [12]: 1,
263
+ [13]: 1,
264
+ [15]: 1,
265
+ [16]: 1,
266
+ [17]: 1,
267
+ [18]: 1,
268
+ [19]: 1,
269
+ [20]: 1,
270
+ [21]: 0,
271
+ [22]: 0,
272
+ [23]: 1,
273
+ [27]: 1,
274
+ [28]: 1,
275
+ [29]: 1,
276
+ [30]: 1,
277
+ [31]: 1,
278
+ [32]: 1,
279
+ [33]: 1,
280
+ [38]: 1,
281
+ [36]: 1,
282
+ [37]: 1,
283
+ [39]: 1,
284
+ [34]: 3,
285
+ [35]: 3,
286
+ [41]: 1
287
+ };
288
+ /** WebHID filter matching the wheel's vendor interface (interface 0). */
289
+ const WHEEL_DEVICE_FILTER = {
290
+ vendorId: VID,
291
+ productId: PID,
292
+ usagePage: INTERFACE_0_USAGE_PAGE,
293
+ usage: 161
294
+ };
295
+ /** Whether `device` exposes the wheel's vendor interface. */
296
+ function isWheelDevice(device) {
297
+ return device.vendorId === WHEEL_DEVICE_FILTER.vendorId && device.productId === WHEEL_DEVICE_FILTER.productId && device.collections.some((c) => c.usagePage === WHEEL_DEVICE_FILTER.usagePage && c.usage === WHEEL_DEVICE_FILTER.usage);
273
298
  }
274
- function clamp(val, min, max) {
275
- return Math.max(min, Math.min(val, max));
299
+ /**
300
+ * Returns the payload of a feature report. The WebHID spec allows the data to
301
+ * start with the report ID; payloads are exactly {@link REPORT_SIZE} bytes, so
302
+ * the length tells the layouts apart (a first-byte check is ambiguous: a
303
+ * motion range of 802 is 0x0322).
304
+ *
305
+ * @throws Error if the payload is too short.
306
+ */
307
+ function featureReportPayload(view, reportId) {
308
+ const offset = view.byteLength > 64 ? 1 : 0;
309
+ const length = view.byteLength - offset;
310
+ if (length < 64) throw new Error(`Feature report 0x${reportId.toString(16)} is too short: expected 64 bytes, received ${length}`);
311
+ return new DataView(view.buffer, view.byteOffset + offset, length);
312
+ }
313
+ /** Decodes `EffectSettingsTypeDef`. */
314
+ function parseEffectSettings(view) {
315
+ const r = new StructReader(view);
316
+ return {
317
+ motionRange: r.u16(),
318
+ staticDampeningStrength: r.u16(),
319
+ softStopDampeningStrength: r.u16(),
320
+ totalEffectStrength: r.u8(),
321
+ integratedSpringStrength: r.u8(),
322
+ softStopRange: r.u8(),
323
+ softStopStrength: r.u8(),
324
+ directXConstantDirection: r.i8(),
325
+ directXSpringStrength: r.u8(),
326
+ directXConstantStrength: r.u8(),
327
+ directXPeriodicStrength: r.u8(),
328
+ dynamicDampeningStrength: r.u16()
329
+ };
330
+ }
331
+ /** Decodes `HardwareSettingsTypeDef`. */
332
+ function parseHardwareSettings(view) {
333
+ const r = new StructReader(view);
334
+ return {
335
+ encoderCPR: r.u16(),
336
+ integralGain: r.u16(),
337
+ proportionalGain: r.u8(),
338
+ forceEnabled: r.u8(),
339
+ debugTorque: r.u8(),
340
+ amplifierGain: r.u8(),
341
+ calibrationMagnitude: r.u8(),
342
+ calibrationSpeed: r.u8(),
343
+ powerLimit: r.u8(),
344
+ brakingLimit: r.u8(),
345
+ positionSmoothing: r.u8(),
346
+ speedBufferSize: r.u8(),
347
+ encoderDirection: r.i8(),
348
+ forceDirection: r.i8(),
349
+ polePairs: r.u8()
350
+ };
351
+ }
352
+ /** Decodes `GpioExtensionSettingsTypeDef`. */
353
+ function parseGpioSettings(view) {
354
+ const r = new StructReader(view);
355
+ return {
356
+ extensionMode: r.u8(),
357
+ pinMode: r.array(10, () => r.u8()),
358
+ buttonMode: r.array(32, () => r.u8()),
359
+ spiMode: r.u8(),
360
+ spiLatchMode: r.u8(),
361
+ spiLatchDelay: r.u8(),
362
+ spiClkPulseLength: r.u8()
363
+ };
364
+ }
365
+ /** Decodes `AdcExtensionSettingsTypeDef`. */
366
+ function parseAdcSettings(view) {
367
+ const r = new StructReader(view);
368
+ return {
369
+ rAxisMin: r.array(3, () => r.u16()),
370
+ rAxisMax: r.array(3, () => r.u16()),
371
+ rAxisSmoothing: r.array(3, () => r.u8()),
372
+ rAxisToButtonLow: r.array(3, () => r.u8()),
373
+ rAxisToButtonHigh: r.array(3, () => r.u8()),
374
+ rAxisInvert: r.array(3, () => r.u8())
375
+ };
376
+ }
377
+ /** Decodes `FirmwareLicenseTypeDef`. */
378
+ function parseFirmwareLicense(view) {
379
+ const r = new StructReader(view);
380
+ return {
381
+ firmwareVersion: {
382
+ releaseType: r.u8(),
383
+ major: r.u8(),
384
+ minor: r.u8(),
385
+ patch: r.u8()
386
+ },
387
+ serialKey: r.array(3, () => r.u32()),
388
+ deviceId: r.array(3, () => r.u32()),
389
+ isRegistered: r.u8()
390
+ };
391
+ }
392
+ /** Whether an input report is the vendor interface's generic report. */
393
+ function isGenericReport(reportId) {
394
+ return reportId === 163;
395
+ }
396
+ /** Decodes `DeviceStateTypeDef` from an input report (without report ID). */
397
+ function parseDeviceState(view) {
398
+ const r = new StructReader(view);
399
+ return {
400
+ firmwareVersion: {
401
+ releaseType: r.u8(),
402
+ major: r.u8(),
403
+ minor: r.u8(),
404
+ patch: r.u8()
405
+ },
406
+ isRegistered: r.u8(),
407
+ position: r.i16(),
408
+ torque: r.i16()
409
+ };
410
+ }
411
+ /**
412
+ * Creates a generic vendor report payload: {@link REPORT_SIZE} bytes whose
413
+ * first byte is `command` (`DataReportTypeDef`).
414
+ */
415
+ function dataReport(command, write) {
416
+ const data = /* @__PURE__ */ new Uint8Array(64);
417
+ const view = new DataView(data.buffer);
418
+ view.setUint8(0, command);
419
+ write?.(view);
420
+ return data;
421
+ }
422
+ /** Encodes a command without arguments (reboot, save, DFU, reset center). */
423
+ function encodeCommand(command) {
424
+ return dataReport(command);
425
+ }
426
+ /**
427
+ * Writes a setting value of the given wire type at `offset`.
428
+ *
429
+ * @returns The value as the device will store it.
430
+ * @throws RangeError if `value` is not a finite number.
431
+ */
432
+ function writeSettingValue(view, offset, type, value) {
433
+ switch (type) {
434
+ case 0: {
435
+ const v = toClampedInt(value, -128, 127, "value");
436
+ view.setInt8(offset, v);
437
+ return v;
438
+ }
439
+ case 1: {
440
+ const v = toClampedInt(value, 0, 255, "value");
441
+ view.setUint8(offset, v);
442
+ return v;
443
+ }
444
+ case 2: {
445
+ const v = toClampedInt(value, -32768, 32767, "value");
446
+ view.setInt16(offset, v, true);
447
+ return v;
448
+ }
449
+ case 3: {
450
+ const v = toClampedInt(value, 0, 65535, "value");
451
+ view.setUint16(offset, v, true);
452
+ return v;
453
+ }
454
+ case 4:
455
+ assertFinite(value, "value");
456
+ view.setFloat32(offset, value, true);
457
+ return view.getFloat32(offset, true);
458
+ default: throw new Error(`Unsupported field type: ${String(type)}`);
459
+ }
460
+ }
461
+ /**
462
+ * Encodes a single setting (`FieldDataTypeDef`).
463
+ *
464
+ * @returns The report payload, and the value as the device will store it.
465
+ * @throws RangeError if `field` is not a known setting, `index` is not an
466
+ * integer in `[0, 255]` or `value` is not a finite number.
467
+ */
468
+ function encodeSetting(field, index, value) {
469
+ if (!Object.hasOwn(FIELD_TYPE_MAP, field)) throw new RangeError(`field must be a known SettingField, received ${String(field)}`);
470
+ if (!Number.isInteger(index) || index < 0 || index > 255) throw new RangeError(`index must be an integer in [0, 255], received ${String(index)}`);
471
+ let storedValue = 0;
472
+ return {
473
+ data: dataReport(20, (view) => {
474
+ view.setUint8(1, field);
475
+ view.setUint8(2, index);
476
+ storedValue = writeSettingValue(view, 3, FIELD_TYPE_MAP[field], value);
477
+ }),
478
+ storedValue
479
+ };
480
+ }
481
+ /**
482
+ * Encodes `DirectControlTypeDef`.
483
+ *
484
+ * @throws RangeError if any value is not a finite number.
485
+ */
486
+ function encodeDirectControl(control) {
487
+ return dataReport(16, (view) => {
488
+ view.setInt16(1, toClampedInt(control.springForce, -1e4, 1e4, "springForce"), true);
489
+ view.setInt16(3, toClampedInt(control.constantForce, -1e4, 1e4, "constantForce"), true);
490
+ view.setInt16(5, toClampedInt(control.periodicForce, -1e4, 1e4, "periodicForce"), true);
491
+ view.setUint8(7, toClampedInt(control.forceDrop, 0, 100, "forceDrop"));
492
+ });
276
493
  }
277
-
278
- //#endregion
279
- //#region src/wheel-api.ts
494
+ /**
495
+ * Encodes a firmware activation key: three hexadecimal segments separated by
496
+ * `-`, written as little-endian 32-bit values after the command byte.
497
+ *
498
+ * @remarks
499
+ * Sent without the device type byte that the protocol page's
500
+ * `FirmwareActivationTypeDef` declares; see `reference-cpp/README.md`.
501
+ *
502
+ * @throws Error if the key is malformed.
503
+ */
504
+ function encodeFirmwareActivation(license) {
505
+ const segments = license.trim().split("-");
506
+ if (segments.length !== 3) throw new Error("Invalid license format: expected 3 segments separated by \"-\"");
507
+ const values = segments.map((segment, i) => {
508
+ if (!/^[0-9A-Fa-f]{1,8}$/.test(segment)) throw new Error(`Invalid license format: segment ${i + 1} is not a hexadecimal number of 1 to 8 digits`);
509
+ return Number.parseInt(segment, 16);
510
+ });
511
+ return dataReport(19, (view) => {
512
+ values.forEach((value, i) => {
513
+ view.setUint32(1 + i * 4, value, true);
514
+ });
515
+ });
516
+ }
517
+ // src/wheel-api.ts
280
518
  /**
281
519
  * WebHID-based API for communicating with the wheel controller.
282
520
  *
@@ -287,56 +525,78 @@ function clamp(val, min, max) {
287
525
  * const wheel = new WheelApi();
288
526
  *
289
527
  * wheel.on("stateReceived", (state) => {
290
- * console.log("Position:", state.position);
528
+ * console.log("Position:", state.positionDegrees);
291
529
  * });
292
530
  *
293
- * await wheel.connect();
294
- *
295
- * // ... later
531
+ * // The device picker must be opened from a user action.
532
+ * connectButton.addEventListener("click", () => {
533
+ * wheel.connect().catch(console.error);
534
+ * });
296
535
  *
297
- * await wheel.disconnect();
298
- * wheel.destroy();
536
+ * // Later, for example when the page or component unmounts.
537
+ * // destroy() also disconnects.
538
+ * await wheel.destroy();
299
539
  * ```
300
540
  */
301
541
  var WheelApi = class WheelApi extends EventEmitter {
542
+ #device = null;
543
+ #lastState = null;
544
+ #cachedMotionRange = null;
545
+ #queue = Promise.resolve();
546
+ #pendingConnections = 0;
547
+ #unplugged = /* @__PURE__ */ new WeakSet();
548
+ #destroyed = false;
549
+ #autoConnect;
550
+ /** @param options - See {@link WheelApiOptions}. */
551
+ constructor(options = {}) {
552
+ super();
553
+ if (!WheelApi.isSupported()) throw new Error("WebHID is not available. It requires a supported browser and a secure context (HTTPS or localhost)");
554
+ this.#autoConnect = options.autoConnect ?? true;
555
+ if (this.#autoConnect) navigator.hid.addEventListener("connect", this.#handleConnect);
556
+ navigator.hid.addEventListener("disconnect", this.#handleDisconnect);
557
+ }
302
558
  /**
303
559
  * Last received device state.
304
560
  * @returns Device state, or `null` if no state received yet.
305
561
  */
306
562
  get lastState() {
307
- return this._lastState ? { ...this._lastState } : null;
563
+ if (!this.#lastState) return null;
564
+ return {
565
+ ...this.#lastState,
566
+ firmwareVersion: { ...this.#lastState.firmwareVersion }
567
+ };
308
568
  }
309
569
  /**
310
570
  * Current wheel position in degrees.
311
- * @returns Position in degrees, or `null` if not connected.
571
+ * @returns Position in degrees, or `null` if no state has been received or
572
+ * the motion range is unknown.
312
573
  */
313
574
  get positionDegrees() {
314
- if (!this.lastState || this.cachedMotionRange === null) return null;
315
- return convertPositionToDegrees(this.lastState.position, this.cachedMotionRange);
575
+ if (!this.#lastState || this.#cachedMotionRange === null) return null;
576
+ return convertPositionToDegrees(this.#lastState.position, this.#cachedMotionRange);
316
577
  }
317
578
  /**
318
579
  * Current torque normalized to [-100, 100] range.
319
- * @returns Normalized torque, or `null` if not connected.
580
+ * @returns Normalized torque, or `null` if no state has been received.
320
581
  */
321
582
  get torqueNormalized() {
322
- if (!this.lastState) return null;
323
- return normalizeTorque(this.lastState.torque);
583
+ return this.#lastState?.torqueNormalized ?? null;
324
584
  }
325
585
  /**
326
586
  * Current firmware release type.
327
- * @returns Release type number, or `null` if not connected.
587
+ * @returns Release type number, or `null` if no state has been received.
328
588
  */
329
589
  get firmwareReleaseType() {
330
- if (!this.lastState) return null;
331
- return this.lastState.firmwareVersion.releaseType;
590
+ return this.#lastState?.firmwareVersion.releaseType ?? null;
332
591
  }
333
592
  /**
334
593
  * Current firmware version string.
335
- * @returns Version string (e.g., "1.2.3"), or `null` if not connected.
594
+ * @returns Version string (e.g., "1.2.3"), or `null` if no state has been
595
+ * received.
336
596
  */
337
597
  get firmwareVersion() {
338
- if (!this.lastState) return null;
339
- const v = this.lastState.firmwareVersion;
598
+ if (!this.#lastState) return null;
599
+ const v = this.#lastState.firmwareVersion;
340
600
  return `${v.major}.${v.minor}.${v.patch}`;
341
601
  }
342
602
  /**
@@ -344,71 +604,76 @@ var WheelApi = class WheelApi extends EventEmitter {
344
604
  * @returns `true` if connected and opened.
345
605
  */
346
606
  get isConnected() {
347
- return this.device?.opened ?? false;
607
+ return this.#device?.opened ?? false;
348
608
  }
349
- device = null;
350
- _lastState = null;
351
- cachedMotionRange = null;
352
- constructor() {
353
- super();
354
- if (!WheelApi.isSupported()) throw new Error("WebHID is not supported in this browser.");
355
- navigator.hid.addEventListener("connect", this.handleConnect);
356
- navigator.hid.addEventListener("disconnect", this.handleDisconnect);
609
+ /**
610
+ * Whether a previously authorized wheel connects automatically when plugged
611
+ * in. Set with {@link WheelApiOptions.autoConnect}.
612
+ */
613
+ get autoConnect() {
614
+ return this.#autoConnect;
357
615
  }
358
616
  /**
359
- * Checks if WebHID is supported in the current browser.
360
- * @returns `true` if supported (Chrome/Edge/Opera).
617
+ * Checks whether the current environment supports WebHID.
618
+ * @returns `false` outside browsers (for example during server-side
619
+ * rendering) and in browsers without WebHID.
361
620
  */
362
621
  static isSupported() {
363
- return "hid" in navigator;
622
+ return typeof navigator !== "undefined" && "hid" in navigator;
364
623
  }
365
624
  /**
366
625
  * Opens the browser's device picker to connect to a wheel.
367
- * @returns `true` if connection was successful.
626
+ *
627
+ * @remarks
628
+ * Must be called from a user gesture (e.g. a click handler), as required by
629
+ * `navigator.hid.requestDevice()`. If another wheel is already connected it
630
+ * is disconnected first.
631
+ *
632
+ * @returns `true` if a device was connected, `false` if the user closed the
633
+ * picker without selecting one.
634
+ * @throws Error if the selected device could not be opened. The underlying
635
+ * `DOMException` is available as `cause`.
368
636
  */
369
637
  async connect() {
370
- const devices = await navigator.hid.requestDevice({ filters: [{
371
- vendorId: VID,
372
- productId: PID,
373
- usagePage: INTERFACE_0_USAGE_PAGE,
374
- usage: INTERFACE_0_USAGE
375
- }] });
376
- if (devices.length === 0) return false;
377
- return await this.openDevice(devices[0]);
638
+ const device = (await navigator.hid.requestDevice({ filters: [WHEEL_DEVICE_FILTER] }))[0];
639
+ if (!device) return false;
640
+ await this.#openDevice(device);
641
+ return true;
378
642
  }
379
643
  /**
380
644
  * Attempts to reconnect to a previously authorized device.
381
- * @returns `true` if a device was found and connected.
645
+ * @returns `true` if a device was found and connected, `false` if no
646
+ * previously authorized wheel is available.
647
+ * @throws Error if the device was found but could not be opened. The
648
+ * underlying `DOMException` is available as `cause`.
382
649
  */
383
650
  async tryAutoConnect() {
384
- const validDevice = (await navigator.hid.getDevices()).find((d) => isTargetDevice(d));
385
- if (validDevice) return await this.openDevice(validDevice);
386
- return false;
651
+ const device = (await navigator.hid.getDevices()).find((d) => isWheelDevice(d));
652
+ if (!device) return false;
653
+ await this.#openDevice(device);
654
+ return true;
387
655
  }
388
656
  /**
389
- * Disconnects from the current device.
657
+ * Disconnects from the current device. A connection in progress finishes
658
+ * first.
390
659
  */
391
660
  async disconnect() {
392
- if (!this.device) return;
393
- const deviceToDisconnect = this.device;
394
- try {
395
- this.device.removeEventListener("inputreport", this.handleInputReport);
396
- await this.device.close();
397
- } catch {} finally {
398
- this.device = null;
399
- this._lastState = null;
400
- this.cachedMotionRange = null;
401
- this.emit("deviceDisconnected", deviceToDisconnect);
402
- }
661
+ await this.#enqueue(() => this.#disconnectNow());
403
662
  }
404
663
  /**
405
664
  * Cleans up all resources and event listeners.
406
665
  * Must be called when the API instance is no longer needed.
666
+ *
667
+ * @remarks
668
+ * A {@link WheelApi.connect} or {@link WheelApi.tryAutoConnect} call that is
669
+ * still pending rejects instead of connecting; `destroy()` resolves once it
670
+ * has finished.
407
671
  */
408
672
  async destroy() {
673
+ this.#destroyed = true;
409
674
  await this.disconnect();
410
- navigator.hid.removeEventListener("connect", this.handleConnect);
411
- navigator.hid.removeEventListener("disconnect", this.handleDisconnect);
675
+ navigator.hid.removeEventListener("connect", this.#handleConnect);
676
+ navigator.hid.removeEventListener("disconnect", this.#handleDisconnect);
412
677
  this.removeAllListeners();
413
678
  }
414
679
  /**
@@ -416,93 +681,35 @@ var WheelApi = class WheelApi extends EventEmitter {
416
681
  * @returns Effect settings object.
417
682
  */
418
683
  async readEffectSettings() {
419
- const r = new StructReader(await this.getFeatureReport(ReportType.EffectSettingsFeature));
420
- return {
421
- motionRange: r.u16(),
422
- staticDampeningStrength: r.u16(),
423
- softStopDampeningStrength: r.u16(),
424
- totalEffectStrength: r.u8(),
425
- integratedSpringStrength: r.u8(),
426
- softStopRange: r.u8(),
427
- softStopStrength: r.u8(),
428
- directXConstantDirection: r.i8(),
429
- directXSpringStrength: r.u8(),
430
- directXConstantStrength: r.u8(),
431
- directXPeriodicStrength: r.u8()
432
- };
684
+ return parseEffectSettings(await this.#getFeatureReport(34));
433
685
  }
434
686
  /**
435
687
  * Reads the current hardware settings from the device.
436
688
  * @returns Hardware settings object.
437
689
  */
438
690
  async readHardwareSettings() {
439
- const r = new StructReader(await this.getFeatureReport(ReportType.HardwareSettingsFeature));
440
- return {
441
- encoderCPR: r.u16(),
442
- integralGain: r.u16(),
443
- proportionalGain: r.u8(),
444
- forceEnabled: r.u8(),
445
- debugTorque: r.u8(),
446
- amplifierGain: r.u8(),
447
- calibrationMagnitude: r.u8(),
448
- calibrationSpeed: r.u8(),
449
- powerLimit: r.u8(),
450
- brakingLimit: r.u8(),
451
- positionSmoothing: r.u8(),
452
- speedBufferSize: r.u8(),
453
- encoderDirection: r.i8(),
454
- forceDirection: r.i8(),
455
- polePairs: r.u8()
456
- };
691
+ return parseHardwareSettings(await this.#getFeatureReport(33));
457
692
  }
458
693
  /**
459
694
  * Reads the current GPIO extension settings from the device.
460
695
  * @returns GPIO settings object.
461
696
  */
462
697
  async readGpioExtensionSettings() {
463
- const r = new StructReader(await this.getFeatureReport(ReportType.GpioSettingsFeature));
464
- return {
465
- extensionMode: r.u8(),
466
- pinMode: r.array(10, () => r.u8()),
467
- buttonMode: r.array(32, () => r.u8()),
468
- spiMode: r.u8(),
469
- spiLatchMode: r.u8(),
470
- spiLatchDelay: r.u8(),
471
- spiClkPulseLength: r.u8()
472
- };
698
+ return parseGpioSettings(await this.#getFeatureReport(161));
473
699
  }
474
700
  /**
475
701
  * Reads the current ADC extension settings from the device.
476
702
  * @returns ADC settings object.
477
703
  */
478
704
  async readAdcExtensionSettings() {
479
- const r = new StructReader(await this.getFeatureReport(ReportType.AdcSettingsFeature));
480
- return {
481
- rAxisMin: r.array(3, () => r.u16()),
482
- rAxisMax: r.array(3, () => r.u16()),
483
- rAxisSmoothing: r.array(3, () => r.u8()),
484
- rAxisToButtonLow: r.array(3, () => r.u8()),
485
- rAxisToButtonHigh: r.array(3, () => r.u8()),
486
- rAxisInvert: r.array(3, () => r.u8())
487
- };
705
+ return parseAdcSettings(await this.#getFeatureReport(162));
488
706
  }
489
707
  /**
490
708
  * Reads the firmware license information from the device.
491
709
  * @returns Firmware license object.
492
710
  */
493
711
  async readFirmwareLicense() {
494
- const r = new StructReader(await this.getFeatureReport(ReportType.FirmwareLicenseFeature));
495
- return {
496
- firmwareVersion: {
497
- releaseType: r.u8(),
498
- major: r.u8(),
499
- minor: r.u8(),
500
- patch: r.u8()
501
- },
502
- serialKey: r.array(3, () => r.u32()),
503
- deviceId: r.array(3, () => r.u32()),
504
- isRegistered: r.u8()
505
- };
712
+ return parseFirmwareLicense(await this.#getFeatureReport(37));
506
713
  }
507
714
  /**
508
715
  * Reads all settings from the device sequentially.
@@ -518,166 +725,185 @@ var WheelApi = class WheelApi extends EventEmitter {
518
725
  }
519
726
  /**
520
727
  * Writes a single setting value to the device.
728
+ *
729
+ * @remarks
730
+ * Values are rounded to the nearest integer and clamped to the range of the
731
+ * field's wire type.
732
+ *
733
+ * {@link SettingField.ForceEnabled}, {@link SettingField.AmplifierGain},
734
+ * {@link SettingField.PinMode} and {@link SettingField.ResetCenterOnZ0} only
735
+ * take effect, and read back with the new value, after
736
+ * {@link WheelApi.saveAndReboot}.
737
+ *
521
738
  * @param field - The setting field to write.
522
- * @param index - Sub-index for array-based settings.
739
+ * @param index - Index for array settings, such as the pin for
740
+ * {@link SettingField.PinMode}; `0` for other settings.
523
741
  * @param value - The value to write.
742
+ * @throws Error if the device is not connected.
743
+ * @throws RangeError if `field` is not a known setting, `index` is not an
744
+ * integer in `[0, 255]` or `value` is not a finite number.
524
745
  */
525
746
  async sendSetting(field, index, value) {
526
- if (!this.device?.opened) throw new Error("Device is not connected");
527
- const type = FIELD_TYPE_MAP[field];
528
- const buffer = new ArrayBuffer(REPORT_SIZE);
529
- const view = new DataView(buffer);
530
- view.setUint8(0, ReportData.DataSettingsFieldData);
531
- view.setUint8(1, field);
532
- view.setUint8(2, index);
533
- const VAL_OFFSET = 3;
534
- switch (type) {
535
- case FieldType.Int8:
536
- view.setInt8(VAL_OFFSET, clamp(value, -128, 127));
537
- break;
538
- case FieldType.Uint8:
539
- view.setUint8(VAL_OFFSET, clamp(value, 0, 255));
540
- break;
541
- case FieldType.Int16:
542
- view.setInt16(VAL_OFFSET, clamp(value, -32768, 32767), true);
543
- break;
544
- case FieldType.Uint16:
545
- view.setUint16(VAL_OFFSET, clamp(value, 0, 65535), true);
546
- break;
547
- }
548
- await this.device.sendReport(ReportType.GenericInputOutput, new Uint8Array(buffer));
549
- if (field === SettingField.MotionRange) this.cachedMotionRange = value;
747
+ const device = this.#requireDevice();
748
+ const { data, storedValue } = encodeSetting(field, index, value);
749
+ await this.#sendData(device, data);
750
+ if (field === 5) this.#cachedMotionRange = storedValue;
550
751
  }
551
752
  /**
552
753
  * Sends direct force feedback control to the device.
754
+ *
755
+ * @remarks
756
+ * Values are rounded to the nearest integer and clamped to their documented
757
+ * ranges.
758
+ *
759
+ * The device falls back to its default mode when direct control reports
760
+ * stop, so send them continuously while direct control is in use.
761
+ *
553
762
  * @param control - Force feedback control values.
763
+ * @throws Error if the device is not connected.
764
+ * @throws RangeError if any value is not a finite number.
554
765
  */
555
766
  async sendDirectControl(control) {
556
- if (!this.device?.opened) throw new Error("Device is not connected");
557
- const buffer = new ArrayBuffer(REPORT_SIZE);
558
- const view = new DataView(buffer);
559
- view.setUint8(0, ReportData.DataOverrideData);
560
- view.setInt16(1, clamp(control.springForce, -1e4, 1e4), true);
561
- view.setInt16(3, clamp(control.constantForce, -1e4, 1e4), true);
562
- view.setInt16(5, clamp(control.periodicForce, -1e4, 1e4), true);
563
- view.setUint8(7, clamp(control.forceDrop, 0, 100));
564
- await this.device.sendReport(ReportType.GenericInputOutput, new Uint8Array(buffer));
767
+ const device = this.#requireDevice();
768
+ await this.#sendData(device, encodeDirectControl(control));
565
769
  }
566
770
  /**
567
- * Sends the firmware activation license key to the device.
568
- * Expected format: "XXXXXXXX-XXXXXXXX-XXXXXXXX" (Hex strings)
569
- * @param license - The license key string.
570
- * @returns `true` if the format was valid and sent, `false` otherwise.
771
+ * Sends the firmware activation key to the device. Nothing is sent if the
772
+ * device already reports itself as registered.
773
+ *
774
+ * @remarks
775
+ * The device then saves its settings and reboots, so it disconnects.
776
+ *
777
+ * @param license - Three hexadecimal segments separated by `-`, for example
778
+ * `"0123ABCD-4567EF01-89ABCDEF"`.
779
+ * @throws Error if the device is not connected or the key is malformed.
571
780
  */
572
781
  async sendFirmwareActivation(license) {
573
- if (!this.device?.opened) throw new Error("Device is not connected");
574
- if (this._lastState?.isRegistered === 1) return true;
575
- const chunks = license.trim().split("-");
576
- if (chunks.length !== 3) throw new Error("Invalid license format: Incorrect number of segments.");
577
- const buffer = new ArrayBuffer(REPORT_SIZE);
578
- const view = new DataView(buffer);
579
- view.setUint8(0, ReportData.DataFirmwareActivationData);
580
- for (let i = 0; i < 3; i++) {
581
- const chunk = chunks[i];
582
- if (!/^[0-9A-Fa-f]{8}$/.test(chunk)) throw new Error(`Invalid license format: Segment ${i + 1} is not a valid 8-character hex string.`);
583
- const value = parseInt(chunk, 16);
584
- view.setUint32(1 + i * 4, value, true);
585
- }
586
- await this.device.sendReport(ReportType.GenericInputOutput, new Uint8Array(buffer));
587
- return true;
782
+ const device = this.#requireDevice();
783
+ const data = encodeFirmwareActivation(license);
784
+ if (this.#lastState?.isRegistered === 1) return;
785
+ await this.#sendData(device, data);
588
786
  }
589
787
  /**
590
- * Saves current settings to flash and reboots the controller.
788
+ * Saves the current settings to flash and reboots the controller. Settings
789
+ * that only apply on save take effect after the reboot.
591
790
  */
592
791
  async saveAndReboot() {
593
- await this.sendGenericCommand(ReportData.CommandSaveSettings);
792
+ await this.#sendGenericCommand(2);
594
793
  }
595
794
  /**
596
795
  * Reboots the controller without saving settings.
597
796
  */
598
797
  async rebootController() {
599
- await this.sendGenericCommand(ReportData.CommandReboot);
798
+ await this.#sendGenericCommand(1);
600
799
  }
601
800
  /**
602
801
  * Switches the device to DFU mode for firmware updates.
603
802
  */
604
803
  async switchToDfu() {
605
- await this.sendGenericCommand(ReportData.CommandDfuMode);
804
+ await this.#sendGenericCommand(3);
606
805
  }
607
806
  /**
608
807
  * Sets the current wheel position as center.
609
808
  */
610
809
  async resetWheelCenter() {
611
- await this.sendGenericCommand(ReportData.CommandResetCenter);
810
+ await this.#sendGenericCommand(4);
612
811
  }
613
- handleConnect = (event) => {
614
- if (this.device?.opened) return;
615
- if (isTargetDevice(event.device)) this.openDevice(event.device).catch((error) => {
812
+ #handleConnect = (event) => {
813
+ if (this.#device?.opened || this.#pendingConnections > 0) return;
814
+ if (isWheelDevice(event.device)) this.#openDevice(event.device).catch((error) => {
616
815
  this.emit("error", new Error("Failed to auto-connect to device", { cause: error }));
617
816
  });
618
817
  };
619
- handleDisconnect = (event) => {
620
- if (event.device === this.device) this.disconnect();
818
+ #handleDisconnect = (event) => {
819
+ this.#unplugged.add(event.device);
820
+ if (event.device === this.#device) this.disconnect();
621
821
  };
622
- handleInputReport = (event) => {
822
+ #handleInputReport = (event) => {
623
823
  try {
624
- if (event.reportId !== ReportType.GenericInputOutput) return;
625
- const r = new StructReader(event.data);
824
+ if (!isGenericReport(event.reportId)) return;
825
+ const raw = parseDeviceState(event.data);
626
826
  const newState = {
627
- firmwareVersion: {
628
- releaseType: r.u8(),
629
- major: r.u8(),
630
- minor: r.u8(),
631
- patch: r.u8()
632
- },
633
- isRegistered: r.u8(),
634
- position: r.i16(),
635
- torque: r.i16(),
636
- positionDegrees: null,
637
- torqueNormalized: 0
827
+ ...raw,
828
+ positionDegrees: this.#cachedMotionRange === null ? null : convertPositionToDegrees(raw.position, this.#cachedMotionRange),
829
+ torqueNormalized: normalizeTorque(raw.torque)
638
830
  };
639
- newState.positionDegrees = this.cachedMotionRange !== null ? convertPositionToDegrees(newState.position, this.cachedMotionRange) : null;
640
- newState.torqueNormalized = normalizeTorque(newState.torque);
641
- this._lastState = newState;
831
+ this.#lastState = newState;
642
832
  this.emit("stateReceived", newState);
643
833
  } catch (error) {
644
834
  this.emit("error", new Error("Failed to process input report", { cause: error }));
645
835
  }
646
836
  };
647
- async openDevice(device) {
837
+ /**
838
+ * Runs `task` after every connect and disconnect queued before it, so that
839
+ * overlapping calls (for example {@link WheelApi.tryAutoConnect} racing a
840
+ * `connect` event on page load) cannot interleave.
841
+ */
842
+ #enqueue(task) {
843
+ const run = this.#queue.then(task);
844
+ this.#queue = run.then(() => void 0, () => void 0);
845
+ return run;
846
+ }
847
+ #openDevice(device) {
848
+ this.#pendingConnections++;
849
+ return this.#enqueue(() => this.#openDeviceNow(device)).finally(() => {
850
+ this.#pendingConnections--;
851
+ });
852
+ }
853
+ async #openDeviceNow(device) {
854
+ if (this.#destroyed) throw new Error("WheelApi has been destroyed");
855
+ if (this.#device === device && device.opened) return;
856
+ await this.#disconnectNow();
857
+ this.#unplugged.delete(device);
858
+ const openedHere = !device.opened;
859
+ if (openedHere) try {
860
+ await device.open();
861
+ } catch (error) {
862
+ throw new Error("Failed to open device", { cause: error });
863
+ }
864
+ let motionRange = null;
648
865
  try {
649
- this.cachedMotionRange = null;
650
- this._lastState = null;
651
- this.device = device;
652
- if (!this.device.opened) await this.device.open();
653
- try {
654
- this.cachedMotionRange = (await this.readEffectSettings()).motionRange;
655
- } catch {
656
- this.cachedMotionRange = null;
657
- }
658
- this.device.addEventListener("inputreport", this.handleInputReport);
659
- this.emit("deviceConnected", this.device);
660
- return true;
661
- } catch {
662
- if (this.device?.opened) await this.device.close().catch(() => {});
663
- this.device = null;
664
- this.cachedMotionRange = null;
665
- return false;
866
+ motionRange = parseEffectSettings(await this.#readFeatureReport(device, 34)).motionRange;
867
+ } catch {}
868
+ if (this.#destroyed || this.#unplugged.has(device)) {
869
+ if (openedHere) await device.close().catch(() => void 0);
870
+ throw new Error(this.#destroyed ? "WheelApi has been destroyed" : "Device was disconnected while connecting");
666
871
  }
872
+ this.#device = device;
873
+ this.#lastState = null;
874
+ this.#cachedMotionRange = motionRange;
875
+ device.addEventListener("inputreport", this.#handleInputReport);
876
+ this.emit("deviceConnected", device);
877
+ }
878
+ async #disconnectNow() {
879
+ const device = this.#device;
880
+ if (!device) return;
881
+ this.#device = null;
882
+ this.#lastState = null;
883
+ this.#cachedMotionRange = null;
884
+ device.removeEventListener("inputreport", this.#handleInputReport);
885
+ try {
886
+ await device.close();
887
+ } catch {}
888
+ this.emit("deviceDisconnected", device);
667
889
  }
668
- async sendGenericCommand(reportData) {
669
- if (!this.device?.opened) throw new Error("Device is not connected");
670
- const data = new Uint8Array(REPORT_SIZE);
671
- data[0] = reportData;
672
- await this.device.sendReport(ReportType.GenericInputOutput, data);
890
+ /** Returns the open device, or throws if no device is connected. */
891
+ #requireDevice() {
892
+ if (!this.#device?.opened) throw new Error("Device is not connected");
893
+ return this.#device;
673
894
  }
674
- async getFeatureReport(reportId) {
675
- if (!this.device?.opened) throw new Error("Device is not connected");
676
- const view = await this.device.receiveFeatureReport(reportId);
677
- const offset = 1;
678
- return new DataView(view.buffer, view.byteOffset + offset, view.byteLength - offset);
895
+ async #sendGenericCommand(command) {
896
+ await this.#sendData(this.#requireDevice(), encodeCommand(command));
897
+ }
898
+ /** Sends a payload on the vendor interface's generic report. */
899
+ async #sendData(device, data) {
900
+ await device.sendReport(163, data);
901
+ }
902
+ #getFeatureReport(reportId) {
903
+ return this.#readFeatureReport(this.#requireDevice(), reportId);
904
+ }
905
+ async #readFeatureReport(device, reportId) {
906
+ return featureReportPayload(await device.receiveFeatureReport(reportId), reportId);
679
907
  }
680
908
  };
681
-
682
- //#endregion
683
- export { AmplifierGain, ButtonMode, ExtensionMode, FIELD_TYPE_MAP, FieldType, INTERFACE_0_USAGE, INTERFACE_0_USAGE_PAGE, PID, PinMode, RAW_POSITION_MAX, RAW_TORQUE_MAX, REPORT_SIZE, ReportData, ReportType, SettingField, SpiLatchMode, SpiMode, VID, WheelApi, convertPositionToDegrees, normalizeTorque };
909
+ export { AmplifierGain, ButtonMode, ExtensionMode, PID, PinMode, RAW_POSITION_MAX, RAW_TORQUE_MAX, SettingField, SpiLatchMode, SpiMode, VID, WheelApi, convertPositionToDegrees, normalizeTorque };