@v5x/serial 0.5.3 → 0.5.5

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 (54) hide show
  1. package/README.md +72 -6
  2. package/dist/Vex.d.ts +4 -4
  3. package/dist/VexCRC.d.ts +0 -1
  4. package/dist/VexConnection.d.ts +81 -23
  5. package/dist/VexDevice.d.ts +41 -155
  6. package/{dts/VexDevice.d.ts → dist/VexDeviceState.d.ts} +63 -55
  7. package/dist/VexError.d.ts +47 -0
  8. package/dist/VexFirmware.d.ts +45 -0
  9. package/dist/VexIniConfig.d.ts +1 -1
  10. package/dist/VexPacket.d.ts +3 -512
  11. package/dist/VexPacketBase.d.ts +21 -0
  12. package/dist/VexPacketEncoder.d.ts +55 -0
  13. package/{dts/VexPacket.d.ts → dist/VexPacketModels.d.ts} +3 -107
  14. package/dist/VexPacketView.d.ts +3 -3
  15. package/dist/VexTransfers.d.ts +20 -0
  16. package/dist/index.cjs +4541 -0
  17. package/dist/index.cjs.map +25 -0
  18. package/dist/index.d.ts +9 -9
  19. package/dist/index.js +4460 -0
  20. package/dist/index.js.map +25 -0
  21. package/package.json +40 -72
  22. package/dist/v5-serial-protocol.cjs.js +0 -4516
  23. package/dist/v5-serial-protocol.cjs.js.map +0 -1
  24. package/dist/v5-serial-protocol.es.js +0 -4401
  25. package/dist/v5-serial-protocol.es.js.map +0 -1
  26. package/dts/Vex.d.ts +0 -235
  27. package/dts/Vex.js +0 -189
  28. package/dts/Vex.js.map +0 -1
  29. package/dts/VexCRC.d.ts +0 -19
  30. package/dts/VexCRC.js +0 -89
  31. package/dts/VexCRC.js.map +0 -1
  32. package/dts/VexConnection.d.ts +0 -45
  33. package/dts/VexConnection.js +0 -500
  34. package/dts/VexConnection.js.map +0 -1
  35. package/dts/VexDevice.js +0 -944
  36. package/dts/VexDevice.js.map +0 -1
  37. package/dts/VexEvent.d.ts +0 -16
  38. package/dts/VexEvent.js +0 -47
  39. package/dts/VexEvent.js.map +0 -1
  40. package/dts/VexFirmwareVersion.d.ts +0 -55
  41. package/dts/VexFirmwareVersion.js +0 -104
  42. package/dts/VexFirmwareVersion.js.map +0 -1
  43. package/dts/VexIniConfig.d.ts +0 -27
  44. package/dts/VexIniConfig.js +0 -122
  45. package/dts/VexIniConfig.js.map +0 -1
  46. package/dts/VexPacket.js +0 -1036
  47. package/dts/VexPacket.js.map +0 -1
  48. package/dts/VexPacketView.d.ts +0 -18
  49. package/dts/VexPacketView.js +0 -84
  50. package/dts/VexPacketView.js.map +0 -1
  51. package/dts/index.d.ts +0 -9
  52. package/dts/index.js +0 -10
  53. package/dts/index.js.map +0 -1
  54. package/index.d.ts +0 -1098
@@ -1,4401 +0,0 @@
1
- /**
2
- * V5 Serial Protocol v0.5.2
3
- * Copyright 2022-2026 jerrylum <me@jerryio.com>
4
- */
5
-
6
- var AllPackets = /*#__PURE__*/Object.freeze({
7
- __proto__: null,
8
- get PacketEncoder () { return PacketEncoder; },
9
- get Packet () { return Packet; },
10
- get DeviceBoundPacket () { return DeviceBoundPacket; },
11
- get Query1H2DPacket () { return Query1H2DPacket; },
12
- get SystemVersionH2DPacket () { return SystemVersionH2DPacket; },
13
- get UpdateMatchModeH2DPacket () { return UpdateMatchModeH2DPacket; },
14
- get GetMatchStatusH2DPacket () { return GetMatchStatusH2DPacket; },
15
- get GetRadioModeH2DPacket () { return GetRadioModeH2DPacket; },
16
- get FileControlH2DPacket () { return FileControlH2DPacket; },
17
- get InitFileTransferH2DPacket () { return InitFileTransferH2DPacket; },
18
- get ExitFileTransferH2DPacket () { return ExitFileTransferH2DPacket; },
19
- get WriteFileH2DPacket () { return WriteFileH2DPacket; },
20
- get ReadFileH2DPacket () { return ReadFileH2DPacket; },
21
- get LinkFileH2DPacket () { return LinkFileH2DPacket; },
22
- get GetDirectoryFileCountH2DPacket () { return GetDirectoryFileCountH2DPacket; },
23
- get GetDirectoryEntryH2DPacket () { return GetDirectoryEntryH2DPacket; },
24
- get LoadFileActionH2DPacket () { return LoadFileActionH2DPacket; },
25
- get GetFileMetadataH2DPacket () { return GetFileMetadataH2DPacket; },
26
- get SetFileMetadataH2DPacket () { return SetFileMetadataH2DPacket; },
27
- get EraseFileH2DPacket () { return EraseFileH2DPacket; },
28
- get GetProgramSlotInfoH2DPacket () { return GetProgramSlotInfoH2DPacket; },
29
- get FileClearUpH2DPacket () { return FileClearUpH2DPacket; },
30
- get FileFormatH2DPacket () { return FileFormatH2DPacket; },
31
- get GetSystemFlagsH2DPacket () { return GetSystemFlagsH2DPacket; },
32
- get GetDeviceStatusH2DPacket () { return GetDeviceStatusH2DPacket; },
33
- get GetSystemStatusH2DPacket () { return GetSystemStatusH2DPacket; },
34
- get GetFdtStatusH2DPacket () { return GetFdtStatusH2DPacket; },
35
- get GetLogCountH2DPacket () { return GetLogCountH2DPacket; },
36
- get ReadLogPageH2DPacket () { return ReadLogPageH2DPacket; },
37
- get GetRadioStatusH2DPacket () { return GetRadioStatusH2DPacket; },
38
- get GetUserDataH2DPacket () { return GetUserDataH2DPacket; },
39
- get ScreenCaptureH2DPacket () { return ScreenCaptureH2DPacket; },
40
- get SendDashTouchH2DPacket () { return SendDashTouchH2DPacket; },
41
- get SelectDashH2DPacket () { return SelectDashH2DPacket; },
42
- get EnableDashH2DPacket () { return EnableDashH2DPacket; },
43
- get DisableDashH2DPacket () { return DisableDashH2DPacket; },
44
- get ReadKeyValueH2DPacket () { return ReadKeyValueH2DPacket; },
45
- get WriteKeyValueH2DPacket () { return WriteKeyValueH2DPacket; },
46
- get GetSlot1to4InfoH2DPacket () { return GetSlot1to4InfoH2DPacket; },
47
- get GetSlot5to8InfoH2DPacket () { return GetSlot5to8InfoH2DPacket; },
48
- get FactoryStatusH2DPacket () { return FactoryStatusH2DPacket; },
49
- get FactoryEnableH2DPacket () { return FactoryEnableH2DPacket; },
50
- get HostBoundPacket () { return HostBoundPacket; },
51
- get Query1ReplyD2HPacket () { return Query1ReplyD2HPacket; },
52
- get SystemVersionReplyD2HPacket () { return SystemVersionReplyD2HPacket; },
53
- get MatchModeReplyD2HPacket () { return MatchModeReplyD2HPacket; },
54
- get MatchStatusReplyD2HPacket () { return MatchStatusReplyD2HPacket; },
55
- get FileControlReplyD2HPacket () { return FileControlReplyD2HPacket; },
56
- get InitFileTransferReplyD2HPacket () { return InitFileTransferReplyD2HPacket; },
57
- get ExitFileTransferReplyD2HPacket () { return ExitFileTransferReplyD2HPacket; },
58
- get WriteFileReplyD2HPacket () { return WriteFileReplyD2HPacket; },
59
- get ReadFileReplyD2HPacket () { return ReadFileReplyD2HPacket; },
60
- get LinkFileReplyD2HPacket () { return LinkFileReplyD2HPacket; },
61
- get GetDirectoryFileCountReplyD2HPacket () { return GetDirectoryFileCountReplyD2HPacket; },
62
- get GetDirectoryEntryReplyD2HPacket () { return GetDirectoryEntryReplyD2HPacket; },
63
- get LoadFileActionReplyD2HPacket () { return LoadFileActionReplyD2HPacket; },
64
- get GetFileMetadataReplyD2HPacket () { return GetFileMetadataReplyD2HPacket; },
65
- get SetFileMetadataReplyD2HPacket () { return SetFileMetadataReplyD2HPacket; },
66
- get EraseFileReplyD2HPacket () { return EraseFileReplyD2HPacket; },
67
- get GetProgramSlotInfoReplyD2HPacket () { return GetProgramSlotInfoReplyD2HPacket; },
68
- get FileClearUpReplyD2HPacket () { return FileClearUpReplyD2HPacket; },
69
- get FileFormatReplyD2HPacket () { return FileFormatReplyD2HPacket; },
70
- get GetSystemFlagsReplyD2HPacket () { return GetSystemFlagsReplyD2HPacket; },
71
- get GetDeviceStatusReplyD2HPacket () { return GetDeviceStatusReplyD2HPacket; },
72
- get GetSystemStatusReplyD2HPacket () { return GetSystemStatusReplyD2HPacket; },
73
- get GetFdtStatusReplyD2HPacket () { return GetFdtStatusReplyD2HPacket; },
74
- get GetLogCountReplyD2HPacket () { return GetLogCountReplyD2HPacket; },
75
- get ReadLogPageReplyD2HPacket () { return ReadLogPageReplyD2HPacket; },
76
- get GetRadioStatusReplyD2HPacket () { return GetRadioStatusReplyD2HPacket; },
77
- get GetUserDataReplyD2HPacket () { return GetUserDataReplyD2HPacket; },
78
- get ScreenCaptureReplyD2HPacket () { return ScreenCaptureReplyD2HPacket; },
79
- get SendDashTouchReplyD2HPacket () { return SendDashTouchReplyD2HPacket; },
80
- get SelectDashReplyD2HPacket () { return SelectDashReplyD2HPacket; },
81
- get EnableDashReplyD2HPacket () { return EnableDashReplyD2HPacket; },
82
- get DisableDashReplyD2HPacket () { return DisableDashReplyD2HPacket; },
83
- get ReadKeyValueReplyD2HPacket () { return ReadKeyValueReplyD2HPacket; },
84
- get WriteKeyValueReplyD2HPacket () { return WriteKeyValueReplyD2HPacket; },
85
- get GetSlot1to4InfoReplyD2HPacket () { return GetSlot1to4InfoReplyD2HPacket; },
86
- get GetSlot5to8InfoReplyD2HPacket () { return GetSlot5to8InfoReplyD2HPacket; },
87
- get FactoryStatusReplyD2HPacket () { return FactoryStatusReplyD2HPacket; },
88
- get FactoryEnableReplyD2HPacket () { return FactoryEnableReplyD2HPacket; }
89
- });
90
-
91
- const USER_PROG_CHUNK_SIZE = 4096; // chunk size
92
- const USER_FLASH_START = 0x03000000; // start address of memory
93
- const USER_FLASH_SYS_CODE_START = 0x03400000; // start address of system code
94
- const USER_FLASH_USR_CODE_START = 0x03800000; // start address of user code
95
- const USER_FLASH_END = 0x08000000; // end address of memory
96
- const USER_FLASH_MAX_FILE_SIZE = 0x200000; // maximum file size for qspi
97
- const USER_FLASH_START_B = 0x10200000; // special app flash start
98
- const USER_FLASH_END_B = 0x10400000; // special app flash end
99
- const USER_FLASH_START_C = 0x30200000; // special app flash start
100
- const USER_FLASH_END_C = 0x31000000; // special app flash end
101
- var FileVendor;
102
- (function (FileVendor) {
103
- // a.k.a vid
104
- FileVendor[FileVendor["USER"] = 1] = "USER";
105
- FileVendor[FileVendor["SYS"] = 15] = "SYS";
106
- FileVendor[FileVendor["DEV1"] = 16] = "DEV1";
107
- FileVendor[FileVendor["DEV2"] = 24] = "DEV2";
108
- FileVendor[FileVendor["DEV3"] = 32] = "DEV3";
109
- FileVendor[FileVendor["DEV4"] = 40] = "DEV4";
110
- FileVendor[FileVendor["DEV5"] = 48] = "DEV5";
111
- FileVendor[FileVendor["DEV6"] = 56] = "DEV6";
112
- FileVendor[FileVendor["VEXVM"] = 64] = "VEXVM";
113
- FileVendor[FileVendor["VEX"] = 240] = "VEX";
114
- FileVendor[FileVendor["UNDEFINED"] = 241] = "UNDEFINED";
115
- })(FileVendor || (FileVendor = {}));
116
- var FileDownloadTarget;
117
- (function (FileDownloadTarget) {
118
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_DDR"] = 0] = "FILE_TARGET_DDR";
119
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_QSPI"] = 1] = "FILE_TARGET_QSPI";
120
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_CBUF"] = 2] = "FILE_TARGET_CBUF";
121
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_VBUF"] = 3] = "FILE_TARGET_VBUF";
122
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_DDRC"] = 4] = "FILE_TARGET_DDRC";
123
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_DDRE"] = 5] = "FILE_TARGET_DDRE";
124
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_FLASH"] = 6] = "FILE_TARGET_FLASH";
125
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_RADIO"] = 7] = "FILE_TARGET_RADIO";
126
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_A1"] = 13] = "FILE_TARGET_A1";
127
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_B1"] = 14] = "FILE_TARGET_B1";
128
- FileDownloadTarget[FileDownloadTarget["FILE_TARGET_B2"] = 15] = "FILE_TARGET_B2";
129
- })(FileDownloadTarget || (FileDownloadTarget = {}));
130
- var FileInitAction;
131
- (function (FileInitAction) {
132
- FileInitAction[FileInitAction["WRITE"] = 1] = "WRITE";
133
- FileInitAction[FileInitAction["READ"] = 2] = "READ";
134
- })(FileInitAction || (FileInitAction = {}));
135
- var FileInitOption;
136
- (function (FileInitOption) {
137
- FileInitOption[FileInitOption["NONE"] = 0] = "NONE";
138
- FileInitOption[FileInitOption["OVERWRITE"] = 1] = "OVERWRITE";
139
- })(FileInitOption || (FileInitOption = {}));
140
- var FileLoadAction;
141
- (function (FileLoadAction) {
142
- FileLoadAction[FileLoadAction["RUN"] = 0] = "RUN";
143
- FileLoadAction[FileLoadAction["STOP"] = 128] = "STOP";
144
- })(FileLoadAction || (FileLoadAction = {}));
145
- var FileExitAction;
146
- (function (FileExitAction) {
147
- FileExitAction[FileExitAction["EXIT_NONE"] = 0] = "EXIT_NONE";
148
- FileExitAction[FileExitAction["EXIT_RUN"] = 1] = "EXIT_RUN";
149
- FileExitAction[FileExitAction["EXIT_HALT"] = 3] = "EXIT_HALT";
150
- })(FileExitAction || (FileExitAction = {}));
151
- var RadioChannelType;
152
- (function (RadioChannelType) {
153
- RadioChannelType[RadioChannelType["PIT"] = 0] = "PIT";
154
- RadioChannelType[RadioChannelType["DOWNLOAD"] = 1] = "DOWNLOAD";
155
- })(RadioChannelType || (RadioChannelType = {}));
156
- var AckType;
157
- (function (AckType) {
158
- AckType[AckType["CDC2_ACK"] = 118] = "CDC2_ACK";
159
- AckType[AckType["CDC2_NACK"] = 255] = "CDC2_NACK";
160
- AckType[AckType["CDC2_NACK_PACKET_CRC"] = 206] = "CDC2_NACK_PACKET_CRC";
161
- AckType[AckType["CDC2_NACK_CMD_LENGTH"] = 208] = "CDC2_NACK_CMD_LENGTH";
162
- AckType[AckType["CDC2_NACK_SIZE"] = 209] = "CDC2_NACK_SIZE";
163
- AckType[AckType["CDC2_NACK_CRC"] = 210] = "CDC2_NACK_CRC";
164
- AckType[AckType["CDC2_NACK_FILE"] = 211] = "CDC2_NACK_FILE";
165
- AckType[AckType["CDC2_NACK_INIT"] = 212] = "CDC2_NACK_INIT";
166
- AckType[AckType["CDC2_NACK_FUNC"] = 213] = "CDC2_NACK_FUNC";
167
- AckType[AckType["CDC2_NACK_ALIGN"] = 214] = "CDC2_NACK_ALIGN";
168
- AckType[AckType["CDC2_NACK_ADDR"] = 215] = "CDC2_NACK_ADDR";
169
- AckType[AckType["CDC2_NACK_INCOMPLETE"] = 216] = "CDC2_NACK_INCOMPLETE";
170
- AckType[AckType["CDC2_NACK_DIR_INDEX"] = 217] = "CDC2_NACK_DIR_INDEX";
171
- AckType[AckType["CDC2_NACK_MAX_USER_FILES"] = 218] = "CDC2_NACK_MAX_USER_FILES";
172
- AckType[AckType["CDC2_NACK_FILE_EXISTS"] = 219] = "CDC2_NACK_FILE_EXISTS";
173
- AckType[AckType["CDC2_NACK_FILE_SYS_FULL"] = 220] = "CDC2_NACK_FILE_SYS_FULL";
174
- AckType[AckType["TIMEOUT"] = 256] = "TIMEOUT";
175
- AckType[AckType["WRITE_ERROR"] = 257] = "WRITE_ERROR";
176
- })(AckType || (AckType = {}));
177
- var SmartDeviceType;
178
- (function (SmartDeviceType) {
179
- SmartDeviceType[SmartDeviceType["EMPTY"] = 0] = "EMPTY";
180
- SmartDeviceType[SmartDeviceType["V5_POWER"] = 1] = "V5_POWER";
181
- SmartDeviceType[SmartDeviceType["MOTOR"] = 2] = "MOTOR";
182
- SmartDeviceType[SmartDeviceType["LED"] = 3] = "LED";
183
- SmartDeviceType[SmartDeviceType["ABS_ENCODER_SENSOR"] = 4] = "ABS_ENCODER_SENSOR";
184
- SmartDeviceType[SmartDeviceType["CR_MOTOR"] = 5] = "CR_MOTOR";
185
- SmartDeviceType[SmartDeviceType["IMU_SENSOR"] = 6] = "IMU_SENSOR";
186
- SmartDeviceType[SmartDeviceType["DISTANCE_SENSOR"] = 7] = "DISTANCE_SENSOR";
187
- SmartDeviceType[SmartDeviceType["RADIO_SENSOR"] = 8] = "RADIO_SENSOR";
188
- SmartDeviceType[SmartDeviceType["CONTROLLER"] = 9] = "CONTROLLER";
189
- SmartDeviceType[SmartDeviceType["BRAIN"] = 10] = "BRAIN";
190
- SmartDeviceType[SmartDeviceType["VISION_SENSOR"] = 11] = "VISION_SENSOR";
191
- SmartDeviceType[SmartDeviceType["ADI"] = 12] = "ADI";
192
- SmartDeviceType[SmartDeviceType["PARTNER_CONTROLLER"] = 13] = "PARTNER_CONTROLLER";
193
- SmartDeviceType[SmartDeviceType["BATTERY"] = 14] = "BATTERY";
194
- SmartDeviceType[SmartDeviceType["SOL"] = 15] = "SOL";
195
- SmartDeviceType[SmartDeviceType["OPTICAL_SENSOR"] = 16] = "OPTICAL_SENSOR";
196
- SmartDeviceType[SmartDeviceType["MAGNET"] = 17] = "MAGNET";
197
- SmartDeviceType[SmartDeviceType["GPS_SENSOR"] = 20] = "GPS_SENSOR";
198
- SmartDeviceType[SmartDeviceType["UNDEFINED_SENSOR"] = 255] = "UNDEFINED_SENSOR";
199
- })(SmartDeviceType || (SmartDeviceType = {}));
200
- var SerialDeviceType;
201
- (function (SerialDeviceType) {
202
- SerialDeviceType[SerialDeviceType["V5_BRAIN"] = 1281] = "V5_BRAIN";
203
- SerialDeviceType[SerialDeviceType["V5_BRAIN_DFU"] = 1282] = "V5_BRAIN_DFU";
204
- SerialDeviceType[SerialDeviceType["V5_CONTROLLER"] = 1283] = "V5_CONTROLLER";
205
- SerialDeviceType[SerialDeviceType["XILINX"] = 256] = "XILINX";
206
- SerialDeviceType[SerialDeviceType["IQ_BRAIN"] = 2] = "IQ_BRAIN";
207
- SerialDeviceType[SerialDeviceType["IQ_BRAIN2"] = 3] = "IQ_BRAIN2";
208
- SerialDeviceType[SerialDeviceType["IQ_BRAIN_DFU"] = 255] = "IQ_BRAIN_DFU";
209
- SerialDeviceType[SerialDeviceType["IQ2_BRAIN"] = 512] = "IQ2_BRAIN";
210
- SerialDeviceType[SerialDeviceType["IQ2_BRAIN_DFU"] = 527] = "IQ2_BRAIN_DFU";
211
- SerialDeviceType[SerialDeviceType["IQ2_CONTROLLER"] = 528] = "IQ2_CONTROLLER";
212
- SerialDeviceType[SerialDeviceType["IQ2_CONTROLLER_DFU"] = 543] = "IQ2_CONTROLLER_DFU";
213
- SerialDeviceType[SerialDeviceType["EXP_BRAIN"] = 1536] = "EXP_BRAIN";
214
- SerialDeviceType[SerialDeviceType["EXP_BRAIN_DFU"] = 1551] = "EXP_BRAIN_DFU";
215
- SerialDeviceType[SerialDeviceType["EXP_CONTROLLER"] = 1552] = "EXP_CONTROLLER";
216
- SerialDeviceType[SerialDeviceType["EXP_CONTROLLER_DFU"] = 1567] = "EXP_CONTROLLER_DFU";
217
- SerialDeviceType[SerialDeviceType["PIXY"] = 61440] = "PIXY";
218
- SerialDeviceType[SerialDeviceType["PIXY_DFU"] = 12] = "PIXY_DFU";
219
- SerialDeviceType[SerialDeviceType["VEXCAM"] = 1287] = "VEXCAM";
220
- SerialDeviceType[SerialDeviceType["VEXCAM_DFU"] = 1288] = "VEXCAM_DFU";
221
- SerialDeviceType[SerialDeviceType["SENSOR_TEST"] = 1535] = "SENSOR_TEST";
222
- SerialDeviceType[SerialDeviceType["CORTEX_PROGCBL"] = 10] = "CORTEX_PROGCBL";
223
- SerialDeviceType[SerialDeviceType["CORTEX_BRAIN"] = 11] = "CORTEX_BRAIN";
224
- // Jerry says this was copied from the official source code ¯\_(ツ)_/¯
225
- // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values
226
- SerialDeviceType[SerialDeviceType["CORTEX_JOYSTK"] = 12] = "CORTEX_JOYSTK";
227
- SerialDeviceType[SerialDeviceType["VEXNET_KEY_20"] = 7] = "VEXNET_KEY_20";
228
- SerialDeviceType[SerialDeviceType["VEXNET_KEY_10"] = 9587] = "VEXNET_KEY_10";
229
- SerialDeviceType[SerialDeviceType["PROLIFIC"] = 8963] = "PROLIFIC";
230
- })(SerialDeviceType || (SerialDeviceType = {}));
231
- /**
232
- * found from {@link https://gist.github.com/meisZWFLZ/9ebdd694060137b44959ff7ac80ff4e8 gist}
233
- * @see {@link https://drive.google.com/drive/folders/11pSNKakbXp7hOYBQ3HNwprFaLalnXOgR screen images}
234
- */
235
- var SelectDashScreen;
236
- (function (SelectDashScreen) {
237
- SelectDashScreen[SelectDashScreen["HOME"] = 0] = "HOME";
238
- SelectDashScreen[SelectDashScreen["BATTERY"] = 1] = "BATTERY";
239
- SelectDashScreen[SelectDashScreen["LED"] = 3] = "LED";
240
- SelectDashScreen[SelectDashScreen["MATCH_CONFIG"] = 4] = "MATCH_CONFIG";
241
- SelectDashScreen[SelectDashScreen["MATCH_CONFIG_MORE"] = 5] = "MATCH_CONFIG_MORE";
242
- SelectDashScreen[SelectDashScreen["WIRING"] = 6] = "WIRING";
243
- SelectDashScreen[SelectDashScreen["RADIO"] = 8] = "RADIO";
244
- SelectDashScreen[SelectDashScreen["BRAIN"] = 10] = "BRAIN";
245
- SelectDashScreen[SelectDashScreen["RUN_PROGRAM"] = 13] = "RUN_PROGRAM";
246
- SelectDashScreen[SelectDashScreen["DRIVE_PROGRAM_CONTROL_LEFT_MAPPING"] = 14] = "DRIVE_PROGRAM_CONTROL_LEFT_MAPPING";
247
- SelectDashScreen[SelectDashScreen["DRIVE_PROGRAM_MENU"] = 15] = "DRIVE_PROGRAM_MENU";
248
- SelectDashScreen[SelectDashScreen["DEVICES"] = 16] = "DEVICES";
249
- SelectDashScreen[SelectDashScreen["USER_PROGRAM_FOLDER"] = 17] = "USER_PROGRAM_FOLDER";
250
- SelectDashScreen[SelectDashScreen["VEX_PROGRAM_FOLDER"] = 18] = "VEX_PROGRAM_FOLDER";
251
- SelectDashScreen[SelectDashScreen["SETTINGS"] = 19] = "SETTINGS";
252
- /** theres some scary looking stuff in here */
253
- SelectDashScreen[SelectDashScreen["SCARY_CONFIGURATION"] = 20] = "SCARY_CONFIGURATION";
254
- SelectDashScreen[SelectDashScreen["LANGUAGE"] = 21] = "LANGUAGE";
255
- SelectDashScreen[SelectDashScreen["DRIVE_MOTOR_CONFIG"] = 22] = "DRIVE_MOTOR_CONFIG";
256
- SelectDashScreen[SelectDashScreen["PROGRAM_MENU"] = 24] = "PROGRAM_MENU";
257
- SelectDashScreen[SelectDashScreen["SHUTDOWN"] = 25] = "SHUTDOWN";
258
- SelectDashScreen[SelectDashScreen["CONTROLLER_2_MAPPING"] = 26] = "CONTROLLER_2_MAPPING";
259
- /** theres some even more scary looking stuff in here */
260
- SelectDashScreen[SelectDashScreen["SCARY_CONFIGURATION_MORE"] = 27] = "SCARY_CONFIGURATION_MORE";
261
- /** maybe this is scarier.. */
262
- SelectDashScreen[SelectDashScreen["CONFIRM_XX"] = 28] = "CONFIRM_XX";
263
- SelectDashScreen[SelectDashScreen["CONTROLLER_1_MAPPING"] = 29] = "CONTROLLER_1_MAPPING";
264
- SelectDashScreen[SelectDashScreen["DRIVE_PROGRAM_CONTROL_DUAL_MAPPING"] = 30] = "DRIVE_PROGRAM_CONTROL_DUAL_MAPPING";
265
- SelectDashScreen[SelectDashScreen["DRIVE_PROGRAM_CONTROL_SPLIT_MAPPING"] = 31] = "DRIVE_PROGRAM_CONTROL_SPLIT_MAPPING";
266
- SelectDashScreen[SelectDashScreen["DRIVE_PROGRAM_CONTROL_RIGHT_MAPPING"] = 32] = "DRIVE_PROGRAM_CONTROL_RIGHT_MAPPING";
267
- /** thats such a bad name */
268
- SelectDashScreen[SelectDashScreen["MATCH_2_4_PLAYERS"] = 33] = "MATCH_2_4_PLAYERS";
269
- SelectDashScreen[SelectDashScreen["EVENT_LOG"] = 34] = "EVENT_LOG";
270
- SelectDashScreen[SelectDashScreen["USER_PROGRAM_WIRING"] = 40] = "USER_PROGRAM_WIRING";
271
- SelectDashScreen[SelectDashScreen["CLAWBOT_PROGRAM_MENU"] = 41] = "CLAWBOT_PROGRAM_MENU";
272
- /** aka regulatory */
273
- SelectDashScreen[SelectDashScreen["ABOUT"] = 42] = "ABOUT";
274
- SelectDashScreen[SelectDashScreen["LANGUAGE_MORE"] = 43] = "LANGUAGE_MORE";
275
- SelectDashScreen[SelectDashScreen["OBJECT_COLOR"] = 45] = "OBJECT_COLOR";
276
- SelectDashScreen[SelectDashScreen["SIGNATURE_ID"] = 46] = "SIGNATURE_ID";
277
- SelectDashScreen[SelectDashScreen["LOG_DATA"] = 47] = "LOG_DATA";
278
- })(SelectDashScreen || (SelectDashScreen = {}));
279
-
280
- /******************************************************************************
281
- Copyright (c) Microsoft Corporation.
282
-
283
- Permission to use, copy, modify, and/or distribute this software for any
284
- purpose with or without fee is hereby granted.
285
-
286
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
287
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
288
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
289
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
290
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
291
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
292
- PERFORMANCE OF THIS SOFTWARE.
293
- ***************************************************************************** */
294
-
295
- function __awaiter(thisArg, _arguments, P, generator) {
296
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
297
- return new (P || (P = Promise))(function (resolve, reject) {
298
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
299
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
300
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
301
- step((generator = generator.apply(thisArg, _arguments || [])).next());
302
- });
303
- }
304
-
305
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
306
- var e = new Error(message);
307
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
308
- };
309
-
310
- class VexEventEmitter {
311
- constructor() {
312
- this.handlerMap = new Map();
313
- }
314
- on(eventName, listener) {
315
- let listeners = this.handlerMap.get(eventName);
316
- listeners !== null && listeners !== void 0 ? listeners : (listeners = []);
317
- listeners.push(listener);
318
- this.handlerMap.set(eventName, listeners);
319
- }
320
- remove(eventName, listener) {
321
- let listeners = this.handlerMap.get(eventName);
322
- listeners !== null && listeners !== void 0 ? listeners : (listeners = []);
323
- const index = listeners.indexOf(listener);
324
- if (index > -1) {
325
- listeners.splice(index, 1);
326
- }
327
- this.handlerMap.set(eventName, listeners);
328
- }
329
- emit(eventName, data) {
330
- var _a;
331
- ((_a = this.handlerMap.get(eventName)) !== null && _a !== void 0 ? _a : []).forEach((callback) => {
332
- callback(data);
333
- });
334
- }
335
- clearListeners() {
336
- this.handlerMap.clear();
337
- }
338
- }
339
- class VexEventTarget {
340
- constructor() {
341
- this.emitter = new VexEventEmitter();
342
- }
343
- emit(eventName, data) {
344
- this.emitter.emit(String(eventName), data);
345
- }
346
- on(eventName, listener) {
347
- this.emitter.on(String(eventName), listener);
348
- }
349
- remove(eventName, listener) {
350
- this.emitter.remove(String(eventName), listener);
351
- }
352
- clearListeners() {
353
- this.emitter.clearListeners();
354
- }
355
- }
356
-
357
- /**
358
- * This is a class to make it easier to handle passing the VEXos version
359
- * information around in the application. This provides ways to get any
360
- * form of the string representation and quickly compare versions.
361
- */
362
- class VexFirmwareVersion {
363
- constructor(major, minor, build, beta) {
364
- this.major = major;
365
- this.minor = minor;
366
- this.build = build;
367
- this.beta = beta;
368
- }
369
- /**
370
- * Take a a string of MAJOR.MINOR.BUILD.bBETA and converts it to a
371
- * VexFirmwareVersion instance
372
- * @param version the string to process
373
- * @returns a VexFirmwareVersion representing the provided string
374
- */
375
- static fromString(version) {
376
- const parts = version
377
- .toLowerCase()
378
- .replace(/b/g, "")
379
- .split(".")
380
- .map((x) => parseInt(x, 10));
381
- while (parts.length < 4) {
382
- parts.push(0);
383
- }
384
- return new VexFirmwareVersion(parts[0], parts[1], parts[2], parts[3]);
385
- }
386
- /**
387
- * Take a a Uint8Array and converts it to a VexFirmwareVersion instance
388
- * @param data the array to process
389
- * @param offset the offset to start at
390
- * @returns a VexFirmwareVersion representing the provided string
391
- */
392
- static fromUint8Array(data, offset = 0, reverse = false) {
393
- return new VexFirmwareVersion(data[offset + (reverse ? 3 : 0)], data[offset + (reverse ? 2 : 1)], data[offset + (reverse ? 1 : 2)], data[offset + (reverse ? 0 : 3)]);
394
- }
395
- static allZero() {
396
- return new VexFirmwareVersion(0, 0, 0, 0);
397
- }
398
- /**
399
- * Take a a string of MAJOR_MINOR_BUILD_BETA and converts it to a
400
- * VexFirmwareVersion instance
401
- * @param version the string to process
402
- * @returns a VexFirmwareVersion representing the provided string
403
- */
404
- static fromCatalogString(version) {
405
- return VexFirmwareVersion.fromString(version.replace(/_/g, "."));
406
- }
407
- isBeta() {
408
- return this.beta !== 0;
409
- }
410
- /**
411
- * returns version as Uint Array
412
- */
413
- toUint8Array(reverse = false) {
414
- const data = new Uint8Array(4);
415
- data[reverse ? 3 : 0] = this.major;
416
- data[reverse ? 2 : 1] = this.minor;
417
- data[reverse ? 1 : 2] = this.build;
418
- data[reverse ? 0 : 3] = this.beta;
419
- return data;
420
- }
421
- /**
422
- * returns version as major.minor.build
423
- */
424
- toUserString() {
425
- return `${this.major}.${this.minor}.${this.build}`;
426
- }
427
- /**
428
- * returns version as ${major}.${minor}.{build}.b${beta}
429
- */
430
- toInternalString() {
431
- return `${this.toUserString()}.b${this.beta}`;
432
- }
433
- /**
434
- * compares this version to the provided version.
435
- * * if this < b: negative
436
- * * if this = b: 0
437
- * * if this > b: positive
438
- * @param that the version to compare again
439
- */
440
- compare(that) {
441
- const majorComp = this.major - that.major;
442
- const minorComp = this.minor - that.minor;
443
- const buildComp = this.build - that.build;
444
- const betaComp = this.beta - that.beta;
445
- if (majorComp !== 0) {
446
- return majorComp;
447
- }
448
- else if (minorComp !== 0) {
449
- return minorComp;
450
- }
451
- else if (buildComp !== 0) {
452
- return buildComp;
453
- }
454
- else if (betaComp !== 0) {
455
- return betaComp;
456
- }
457
- return 0;
458
- }
459
- }
460
-
461
- class PacketView extends DataView {
462
- constructor(buffer, offset = 0, length = buffer.byteLength - offset) {
463
- super(buffer, offset, length);
464
- this.position = 0;
465
- this.littleEndianDefault = true;
466
- }
467
- static fromPacket(packet) {
468
- const view = new PacketView(packet.data.buffer, packet.data.byteOffset);
469
- view.position = packet.ackIndex + 1;
470
- return view;
471
- }
472
- nextInt8() {
473
- const result = this.getInt8(this.position);
474
- this.position += 1;
475
- return result;
476
- }
477
- nextUint8() {
478
- const result = this.getUint8(this.position);
479
- this.position += 1;
480
- return result;
481
- }
482
- nextInt16(littleEndian = this.littleEndianDefault) {
483
- const result = this.getInt16(this.position, littleEndian);
484
- this.position += 2;
485
- return result;
486
- }
487
- nextUint16(littleEndian = this.littleEndianDefault) {
488
- const result = this.getUint16(this.position, littleEndian);
489
- this.position += 2;
490
- return result;
491
- }
492
- nextInt32(littleEndian = this.littleEndianDefault) {
493
- const result = this.getInt32(this.position, littleEndian);
494
- this.position += 4;
495
- return result;
496
- }
497
- nextUint32(littleEndian = this.littleEndianDefault) {
498
- const result = this.getUint32(this.position, littleEndian);
499
- this.position += 4;
500
- return result;
501
- }
502
- nextString(length) {
503
- let result = "";
504
- for (let i = 0; i < length; i++) {
505
- result += String.fromCharCode(this.nextUint8());
506
- }
507
- return result;
508
- }
509
- nextNTBS(length) {
510
- // this length is different from the document
511
- let result = "";
512
- const lastPosition = this.position;
513
- for (let i = 0; i < length; i++) {
514
- if (this.byteLength <= this.position)
515
- break;
516
- const g = this.nextUint8();
517
- if (g === 0)
518
- break;
519
- result += String.fromCharCode(g);
520
- }
521
- this.position = lastPosition + length;
522
- return result;
523
- }
524
- nextVarNTBS(length) {
525
- // this length is different from the document
526
- let result = "";
527
- for (let i = 0; i < length; i++) {
528
- if (this.byteLength <= this.position)
529
- break;
530
- const g = this.nextUint8();
531
- if (g === 0)
532
- break;
533
- result += String.fromCharCode(g);
534
- }
535
- return result;
536
- }
537
- nextVersion(reverse = false) {
538
- const result = VexFirmwareVersion.fromUint8Array(new Uint8Array(this.buffer), this.position, reverse);
539
- this.position += 4;
540
- return result;
541
- }
542
- }
543
-
544
- const CRC16TABLE = [
545
- 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108,
546
- 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210,
547
- 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b,
548
- 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401,
549
- 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee,
550
- 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6,
551
- 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d,
552
- 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
553
- 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5,
554
- 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc,
555
- 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4,
556
- 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd,
557
- 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13,
558
- 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a,
559
- 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e,
560
- 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
561
- 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1,
562
- 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb,
563
- 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0,
564
- 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8,
565
- 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657,
566
- 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9,
567
- 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882,
568
- 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
569
- 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e,
570
- 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07,
571
- 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d,
572
- 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74,
573
- 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
574
- ];
575
- class CrcGenerator {
576
- constructor() {
577
- this.crc32Table = new Uint32Array(256);
578
- this.crc32GenTable();
579
- }
580
- /**
581
- * Calculate CRC16 for buffer
582
- */
583
- crc16(buf, initValue) {
584
- const numberOfBytes = buf.byteLength;
585
- let accumulator = initValue;
586
- let i;
587
- let j;
588
- // now calculate CRC16
589
- for (j = 0; j < numberOfBytes; j++) {
590
- i = ((accumulator >>> 8) ^ buf[j]) & 0xff;
591
- accumulator = ((accumulator << 8) ^ CRC16TABLE[i]) >>> 0;
592
- }
593
- return (accumulator & 0xffff) >>> 0;
594
- }
595
- /**
596
- * Generate CRC32 reverse table
597
- */
598
- crc32GenTable() {
599
- let i;
600
- let j;
601
- let crcAccumulator;
602
- for (i = 0; i < 256; i++) {
603
- crcAccumulator = i << 24;
604
- for (j = 0; j < 8; j++) {
605
- if ((crcAccumulator & 0x80000000) !== 0)
606
- crcAccumulator =
607
- (crcAccumulator << 1) ^ CrcGenerator.POLYNOMIAL_CRC32;
608
- else
609
- crcAccumulator = crcAccumulator << 1;
610
- }
611
- this.crc32Table[i] = crcAccumulator;
612
- }
613
- }
614
- /**
615
- * Calculate CRC32 for buffer
616
- */
617
- crc32(buf, initValue) {
618
- const numberOfBytes = buf.byteLength;
619
- let crcAccumulator = initValue;
620
- let i;
621
- let j;
622
- // now calculate CRC32
623
- for (j = 0; j < numberOfBytes; j++) {
624
- i = ((crcAccumulator >>> 24) ^ buf[j]) & 0xff;
625
- crcAccumulator = ((crcAccumulator << 8) ^ this.crc32Table[i]) >>> 0;
626
- }
627
- return (crcAccumulator & 0xffffffff) >>> 0;
628
- }
629
- }
630
- CrcGenerator.POLYNOMIAL_CRC32 = 79764919;
631
- CrcGenerator.POLYNOMIAL_CRC16 = 4129;
632
-
633
- class PacketEncoder {
634
- static getInstance() {
635
- if (Packet.ENCODER === undefined) {
636
- Packet.ENCODER = new PacketEncoder();
637
- }
638
- return Packet.ENCODER;
639
- }
640
- constructor() {
641
- this.allPacketsTable = {};
642
- this.vexVersion = 0;
643
- this.crcgen = new CrcGenerator();
644
- Object.values(AllPackets).forEach((packet) => {
645
- if (packet.prototype instanceof HostBoundPacket) {
646
- this.allPacketsTable[
647
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
648
- packet.COMMAND_ID + " " + packet.COMMAND_EXTENDED_ID] = packet;
649
- }
650
- });
651
- }
652
- /**
653
- * Create the vex CDC header
654
- * @param buf the bytes to send
655
- */
656
- createHeader(buf) {
657
- // create a buffer if is is not defined
658
- if (buf === undefined || buf.byteLength < PacketEncoder.HEADERS_LENGTH) {
659
- buf = new ArrayBuffer(PacketEncoder.HEADERS_LENGTH);
660
- }
661
- const h = new Uint8Array(buf);
662
- h.set(PacketEncoder.HEADER_TO_DEVICE);
663
- return h;
664
- }
665
- /**
666
- * Create the vex CDC simple message
667
- * @param cmd the CDC command byte
668
- */
669
- cdcCommand(cmd) {
670
- const buf = new ArrayBuffer(PacketEncoder.HEADERS_LENGTH + 1);
671
- const h = this.createHeader(buf);
672
- h.set([cmd], PacketEncoder.HEADERS_LENGTH);
673
- return h;
674
- }
675
- /**
676
- * Create the vex CDC simple message
677
- * @param cmd the CDC command byte
678
- * @param data the data to send
679
- */
680
- cdcCommandWithData(cmd, data) {
681
- const buf = new ArrayBuffer(PacketEncoder.HEADERS_LENGTH + 2 + data.length);
682
- const h = this.createHeader(buf);
683
- // add command and length bytes
684
- h.set([cmd, data.length], PacketEncoder.HEADERS_LENGTH);
685
- // add the message data
686
- h.set(data, PacketEncoder.HEADERS_LENGTH + 2);
687
- return h;
688
- }
689
- /**
690
- * Create the vex CDC extended message
691
- * @param cmd the CDC command byte
692
- * @param ext the CDC extended command byte
693
- * @return a message
694
- */
695
- cdc2Command(cmd, ext) {
696
- const buf = new ArrayBuffer(PacketEncoder.HEADERS_LENGTH + 5);
697
- const h = this.createHeader(buf);
698
- h.set([cmd, ext, 0], PacketEncoder.HEADERS_LENGTH);
699
- // Add CRC
700
- const crc = this.crcgen.crc16(h.subarray(0, buf.byteLength - 2), 0) >>> 0;
701
- h.set([crc >>> 8, crc & 0xff], buf.byteLength - 2);
702
- return h;
703
- }
704
- /**
705
- * Calculate buffer length for new CDC extended command
706
- * @param data the CDC extended command payload
707
- * @returns the required buffer length of the command message
708
- */
709
- cdc2CommandBufferLength(data) {
710
- // New command use header + 1 byte command
711
- // + 1 byte function
712
- // + 1 byte data length
713
- let length = PacketEncoder.HEADERS_LENGTH + data.length + 3 + 2;
714
- // If data length is > 127 bytes then an additional data length byte is added
715
- if (data.length > 127)
716
- length += 1;
717
- return length;
718
- }
719
- /**
720
- * Create the vex CDC extended message with some data
721
- * @param cmd the CDC command byte
722
- * @param ext the CDC extended command byte
723
- * @param data the CDC extended command payload
724
- * @return a message
725
- */
726
- cdc2CommandWithData(cmd, ext, data) {
727
- const buf = new ArrayBuffer(this.cdc2CommandBufferLength(data));
728
- const h = this.createHeader(buf);
729
- // add command and length bytes
730
- if (data.length < 128) {
731
- h.set([cmd, ext, data.length], PacketEncoder.HEADERS_LENGTH);
732
- // add the message data
733
- h.set(data, PacketEncoder.HEADERS_LENGTH + 3);
734
- }
735
- else {
736
- const lengthMsb = ((data.length >>> 8) | 0x80) >>> 0;
737
- const lengthLsb = (data.length & 0xff) >>> 0;
738
- h.set([cmd, ext, lengthMsb, lengthLsb], PacketEncoder.HEADERS_LENGTH);
739
- // add the message data
740
- h.set(data, PacketEncoder.HEADERS_LENGTH + 4);
741
- }
742
- // Add CRC (little endian)
743
- const crc = this.crcgen.crc16(h.subarray(0, buf.byteLength - 2), 0);
744
- h.set([crc >>> 8, crc & 0xff], buf.byteLength - 2);
745
- return h;
746
- }
747
- validateHeader(data) {
748
- return !(data[0] !== PacketEncoder.HEADER_TO_HOST[0] ||
749
- data[1] !== PacketEncoder.HEADER_TO_HOST[1]);
750
- }
751
- validateMessageCdc(data) {
752
- const message = data.subarray(0, data.byteLength - 2);
753
- const lastTwoBytes = (data[data.byteLength - 2] << 8) + data[data.byteLength - 1];
754
- return this.crcgen.crc16(message, 0) === lastTwoBytes;
755
- }
756
- getPayloadSize(data) {
757
- let t = 0;
758
- let a = data[3];
759
- if ((128 & a) !== 0) {
760
- t = 127 & a;
761
- a = data[4];
762
- }
763
- return (t << 8) + a;
764
- }
765
- }
766
- PacketEncoder.HEADERS_LENGTH = 4;
767
- PacketEncoder.HEADER_TO_DEVICE = [201, 54, 184, 71];
768
- PacketEncoder.HEADER_TO_HOST = [170, 85];
769
- PacketEncoder.J2000_EPOCH = 946684800;
770
- class Packet {
771
- constructor(rawData) {
772
- this.data =
773
- rawData instanceof ArrayBuffer ? new Uint8Array(rawData) : rawData;
774
- }
775
- }
776
- class DeviceBoundPacket extends Packet {
777
- constructor(payload) {
778
- super(new Uint8Array());
779
- // eslint-disable-next-line no-proto, @typescript-eslint/no-explicit-any
780
- const me = this.__proto__.constructor;
781
- if (me.COMMAND_EXTENDED_ID === undefined) {
782
- if (payload === undefined) {
783
- this.data = Packet.ENCODER.cdcCommand(me.COMMAND_ID);
784
- }
785
- else {
786
- this.data = Packet.ENCODER.cdcCommandWithData(me.COMMAND_ID, payload);
787
- }
788
- }
789
- else {
790
- if (payload === undefined) {
791
- this.data = Packet.ENCODER.cdc2Command(me.COMMAND_ID, me.COMMAND_EXTENDED_ID);
792
- }
793
- else {
794
- this.data = Packet.ENCODER.cdc2CommandWithData(me.COMMAND_ID, me.COMMAND_EXTENDED_ID, payload);
795
- }
796
- }
797
- }
798
- }
799
- class Query1H2DPacket extends DeviceBoundPacket {
800
- constructor() {
801
- super(undefined);
802
- }
803
- }
804
- Query1H2DPacket.COMMAND_ID = 33;
805
- Query1H2DPacket.COMMAND_EXTENDED_ID = undefined;
806
- class SystemVersionH2DPacket extends DeviceBoundPacket {
807
- constructor() {
808
- super(undefined);
809
- }
810
- }
811
- SystemVersionH2DPacket.COMMAND_ID = 164;
812
- SystemVersionH2DPacket.COMMAND_EXTENDED_ID = undefined;
813
- class UpdateMatchModeH2DPacket extends DeviceBoundPacket {
814
- constructor(mode, matchClock) {
815
- let bit1;
816
- switch (mode) {
817
- case "autonomous":
818
- bit1 = 10;
819
- break;
820
- case "driver":
821
- bit1 = 8;
822
- break;
823
- case "disabled":
824
- bit1 = 11;
825
- }
826
- const payload = new Uint8Array(5);
827
- const view = new DataView(payload.buffer);
828
- payload[0] = (15 & bit1) >>> 0;
829
- view.setUint32(1, matchClock, true);
830
- super(payload);
831
- }
832
- }
833
- UpdateMatchModeH2DPacket.COMMAND_ID = 88;
834
- UpdateMatchModeH2DPacket.COMMAND_EXTENDED_ID = 193;
835
- class GetMatchStatusH2DPacket extends DeviceBoundPacket {
836
- constructor() {
837
- super(undefined);
838
- }
839
- }
840
- GetMatchStatusH2DPacket.COMMAND_ID = 88;
841
- GetMatchStatusH2DPacket.COMMAND_EXTENDED_ID = 194;
842
- class GetRadioModeH2DPacket extends DeviceBoundPacket {
843
- constructor(mode) {
844
- const payload = new Uint8Array(1);
845
- payload[0] = mode;
846
- super(payload);
847
- }
848
- }
849
- GetRadioModeH2DPacket.COMMAND_ID = 88;
850
- GetRadioModeH2DPacket.COMMAND_EXTENDED_ID = 65;
851
- class FileControlH2DPacket extends DeviceBoundPacket {
852
- constructor(a, b) {
853
- const payload = new Uint8Array(2);
854
- payload.set([a, b], 0);
855
- super(payload);
856
- }
857
- }
858
- FileControlH2DPacket.COMMAND_ID = 86;
859
- FileControlH2DPacket.COMMAND_EXTENDED_ID = 16;
860
- class InitFileTransferH2DPacket extends DeviceBoundPacket {
861
- constructor(operation, target, vendor, options, binary, addr, name, type, version = new VexFirmwareVersion(1, 0, 0, 0)) {
862
- const payload = new Uint8Array(52);
863
- const view = new DataView(payload.buffer);
864
- view.setUint8(0, operation);
865
- view.setUint8(1, target);
866
- view.setUint8(2, vendor);
867
- view.setUint8(3, options);
868
- view.setUint32(4, binary.length, true);
869
- view.setUint32(8, addr, true);
870
- view.setUint32(12, operation === FileInitAction.WRITE
871
- ? Packet.ENCODER.crcgen.crc32(binary, 0)
872
- : 0, true);
873
- const re = /(?:\.([^.]+))?$/;
874
- const reResult = re.exec(name);
875
- let ext = reResult != null ? reResult[1] : undefined;
876
- ext !== null && ext !== void 0 ? ext : (ext = "");
877
- // files with gz extension are also type bin
878
- ext = ext === "gz" ? "bin" : ext;
879
- payload.set(new TextEncoder().encode(type !== null && type !== void 0 ? type : ext), 16);
880
- const timestamp = ((Date.now() / 1000) >>> 0) - PacketEncoder.J2000_EPOCH;
881
- view.setUint32(20, timestamp, true);
882
- payload.set(version.toUint8Array(), 24);
883
- // filename
884
- const nameEncoded = new TextEncoder().encode(name);
885
- let offset = nameEncoded.length - 23;
886
- if (offset < 0)
887
- offset = 0;
888
- payload.set(nameEncoded.subarray(offset, offset + 23), 28);
889
- view.setUint8(51, 0);
890
- super(payload);
891
- }
892
- }
893
- InitFileTransferH2DPacket.COMMAND_ID = 86;
894
- InitFileTransferH2DPacket.COMMAND_EXTENDED_ID = 17;
895
- class ExitFileTransferH2DPacket extends DeviceBoundPacket {
896
- constructor(action) {
897
- const payload = new Uint8Array(1);
898
- payload[0] = action;
899
- super(payload);
900
- }
901
- }
902
- ExitFileTransferH2DPacket.COMMAND_ID = 86;
903
- ExitFileTransferH2DPacket.COMMAND_EXTENDED_ID = 18;
904
- class WriteFileH2DPacket extends DeviceBoundPacket {
905
- constructor(addr, buf) {
906
- const payload = new Uint8Array(4 + buf.length);
907
- const view = new DataView(payload.buffer);
908
- view.setUint32(0, addr, true);
909
- payload.set(buf, 4);
910
- super(payload);
911
- }
912
- }
913
- WriteFileH2DPacket.COMMAND_ID = 86;
914
- WriteFileH2DPacket.COMMAND_EXTENDED_ID = 19;
915
- class ReadFileH2DPacket extends DeviceBoundPacket {
916
- constructor(addr, size) {
917
- const payload = new Uint8Array(6);
918
- const view = new DataView(payload.buffer);
919
- view.setUint32(0, addr, true);
920
- view.setUint16(4, size, true);
921
- super(payload);
922
- }
923
- }
924
- ReadFileH2DPacket.COMMAND_ID = 86;
925
- ReadFileH2DPacket.COMMAND_EXTENDED_ID = 20;
926
- class LinkFileH2DPacket extends DeviceBoundPacket {
927
- constructor(vendor, fileName, options) {
928
- const str = new TextEncoder().encode(fileName);
929
- const payload = new Uint8Array(26);
930
- payload.set([vendor, options], 0);
931
- payload.set(str.subarray(0, 23), 2);
932
- super(payload);
933
- }
934
- }
935
- LinkFileH2DPacket.COMMAND_ID = 86;
936
- LinkFileH2DPacket.COMMAND_EXTENDED_ID = 21;
937
- class GetDirectoryFileCountH2DPacket extends DeviceBoundPacket {
938
- constructor(vendor) {
939
- const payload = new Uint8Array(2);
940
- payload.set([vendor, 0], 0);
941
- super(payload);
942
- }
943
- }
944
- GetDirectoryFileCountH2DPacket.COMMAND_ID = 86;
945
- GetDirectoryFileCountH2DPacket.COMMAND_EXTENDED_ID = 22;
946
- class GetDirectoryEntryH2DPacket extends DeviceBoundPacket {
947
- constructor(index) {
948
- const payload = new Uint8Array(2);
949
- payload.set([index, 0], 0);
950
- super(payload);
951
- }
952
- }
953
- GetDirectoryEntryH2DPacket.COMMAND_ID = 86;
954
- GetDirectoryEntryH2DPacket.COMMAND_EXTENDED_ID = 23;
955
- class LoadFileActionH2DPacket extends DeviceBoundPacket {
956
- constructor(vendor, actionId, fileNameOrSlotNumber) {
957
- let fileName;
958
- if (typeof fileNameOrSlotNumber === "string") {
959
- fileName = fileNameOrSlotNumber;
960
- }
961
- else {
962
- fileName = "___s_" + (fileNameOrSlotNumber - 1) + ".bin";
963
- }
964
- const encodedName = new TextEncoder().encode(fileName);
965
- const payload = new Uint8Array(26);
966
- payload.set([vendor, actionId], 0);
967
- payload.set(encodedName.subarray(0, 23), 2);
968
- super(payload);
969
- }
970
- }
971
- LoadFileActionH2DPacket.COMMAND_ID = 86;
972
- LoadFileActionH2DPacket.COMMAND_EXTENDED_ID = 24;
973
- class GetFileMetadataH2DPacket extends DeviceBoundPacket {
974
- constructor(vendor, fileName, options) {
975
- const encodedName = new TextEncoder().encode(fileName);
976
- const payload = new Uint8Array(26);
977
- payload.set([vendor, options], 0);
978
- payload.set(encodedName.subarray(0, 23), 2);
979
- super(payload);
980
- }
981
- }
982
- GetFileMetadataH2DPacket.COMMAND_ID = 86;
983
- GetFileMetadataH2DPacket.COMMAND_EXTENDED_ID = 25;
984
- class SetFileMetadataH2DPacket extends DeviceBoundPacket {
985
- constructor(vendor, fileName, fileInfo, options) {
986
- const encodedName = new TextEncoder().encode(fileName);
987
- const encodedType = new TextEncoder().encode(fileInfo.type);
988
- const payload = new Uint8Array(42);
989
- const view = new DataView(payload.buffer);
990
- view.setUint8(0, vendor);
991
- view.setUint8(1, options);
992
- view.setUint32(2, fileInfo.loadAddress, true);
993
- payload.set(encodedType.subarray(0, 4), 6);
994
- const timestamp = fileInfo.timestamp - PacketEncoder.J2000_EPOCH + 100; // XXX: + 100 TEST ONLY
995
- view.setUint32(10, timestamp, true);
996
- payload.set(fileInfo.version.toUint8Array(), 14);
997
- payload.set(encodedName.subarray(0, 23), 18);
998
- super(payload);
999
- }
1000
- }
1001
- // DOES NOT WORK
1002
- SetFileMetadataH2DPacket.COMMAND_ID = 86;
1003
- SetFileMetadataH2DPacket.COMMAND_EXTENDED_ID = 26;
1004
- class EraseFileH2DPacket extends DeviceBoundPacket {
1005
- constructor(vendor, fileName) {
1006
- const encodedName = new TextEncoder().encode(fileName);
1007
- const payload = new Uint8Array(26);
1008
- payload.set([vendor, 128], 0);
1009
- payload.set(encodedName.subarray(0, 23), 2);
1010
- super(payload);
1011
- }
1012
- }
1013
- EraseFileH2DPacket.COMMAND_ID = 86;
1014
- EraseFileH2DPacket.COMMAND_EXTENDED_ID = 27;
1015
- class GetProgramSlotInfoH2DPacket extends DeviceBoundPacket {
1016
- constructor(vendor, fileName) {
1017
- const encodedName = new TextEncoder().encode(fileName);
1018
- const payload = new Uint8Array(26);
1019
- payload.set([vendor, 0], 0);
1020
- payload.set(encodedName.subarray(0, 23), 2);
1021
- super(payload);
1022
- }
1023
- }
1024
- GetProgramSlotInfoH2DPacket.COMMAND_ID = 86;
1025
- GetProgramSlotInfoH2DPacket.COMMAND_EXTENDED_ID = 28;
1026
- class FileClearUpH2DPacket extends DeviceBoundPacket {
1027
- constructor(vendor) {
1028
- const payload = new Uint8Array(2);
1029
- payload.set([vendor, 0], 0);
1030
- super(payload);
1031
- }
1032
- }
1033
- FileClearUpH2DPacket.COMMAND_ID = 86;
1034
- FileClearUpH2DPacket.COMMAND_EXTENDED_ID = 30;
1035
- class FileFormatH2DPacket extends DeviceBoundPacket {
1036
- constructor() {
1037
- const payload = new Uint8Array(4);
1038
- payload.set([68, 67, 66, 65], 0);
1039
- super(payload);
1040
- }
1041
- }
1042
- FileFormatH2DPacket.COMMAND_ID = 86;
1043
- FileFormatH2DPacket.COMMAND_EXTENDED_ID = 31;
1044
- class GetSystemFlagsH2DPacket extends DeviceBoundPacket {
1045
- }
1046
- GetSystemFlagsH2DPacket.COMMAND_ID = 86;
1047
- GetSystemFlagsH2DPacket.COMMAND_EXTENDED_ID = 32;
1048
- class GetDeviceStatusH2DPacket extends DeviceBoundPacket {
1049
- constructor() {
1050
- super(undefined);
1051
- }
1052
- }
1053
- GetDeviceStatusH2DPacket.COMMAND_ID = 86;
1054
- GetDeviceStatusH2DPacket.COMMAND_EXTENDED_ID = 33;
1055
- class GetSystemStatusH2DPacket extends DeviceBoundPacket {
1056
- constructor() {
1057
- super(undefined);
1058
- }
1059
- }
1060
- GetSystemStatusH2DPacket.COMMAND_ID = 86;
1061
- GetSystemStatusH2DPacket.COMMAND_EXTENDED_ID = 34;
1062
- class GetFdtStatusH2DPacket extends DeviceBoundPacket {
1063
- constructor() {
1064
- super(undefined);
1065
- }
1066
- }
1067
- GetFdtStatusH2DPacket.COMMAND_ID = 86;
1068
- GetFdtStatusH2DPacket.COMMAND_EXTENDED_ID = 35;
1069
- class GetLogCountH2DPacket extends DeviceBoundPacket {
1070
- constructor() {
1071
- super(undefined);
1072
- }
1073
- }
1074
- GetLogCountH2DPacket.COMMAND_ID = 86;
1075
- GetLogCountH2DPacket.COMMAND_EXTENDED_ID = 36;
1076
- class ReadLogPageH2DPacket extends DeviceBoundPacket {
1077
- constructor(offset, count) {
1078
- const payload = new Uint8Array(8);
1079
- const view = new DataView(payload.buffer);
1080
- view.setUint32(0, offset, true);
1081
- view.setUint32(4, count, true);
1082
- super(payload);
1083
- }
1084
- }
1085
- ReadLogPageH2DPacket.COMMAND_ID = 86;
1086
- ReadLogPageH2DPacket.COMMAND_EXTENDED_ID = 37;
1087
- class GetRadioStatusH2DPacket extends DeviceBoundPacket {
1088
- constructor() {
1089
- super(undefined);
1090
- }
1091
- }
1092
- GetRadioStatusH2DPacket.COMMAND_ID = 86;
1093
- GetRadioStatusH2DPacket.COMMAND_EXTENDED_ID = 38;
1094
- class GetUserDataH2DPacket extends DeviceBoundPacket {
1095
- constructor(e) {
1096
- var _a;
1097
- const input = (_a = e === null || e === void 0 ? void 0 : e.slice(0, 224)) !== null && _a !== void 0 ? _a : new Uint8Array(0);
1098
- const payload = new Uint8Array(2 + input.length);
1099
- payload[0] = 1; // stdio channel
1100
- payload[1] = input.length;
1101
- payload.set(input, 2);
1102
- super(payload);
1103
- }
1104
- }
1105
- // UNCONFIRMED
1106
- GetUserDataH2DPacket.COMMAND_ID = 86;
1107
- GetUserDataH2DPacket.COMMAND_EXTENDED_ID = 39;
1108
- class ScreenCaptureH2DPacket extends DeviceBoundPacket {
1109
- constructor(e) {
1110
- const payload = new Uint8Array(1);
1111
- payload[0] = e;
1112
- super(payload);
1113
- }
1114
- }
1115
- ScreenCaptureH2DPacket.COMMAND_ID = 86;
1116
- ScreenCaptureH2DPacket.COMMAND_EXTENDED_ID = 40;
1117
- class SendDashTouchH2DPacket extends DeviceBoundPacket {
1118
- constructor(x, y, press) {
1119
- const payload = new Uint8Array(6);
1120
- const view = new DataView(payload.buffer);
1121
- view.setUint16(0, x, true);
1122
- view.setUint16(2, y, true);
1123
- view.setUint16(4, press ? 1 : 0, true);
1124
- super(payload);
1125
- }
1126
- }
1127
- SendDashTouchH2DPacket.COMMAND_ID = 86;
1128
- SendDashTouchH2DPacket.COMMAND_EXTENDED_ID = 42;
1129
- class SelectDashH2DPacket extends DeviceBoundPacket {
1130
- /** @param port untested */
1131
- constructor(screen, port) {
1132
- const payload = new Uint8Array(2);
1133
- payload[0] = screen;
1134
- payload[1] = port;
1135
- super(payload);
1136
- }
1137
- }
1138
- // UNSURE
1139
- SelectDashH2DPacket.COMMAND_ID = 86;
1140
- SelectDashH2DPacket.COMMAND_EXTENDED_ID = 43;
1141
- class EnableDashH2DPacket extends DeviceBoundPacket {
1142
- constructor(unknown1) {
1143
- if (unknown1 === undefined) {
1144
- super(undefined);
1145
- }
1146
- else {
1147
- const payload = new Uint8Array(1);
1148
- payload[0] = unknown1;
1149
- super(payload);
1150
- }
1151
- }
1152
- }
1153
- // UNSURE
1154
- EnableDashH2DPacket.COMMAND_ID = 86;
1155
- EnableDashH2DPacket.COMMAND_EXTENDED_ID = 44;
1156
- class DisableDashH2DPacket extends DeviceBoundPacket {
1157
- constructor() {
1158
- super(undefined);
1159
- }
1160
- }
1161
- // UNSURE
1162
- DisableDashH2DPacket.COMMAND_ID = 86;
1163
- DisableDashH2DPacket.COMMAND_EXTENDED_ID = 45;
1164
- class ReadKeyValueH2DPacket extends DeviceBoundPacket {
1165
- constructor(key) {
1166
- const payload = new Uint8Array(32);
1167
- payload.set(new TextEncoder().encode(key), 0);
1168
- super(payload);
1169
- }
1170
- }
1171
- // UNSURE
1172
- ReadKeyValueH2DPacket.COMMAND_ID = 86;
1173
- ReadKeyValueH2DPacket.COMMAND_EXTENDED_ID = 46;
1174
- class WriteKeyValueH2DPacket extends DeviceBoundPacket {
1175
- constructor(key, value) {
1176
- let strk = new TextEncoder().encode(key);
1177
- const strv = new TextEncoder().encode(value);
1178
- if (strk.byteLength > 31)
1179
- strk = strk.subarray(0, 31);
1180
- const payload = new Uint8Array(strk.length + strv.length + 20);
1181
- payload.set(strk, 0);
1182
- payload.set(strv, strk.length + 1);
1183
- super(payload);
1184
- }
1185
- }
1186
- // UNSURE
1187
- WriteKeyValueH2DPacket.COMMAND_ID = 86;
1188
- WriteKeyValueH2DPacket.COMMAND_EXTENDED_ID = 47;
1189
- class GetSlot1to4InfoH2DPacket extends DeviceBoundPacket {
1190
- constructor() {
1191
- super(undefined);
1192
- }
1193
- }
1194
- GetSlot1to4InfoH2DPacket.COMMAND_ID = 86;
1195
- GetSlot1to4InfoH2DPacket.COMMAND_EXTENDED_ID = 49;
1196
- class GetSlot5to8InfoH2DPacket extends DeviceBoundPacket {
1197
- constructor() {
1198
- super(undefined);
1199
- }
1200
- }
1201
- GetSlot5to8InfoH2DPacket.COMMAND_ID = 86;
1202
- GetSlot5to8InfoH2DPacket.COMMAND_EXTENDED_ID = 50;
1203
- class FactoryStatusH2DPacket extends DeviceBoundPacket {
1204
- }
1205
- FactoryStatusH2DPacket.COMMAND_ID = 86;
1206
- FactoryStatusH2DPacket.COMMAND_EXTENDED_ID = 241;
1207
- class FactoryEnableH2DPacket extends DeviceBoundPacket {
1208
- constructor() {
1209
- const payload = new Uint8Array(4);
1210
- payload.set([77, 76, 75, 74], 0);
1211
- super(payload);
1212
- }
1213
- }
1214
- FactoryEnableH2DPacket.COMMAND_ID = 86;
1215
- FactoryEnableH2DPacket.COMMAND_EXTENDED_ID = 255;
1216
- class HostBoundPacket extends Packet {
1217
- constructor(data) {
1218
- super(data);
1219
- this.ack = AckType.CDC2_NACK;
1220
- this.payloadSize = Packet.ENCODER.getPayloadSize(this.data);
1221
- const n = this.payloadSize > 128 ? 5 : 4;
1222
- // skip command id check
1223
- this.ack = this.data[(this.ackIndex = n + 1)];
1224
- }
1225
- static isValidPacket(data, n) {
1226
- const ack = data[n + 1];
1227
- return ack === AckType.CDC2_ACK || ack === 167; // XXX: got 167 from MatchStatusReplyD2HPacket
1228
- }
1229
- }
1230
- class Query1ReplyD2HPacket extends HostBoundPacket {
1231
- constructor(data) {
1232
- super(data);
1233
- this.joystickFlag1 = this.data[4];
1234
- this.joystickFlag2 = this.data[5];
1235
- this.brainFlag1 = this.data[6]; // a.k.a vex version
1236
- this.brainFlag2 = this.data[7];
1237
- this.bootloadFlag1 = this.data[10];
1238
- this.bootloadFlag2 = this.data[11];
1239
- }
1240
- }
1241
- Query1ReplyD2HPacket.COMMAND_ID = 33;
1242
- Query1ReplyD2HPacket.COMMAND_EXTENDED_ID = undefined;
1243
- class SystemVersionReplyD2HPacket extends HostBoundPacket {
1244
- constructor(data) {
1245
- super(data);
1246
- this.version = new VexFirmwareVersion(this.data[4], this.data[5], this.data[6], this.data[8]);
1247
- this.hardware = this.data[7];
1248
- }
1249
- }
1250
- SystemVersionReplyD2HPacket.COMMAND_ID = 164;
1251
- SystemVersionReplyD2HPacket.COMMAND_EXTENDED_ID = undefined;
1252
- class MatchModeReplyD2HPacket extends HostBoundPacket {
1253
- constructor(data) {
1254
- super(data);
1255
- const dataView = PacketView.fromPacket(this);
1256
- this.modebit = dataView.nextUint8();
1257
- }
1258
- }
1259
- MatchModeReplyD2HPacket.COMMAND_ID = 88;
1260
- MatchModeReplyD2HPacket.COMMAND_EXTENDED_ID = 193;
1261
- class MatchStatusReplyD2HPacket extends HostBoundPacket {
1262
- constructor(data) {
1263
- super(data);
1264
- const dataView = PacketView.fromPacket(this);
1265
- const n = this.ackIndex;
1266
- this.rssi = dataView.nextInt8();
1267
- this.systemStatusBits = dataView.nextUint16();
1268
- this.radioStatusBits = dataView.nextUint16();
1269
- this.fieldStatusBits = dataView.nextUint8();
1270
- this.matchClock = dataView.nextUint8();
1271
- this.brainBatteryPercent = dataView.nextUint8();
1272
- this.controllerBatteryPercent = dataView.nextUint8();
1273
- this.partnerControllerBatteryPercent = dataView.nextUint8();
1274
- this.pad = dataView.nextUint8();
1275
- this.buttons = dataView.nextUint16();
1276
- this.activeProgram = dataView.nextUint8();
1277
- this.radioType = dataView.nextUint8();
1278
- this.radioChannel = dataView.nextUint8();
1279
- this.radioSlot = dataView.nextUint8();
1280
- this.robotName = dataView.nextNTBS(10);
1281
- this.controllerFlags = dataView.getUint8(n + 28);
1282
- this.rxSignalQuality = dataView.getUint8(n + 29);
1283
- let rawStr = new TextDecoder("UTF-8").decode(data.slice(n + 18, n + this.payloadSize + 28));
1284
- const endIdx = rawStr.indexOf("\0");
1285
- if (endIdx > -1) {
1286
- rawStr = rawStr.substr(0, endIdx);
1287
- }
1288
- this.robotName = rawStr;
1289
- }
1290
- }
1291
- MatchStatusReplyD2HPacket.COMMAND_ID = 88;
1292
- MatchStatusReplyD2HPacket.COMMAND_EXTENDED_ID = 194;
1293
- class FileControlReplyD2HPacket extends HostBoundPacket {
1294
- }
1295
- FileControlReplyD2HPacket.COMMAND_ID = 86;
1296
- FileControlReplyD2HPacket.COMMAND_EXTENDED_ID = 16;
1297
- class InitFileTransferReplyD2HPacket extends HostBoundPacket {
1298
- constructor(data) {
1299
- super(data);
1300
- const dataView = PacketView.fromPacket(this);
1301
- this.windowSize = dataView.nextUint16();
1302
- this.fileSize = dataView.nextUint32();
1303
- this.crc32 = dataView.nextUint32();
1304
- }
1305
- }
1306
- InitFileTransferReplyD2HPacket.COMMAND_ID = 86;
1307
- InitFileTransferReplyD2HPacket.COMMAND_EXTENDED_ID = 17;
1308
- class ExitFileTransferReplyD2HPacket extends HostBoundPacket {
1309
- }
1310
- ExitFileTransferReplyD2HPacket.COMMAND_ID = 86;
1311
- ExitFileTransferReplyD2HPacket.COMMAND_EXTENDED_ID = 18;
1312
- class WriteFileReplyD2HPacket extends HostBoundPacket {
1313
- }
1314
- WriteFileReplyD2HPacket.COMMAND_ID = 86;
1315
- WriteFileReplyD2HPacket.COMMAND_EXTENDED_ID = 19;
1316
- class ReadFileReplyD2HPacket extends HostBoundPacket {
1317
- constructor(data) {
1318
- super(data);
1319
- const dataView = PacketView.fromPacket(this);
1320
- const n = this.ackIndex;
1321
- this.addr = dataView.getUint32(n, true);
1322
- this.length = this.payloadSize - 7;
1323
- this.buf = data.slice(n + 4, n + 4 + this.length);
1324
- }
1325
- static isValidPacket(data, n) {
1326
- return data[4] === 4 ? data[n + 1] === AckType.CDC2_ACK : true;
1327
- }
1328
- }
1329
- ReadFileReplyD2HPacket.COMMAND_ID = 86;
1330
- ReadFileReplyD2HPacket.COMMAND_EXTENDED_ID = 20;
1331
- class LinkFileReplyD2HPacket extends HostBoundPacket {
1332
- }
1333
- LinkFileReplyD2HPacket.COMMAND_ID = 86;
1334
- LinkFileReplyD2HPacket.COMMAND_EXTENDED_ID = 21;
1335
- class GetDirectoryFileCountReplyD2HPacket extends HostBoundPacket {
1336
- constructor(data) {
1337
- super(data);
1338
- const dataView = PacketView.fromPacket(this);
1339
- this.count = dataView.nextUint16();
1340
- }
1341
- }
1342
- GetDirectoryFileCountReplyD2HPacket.COMMAND_ID = 86;
1343
- GetDirectoryFileCountReplyD2HPacket.COMMAND_EXTENDED_ID = 22;
1344
- class GetDirectoryEntryReplyD2HPacket extends HostBoundPacket {
1345
- constructor(data) {
1346
- super(data);
1347
- const dataView = PacketView.fromPacket(this);
1348
- if (this.payloadSize > 4) {
1349
- this.file = {
1350
- index: dataView.nextUint8(),
1351
- size: dataView.nextUint32(),
1352
- loadAddress: dataView.nextUint32(),
1353
- crc32: dataView.nextUint32(),
1354
- type: dataView.nextString(4),
1355
- timestamp: dataView.nextUint32() + PacketEncoder.J2000_EPOCH,
1356
- version: dataView.nextVersion(),
1357
- filename: dataView.nextNTBS(32),
1358
- };
1359
- }
1360
- }
1361
- }
1362
- GetDirectoryEntryReplyD2HPacket.COMMAND_ID = 86;
1363
- GetDirectoryEntryReplyD2HPacket.COMMAND_EXTENDED_ID = 23;
1364
- class LoadFileActionReplyD2HPacket extends HostBoundPacket {
1365
- }
1366
- LoadFileActionReplyD2HPacket.COMMAND_ID = 86;
1367
- LoadFileActionReplyD2HPacket.COMMAND_EXTENDED_ID = 24;
1368
- class GetFileMetadataReplyD2HPacket extends HostBoundPacket {
1369
- constructor(data) {
1370
- super(data);
1371
- const dataView = PacketView.fromPacket(this);
1372
- dataView.nextUint8();
1373
- if (this.payloadSize > 4) {
1374
- this.file = {
1375
- size: dataView.nextUint32(),
1376
- loadAddress: dataView.nextUint32(),
1377
- crc32: dataView.nextUint32(),
1378
- type: dataView.nextString(4),
1379
- timestamp: dataView.nextUint32() + PacketEncoder.J2000_EPOCH,
1380
- version: dataView.nextVersion(),
1381
- };
1382
- }
1383
- }
1384
- }
1385
- GetFileMetadataReplyD2HPacket.COMMAND_ID = 86;
1386
- GetFileMetadataReplyD2HPacket.COMMAND_EXTENDED_ID = 25;
1387
- class SetFileMetadataReplyD2HPacket extends HostBoundPacket {
1388
- }
1389
- SetFileMetadataReplyD2HPacket.COMMAND_ID = 86;
1390
- SetFileMetadataReplyD2HPacket.COMMAND_EXTENDED_ID = 26;
1391
- class EraseFileReplyD2HPacket extends HostBoundPacket {
1392
- }
1393
- EraseFileReplyD2HPacket.COMMAND_ID = 86;
1394
- EraseFileReplyD2HPacket.COMMAND_EXTENDED_ID = 27;
1395
- class GetProgramSlotInfoReplyD2HPacket extends HostBoundPacket {
1396
- constructor(data) {
1397
- super(data);
1398
- const dataView = PacketView.fromPacket(this);
1399
- this.slot = dataView.nextUint8();
1400
- this.requestedSlot = dataView.nextUint8();
1401
- }
1402
- }
1403
- GetProgramSlotInfoReplyD2HPacket.COMMAND_ID = 86;
1404
- GetProgramSlotInfoReplyD2HPacket.COMMAND_EXTENDED_ID = 28;
1405
- class FileClearUpReplyD2HPacket extends HostBoundPacket {
1406
- }
1407
- FileClearUpReplyD2HPacket.COMMAND_ID = 86;
1408
- FileClearUpReplyD2HPacket.COMMAND_EXTENDED_ID = 30;
1409
- class FileFormatReplyD2HPacket extends HostBoundPacket {
1410
- }
1411
- FileFormatReplyD2HPacket.COMMAND_ID = 86;
1412
- FileFormatReplyD2HPacket.COMMAND_EXTENDED_ID = 31;
1413
- class GetSystemFlagsReplyD2HPacket extends HostBoundPacket {
1414
- constructor(data) {
1415
- super(data);
1416
- const dataView = PacketView.fromPacket(this);
1417
- this.radioSearching = false;
1418
- this.currentProgram = 0;
1419
- this.flags = dataView.nextUint32();
1420
- const hasPartner = (8192 & this.flags) !== 0;
1421
- const hasRadio = (1536 & this.flags) === 1536;
1422
- const byte1 = dataView.nextUint8();
1423
- const byte2 = dataView.nextUint8();
1424
- if (this.payloadSize === 11) {
1425
- this.battery = 8 * (byte1 & 0x0f);
1426
- if ((this.flags & 0x100) !== 0 || hasRadio)
1427
- this.controllerBatteryPercent = 8 * ((byte1 >> 4) & 0x0f);
1428
- if (hasRadio)
1429
- this.radioQuality = 8 * (byte2 & 0x0f);
1430
- this.radioSearching = (this.flags & 0x600) === 0x200;
1431
- if (hasPartner)
1432
- this.partnerControllerBatteryPercent = 8 * ((byte2 >> 4) & 0x0f);
1433
- this.currentProgram = dataView.nextUint8();
1434
- if (this.battery != null && this.battery > 100)
1435
- this.battery = 100;
1436
- if (this.controllerBatteryPercent != null &&
1437
- this.controllerBatteryPercent > 100)
1438
- this.controllerBatteryPercent = 100;
1439
- if (this.radioQuality != null && this.radioQuality > 100)
1440
- this.radioQuality = 100;
1441
- if (this.partnerControllerBatteryPercent != null &&
1442
- this.partnerControllerBatteryPercent > 100)
1443
- this.partnerControllerBatteryPercent = 100;
1444
- }
1445
- }
1446
- }
1447
- GetSystemFlagsReplyD2HPacket.COMMAND_ID = 86;
1448
- GetSystemFlagsReplyD2HPacket.COMMAND_EXTENDED_ID = 32;
1449
- class GetDeviceStatusReplyD2HPacket extends HostBoundPacket {
1450
- constructor(data) {
1451
- super(data);
1452
- const dataView = PacketView.fromPacket(this);
1453
- this.count = dataView.nextUint8();
1454
- this.devices = [];
1455
- for (let i = 0; i < this.count; i++) {
1456
- this.devices.push({
1457
- port: dataView.nextUint8(),
1458
- type: dataView.nextUint8(),
1459
- status: dataView.nextUint8(),
1460
- betaversion: dataView.nextUint8(),
1461
- version: dataView.nextUint16(),
1462
- bootversion: dataView.nextUint16(),
1463
- });
1464
- }
1465
- }
1466
- }
1467
- GetDeviceStatusReplyD2HPacket.COMMAND_ID = 86;
1468
- GetDeviceStatusReplyD2HPacket.COMMAND_EXTENDED_ID = 33;
1469
- class GetSystemStatusReplyD2HPacket extends HostBoundPacket {
1470
- constructor(data) {
1471
- super(data);
1472
- const dataView = PacketView.fromPacket(this);
1473
- dataView.nextUint8();
1474
- this.systemVersion = dataView.nextVersion();
1475
- this.cpu0Version = dataView.nextVersion();
1476
- this.cpu1Version = dataView.nextVersion();
1477
- this.touchVersion = dataView.nextVersion(true);
1478
- this.uniqueId = 1234;
1479
- this.sysflags = [0, 0, 0, 0, 0, 0, 0];
1480
- this.goldenVersion = VexFirmwareVersion.allZero();
1481
- this.nxpVersion = VexFirmwareVersion.allZero();
1482
- this.eventBrain = false;
1483
- this.romBootloaderActive = false;
1484
- this.ramBootloaderActive = false;
1485
- if (this.payloadSize > 25) {
1486
- this.uniqueId = dataView.nextUint32();
1487
- this.sysflags = [
1488
- dataView.nextUint8(),
1489
- dataView.nextUint8(),
1490
- dataView.nextUint8(),
1491
- dataView.nextUint8(),
1492
- dataView.nextUint8(),
1493
- 0,
1494
- dataView.nextUint8(),
1495
- ];
1496
- this.eventBrain = (1 & this.sysflags[6]) !== 0;
1497
- this.romBootloaderActive = (2 & this.sysflags[6]) !== 0;
1498
- this.ramBootloaderActive = (4 & this.sysflags[6]) !== 0;
1499
- dataView.nextUint16();
1500
- this.goldenVersion = dataView.nextVersion();
1501
- }
1502
- if (this.payloadSize > 37) {
1503
- this.nxpVersion = dataView.nextVersion();
1504
- }
1505
- }
1506
- }
1507
- GetSystemStatusReplyD2HPacket.COMMAND_ID = 86;
1508
- GetSystemStatusReplyD2HPacket.COMMAND_EXTENDED_ID = 34;
1509
- class GetFdtStatusReplyD2HPacket extends HostBoundPacket {
1510
- constructor(data) {
1511
- super(data);
1512
- const dataView = PacketView.fromPacket(this);
1513
- this.count = dataView.nextUint8();
1514
- this.status = [];
1515
- for (let i = 0; i < this.count; i++) {
1516
- this.status.push({
1517
- index: dataView.nextUint8(),
1518
- type: dataView.nextUint8(),
1519
- status: dataView.nextUint8(),
1520
- betaversion: dataView.nextUint8(),
1521
- version: dataView.nextUint16(),
1522
- bootversion: dataView.nextUint16(),
1523
- });
1524
- }
1525
- }
1526
- }
1527
- GetFdtStatusReplyD2HPacket.COMMAND_ID = 86;
1528
- GetFdtStatusReplyD2HPacket.COMMAND_EXTENDED_ID = 35;
1529
- class GetLogCountReplyD2HPacket extends HostBoundPacket {
1530
- constructor(data) {
1531
- super(data);
1532
- const dataView = PacketView.fromPacket(this);
1533
- dataView.nextUint8();
1534
- this.count = dataView.nextUint32();
1535
- }
1536
- }
1537
- GetLogCountReplyD2HPacket.COMMAND_ID = 86;
1538
- GetLogCountReplyD2HPacket.COMMAND_EXTENDED_ID = 36;
1539
- class ReadLogPageReplyD2HPacket extends HostBoundPacket {
1540
- constructor(data) {
1541
- super(data);
1542
- const dataView = PacketView.fromPacket(this);
1543
- const n = this.ackIndex;
1544
- const size = dataView.nextUint8();
1545
- this.offset = dataView.nextUint32();
1546
- this.count = dataView.nextUint16();
1547
- this.entries = [];
1548
- let j = n + 8;
1549
- for (let i = 0; i < this.count; i++) {
1550
- this.entries.push({
1551
- code: dataView.getUint8(j),
1552
- type: dataView.getUint8(j + 1),
1553
- desc: dataView.getUint8(j + 2),
1554
- spare: dataView.getUint8(j + 3),
1555
- time: dataView.getUint32(j + 4, true),
1556
- });
1557
- j += size;
1558
- }
1559
- }
1560
- }
1561
- ReadLogPageReplyD2HPacket.COMMAND_ID = 86;
1562
- ReadLogPageReplyD2HPacket.COMMAND_EXTENDED_ID = 37;
1563
- class GetRadioStatusReplyD2HPacket extends HostBoundPacket {
1564
- constructor(data) {
1565
- super(data);
1566
- const dataView = PacketView.fromPacket(this);
1567
- const n = this.ackIndex;
1568
- this.device = dataView.nextUint8();
1569
- this.quality = dataView.nextUint16();
1570
- this.strength = dataView.nextInt16();
1571
- this.channel = this.data[n + 6];
1572
- this.timeslot = this.data[n + 7];
1573
- }
1574
- }
1575
- GetRadioStatusReplyD2HPacket.COMMAND_ID = 86;
1576
- GetRadioStatusReplyD2HPacket.COMMAND_EXTENDED_ID = 38;
1577
- class GetUserDataReplyD2HPacket extends HostBoundPacket {
1578
- }
1579
- GetUserDataReplyD2HPacket.COMMAND_ID = 86;
1580
- GetUserDataReplyD2HPacket.COMMAND_EXTENDED_ID = 39;
1581
- class ScreenCaptureReplyD2HPacket extends HostBoundPacket {
1582
- }
1583
- ScreenCaptureReplyD2HPacket.COMMAND_ID = 86;
1584
- ScreenCaptureReplyD2HPacket.COMMAND_EXTENDED_ID = 40;
1585
- // export class UserProgramControlReplyD2HPacket extends HostBoundPacket {
1586
- // static COMMAND_ID = 86;
1587
- // static COMMAND_EXTENDED_ID = 41;
1588
- // }
1589
- class SendDashTouchReplyD2HPacket extends HostBoundPacket {
1590
- }
1591
- SendDashTouchReplyD2HPacket.COMMAND_ID = 86;
1592
- SendDashTouchReplyD2HPacket.COMMAND_EXTENDED_ID = 42;
1593
- class SelectDashReplyD2HPacket extends HostBoundPacket {
1594
- }
1595
- SelectDashReplyD2HPacket.COMMAND_ID = 86;
1596
- SelectDashReplyD2HPacket.COMMAND_EXTENDED_ID = 43;
1597
- class EnableDashReplyD2HPacket extends HostBoundPacket {
1598
- }
1599
- EnableDashReplyD2HPacket.COMMAND_ID = 86;
1600
- EnableDashReplyD2HPacket.COMMAND_EXTENDED_ID = 44;
1601
- class DisableDashReplyD2HPacket extends HostBoundPacket {
1602
- }
1603
- DisableDashReplyD2HPacket.COMMAND_ID = 86;
1604
- DisableDashReplyD2HPacket.COMMAND_EXTENDED_ID = 45;
1605
- class ReadKeyValueReplyD2HPacket extends HostBoundPacket {
1606
- constructor(data) {
1607
- super(data);
1608
- const dataView = PacketView.fromPacket(this);
1609
- this.value = dataView.nextVarNTBS(255);
1610
- }
1611
- }
1612
- ReadKeyValueReplyD2HPacket.COMMAND_ID = 86;
1613
- ReadKeyValueReplyD2HPacket.COMMAND_EXTENDED_ID = 46;
1614
- class WriteKeyValueReplyD2HPacket extends HostBoundPacket {
1615
- }
1616
- WriteKeyValueReplyD2HPacket.COMMAND_ID = 86;
1617
- WriteKeyValueReplyD2HPacket.COMMAND_EXTENDED_ID = 47;
1618
- class GetSlot1to4InfoReplyD2HPacket extends HostBoundPacket {
1619
- constructor(data, start = 1) {
1620
- super(data);
1621
- const dataView = PacketView.fromPacket(this);
1622
- this.slotFlags = dataView.nextUint8();
1623
- this.slots = [];
1624
- for (let i = 0; i < 4; i++) {
1625
- const hasData = (this.slotFlags & Math.pow(2, start - 1 + i)) !== 0;
1626
- if (!hasData)
1627
- continue;
1628
- const iconNum = dataView.nextUint16();
1629
- const nameLen = dataView.nextUint8();
1630
- const name = dataView.nextString(nameLen);
1631
- this.slots.push({
1632
- slot: start + i,
1633
- icon: iconNum,
1634
- name,
1635
- });
1636
- }
1637
- }
1638
- }
1639
- GetSlot1to4InfoReplyD2HPacket.COMMAND_ID = 86;
1640
- GetSlot1to4InfoReplyD2HPacket.COMMAND_EXTENDED_ID = 49;
1641
- class GetSlot5to8InfoReplyD2HPacket extends GetSlot1to4InfoReplyD2HPacket {
1642
- constructor(data) {
1643
- super(data, 5);
1644
- this.slotStartIndex = 5;
1645
- }
1646
- }
1647
- GetSlot5to8InfoReplyD2HPacket.COMMAND_ID = 86;
1648
- GetSlot5to8InfoReplyD2HPacket.COMMAND_EXTENDED_ID = 50;
1649
- class FactoryStatusReplyD2HPacket extends HostBoundPacket {
1650
- constructor(data) {
1651
- super(data);
1652
- const dataView = PacketView.fromPacket(this);
1653
- this.status = dataView.nextUint8();
1654
- this.percent = dataView.nextUint8();
1655
- }
1656
- }
1657
- FactoryStatusReplyD2HPacket.COMMAND_ID = 86;
1658
- FactoryStatusReplyD2HPacket.COMMAND_EXTENDED_ID = 241;
1659
- class FactoryEnableReplyD2HPacket extends HostBoundPacket {
1660
- }
1661
- FactoryEnableReplyD2HPacket.COMMAND_ID = 86;
1662
- FactoryEnableReplyD2HPacket.COMMAND_EXTENDED_ID = 255;
1663
-
1664
- const thePacketEncoder = PacketEncoder.getInstance();
1665
- /**
1666
- * A connection to a V5 device.
1667
- * Emit events: connected, disconnected
1668
- */
1669
- class VexSerialConnection extends VexEventTarget {
1670
- get isConnected() {
1671
- return (this.port !== undefined &&
1672
- this.reader !== undefined &&
1673
- this.writer !== undefined);
1674
- }
1675
- constructor(serial) {
1676
- super();
1677
- this.filters = [{ usbVendorId: 10376 }];
1678
- this.callbacksQueue = [];
1679
- this.serial = serial;
1680
- }
1681
- close() {
1682
- var _a, _b, _c;
1683
- return __awaiter(this, void 0, void 0, function* () {
1684
- if (!this.isConnected)
1685
- return;
1686
- try {
1687
- yield ((_a = this.writer) === null || _a === void 0 ? void 0 : _a.close());
1688
- this.writer = undefined;
1689
- }
1690
- catch (e) { }
1691
- try {
1692
- yield ((_b = this.reader) === null || _b === void 0 ? void 0 : _b.cancel());
1693
- try {
1694
- while (this.reader != null) {
1695
- const { done } = yield this.reader.read();
1696
- if (done)
1697
- break;
1698
- }
1699
- }
1700
- catch (e) { }
1701
- this.reader = undefined;
1702
- }
1703
- catch (e) { }
1704
- try {
1705
- yield new Promise((resolve) => setTimeout(resolve, 1)); // HACK: wait for the lock to be released
1706
- yield ((_c = this.port) === null || _c === void 0 ? void 0 : _c.close());
1707
- this.port = undefined;
1708
- }
1709
- catch (e) {
1710
- console.warn("Close port error.", e);
1711
- }
1712
- finally {
1713
- this.emit("disconnected", undefined);
1714
- }
1715
- });
1716
- }
1717
- open(use = 0, askUser = true) {
1718
- return __awaiter(this, void 0, void 0, function* () {
1719
- if (this.port !== undefined)
1720
- throw new Error("Already connected.");
1721
- let port;
1722
- if (use !== undefined) {
1723
- const ports = (yield this.serial.getPorts())
1724
- .filter((p) => {
1725
- const info = p.getInfo();
1726
- return this.filters.find((f) => (f.usbVendorId === undefined ||
1727
- f.usbVendorId === info.usbVendorId) &&
1728
- (f.usbProductId === undefined ||
1729
- f.usbProductId === info.usbProductId));
1730
- })
1731
- .filter((e) => e.readable !== null);
1732
- port = ports[use];
1733
- }
1734
- if (port == null && askUser) {
1735
- try {
1736
- port = yield this.serial.requestPort({ filters: this.filters });
1737
- }
1738
- catch (e) {
1739
- //console.warn("No valid port selected.");
1740
- }
1741
- }
1742
- if (port == null)
1743
- return undefined;
1744
- if (port.readable != null)
1745
- return false;
1746
- try {
1747
- yield port.open({ baudRate: 115200 });
1748
- this.port = port;
1749
- this.port.addEventListener("disconnect", () => {
1750
- void this.close();
1751
- });
1752
- this.emit("connected", undefined);
1753
- this.writer = this.port.writable.getWriter();
1754
- this.reader = this.port.readable.getReader();
1755
- void this.startReader();
1756
- return true;
1757
- }
1758
- catch (e) {
1759
- return false;
1760
- }
1761
- });
1762
- }
1763
- writeData(rawData, resolve, timeout = 1000) {
1764
- void this.writeDataAsync(rawData, timeout).then(resolve);
1765
- }
1766
- writeDataAsync(rawData, timeout = 1000) {
1767
- return __awaiter(this, void 0, void 0, function* () {
1768
- return yield new Promise((resolve) => {
1769
- if (this.writer === undefined) {
1770
- resolve(AckType.CDC2_NACK);
1771
- return;
1772
- }
1773
- const data = rawData instanceof DeviceBoundPacket ? rawData.data : rawData;
1774
- const cb = {
1775
- callback: resolve,
1776
- timeout: setTimeout(() => {
1777
- var _a;
1778
- (_a = this.callbacksQueue.shift()) === null || _a === void 0 ? void 0 : _a.callback(AckType.TIMEOUT);
1779
- }, timeout),
1780
- wantedCommandId: rawData instanceof DeviceBoundPacket
1781
- ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
1782
- rawData.constructor.COMMAND_ID
1783
- : undefined,
1784
- wantedCommandExId: rawData instanceof DeviceBoundPacket
1785
- ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
1786
- rawData.constructor.COMMAND_EXTENDED_ID
1787
- : undefined,
1788
- };
1789
- this.callbacksQueue.push(cb);
1790
- this.writer
1791
- .write(data)
1792
- .then(() => {
1793
- logData(data, 100);
1794
- })
1795
- .catch(() => {
1796
- this.callbacksQueue.splice(this.callbacksQueue.indexOf(cb), 1);
1797
- resolve(AckType.WRITE_ERROR);
1798
- });
1799
- });
1800
- });
1801
- }
1802
- readData(cache, expectedSize) {
1803
- return __awaiter(this, void 0, void 0, function* () {
1804
- if (this.reader == null)
1805
- throw new Error("No reader");
1806
- while (cache.byteLength < expectedSize) {
1807
- const { value: readData, done: isDone } = yield this.reader.read();
1808
- if (isDone)
1809
- throw new Error("No data");
1810
- cache = binaryArrayJoin(cache, readData);
1811
- }
1812
- return cache;
1813
- });
1814
- }
1815
- startReader() {
1816
- return __awaiter(this, void 0, void 0, function* () {
1817
- let cache = new Uint8Array([]);
1818
- let sliceIdx = 0;
1819
- for (;;)
1820
- try {
1821
- cache = yield this.readData(cache, 5);
1822
- sliceIdx = 0;
1823
- if (!thePacketEncoder.validateHeader(cache))
1824
- throw new Error("Invalid header");
1825
- const payloadExpectedSize = thePacketEncoder.getPayloadSize(cache);
1826
- const n = payloadExpectedSize > 128 ? 5 : 4;
1827
- const totalSize = n + payloadExpectedSize;
1828
- cache = yield this.readData(cache, totalSize);
1829
- sliceIdx = totalSize;
1830
- const cmdId = cache[2];
1831
- const hasExtId = cmdId === 88 || cmdId === 86;
1832
- const cmdExId = hasExtId ? cache[n] : undefined;
1833
- const ack = cache[n + 1];
1834
- if (hasExtId) {
1835
- if (!thePacketEncoder.validateMessageCdc(cache))
1836
- throw new Error("Invalid message CDC");
1837
- }
1838
- let callbackInfo;
1839
- let wantedCmdId;
1840
- let wantedCmdExId;
1841
- let tryIdx = 0;
1842
- while ((callbackInfo = this.callbacksQueue[tryIdx++]) !== null) {
1843
- wantedCmdId = callbackInfo === null || callbackInfo === void 0 ? void 0 : callbackInfo.wantedCommandId;
1844
- wantedCmdExId = callbackInfo === null || callbackInfo === void 0 ? void 0 : callbackInfo.wantedCommandExId;
1845
- if ((wantedCmdId !== undefined && wantedCmdId !== cmdId) ||
1846
- (wantedCmdExId !== undefined && wantedCmdExId !== cmdExId)) {
1847
- continue;
1848
- }
1849
- break;
1850
- }
1851
- if (callbackInfo === undefined) {
1852
- console.warn("Unexpected command", cmdId, cmdExId, ack);
1853
- // TODO: trigger event
1854
- continue;
1855
- }
1856
- const data = cache.slice(0, sliceIdx);
1857
- const PackageType = thePacketEncoder.allPacketsTable[wantedCmdId + " " + wantedCmdExId];
1858
- if ((wantedCmdId === undefined && wantedCmdExId === undefined) ||
1859
- PackageType === undefined) {
1860
- callbackInfo.callback(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength));
1861
- }
1862
- else {
1863
- if (!hasExtId || PackageType.isValidPacket(data, n)) {
1864
- callbackInfo.callback(new PackageType(data));
1865
- }
1866
- else {
1867
- console.warn("ack", ack);
1868
- callbackInfo.callback(ack);
1869
- }
1870
- }
1871
- clearTimeout(callbackInfo.timeout);
1872
- this.callbacksQueue.splice(tryIdx - 1, 1);
1873
- }
1874
- catch (e) {
1875
- if (!(e instanceof Error && e.message === "No data")) {
1876
- console.warn("Read error.", e, cache);
1877
- }
1878
- yield this.close();
1879
- break;
1880
- }
1881
- finally {
1882
- cache = cache.slice(sliceIdx);
1883
- }
1884
- });
1885
- }
1886
- query1() {
1887
- return __awaiter(this, void 0, void 0, function* () {
1888
- const result = yield this.writeDataAsync(new Query1H2DPacket(), 100);
1889
- return result instanceof Query1ReplyD2HPacket ? result : null;
1890
- });
1891
- }
1892
- getSystemVersion() {
1893
- return __awaiter(this, void 0, void 0, function* () {
1894
- const result = yield this.writeDataAsync(new SystemVersionH2DPacket());
1895
- return result instanceof SystemVersionReplyD2HPacket
1896
- ? result.version
1897
- : null;
1898
- });
1899
- }
1900
- }
1901
- class V5SerialConnection extends VexSerialConnection {
1902
- constructor() {
1903
- super(...arguments);
1904
- this.filters = [
1905
- { usbVendorId: 10376, usbProductId: SerialDeviceType.V5_BRAIN },
1906
- { usbVendorId: 10376, usbProductId: SerialDeviceType.V5_BRAIN_DFU },
1907
- { usbVendorId: 10376, usbProductId: SerialDeviceType.V5_CONTROLLER },
1908
- ];
1909
- }
1910
- getDeviceStatus() {
1911
- return __awaiter(this, void 0, void 0, function* () {
1912
- const result = yield this.writeDataAsync(new GetDeviceStatusH2DPacket());
1913
- return result instanceof GetDeviceStatusReplyD2HPacket ? result : null;
1914
- });
1915
- }
1916
- getRadioStatus() {
1917
- return __awaiter(this, void 0, void 0, function* () {
1918
- const result = yield this.writeDataAsync(new GetRadioStatusH2DPacket());
1919
- return result instanceof GetRadioStatusReplyD2HPacket ? result : null;
1920
- });
1921
- }
1922
- getSystemFlags() {
1923
- return __awaiter(this, void 0, void 0, function* () {
1924
- const result = yield this.writeDataAsync(new GetSystemFlagsH2DPacket());
1925
- return result instanceof GetSystemFlagsReplyD2HPacket ? result : null;
1926
- });
1927
- }
1928
- getSystemStatus(timeout = 1000) {
1929
- return __awaiter(this, void 0, void 0, function* () {
1930
- const result = yield this.writeDataAsync(new GetSystemStatusH2DPacket(), timeout);
1931
- return result instanceof GetSystemStatusReplyD2HPacket ? result : null;
1932
- });
1933
- }
1934
- getMatchStatus() {
1935
- return __awaiter(this, void 0, void 0, function* () {
1936
- const result = yield this.writeDataAsync(new GetMatchStatusH2DPacket());
1937
- return result instanceof MatchStatusReplyD2HPacket ? result : null;
1938
- });
1939
- }
1940
- uploadProgramToDevice(iniConfig, binFileBuf, coldFileBuf, progressCallback) {
1941
- return __awaiter(this, void 0, void 0, function* () {
1942
- const iniFileBuffer = new TextEncoder().encode(iniConfig.createIni());
1943
- const basename = iniConfig.baseName;
1944
- const iniRequest = {
1945
- filename: basename + ".ini",
1946
- buf: iniFileBuffer,
1947
- downloadTarget: FileDownloadTarget.FILE_TARGET_QSPI,
1948
- vendor: FileVendor.USER,
1949
- autoRun: false,
1950
- };
1951
- const r1 = yield this.uploadFileToDevice(iniRequest, (current, total) => {
1952
- progressCallback("INI", current, total);
1953
- });
1954
- if (!r1)
1955
- return false;
1956
- // let prjRequest = { filename: basename + '.prj', buf: prjfile, vid: FileVendor.USER, loadAddr: undefined, exttype: 0, linkedFile: undefined };
1957
- // await this.uploadFileToDeviceAsync(prjRequest, onProgress);
1958
- const coldRequest = coldFileBuf !== undefined
1959
- ? {
1960
- filename: basename + "_lib.bin",
1961
- buf: coldFileBuf,
1962
- downloadTarget: FileDownloadTarget.FILE_TARGET_QSPI,
1963
- vendor: FileVendor.DEV2,
1964
- autoRun: false,
1965
- }
1966
- : undefined;
1967
- if (coldRequest != null) {
1968
- const r2 = yield this.uploadFileToDevice(coldRequest, (current, total) => {
1969
- progressCallback("COLD", current, total);
1970
- });
1971
- if (!r2)
1972
- return;
1973
- }
1974
- const binRequest = {
1975
- filename: basename + ".bin",
1976
- buf: binFileBuf,
1977
- downloadTarget: FileDownloadTarget.FILE_TARGET_QSPI,
1978
- vendor: FileVendor.USER,
1979
- loadAddress: coldFileBuf != null ? 0x07800000 : undefined,
1980
- autoRun: iniConfig.autorun,
1981
- linkedFile: coldRequest,
1982
- };
1983
- const r3 = yield this.uploadFileToDevice(binRequest, (current, total) => {
1984
- progressCallback("BIN", current, total);
1985
- });
1986
- return r3;
1987
- });
1988
- }
1989
- downloadFileToHost(request, downloadTarget = FileDownloadTarget.FILE_TARGET_QSPI, progressCallback) {
1990
- return __awaiter(this, void 0, void 0, function* () {
1991
- // TODO assert that the device is connected
1992
- const { filename, vendor, loadAddress, size } = request;
1993
- let nextAddress = loadAddress !== null && loadAddress !== void 0 ? loadAddress : USER_FLASH_USR_CODE_START;
1994
- const p1 = yield this.writeDataAsync(new InitFileTransferH2DPacket(FileInitAction.READ, downloadTarget, vendor, FileInitOption.NONE, new Uint8Array(), nextAddress, filename, ""));
1995
- if (!(p1 instanceof InitFileTransferReplyD2HPacket))
1996
- throw new Error("InitFileTransferH2DPacket failed");
1997
- const fileSize = size !== null && size !== void 0 ? size : p1.fileSize;
1998
- // console.log("size:", fileSize);
1999
- const bufferChunkSize = p1.windowSize > 0 && p1.windowSize <= USER_PROG_CHUNK_SIZE
2000
- ? p1.windowSize
2001
- : USER_PROG_CHUNK_SIZE;
2002
- let bufferOffset = 0;
2003
- let fileBuf = new Uint8Array(fileSize + bufferChunkSize);
2004
- let lastBlock = false;
2005
- while (!lastBlock) {
2006
- if (fileSize <= bufferOffset + bufferChunkSize) {
2007
- lastBlock = true;
2008
- }
2009
- const p2 = yield this.writeDataAsync(new ReadFileH2DPacket(nextAddress, bufferChunkSize), 3000);
2010
- if (!(p2 instanceof ReadFileReplyD2HPacket))
2011
- throw new Error("ReadFileReplyD2HPacket failed");
2012
- fileBuf.set(new Uint8Array(p2.buf), bufferOffset);
2013
- if (progressCallback != null)
2014
- progressCallback(bufferOffset, fileSize);
2015
- // next chunk
2016
- bufferOffset += bufferChunkSize;
2017
- nextAddress += bufferChunkSize;
2018
- }
2019
- yield this.writeDataAsync(new ExitFileTransferH2DPacket(FileExitAction.EXIT_HALT), 30000);
2020
- // console.log(p3);
2021
- fileBuf = fileBuf.slice(0, fileSize);
2022
- return fileBuf;
2023
- });
2024
- }
2025
- uploadFileToDevice(request, progressCallback) {
2026
- var _a;
2027
- return __awaiter(this, void 0, void 0, function* () {
2028
- let { filename, buf, downloadTarget, vendor, loadAddress, exttype, autoRun, linkedFile, } = request;
2029
- if (buf === undefined) {
2030
- // TODO: check connection status
2031
- return false;
2032
- }
2033
- // no download to special capture or vision buffers
2034
- // if (this.downloadTarget === VexDeviceWebSerial.FILE_TARGET_CBUF || this.downloadTarget === VexDeviceWebSerial.FILE_TARGET_VBUF) {
2035
- // // error !
2036
- // if (doneCallback != undefined) {
2037
- // doneCallback(false);
2038
- // }
2039
- // return;
2040
- // }
2041
- downloadTarget = downloadTarget !== null && downloadTarget !== void 0 ? downloadTarget : FileDownloadTarget.FILE_TARGET_QSPI;
2042
- vendor = vendor !== null && vendor !== void 0 ? vendor : FileVendor.USER;
2043
- let nextAddress = loadAddress !== null && loadAddress !== void 0 ? loadAddress : USER_FLASH_USR_CODE_START;
2044
- // TODO if downloadTarget is FILE_TARGET_A1, FactoryEnable
2045
- //console.log("init file transfer", filename);
2046
- const p1 = yield this.writeDataAsync(new InitFileTransferH2DPacket(FileInitAction.WRITE, downloadTarget, vendor, FileInitOption.OVERWRITE, buf, nextAddress, filename, exttype));
2047
- if (!(p1 instanceof InitFileTransferReplyD2HPacket))
2048
- throw new Error("InitFileTransferH2DPacket failed");
2049
- //console.log(p1);
2050
- if (linkedFile !== undefined) {
2051
- const p3 = yield this.writeDataAsync(new LinkFileH2DPacket((_a = linkedFile.vendor) !== null && _a !== void 0 ? _a : FileVendor.USER, linkedFile.filename, 0), 10000);
2052
- if (!(p3 instanceof LinkFileReplyD2HPacket))
2053
- throw new Error("LinkFileH2DPacket failed");
2054
- }
2055
- const bufferChunkSize = p1.windowSize > 0 && p1.windowSize <= USER_PROG_CHUNK_SIZE
2056
- ? p1.windowSize
2057
- : USER_PROG_CHUNK_SIZE;
2058
- let bufferOffset = 0;
2059
- let lastBlock = false;
2060
- let transferFailed = true;
2061
- let exitReply;
2062
- try {
2063
- while (!lastBlock) {
2064
- let tmpbuf;
2065
- if (buf.byteLength - bufferOffset > bufferChunkSize) {
2066
- tmpbuf = buf.subarray(bufferOffset, bufferOffset + bufferChunkSize);
2067
- }
2068
- else {
2069
- // last chunk
2070
- // word align length
2071
- const length = ((buf.byteLength - bufferOffset + 3) / 4) >>> 0;
2072
- tmpbuf = new Uint8Array(length * 4);
2073
- tmpbuf.set(buf.subarray(bufferOffset, buf.byteLength));
2074
- lastBlock = true;
2075
- }
2076
- const p2 = yield this.writeDataAsync(new WriteFileH2DPacket(nextAddress, tmpbuf), 3000);
2077
- if (!(p2 instanceof WriteFileReplyD2HPacket))
2078
- throw new Error("WriteFileReplyD2HPacket failed");
2079
- if (progressCallback != null)
2080
- progressCallback(bufferOffset, buf.byteLength);
2081
- // next chunk
2082
- bufferOffset += bufferChunkSize;
2083
- nextAddress += bufferChunkSize;
2084
- }
2085
- progressCallback === null || progressCallback === void 0 ? void 0 : progressCallback(buf.byteLength, buf.byteLength);
2086
- transferFailed = false;
2087
- }
2088
- finally {
2089
- exitReply = yield this.writeDataAsync(new ExitFileTransferH2DPacket(transferFailed
2090
- ? FileExitAction.EXIT_HALT
2091
- : autoRun
2092
- ? FileExitAction.EXIT_RUN
2093
- : FileExitAction.EXIT_HALT), 30000);
2094
- }
2095
- return exitReply instanceof ExitFileTransferReplyD2HPacket;
2096
- });
2097
- }
2098
- setMatchMode(mode) {
2099
- return __awaiter(this, void 0, void 0, function* () {
2100
- const result = yield this.writeDataAsync(new UpdateMatchModeH2DPacket(mode, 0));
2101
- return result instanceof MatchModeReplyD2HPacket ? result : null;
2102
- });
2103
- }
2104
- loadProgram(value) {
2105
- return __awaiter(this, void 0, void 0, function* () {
2106
- const result = yield this.writeDataAsync(new LoadFileActionH2DPacket(FileVendor.USER, FileLoadAction.RUN, value));
2107
- return result instanceof LoadFileActionReplyD2HPacket ? result : null;
2108
- });
2109
- }
2110
- stopProgram() {
2111
- return __awaiter(this, void 0, void 0, function* () {
2112
- const result = yield this.writeDataAsync(new LoadFileActionH2DPacket(FileVendor.USER, FileLoadAction.STOP, ""));
2113
- return result instanceof LoadFileActionReplyD2HPacket ? result : null;
2114
- });
2115
- }
2116
- mockTouch(x, y, press) {
2117
- return __awaiter(this, void 0, void 0, function* () {
2118
- const result = yield this.writeDataAsync(new SendDashTouchH2DPacket(x, y, press));
2119
- return result instanceof SendDashTouchReplyD2HPacket ? result : null;
2120
- });
2121
- }
2122
- /** @param port untested */
2123
- openScreen(screen, port) {
2124
- return __awaiter(this, void 0, void 0, function* () {
2125
- const result = yield this.writeDataAsync(new SelectDashH2DPacket(screen, port));
2126
- return result instanceof SendDashTouchReplyD2HPacket ? result : null;
2127
- });
2128
- }
2129
- }
2130
- function logData(data, limitedSize) {
2131
- if (data === undefined)
2132
- return;
2133
- limitedSize || (limitedSize = data.length);
2134
- let a = "";
2135
- for (let n = 0; n < data.length && n < limitedSize; n++)
2136
- a += ("00" + data[n].toString(16)).substr(-2, 2) + " ";
2137
- limitedSize < data.length && (a += " ... ");
2138
- // console.log(a);
2139
- // XXX: NOT USED?
2140
- }
2141
- function binaryArrayJoin(left, right) {
2142
- const leftSize = left != null ? left.byteLength : 0;
2143
- const rightSize = right != null ? right.byteLength : 0;
2144
- const all = new Uint8Array(leftSize + rightSize);
2145
- return all.length === 0
2146
- ? new Uint8Array()
2147
- : (left != null && all.set(new Uint8Array(left), 0),
2148
- right != null && all.set(new Uint8Array(right), leftSize),
2149
- all);
2150
- }
2151
-
2152
- function downloadFileFromInternet(link) {
2153
- return __awaiter(this, void 0, void 0, function* () {
2154
- return yield new Promise((resolve, reject) => {
2155
- const oReq = new XMLHttpRequest();
2156
- oReq.open("GET", link, true);
2157
- oReq.responseType = "arraybuffer";
2158
- oReq.onload = function (_oEvent) {
2159
- const arrayBuffer = oReq.response; // Note: not oReq.responseText
2160
- resolve(arrayBuffer);
2161
- };
2162
- oReq.onerror = function (oEvent) {
2163
- reject(oEvent);
2164
- };
2165
- oReq.send(null);
2166
- });
2167
- });
2168
- }
2169
- function sleepUntilAsync(f, timeout, interval = 20) {
2170
- return __awaiter(this, void 0, void 0, function* () {
2171
- return yield new Promise((resolve) => {
2172
- let lastTime = new Date().getTime();
2173
- let stopped = false;
2174
- const stopper = setTimeout(() => {
2175
- stopped = true;
2176
- resolve(false);
2177
- }, timeout);
2178
- const checker = (val) => {
2179
- if (stopped)
2180
- return;
2181
- if (val) {
2182
- clearTimeout(stopper);
2183
- resolve(true);
2184
- }
2185
- else if (new Date().getTime() - lastTime > interval) {
2186
- lastTime = new Date().getTime();
2187
- void f().then(checker);
2188
- }
2189
- else
2190
- setTimeout(() => {
2191
- lastTime = new Date().getTime();
2192
- void f().then(checker);
2193
- }, new Date().getTime() - lastTime);
2194
- };
2195
- void f().then(checker);
2196
- });
2197
- });
2198
- }
2199
- function sleepUntil(f, timeout, interval = 20) {
2200
- return __awaiter(this, void 0, void 0, function* () {
2201
- return yield new Promise((resolve) => {
2202
- const timeWas = new Date().getTime();
2203
- const wait = setInterval(function () {
2204
- if (f()) {
2205
- clearInterval(wait);
2206
- resolve(true);
2207
- }
2208
- else if (new Date().getTime() - timeWas > timeout) {
2209
- // Timeout
2210
- clearInterval(wait);
2211
- resolve(false);
2212
- }
2213
- }, interval);
2214
- });
2215
- });
2216
- }
2217
- function sleep(ms) {
2218
- return __awaiter(this, void 0, void 0, function* () {
2219
- return yield new Promise((resolve) => setTimeout(resolve, ms));
2220
- });
2221
- }
2222
- class VexSerialDevice extends VexEventTarget {
2223
- get isConnected() {
2224
- return this.connection != null ? this.connection.isConnected : false;
2225
- }
2226
- get deviceType() {
2227
- var _a, _b;
2228
- return this.isConnected
2229
- ? (_b = (_a = this.connection) === null || _a === void 0 ? void 0 : _a.port) === null || _b === void 0 ? void 0 : _b.getInfo().usbProductId
2230
- : undefined;
2231
- }
2232
- constructor(defaultSerial) {
2233
- super();
2234
- this.defaultSerial = defaultSerial;
2235
- }
2236
- }
2237
- class V5SerialDeviceState {
2238
- constructor(instance) {
2239
- this._isFileTransferring = false;
2240
- this.brain = {
2241
- activeProgram: 0,
2242
- battery: {
2243
- batteryPercent: 0,
2244
- isCharging: false,
2245
- },
2246
- button: {
2247
- isPressed: false,
2248
- isDoublePressed: false,
2249
- },
2250
- cpu0Version: VexFirmwareVersion.allZero(),
2251
- cpu1Version: VexFirmwareVersion.allZero(),
2252
- isAvailable: false,
2253
- settings: {
2254
- isScreenReversed: false,
2255
- isWhiteTheme: false,
2256
- usingLanguage: 0,
2257
- },
2258
- systemVersion: VexFirmwareVersion.allZero(),
2259
- uniqueId: 0,
2260
- };
2261
- this.controllers = [
2262
- {
2263
- battery: 0,
2264
- isAvailable: false,
2265
- isCharging: false,
2266
- },
2267
- {
2268
- battery: 0,
2269
- isAvailable: false,
2270
- },
2271
- ];
2272
- this.devices = [];
2273
- this.isFieldControllerConnected = false;
2274
- this.matchMode = "disabled";
2275
- this.radio = {
2276
- channel: 0,
2277
- isAvailable: false,
2278
- isConnected: false,
2279
- isVexNet: false,
2280
- isRadioData: false,
2281
- latency: 0,
2282
- signalQuality: 0,
2283
- signalStrength: 0,
2284
- };
2285
- this._instance = instance;
2286
- }
2287
- }
2288
- class V5Brain {
2289
- constructor(state) {
2290
- this.state = state;
2291
- }
2292
- get isRunningProgram() {
2293
- return this.activeProgram !== 0;
2294
- }
2295
- get activeProgram() {
2296
- return this.state.brain.activeProgram;
2297
- }
2298
- set activeProgram(value) {
2299
- void (() => __awaiter(this, void 0, void 0, function* () {
2300
- if (this.state.brain.activeProgram === value)
2301
- return;
2302
- const conn = this.state._instance.connection;
2303
- if (conn == null)
2304
- return;
2305
- const fn = value === 0
2306
- ? yield conn.stopProgram()
2307
- : yield conn.loadProgram(value);
2308
- if (fn != null)
2309
- this.state.brain.activeProgram = value;
2310
- }))();
2311
- }
2312
- get battery() {
2313
- return new V5Battery(this.state);
2314
- }
2315
- get button() {
2316
- return new V5BrainButton(this.state);
2317
- }
2318
- get cpu0Version() {
2319
- return this.state.brain.cpu0Version;
2320
- }
2321
- get cpu1Version() {
2322
- return this.state.brain.cpu1Version;
2323
- }
2324
- get isAvailable() {
2325
- return this.state.brain.isAvailable;
2326
- }
2327
- get settings() {
2328
- return new V5BrainSettings(this.state);
2329
- }
2330
- get systemVersion() {
2331
- return this.state.brain.systemVersion;
2332
- }
2333
- get uniqueId() {
2334
- return this.state.brain.uniqueId;
2335
- }
2336
- getValue(key) {
2337
- var _a;
2338
- return __awaiter(this, void 0, void 0, function* () {
2339
- const result = yield ((_a = this.state._instance.connection) === null || _a === void 0 ? void 0 : _a.writeDataAsync(new ReadKeyValueH2DPacket(key)));
2340
- return result instanceof ReadKeyValueReplyD2HPacket
2341
- ? result.value
2342
- : undefined;
2343
- });
2344
- }
2345
- setValue(key, value) {
2346
- var _a;
2347
- return __awaiter(this, void 0, void 0, function* () {
2348
- const result = yield ((_a = this.state._instance.connection) === null || _a === void 0 ? void 0 : _a.writeDataAsync(new WriteKeyValueH2DPacket(key, value)));
2349
- return result instanceof WriteKeyValueReplyD2HPacket;
2350
- });
2351
- }
2352
- listFiles(vendor = FileVendor.USER) {
2353
- return __awaiter(this, void 0, void 0, function* () {
2354
- const conn = this.state._instance.connection;
2355
- if (conn == null || !conn.isConnected)
2356
- return;
2357
- const result = yield conn.writeDataAsync(new GetDirectoryFileCountH2DPacket(vendor));
2358
- if (!(result instanceof GetDirectoryFileCountReplyD2HPacket))
2359
- return;
2360
- const files = [];
2361
- for (let i = 0; i < result.count; i++) {
2362
- const result2 = yield conn.writeDataAsync(new GetDirectoryEntryH2DPacket(i));
2363
- if (!(result2 instanceof GetDirectoryEntryReplyD2HPacket))
2364
- return;
2365
- // .file is undefined if the file is not found
2366
- // .file is a file entry but not a file handle
2367
- if (result2.file != null) {
2368
- files.push({
2369
- filename: result2.file.filename,
2370
- vendor,
2371
- loadAddress: result2.file.loadAddress,
2372
- size: result2.file.size,
2373
- crc32: result2.file.crc32,
2374
- type: result2.file.type,
2375
- timestamp: result2.file.timestamp,
2376
- version: result2.file.version,
2377
- });
2378
- }
2379
- }
2380
- return files;
2381
- });
2382
- }
2383
- listProgram() {
2384
- var _a, _b;
2385
- return __awaiter(this, void 0, void 0, function* () {
2386
- const conn = this.state._instance.connection;
2387
- if (conn == null || !conn.isConnected)
2388
- return;
2389
- const files = yield this.listFiles(FileVendor.USER);
2390
- if (files === undefined)
2391
- return;
2392
- const programList = [];
2393
- const iniFiles = files.filter((file) => { var _a; return (_a = (file === null || file === void 0 ? void 0 : file.filename.search(/.ini$/)) > 0) !== null && _a !== void 0 ? _a : false; });
2394
- for (let i = 0; i < iniFiles.length; i++) {
2395
- const ini = iniFiles[i];
2396
- if (ini.size === 0)
2397
- continue;
2398
- const programName = (_b = (_a = /(.+?)(\.[^.]*$|$)/.exec(ini.filename)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : "";
2399
- const bin = files.filter((e) => e != null && e.filename === programName + ".bin")[0];
2400
- if (bin == null || bin.timestamp === 0 || bin.size === 0)
2401
- continue;
2402
- const n = new Date();
2403
- n.setTime(1000 * bin.timestamp);
2404
- const program = {
2405
- name: programName,
2406
- binfile: bin.filename,
2407
- size: ini.size + bin.size,
2408
- slot: -1,
2409
- time: n,
2410
- requestedSlot: -1,
2411
- };
2412
- const result2 = yield (conn === null || conn === void 0 ? void 0 : conn.writeDataAsync(new GetProgramSlotInfoH2DPacket(FileVendor.USER, program.binfile)));
2413
- if (result2 instanceof GetProgramSlotInfoReplyD2HPacket) {
2414
- program.slot = result2.slot;
2415
- program.requestedSlot = result2.requestedSlot;
2416
- }
2417
- programList.push(program);
2418
- }
2419
- return programList;
2420
- });
2421
- }
2422
- readFile(request, downloadTarget = FileDownloadTarget.FILE_TARGET_QSPI, progressCallback) {
2423
- return __awaiter(this, void 0, void 0, function* () {
2424
- const conn = this.state._instance.connection;
2425
- if (conn == null || !conn.isConnected)
2426
- return;
2427
- this.state._isFileTransferring = true;
2428
- let handle;
2429
- // If request is a string, then it is a filename
2430
- if (typeof request === "string") {
2431
- handle = { filename: request, vendor: FileVendor.USER };
2432
- }
2433
- else {
2434
- handle = request;
2435
- }
2436
- try {
2437
- return yield conn.downloadFileToHost(handle, downloadTarget, progressCallback);
2438
- }
2439
- catch (e) {
2440
- this.state._isFileTransferring = false;
2441
- throw e;
2442
- }
2443
- });
2444
- }
2445
- removeFile(request) {
2446
- return __awaiter(this, void 0, void 0, function* () {
2447
- const conn = this.state._instance.connection;
2448
- if (conn == null || !conn.isConnected)
2449
- return;
2450
- let vendor, filename;
2451
- // If request is a string, then it is a filename
2452
- if (typeof request === "string") {
2453
- vendor = FileVendor.USER;
2454
- filename = request;
2455
- }
2456
- else {
2457
- vendor = request.vendor;
2458
- filename = request.filename;
2459
- }
2460
- const result = yield conn.writeDataAsync(new EraseFileH2DPacket(vendor, filename));
2461
- const result2 = yield conn.writeDataAsync(new ExitFileTransferH2DPacket(FileExitAction.EXIT_HALT));
2462
- if (!(result instanceof EraseFileReplyD2HPacket))
2463
- return false;
2464
- if (!(result2 instanceof ExitFileTransferReplyD2HPacket))
2465
- return false;
2466
- return true;
2467
- });
2468
- }
2469
- removeAllFiles() {
2470
- return __awaiter(this, void 0, void 0, function* () {
2471
- const conn = this.state._instance.connection;
2472
- if (conn == null || !conn.isConnected)
2473
- return undefined;
2474
- const result = yield conn.writeDataAsync(new FileClearUpH2DPacket(FileVendor.USER), 30000);
2475
- return result instanceof FileClearUpReplyD2HPacket;
2476
- });
2477
- }
2478
- uploadFirmware(publicUrl = "https://content.vexrobotics.com/vexos/public/V5/", usingVersion, progressCallback) {
2479
- return __awaiter(this, void 0, void 0, function* () {
2480
- const device = this.state._instance;
2481
- const conn = device.connection;
2482
- if (conn == null || !conn.isConnected)
2483
- return;
2484
- const pcb = progressCallback !== null && progressCallback !== void 0 ? progressCallback : (() => { });
2485
- let vexos, bootBin, assertBin;
2486
- try {
2487
- if (usingVersion === undefined) {
2488
- pcb("FETCH CATALOG", 0, 1);
2489
- const catalog = yield downloadFileFromInternet(publicUrl + "catalog.txt");
2490
- const latestVersion = new TextDecoder().decode(catalog);
2491
- usingVersion = latestVersion;
2492
- pcb("FETCH CATALOG", 1, 1);
2493
- console.log("fetched catalog.txt", latestVersion);
2494
- }
2495
- pcb("FETCH VEXOS", 0, 1);
2496
- vexos = yield downloadFileFromInternet(publicUrl + usingVersion + ".vexos");
2497
- pcb("FETCH VEXOS", 1, 1);
2498
- pcb("UNZIP VEXOS", 0, 1);
2499
- const { unzip } = yield Promise.resolve().then(function () { return unzipit_module; });
2500
- const { entries } = yield unzip(vexos);
2501
- bootBin = yield entries[usingVersion + "/BOOT.bin"].arrayBuffer();
2502
- assertBin = yield entries[usingVersion + "/assets.bin"].arrayBuffer();
2503
- pcb("UNZIP VEXOS", 1, 1);
2504
- }
2505
- catch (e) {
2506
- return undefined;
2507
- }
2508
- try {
2509
- this.state._isFileTransferring = true;
2510
- pcb("FACTORY ENB BOOT", 0, 0);
2511
- const result = yield conn.writeDataAsync(new FactoryEnableH2DPacket());
2512
- if (!(result instanceof FactoryEnableReplyD2HPacket))
2513
- return false;
2514
- const bootWriteRequest = {
2515
- filename: "null.bin",
2516
- vendor: FileVendor.USER,
2517
- loadAddress: USER_FLASH_USR_CODE_START,
2518
- buf: new Uint8Array(bootBin),
2519
- downloadTarget: FileDownloadTarget.FILE_TARGET_B1,
2520
- exttype: "bin",
2521
- autoRun: true,
2522
- linkedFile: undefined,
2523
- };
2524
- const result2 = yield conn.uploadFileToDevice(bootWriteRequest, (c, t) => {
2525
- pcb("UPLOAD BOOT", c, t);
2526
- });
2527
- if (!result2)
2528
- return false;
2529
- while (true) {
2530
- const result3 = yield conn.writeDataAsync(new FactoryStatusH2DPacket(), 10000);
2531
- if (result3 instanceof FactoryStatusReplyD2HPacket) {
2532
- switch (result3.status) {
2533
- case 2:
2534
- pcb("ERASE BOOT", result3.percent, 100);
2535
- break;
2536
- case 3:
2537
- pcb("WRITE BOOT", result3.percent, 100);
2538
- break;
2539
- case 4:
2540
- pcb("VERIFY BOOT", result3.percent, 100);
2541
- break;
2542
- case 8:
2543
- pcb("FINISHING BOOT", result3.percent, 100);
2544
- break;
2545
- }
2546
- if (result3.status === 0 && result3.percent === 100)
2547
- break;
2548
- }
2549
- else {
2550
- return false;
2551
- }
2552
- yield sleep(500);
2553
- }
2554
- pcb("FACTORY ENB ASSERT", 0, 0);
2555
- const result5 = yield conn.writeDataAsync(new FactoryEnableH2DPacket());
2556
- if (!(result5 instanceof FactoryEnableReplyD2HPacket))
2557
- return false;
2558
- const assertWriteRequest = {
2559
- filename: "null.bin",
2560
- vendor: FileVendor.USER,
2561
- loadAddress: USER_FLASH_USR_CODE_START,
2562
- buf: new Uint8Array(assertBin),
2563
- downloadTarget: FileDownloadTarget.FILE_TARGET_A1,
2564
- exttype: "bin",
2565
- autoRun: true,
2566
- linkedFile: undefined,
2567
- };
2568
- const result6 = yield conn.uploadFileToDevice(assertWriteRequest, (c, t) => {
2569
- pcb("UPLOAD ASSERT", c, t);
2570
- });
2571
- if (!result6)
2572
- return false;
2573
- while (true) {
2574
- const result7 = yield conn.writeDataAsync(new FactoryStatusH2DPacket(), 10000);
2575
- if (result7 instanceof FactoryStatusReplyD2HPacket) {
2576
- switch (result7.status) {
2577
- case 2:
2578
- pcb("ERASE ASSERT", result7.percent, 100);
2579
- break;
2580
- case 3:
2581
- pcb("WRITE ASSERT", result7.percent, 100);
2582
- break;
2583
- case 4:
2584
- pcb("VERIFY ASSERT", result7.percent, 100);
2585
- break;
2586
- case 8:
2587
- pcb("FINISHING ASSERT", result7.percent, 100);
2588
- break;
2589
- }
2590
- if (result7.status === 0 && result7.percent === 100)
2591
- break;
2592
- }
2593
- else {
2594
- return false;
2595
- }
2596
- yield sleep(500);
2597
- }
2598
- }
2599
- catch (e) {
2600
- this.state._isFileTransferring = false;
2601
- throw e;
2602
- }
2603
- return true;
2604
- });
2605
- }
2606
- uploadProgram(iniConfig, binFileBuf, coldFileBuf, progressCallback) {
2607
- return __awaiter(this, void 0, void 0, function* () {
2608
- const device = this.state._instance;
2609
- const conn = device.connection;
2610
- if (conn == null || !conn.isConnected)
2611
- return;
2612
- this.state._isFileTransferring = true;
2613
- try {
2614
- if (device.isV5Controller) {
2615
- yield sleep(250);
2616
- // V5 Controller doesn\'t appear to be connected to a V5 Brain
2617
- if (!(yield device.refresh()))
2618
- return;
2619
- console.log("Transferring to download channel");
2620
- const p1 = yield device.radio.changeChannel(RadioChannelType.DOWNLOAD);
2621
- if (!p1)
2622
- return false;
2623
- yield sleep(250);
2624
- yield sleepUntilAsync(() => __awaiter(this, void 0, void 0, function* () { return (yield (conn === null || conn === void 0 ? void 0 : conn.getSystemStatus(150))) != null; }), 10000, 200);
2625
- console.log("Transferred to download channel");
2626
- }
2627
- const p2 = yield conn.uploadProgramToDevice(iniConfig, binFileBuf, coldFileBuf, progressCallback);
2628
- if (!(p2 !== null && p2 !== void 0 ? p2 : false))
2629
- return false;
2630
- if (device.isV5Controller) {
2631
- // Disconnected
2632
- if (!device.brain.isAvailable)
2633
- return false;
2634
- console.log("Transferring back to pit channel");
2635
- const p3 = yield device.radio.changeChannel(RadioChannelType.PIT);
2636
- if (!p3)
2637
- return false;
2638
- yield sleep(250);
2639
- yield sleepUntilAsync(() => __awaiter(this, void 0, void 0, function* () { return (yield (conn === null || conn === void 0 ? void 0 : conn.getSystemStatus(150))) != null; }), 10000, 200);
2640
- console.log("All done");
2641
- }
2642
- return true;
2643
- }
2644
- catch (e) {
2645
- this.state._isFileTransferring = false;
2646
- throw e;
2647
- }
2648
- });
2649
- }
2650
- writeFile(request, progressCallback) {
2651
- return __awaiter(this, void 0, void 0, function* () {
2652
- this.state._isFileTransferring = true;
2653
- const conn = this.state._instance.connection;
2654
- if (conn == null || !conn.isConnected)
2655
- return undefined;
2656
- try {
2657
- return yield conn.uploadFileToDevice(request, progressCallback);
2658
- }
2659
- catch (e) {
2660
- this.state._isFileTransferring = false;
2661
- throw e;
2662
- }
2663
- });
2664
- }
2665
- /**
2666
- *
2667
- * @param progressCallback Informs the progress of the download.
2668
- * @returns array of bytes where each pixel is represented by 3 consecutive bytes (rgb).
2669
- * This array's length is 272 width * 480 height * 3 channels = 391680 bytes.
2670
- */
2671
- captureScreen(progressCallback) {
2672
- return __awaiter(this, void 0, void 0, function* () {
2673
- // pros implementation: https://github.com/purduesigbots/pros-cli/blob/5ee18656faeb48f51d680bab4b53d5b59cc5a7d5/pros/serial/devices/vex/v5_device.py#L578
2674
- const conn = this.state._instance.connection;
2675
- if (conn == null || !conn.isConnected)
2676
- return undefined;
2677
- yield new Promise((resolve) => {
2678
- conn.writeData(new ScreenCaptureH2DPacket(0), resolve);
2679
- });
2680
- const height = 272;
2681
- const width = 480;
2682
- const channels = 3;
2683
- const messageWidth = 512; // brain goofiness
2684
- const messageChannels = 4; // brain goofiness
2685
- let buf = yield (conn === null || conn === void 0 ? void 0 : conn.downloadFileToHost({
2686
- filename: "screen",
2687
- vendor: FileVendor.SYS,
2688
- loadAddress: 0,
2689
- size: messageWidth * height * messageChannels, // RGBA ig
2690
- }, FileDownloadTarget.FILE_TARGET_CBUF, progressCallback));
2691
- if (buf == null)
2692
- return;
2693
- buf = buf
2694
- // remove the extra columns
2695
- .filter((_byte, i) => i % (messageWidth * messageChannels) < width * messageChannels)
2696
- // remove the fake alpha channel
2697
- .filter((_byte, i) => (i + 1) % messageChannels !== 0);
2698
- // reverse the pixel (bgr -> rgb)
2699
- for (let i = 0; i < buf.length; i += channels) {
2700
- const px = buf.slice(i, i + channels).reverse();
2701
- for (let j = 0; j < px.length; j++) {
2702
- buf[i + j] = px[j];
2703
- }
2704
- }
2705
- return buf;
2706
- });
2707
- }
2708
- }
2709
- class V5Battery {
2710
- constructor(state) {
2711
- this.state = state;
2712
- }
2713
- get batteryPercent() {
2714
- return this.state.brain.battery.batteryPercent;
2715
- }
2716
- get isCharging() {
2717
- return this.state.brain.battery.isCharging;
2718
- }
2719
- }
2720
- class V5BrainButton {
2721
- constructor(state) {
2722
- this.state = state;
2723
- }
2724
- get isPressed() {
2725
- return this.state.brain.button.isPressed;
2726
- }
2727
- get isDoublePressed() {
2728
- return this.state.brain.button.isDoublePressed;
2729
- }
2730
- }
2731
- class V5BrainSettings {
2732
- constructor(state) {
2733
- this.state = state;
2734
- }
2735
- get isScreenReversed() {
2736
- return this.state.brain.settings.isScreenReversed;
2737
- }
2738
- get isWhiteTheme() {
2739
- return this.state.brain.settings.isWhiteTheme;
2740
- }
2741
- get usingLanguage() {
2742
- return this.state.brain.settings.usingLanguage;
2743
- }
2744
- }
2745
- class V5Controller {
2746
- constructor(state, controllerIndex) {
2747
- this.state = state;
2748
- this.controllerIndex = controllerIndex;
2749
- }
2750
- get batteryPercent() {
2751
- return this.state.controllers[this.controllerIndex].battery;
2752
- }
2753
- get isMasterController() {
2754
- return this.controllerIndex === 0;
2755
- }
2756
- get isAvailable() {
2757
- return this.state.controllers[this.controllerIndex].isAvailable;
2758
- }
2759
- get isCharging() {
2760
- return this.state.controllers[this.controllerIndex].isCharging;
2761
- }
2762
- }
2763
- class V5SmartDevice {
2764
- constructor(state, index) {
2765
- this.state = state;
2766
- this.deviceIndex = index;
2767
- }
2768
- getDeviceInfo() {
2769
- return this.state.devices[this.deviceIndex];
2770
- }
2771
- get isAvailable() {
2772
- return this.getDeviceInfo() !== undefined;
2773
- }
2774
- get port() {
2775
- return this.deviceIndex;
2776
- }
2777
- get type() {
2778
- var _a, _b;
2779
- return (_b = (_a = this.getDeviceInfo()) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : SmartDeviceType.EMPTY;
2780
- }
2781
- get version() {
2782
- var _a, _b;
2783
- return (_b = (_a = this.getDeviceInfo()) === null || _a === void 0 ? void 0 : _a.version) !== null && _b !== void 0 ? _b : 0;
2784
- }
2785
- }
2786
- class V5Radio {
2787
- constructor(state) {
2788
- this.state = state;
2789
- }
2790
- get channel() {
2791
- return this.state.radio.channel;
2792
- }
2793
- get isAvailable() {
2794
- return this.state.radio.isAvailable;
2795
- }
2796
- get isConnected() {
2797
- return this.state.radio.isConnected;
2798
- }
2799
- get isVexNet() {
2800
- return this.state.radio.isVexNet;
2801
- }
2802
- get isRadioData() {
2803
- return this.state.radio.isRadioData;
2804
- }
2805
- get latency() {
2806
- return this.state.radio.latency;
2807
- }
2808
- changeChannel(channel) {
2809
- var _a;
2810
- return __awaiter(this, void 0, void 0, function* () {
2811
- const result = yield ((_a = this.state._instance.connection) === null || _a === void 0 ? void 0 : _a.writeDataAsync(new FileControlH2DPacket(1, channel)));
2812
- return result instanceof FileControlReplyD2HPacket;
2813
- });
2814
- }
2815
- }
2816
- class V5SerialDevice extends VexSerialDevice {
2817
- constructor(defaultSerial) {
2818
- super(defaultSerial);
2819
- this.autoReconnect = true;
2820
- this.autoRefresh = true;
2821
- this.pauseRefreshOnFileTransfer = true;
2822
- this._isReconnecting = false;
2823
- this.state = new V5SerialDeviceState(this);
2824
- let isLastRefreshComplete = true;
2825
- this._refreshInterval = setInterval(() => {
2826
- if (this.autoRefresh && isLastRefreshComplete) {
2827
- if (!this.isConnected) {
2828
- this.state.brain.isAvailable = false;
2829
- return;
2830
- }
2831
- if (!this.pauseRefreshOnFileTransfer ||
2832
- !this.state._isFileTransferring) {
2833
- isLastRefreshComplete = false;
2834
- void this.refresh().finally(() => (isLastRefreshComplete = true));
2835
- }
2836
- }
2837
- }, 200);
2838
- }
2839
- get isV5Controller() {
2840
- return this.deviceType === SerialDeviceType.V5_CONTROLLER;
2841
- }
2842
- get brain() {
2843
- return new V5Brain(this.state);
2844
- }
2845
- get controllers() {
2846
- return [new V5Controller(this.state, 0), new V5Controller(this.state, 1)];
2847
- }
2848
- get devices() {
2849
- const rtn = [];
2850
- for (let i = 1; i <= this.state.devices.length; i++) {
2851
- if (this.state.devices[i] != null)
2852
- rtn.push(new V5SmartDevice(this.state, i));
2853
- }
2854
- return rtn;
2855
- }
2856
- get isFieldControllerConnected() {
2857
- return this.state.isFieldControllerConnected;
2858
- }
2859
- get matchMode() {
2860
- return this.state.matchMode;
2861
- }
2862
- set matchMode(value) {
2863
- void (() => __awaiter(this, void 0, void 0, function* () {
2864
- var _a;
2865
- if ((yield ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.setMatchMode(value))) != null)
2866
- this.state.matchMode = value;
2867
- }))();
2868
- }
2869
- get radio() {
2870
- return new V5Radio(this.state);
2871
- }
2872
- mockTouch(x, y, press) {
2873
- var _a;
2874
- return __awaiter(this, void 0, void 0, function* () {
2875
- return !((yield ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.mockTouch(x, y, press))) == null);
2876
- });
2877
- }
2878
- connect(conn) {
2879
- return __awaiter(this, void 0, void 0, function* () {
2880
- if (this.isConnected)
2881
- return true;
2882
- if (conn != null && !conn.isConnected) {
2883
- if ((yield conn.query1()) === null)
2884
- return false;
2885
- this.connection = conn;
2886
- }
2887
- else {
2888
- let tryIdx = 0;
2889
- while (true) {
2890
- const c = new V5SerialConnection(this.defaultSerial);
2891
- const result = yield c.open(tryIdx++, true);
2892
- if (result === undefined)
2893
- return false; // no port left
2894
- if (!result) {
2895
- // has been opened
2896
- yield c.close();
2897
- continue;
2898
- }
2899
- if ((yield c.query1()) === null) {
2900
- // no response
2901
- yield c.close();
2902
- continue;
2903
- }
2904
- this.connection = c;
2905
- break;
2906
- }
2907
- }
2908
- if (!this.isConnected)
2909
- return false;
2910
- yield this.doAfterConnect();
2911
- return true;
2912
- });
2913
- }
2914
- disconnect() {
2915
- var _a;
2916
- return __awaiter(this, void 0, void 0, function* () {
2917
- yield ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.close());
2918
- this.connection = undefined;
2919
- });
2920
- }
2921
- dispose() {
2922
- return __awaiter(this, void 0, void 0, function* () {
2923
- this.autoReconnect = false;
2924
- this.autoRefresh = false;
2925
- clearInterval(this._refreshInterval);
2926
- yield this.disconnect();
2927
- });
2928
- }
2929
- /**
2930
- * @param timeout defaults to 0. If timeout is 0, then it will attempt to reconnect forever
2931
- * @returns
2932
- */
2933
- reconnect(timeout = 0) {
2934
- return __awaiter(this, void 0, void 0, function* () {
2935
- if (this.isConnected)
2936
- return true;
2937
- if (timeout < 0)
2938
- return false;
2939
- const endTime = new Date().getTime() + timeout;
2940
- if (this._isReconnecting) {
2941
- let successBeforeTimeout;
2942
- do {
2943
- successBeforeTimeout = yield sleepUntil(() => !this._isReconnecting, timeout === 0 ? 1000 : timeout);
2944
- // eslint-disable-next-line no-unmodified-loop-condition
2945
- } while (timeout === 0 && !successBeforeTimeout);
2946
- if (this.isConnected)
2947
- return true;
2948
- if (!successBeforeTimeout)
2949
- return false;
2950
- }
2951
- this._isReconnecting = true;
2952
- // eslint-disable-next-line no-unmodified-loop-condition
2953
- while (timeout === 0 || new Date().getTime() < endTime) {
2954
- // console.log("try to reconnect");
2955
- let tryIdx = 0;
2956
- while (true) {
2957
- const c = new V5SerialConnection(this.defaultSerial);
2958
- const result = yield c.open(tryIdx++, false);
2959
- if (result === undefined)
2960
- break; // no port left
2961
- if (!result) {
2962
- // has been opened
2963
- yield c.close();
2964
- continue;
2965
- }
2966
- const result2 = yield c.getSystemStatus(200);
2967
- if (result2 === null) {
2968
- // no response
2969
- yield c.close();
2970
- continue;
2971
- }
2972
- if (this.brain.uniqueId !== 0 &&
2973
- result2.uniqueId !== this.brain.uniqueId) {
2974
- // uuid not match
2975
- yield c.close();
2976
- continue;
2977
- }
2978
- this.connection = c;
2979
- break;
2980
- }
2981
- if (this.isConnected)
2982
- break;
2983
- // try again every second or when the number of ports is different
2984
- const getPortCount = () => __awaiter(this, void 0, void 0, function* () { return (yield this.defaultSerial.getPorts()).length; });
2985
- const portsCount = yield getPortCount();
2986
- yield sleepUntilAsync(() => __awaiter(this, void 0, void 0, function* () { return (yield getPortCount()) !== portsCount; }), 1000);
2987
- }
2988
- this._isReconnecting = false;
2989
- if (!this.isConnected)
2990
- return false;
2991
- void this.doAfterConnect();
2992
- return true;
2993
- });
2994
- }
2995
- doAfterConnect() {
2996
- return __awaiter(this, void 0, void 0, function* () {
2997
- if (this.connection == null)
2998
- return;
2999
- //console.log("doAfterConnect");
3000
- this.connection.on("disconnected", (_data) => {
3001
- if (this.autoReconnect)
3002
- void this.reconnect();
3003
- });
3004
- yield this.refresh();
3005
- });
3006
- }
3007
- refresh() {
3008
- var _a, _b, _c, _d, _e, _f, _g;
3009
- return __awaiter(this, void 0, void 0, function* () {
3010
- const ssPacket = yield ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.getSystemStatus());
3011
- if (ssPacket == null) {
3012
- this.state.brain.isAvailable = false;
3013
- return false;
3014
- }
3015
- this.state.brain.cpu0Version = ssPacket.cpu0Version;
3016
- this.state.brain.cpu1Version = ssPacket.cpu1Version;
3017
- this.state.brain.systemVersion = ssPacket.systemVersion;
3018
- const flags2 = ssPacket.sysflags[2];
3019
- this.state.controllers[0].isCharging = (flags2 & 0b10000000) !== 0;
3020
- this.state.matchMode =
3021
- (flags2 & 0b00100000) !== 0
3022
- ? "disabled"
3023
- : (flags2 & 0b01000000) !== 0
3024
- ? "autonomous"
3025
- : "driver";
3026
- this.state.isFieldControllerConnected = (flags2 & 0b00010000) !== 0;
3027
- const flags4 = ssPacket.sysflags[4];
3028
- this.state.brain.settings.usingLanguage = (flags4 & 0b11110000) >> 4;
3029
- this.state.brain.settings.isWhiteTheme = (flags4 & 0b00000100) !== 0;
3030
- this.state.brain.settings.isScreenReversed = (flags4 & 0b00000001) === 0;
3031
- this.state.brain.uniqueId = ssPacket.uniqueId;
3032
- const sfPacket = yield ((_b = this.connection) === null || _b === void 0 ? void 0 : _b.getSystemFlags());
3033
- if (sfPacket == null)
3034
- return false;
3035
- const flags5 = sfPacket.flags; // Math.pow(2, 32 - i);
3036
- this.state.radio.isRadioData = (flags5 & Math.pow(2, 32 - 12)) !== 0;
3037
- this.state.brain.button.isDoublePressed =
3038
- (flags5 & Math.pow(2, 32 - 14)) !== 0;
3039
- this.state.brain.battery.isCharging = (flags5 & Math.pow(2, 32 - 15)) !== 0;
3040
- this.state.brain.button.isPressed = (flags5 & Math.pow(2, 32 - 17)) !== 0;
3041
- this.state.radio.isVexNet = (flags5 & Math.pow(2, 32 - 18)) !== 0;
3042
- this.state.controllers[1].isAvailable =
3043
- (flags5 & Math.pow(2, 32 - 19)) !== 0;
3044
- this.state.radio.isConnected = (flags5 & Math.pow(2, 32 - 22)) !== 0;
3045
- this.state.radio.isAvailable = (flags5 & Math.pow(2, 32 - 23)) !== 0;
3046
- this.state.brain.battery.batteryPercent = (_c = sfPacket.battery) !== null && _c !== void 0 ? _c : 0;
3047
- this.state.controllers[0].isAvailable =
3048
- this.state.radio.isConnected || this.state.controllers[0].isCharging;
3049
- this.state.controllers[0].battery = (_d = sfPacket.controllerBatteryPercent) !== null && _d !== void 0 ? _d : 0;
3050
- this.state.controllers[1].battery =
3051
- (_e = sfPacket.partnerControllerBatteryPercent) !== null && _e !== void 0 ? _e : 0;
3052
- this.state.brain.activeProgram = sfPacket.currentProgram;
3053
- this.state.brain.isAvailable =
3054
- !this.isV5Controller || this.state.radio.isConnected;
3055
- const rdPacket = yield ((_f = this.connection) === null || _f === void 0 ? void 0 : _f.getRadioStatus());
3056
- if (rdPacket == null)
3057
- return false;
3058
- this.state.radio.channel = rdPacket.channel;
3059
- this.state.radio.latency = rdPacket.timeslot;
3060
- this.state.radio.signalQuality = rdPacket.quality;
3061
- this.state.radio.signalStrength = rdPacket.strength;
3062
- const dsPacket = yield ((_g = this.connection) === null || _g === void 0 ? void 0 : _g.getDeviceStatus());
3063
- if (dsPacket == null)
3064
- return false;
3065
- let missingPorts = this.state.devices
3066
- .map((d) => d === null || d === void 0 ? void 0 : d.port)
3067
- .filter((p) => p !== undefined);
3068
- for (let i = 0; i < dsPacket.devices.length; i++) {
3069
- const device = dsPacket.devices[i];
3070
- this.state.devices[device.port] = device;
3071
- // remove device port from missing ports
3072
- missingPorts = missingPorts.filter((p) => p !== device.port);
3073
- }
3074
- missingPorts.forEach((port) => {
3075
- this.state.devices[port] = undefined;
3076
- });
3077
- return true;
3078
- });
3079
- }
3080
- }
3081
-
3082
- // hey this code seemed really goofy to me, so I changed it,
3083
- // see https://github.com/LemLib/v5-serial-protocol/blob/ef8df5019a5504b5b96fc887ef1587d9ecaa84ea/src/VexIniConfig.ts
3084
- // for unchanged code
3085
- // -@meisZWFLZ
3086
- class BaseIniBuilder {
3087
- constructor() {
3088
- this.str = "";
3089
- }
3090
- addLine(line) {
3091
- this.str += line + "\n";
3092
- }
3093
- addComment(comment) {
3094
- this.addLine("; " + comment);
3095
- return this;
3096
- }
3097
- getContent() {
3098
- return this.str;
3099
- }
3100
- }
3101
- class IniSectionBuilder extends BaseIniBuilder {
3102
- constructor(name, object, keyTransform = (k) => k.toString()) {
3103
- super();
3104
- this.name = name;
3105
- this.object = object;
3106
- this.keyTransform = keyTransform;
3107
- }
3108
- addSingleObjProperty(key, maxValueLength) {
3109
- // if property is empty or nullish, skip it
3110
- if (this.object[key] == null || this.object[key].toString().length === 0)
3111
- return;
3112
- const formattedKey = this.keyTransform(key).padEnd(12).slice(0, 12);
3113
- const trimmedVal = this.object[key].toString().slice(0, maxValueLength);
3114
- this.addLine(`${formattedKey} = "${trimmedVal}"`);
3115
- }
3116
- addObjProperty(key, maxValueLength) {
3117
- const keys = Array.isArray(key) ? key : [key];
3118
- for (const k of keys) {
3119
- this.addSingleObjProperty(k, maxValueLength);
3120
- }
3121
- return this;
3122
- }
3123
- addAllObjProps(maxValueLength) {
3124
- const keys = Object.keys(this.object);
3125
- for (const k of keys) {
3126
- this.addSingleObjProperty(k, maxValueLength);
3127
- }
3128
- return this;
3129
- }
3130
- }
3131
- class IniFileBuilder extends BaseIniBuilder {
3132
- addSection(section) {
3133
- this.addLine(`[${section.name}]`);
3134
- this.str += section.getContent();
3135
- return this;
3136
- }
3137
- }
3138
- class ProgramIniConfig {
3139
- // private options: { [key: string]: string } = {};
3140
- constructor() {
3141
- this.baseName = "slot_1";
3142
- this.autorun = false;
3143
- this.project = { version: "1", ide: "Unknown", file: "none" };
3144
- this.program = {
3145
- version: "1",
3146
- name: "program",
3147
- slot: 0,
3148
- icon: "default.bmp",
3149
- iconalt: "",
3150
- description: "",
3151
- date: "",
3152
- timezone: "0",
3153
- };
3154
- this.config = {}; // { port_22: "..." }
3155
- this.controller1 = {};
3156
- this.controller2 = {};
3157
- this.config = {
3158
- 22: "adi",
3159
- };
3160
- }
3161
- setProgramDate(date) {
3162
- const d = date;
3163
- this.program.date = d.toISOString();
3164
- const tzo = Math.abs(d.getTimezoneOffset());
3165
- const tzh = (tzo / 60) >>> 0;
3166
- const tzm = tzo - tzh * 60;
3167
- this.program.timezone =
3168
- (d.getTimezoneOffset() > 0 ? "-" : "+") +
3169
- this.dec2(tzh) +
3170
- ":" +
3171
- this.dec2(tzm);
3172
- }
3173
- createIni() {
3174
- if (this.program.date.length === 0) {
3175
- this.setProgramDate(new Date());
3176
- }
3177
- return new IniFileBuilder()
3178
- .addComment("")
3179
- .addComment("VEX program ini file")
3180
- .addComment("Generated by Vex V5 Serial Protocol Library")
3181
- .addComment("")
3182
- .addSection(new IniSectionBuilder("project", this.project).addObjProperty("ide", 16))
3183
- .addComment("")
3184
- .addSection(new IniSectionBuilder("program", this.program)
3185
- .addObjProperty("name", 32)
3186
- .addObjProperty("description", 256)
3187
- .addObjProperty("icon", 16)
3188
- .addObjProperty("iconalt", 16)
3189
- .addObjProperty("slot", 16))
3190
- .addComment("")
3191
- .addSection(new IniSectionBuilder("config", this.config, (k) => "port_" + this.dec2(k)).addAllObjProps())
3192
- .addComment("")
3193
- .addSection(new IniSectionBuilder("controller_1", this.controller1).addAllObjProps())
3194
- .addComment("")
3195
- .addSection(new IniSectionBuilder("controller_2", this.controller2).addAllObjProps())
3196
- .getContent();
3197
- }
3198
- dec2(value) {
3199
- const str = ("00" + value.toString(10)).substr(-2, 2);
3200
- return str.toUpperCase();
3201
- }
3202
- }
3203
-
3204
- /* unzipit@1.4.3, license MIT */
3205
- /* global SharedArrayBuffer, process */
3206
-
3207
- function readBlobAsArrayBuffer(blob) {
3208
- if (blob.arrayBuffer) {
3209
- return blob.arrayBuffer();
3210
- }
3211
- return new Promise((resolve, reject) => {
3212
- const reader = new FileReader();
3213
- reader.addEventListener('loadend', () => {
3214
- resolve(reader.result);
3215
- });
3216
- reader.addEventListener('error', reject);
3217
- reader.readAsArrayBuffer(blob);
3218
- });
3219
- }
3220
-
3221
- async function readBlobAsUint8Array(blob) {
3222
- const arrayBuffer = await readBlobAsArrayBuffer(blob);
3223
- return new Uint8Array(arrayBuffer);
3224
- }
3225
-
3226
- function isBlob(v) {
3227
- return typeof Blob !== 'undefined' && v instanceof Blob;
3228
- }
3229
-
3230
- function isSharedArrayBuffer(b) {
3231
- return typeof SharedArrayBuffer !== 'undefined' && b instanceof SharedArrayBuffer;
3232
- }
3233
-
3234
- const isNode =
3235
- (typeof process !== 'undefined') &&
3236
- process.versions &&
3237
- (typeof process.versions.node !== 'undefined') &&
3238
- (typeof process.versions.electron === 'undefined');
3239
-
3240
- function isTypedArraySameAsArrayBuffer(typedArray) {
3241
- return typedArray.byteOffset === 0 && typedArray.byteLength === typedArray.buffer.byteLength;
3242
- }
3243
-
3244
- class ArrayBufferReader {
3245
- constructor(arrayBufferOrView) {
3246
- this.typedArray = (arrayBufferOrView instanceof ArrayBuffer || isSharedArrayBuffer(arrayBufferOrView))
3247
- ? new Uint8Array(arrayBufferOrView)
3248
- : new Uint8Array(arrayBufferOrView.buffer, arrayBufferOrView.byteOffset, arrayBufferOrView.byteLength);
3249
- }
3250
- async getLength() {
3251
- return this.typedArray.byteLength;
3252
- }
3253
- async read(offset, length) {
3254
- return new Uint8Array(this.typedArray.buffer, this.typedArray.byteOffset + offset, length);
3255
- }
3256
- }
3257
-
3258
- class BlobReader {
3259
- constructor(blob) {
3260
- this.blob = blob;
3261
- }
3262
- async getLength() {
3263
- return this.blob.size;
3264
- }
3265
- async read(offset, length) {
3266
- const blob = this.blob.slice(offset, offset + length);
3267
- const arrayBuffer = await readBlobAsArrayBuffer(blob);
3268
- return new Uint8Array(arrayBuffer);
3269
- }
3270
- async sliceAsBlob(offset, length, type = '') {
3271
- return this.blob.slice(offset, offset + length, type);
3272
- }
3273
- }
3274
-
3275
- class HTTPRangeReader {
3276
- constructor(url) {
3277
- this.url = url;
3278
- }
3279
- async getLength() {
3280
- if (this.length === undefined) {
3281
- const req = await fetch(this.url, { method: 'HEAD' });
3282
- if (!req.ok) {
3283
- throw new Error(`failed http request ${this.url}, status: ${req.status}: ${req.statusText}`);
3284
- }
3285
- this.length = parseInt(req.headers.get('content-length'));
3286
- if (Number.isNaN(this.length)) {
3287
- throw Error('could not get length');
3288
- }
3289
- }
3290
- return this.length;
3291
- }
3292
- async read(offset, size) {
3293
- if (size === 0) {
3294
- return new Uint8Array(0);
3295
- }
3296
- const req = await fetch(this.url, {
3297
- headers: {
3298
- Range: `bytes=${offset}-${offset + size - 1}`,
3299
- },
3300
- });
3301
- if (!req.ok) {
3302
- throw new Error(`failed http request ${this.url}, status: ${req.status} offset: ${offset} size: ${size}: ${req.statusText}`);
3303
- }
3304
- const buffer = await req.arrayBuffer();
3305
- return new Uint8Array(buffer);
3306
- }
3307
- }
3308
-
3309
- function inflate(data, buf) {
3310
- var u8=Uint8Array;
3311
- if(data[0]==3 && data[1]==0) return (buf ? buf : new u8(0));
3312
- var bitsF = _bitsF, bitsE = _bitsE, decodeTiny = _decodeTiny, get17 = _get17;
3313
-
3314
- var noBuf = (buf==null);
3315
- if(noBuf) buf = new u8((data.length>>>2)<<3);
3316
-
3317
- var BFINAL=0, BTYPE=0, HLIT=0, HDIST=0, HCLEN=0, ML=0, MD=0;
3318
- var off = 0, pos = 0;
3319
- var lmap, dmap;
3320
-
3321
- while(BFINAL==0) {
3322
- BFINAL = bitsF(data, pos , 1);
3323
- BTYPE = bitsF(data, pos+1, 2); pos+=3;
3324
- //console.log(BFINAL, BTYPE);
3325
-
3326
- if(BTYPE==0) {
3327
- if((pos&7)!=0) pos+=8-(pos&7);
3328
- var p8 = (pos>>>3)+4, len = data[p8-4]|(data[p8-3]<<8); //console.log(len);//bitsF(data, pos, 16),
3329
- if(noBuf) buf=_check(buf, off+len);
3330
- buf.set(new u8(data.buffer, data.byteOffset+p8, len), off);
3331
- //for(var i=0; i<len; i++) buf[off+i] = data[p8+i];
3332
- //for(var i=0; i<len; i++) if(buf[off+i] != data[p8+i]) throw "e";
3333
- pos = ((p8+len)<<3); off+=len; continue;
3334
- }
3335
- if(noBuf) buf=_check(buf, off+(1<<17)); // really not enough in many cases (but PNG and ZIP provide buffer in advance)
3336
- if(BTYPE==1) { lmap = U.flmap; dmap = U.fdmap; ML = (1<<9)-1; MD = (1<<5)-1; }
3337
- if(BTYPE==2) {
3338
- HLIT = bitsE(data, pos , 5)+257;
3339
- HDIST = bitsE(data, pos+ 5, 5)+ 1;
3340
- HCLEN = bitsE(data, pos+10, 4)+ 4; pos+=14;
3341
- for(var i=0; i<38; i+=2) { U.itree[i]=0; U.itree[i+1]=0; }
3342
- var tl = 1;
3343
- for(var i=0; i<HCLEN; i++) { var l=bitsE(data, pos+i*3, 3); U.itree[(U.ordr[i]<<1)+1] = l; if(l>tl)tl=l; } pos+=3*HCLEN; //console.log(itree);
3344
- makeCodes(U.itree, tl);
3345
- codes2map(U.itree, tl, U.imap);
3346
-
3347
- lmap = U.lmap; dmap = U.dmap;
3348
-
3349
- pos = decodeTiny(U.imap, (1<<tl)-1, HLIT+HDIST, data, pos, U.ttree);
3350
- var mx0 = _copyOut(U.ttree, 0, HLIT , U.ltree); ML = (1<<mx0)-1;
3351
- var mx1 = _copyOut(U.ttree, HLIT, HDIST, U.dtree); MD = (1<<mx1)-1;
3352
-
3353
- //var ml = decodeTiny(U.imap, (1<<tl)-1, HLIT , data, pos, U.ltree); ML = (1<<(ml>>>24))-1; pos+=(ml&0xffffff);
3354
- makeCodes(U.ltree, mx0);
3355
- codes2map(U.ltree, mx0, lmap);
3356
-
3357
- //var md = decodeTiny(U.imap, (1<<tl)-1, HDIST, data, pos, U.dtree); MD = (1<<(md>>>24))-1; pos+=(md&0xffffff);
3358
- makeCodes(U.dtree, mx1);
3359
- codes2map(U.dtree, mx1, dmap);
3360
- }
3361
- //var ooff=off, opos=pos;
3362
- while(true) {
3363
- var code = lmap[get17(data, pos) & ML]; pos += code&15;
3364
- var lit = code>>>4; //U.lhst[lit]++;
3365
- if((lit>>>8)==0) { buf[off++] = lit; }
3366
- else if(lit==256) { break; }
3367
- else {
3368
- var end = off+lit-254;
3369
- if(lit>264) { var ebs = U.ldef[lit-257]; end = off + (ebs>>>3) + bitsE(data, pos, ebs&7); pos += ebs&7; }
3370
- //dst[end-off]++;
3371
-
3372
- var dcode = dmap[get17(data, pos) & MD]; pos += dcode&15;
3373
- var dlit = dcode>>>4;
3374
- var dbs = U.ddef[dlit], dst = (dbs>>>4) + bitsF(data, pos, dbs&15); pos += dbs&15;
3375
-
3376
- //var o0 = off-dst, stp = Math.min(end-off, dst);
3377
- //if(stp>20) while(off<end) { buf.copyWithin(off, o0, o0+stp); off+=stp; } else
3378
- //if(end-dst<=off) buf.copyWithin(off, off-dst, end-dst); else
3379
- //if(dst==1) buf.fill(buf[off-1], off, end); else
3380
- if(noBuf) buf=_check(buf, off+(1<<17));
3381
- while(off<end) { buf[off]=buf[off++-dst]; buf[off]=buf[off++-dst]; buf[off]=buf[off++-dst]; buf[off]=buf[off++-dst]; }
3382
- off=end;
3383
- //while(off!=end) { buf[off]=buf[off++-dst]; }
3384
- }
3385
- }
3386
- //console.log(off-ooff, (pos-opos)>>>3);
3387
- }
3388
- //console.log(dst);
3389
- //console.log(tlen, dlen, off-tlen+tcnt);
3390
- return buf.length==off ? buf : buf.slice(0,off);
3391
- }
3392
- function _check(buf, len) {
3393
- var bl=buf.length; if(len<=bl) return buf;
3394
- var nbuf = new Uint8Array(Math.max(bl<<1,len)); nbuf.set(buf,0);
3395
- //for(var i=0; i<bl; i+=4) { nbuf[i]=buf[i]; nbuf[i+1]=buf[i+1]; nbuf[i+2]=buf[i+2]; nbuf[i+3]=buf[i+3]; }
3396
- return nbuf;
3397
- }
3398
-
3399
- function _decodeTiny(lmap, LL, len, data, pos, tree) {
3400
- var bitsE = _bitsE, get17 = _get17;
3401
- var i = 0;
3402
- while(i<len) {
3403
- var code = lmap[get17(data, pos)&LL]; pos+=code&15;
3404
- var lit = code>>>4;
3405
- if(lit<=15) { tree[i]=lit; i++; }
3406
- else {
3407
- var ll = 0, n = 0;
3408
- if(lit==16) {
3409
- n = (3 + bitsE(data, pos, 2)); pos += 2; ll = tree[i-1];
3410
- }
3411
- else if(lit==17) {
3412
- n = (3 + bitsE(data, pos, 3)); pos += 3;
3413
- }
3414
- else if(lit==18) {
3415
- n = (11 + bitsE(data, pos, 7)); pos += 7;
3416
- }
3417
- var ni = i+n;
3418
- while(i<ni) { tree[i]=ll; i++; }
3419
- }
3420
- }
3421
- return pos;
3422
- }
3423
- function _copyOut(src, off, len, tree) {
3424
- var mx=0, i=0, tl=tree.length>>>1;
3425
- while(i<len) { var v=src[i+off]; tree[(i<<1)]=0; tree[(i<<1)+1]=v; if(v>mx)mx=v; i++; }
3426
- while(i<tl ) { tree[(i<<1)]=0; tree[(i<<1)+1]=0; i++; }
3427
- return mx;
3428
- }
3429
-
3430
- function makeCodes(tree, MAX_BITS) { // code, length
3431
- var max_code = tree.length;
3432
- var code, bits, n, i, len;
3433
-
3434
- var bl_count = U.bl_count; for(var i=0; i<=MAX_BITS; i++) bl_count[i]=0;
3435
- for(i=1; i<max_code; i+=2) bl_count[tree[i]]++;
3436
-
3437
- var next_code = U.next_code; // smallest code for each length
3438
-
3439
- code = 0;
3440
- bl_count[0] = 0;
3441
- for (bits = 1; bits <= MAX_BITS; bits++) {
3442
- code = (code + bl_count[bits-1]) << 1;
3443
- next_code[bits] = code;
3444
- }
3445
-
3446
- for (n = 0; n < max_code; n+=2) {
3447
- len = tree[n+1];
3448
- if (len != 0) {
3449
- tree[n] = next_code[len];
3450
- next_code[len]++;
3451
- }
3452
- }
3453
- }
3454
- function codes2map(tree, MAX_BITS, map) {
3455
- var max_code = tree.length;
3456
- var r15 = U.rev15;
3457
- for(var i=0; i<max_code; i+=2) if(tree[i+1]!=0) {
3458
- var lit = i>>1;
3459
- var cl = tree[i+1], val = (lit<<4)|cl; // : (0x8000 | (U.of0[lit-257]<<7) | (U.exb[lit-257]<<4) | cl);
3460
- var rest = (MAX_BITS-cl), i0 = tree[i]<<rest, i1 = i0 + (1<<rest);
3461
- //tree[i]=r15[i0]>>>(15-MAX_BITS);
3462
- while(i0!=i1) {
3463
- var p0 = r15[i0]>>>(15-MAX_BITS);
3464
- map[p0]=val; i0++;
3465
- }
3466
- }
3467
- }
3468
- function revCodes(tree, MAX_BITS) {
3469
- var r15 = U.rev15, imb = 15-MAX_BITS;
3470
- for(var i=0; i<tree.length; i+=2) { var i0 = (tree[i]<<(MAX_BITS-tree[i+1])); tree[i] = r15[i0]>>>imb; }
3471
- }
3472
-
3473
- function _bitsE(dt, pos, length) { return ((dt[pos>>>3] | (dt[(pos>>>3)+1]<<8) )>>>(pos&7))&((1<<length)-1); }
3474
- function _bitsF(dt, pos, length) { return ((dt[pos>>>3] | (dt[(pos>>>3)+1]<<8) | (dt[(pos>>>3)+2]<<16))>>>(pos&7))&((1<<length)-1); }
3475
- /*
3476
- function _get9(dt, pos) {
3477
- return ((dt[pos>>>3] | (dt[(pos>>>3)+1]<<8))>>>(pos&7))&511;
3478
- } */
3479
- function _get17(dt, pos) { // return at least 17 meaningful bytes
3480
- return (dt[pos>>>3] | (dt[(pos>>>3)+1]<<8) | (dt[(pos>>>3)+2]<<16) )>>>(pos&7);
3481
- }
3482
- const U = function(){
3483
- var u16=Uint16Array, u32=Uint32Array;
3484
- return {
3485
- next_code : new u16(16),
3486
- bl_count : new u16(16),
3487
- ordr : [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ],
3488
- of0 : [3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],
3489
- exb : [0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0],
3490
- ldef : new u16(32),
3491
- df0 : [1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 65535, 65535],
3492
- dxb : [0,0,0,0,1,1,2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0],
3493
- ddef : new u32(32),
3494
- flmap: new u16( 512), fltree: [],
3495
- fdmap: new u16( 32), fdtree: [],
3496
- lmap : new u16(32768), ltree : [], ttree:[],
3497
- dmap : new u16(32768), dtree : [],
3498
- imap : new u16( 512), itree : [],
3499
- //rev9 : new u16( 512)
3500
- rev15: new u16(1<<15),
3501
- lhst : new u32(286), dhst : new u32( 30), ihst : new u32(19),
3502
- lits : new u32(15000),
3503
- strt : new u16(1<<16),
3504
- prev : new u16(1<<15)
3505
- };
3506
- } ();
3507
-
3508
- (function(){
3509
- var len = 1<<15;
3510
- for(var i=0; i<len; i++) {
3511
- var x = i;
3512
- x = (((x & 0xaaaaaaaa) >>> 1) | ((x & 0x55555555) << 1));
3513
- x = (((x & 0xcccccccc) >>> 2) | ((x & 0x33333333) << 2));
3514
- x = (((x & 0xf0f0f0f0) >>> 4) | ((x & 0x0f0f0f0f) << 4));
3515
- x = (((x & 0xff00ff00) >>> 8) | ((x & 0x00ff00ff) << 8));
3516
- U.rev15[i] = (((x >>> 16) | (x << 16)))>>>17;
3517
- }
3518
-
3519
- function pushV(tgt, n, sv) { while(n--!=0) tgt.push(0,sv); }
3520
-
3521
- for(var i=0; i<32; i++) { U.ldef[i]=(U.of0[i]<<3)|U.exb[i]; U.ddef[i]=(U.df0[i]<<4)|U.dxb[i]; }
3522
-
3523
- pushV(U.fltree, 144, 8); pushV(U.fltree, 255-143, 9); pushV(U.fltree, 279-255, 7); pushV(U.fltree,287-279,8);
3524
- /*
3525
- var i = 0;
3526
- for(; i<=143; i++) U.fltree.push(0,8);
3527
- for(; i<=255; i++) U.fltree.push(0,9);
3528
- for(; i<=279; i++) U.fltree.push(0,7);
3529
- for(; i<=287; i++) U.fltree.push(0,8);
3530
- */
3531
- makeCodes(U.fltree, 9);
3532
- codes2map(U.fltree, 9, U.flmap);
3533
- revCodes (U.fltree, 9);
3534
-
3535
- pushV(U.fdtree,32,5);
3536
- //for(i=0;i<32; i++) U.fdtree.push(0,5);
3537
- makeCodes(U.fdtree, 5);
3538
- codes2map(U.fdtree, 5, U.fdmap);
3539
- revCodes (U.fdtree, 5);
3540
-
3541
- pushV(U.itree,19,0); pushV(U.ltree,286,0); pushV(U.dtree,30,0); pushV(U.ttree,320,0);
3542
- /*
3543
- for(var i=0; i< 19; i++) U.itree.push(0,0);
3544
- for(var i=0; i<286; i++) U.ltree.push(0,0);
3545
- for(var i=0; i< 30; i++) U.dtree.push(0,0);
3546
- for(var i=0; i<320; i++) U.ttree.push(0,0);
3547
- */
3548
- })();
3549
-
3550
- const crc = {
3551
- table : ( function() {
3552
- var tab = new Uint32Array(256);
3553
- for (var n=0; n<256; n++) {
3554
- var c = n;
3555
- for (var k=0; k<8; k++) {
3556
- if (c & 1) c = 0xedb88320 ^ (c >>> 1);
3557
- else c = c >>> 1;
3558
- }
3559
- tab[n] = c; }
3560
- return tab; })(),
3561
- update : function(c, buf, off, len) {
3562
- for (var i=0; i<len; i++) c = crc.table[(c ^ buf[off+i]) & 0xff] ^ (c >>> 8);
3563
- return c;
3564
- },
3565
- crc : function(b,o,l) { return crc.update(0xffffffff,b,o,l) ^ 0xffffffff; }
3566
- };
3567
-
3568
- function inflateRaw(file, buf) { return inflate(file, buf); }
3569
-
3570
- /* global module */
3571
-
3572
- const config = {
3573
- numWorkers: 1,
3574
- workerURL: '',
3575
- useWorkers: false,
3576
- };
3577
-
3578
- let nextId = 0;
3579
-
3580
- // Requests are put on a queue.
3581
- // We don't send the request to the worker until the worker
3582
- // is finished. This probably adds a small amount of latency
3583
- // but the issue is imagine you have 2 workers. You give worker
3584
- // A x seconds of work to do and worker B y seconds of work to
3585
- // do. You don't know which will finish first. If you give
3586
- // the worker with more work to do the request then you'll
3587
- // waste time.
3588
-
3589
- // note: we can't check `workers.length` for deciding if
3590
- // we've reached `config.numWorkers` because creation the worker
3591
- // is async which means other requests to make workers might
3592
- // come in before a worker gets added to `workers`
3593
- let numWorkers = 0;
3594
- let canUseWorkers = true; // gets set to false if we can't start a worker
3595
- const workers = [];
3596
- const availableWorkers = [];
3597
- const waitingForWorkerQueue = [];
3598
- const currentlyProcessingIdToRequestMap = new Map();
3599
-
3600
- function handleResult(e) {
3601
- makeWorkerAvailable(e.target);
3602
- const {id, error, data} = e.data;
3603
- const request = currentlyProcessingIdToRequestMap.get(id);
3604
- currentlyProcessingIdToRequestMap.delete(id);
3605
- if (error) {
3606
- request.reject(error);
3607
- } else {
3608
- request.resolve(data);
3609
- }
3610
- }
3611
-
3612
- // Because Firefox uses non-standard onerror to signal an error.
3613
- function startWorker(url) {
3614
- return new Promise((resolve, reject) => {
3615
- const worker = new Worker(url);
3616
- worker.onmessage = (e) => {
3617
- if (e.data === 'start') {
3618
- worker.onerror = undefined;
3619
- worker.onmessage = undefined;
3620
- resolve(worker);
3621
- } else {
3622
- reject(new Error(`unexpected message: ${e.data}`));
3623
- }
3624
- };
3625
- worker.onerror = reject;
3626
- });
3627
- }
3628
-
3629
- function dynamicRequire(mod, request) {
3630
- return mod.require ? mod.require(request) : {};
3631
- }
3632
-
3633
- const workerHelper = (function() {
3634
- if (isNode) {
3635
- // We need to use `dynamicRequire` because `require` on it's own will be optimized by webpack.
3636
- const {Worker} = dynamicRequire(module, 'worker_threads');
3637
- return {
3638
- async createWorker(url) {
3639
- return new Worker(url);
3640
- },
3641
- addEventListener(worker, fn) {
3642
- worker.on('message', (data) => {
3643
- fn({target: worker, data});
3644
- });
3645
- },
3646
- async terminate(worker) {
3647
- await worker.terminate();
3648
- },
3649
- };
3650
- } else {
3651
- return {
3652
- async createWorker(url) {
3653
- // I don't understand this security issue
3654
- // Apparently there is some iframe setting or http header
3655
- // that prevents cross domain workers. But, I can manually
3656
- // download the text and do it. I reported this to Chrome
3657
- // and they said it was fine so ¯\_(ツ)_/¯
3658
- try {
3659
- const worker = await startWorker(url);
3660
- return worker;
3661
- } catch (e) {
3662
- console.warn('could not load worker:', url);
3663
- }
3664
-
3665
- let text;
3666
- try {
3667
- const req = await fetch(url, {mode: 'cors'});
3668
- if (!req.ok) {
3669
- throw new Error(`could not load: ${url}`);
3670
- }
3671
- text = await req.text();
3672
- url = URL.createObjectURL(new Blob([text], {type: 'application/javascript'}));
3673
- const worker = await startWorker(url);
3674
- config.workerURL = url; // this is a hack. What's a better way to structure this code?
3675
- return worker;
3676
- } catch (e) {
3677
- console.warn('could not load worker via fetch:', url);
3678
- }
3679
-
3680
- if (text !== undefined) {
3681
- try {
3682
- url = `data:application/javascript;base64,${btoa(text)}`;
3683
- const worker = await startWorker(url);
3684
- config.workerURL = url;
3685
- return worker;
3686
- } catch (e) {
3687
- console.warn('could not load worker via dataURI');
3688
- }
3689
- }
3690
-
3691
- console.warn('workers will not be used');
3692
- throw new Error('can not start workers');
3693
- },
3694
- addEventListener(worker, fn) {
3695
- worker.addEventListener('message', fn);
3696
- },
3697
- async terminate(worker) {
3698
- worker.terminate();
3699
- },
3700
- };
3701
- }
3702
- }());
3703
-
3704
- function makeWorkerAvailable(worker) {
3705
- availableWorkers.push(worker);
3706
- processWaitingForWorkerQueue();
3707
- }
3708
-
3709
- async function getAvailableWorker() {
3710
- if (availableWorkers.length === 0 && numWorkers < config.numWorkers) {
3711
- ++numWorkers; // see comment at numWorkers declaration
3712
- try {
3713
- const worker = await workerHelper.createWorker(config.workerURL);
3714
- workers.push(worker);
3715
- availableWorkers.push(worker);
3716
- workerHelper.addEventListener(worker, handleResult);
3717
- } catch (e) {
3718
- // set this global out-of-band (needs refactor)
3719
- canUseWorkers = false;
3720
- }
3721
- }
3722
- return availableWorkers.pop();
3723
- }
3724
-
3725
- // @param {Uint8Array} src
3726
- // @param {number} uncompressedSize
3727
- // @param {string} [type] mime-type
3728
- // @returns {ArrayBuffer|Blob} ArrayBuffer if type is falsy or Blob otherwise.
3729
- function inflateRawLocal(src, uncompressedSize, type, resolve) {
3730
- const dst = new Uint8Array(uncompressedSize);
3731
- inflateRaw(src, dst);
3732
- resolve(type
3733
- ? new Blob([dst], {type})
3734
- : dst.buffer);
3735
- }
3736
-
3737
- async function processWaitingForWorkerQueue() {
3738
- if (waitingForWorkerQueue.length === 0) {
3739
- return;
3740
- }
3741
-
3742
- if (config.useWorkers && canUseWorkers) {
3743
- const worker = await getAvailableWorker();
3744
- // canUseWorkers might have been set out-of-band (need refactor)
3745
- if (canUseWorkers) {
3746
- if (worker) {
3747
- if (waitingForWorkerQueue.length === 0) {
3748
- // the queue might be empty while we awaited for a worker.
3749
- makeWorkerAvailable(worker);
3750
- return;
3751
- }
3752
- const {id, src, uncompressedSize, type, resolve, reject} = waitingForWorkerQueue.shift();
3753
- currentlyProcessingIdToRequestMap.set(id, {id, resolve, reject});
3754
- const transferables = [];
3755
- // NOTE: Originally I thought you could transfer an ArrayBuffer.
3756
- // The code on this side is often using views into the entire file
3757
- // which means if we transferred we'd lose the entire file. That sucks
3758
- // because it means there's an expensive copy to send the uncompressed
3759
- // data to the worker.
3760
- //
3761
- // Also originally I thought we could send a Blob but we'd need to refactor
3762
- // the code in unzipit/readEntryData as currently it reads the uncompressed
3763
- // bytes.
3764
- //
3765
- //if (!isBlob(src) && !isSharedArrayBuffer(src)) {
3766
- // transferables.push(src);
3767
- //}
3768
- worker.postMessage({
3769
- type: 'inflate',
3770
- data: {
3771
- id,
3772
- type,
3773
- src,
3774
- uncompressedSize,
3775
- },
3776
- }, transferables);
3777
- }
3778
- return;
3779
- }
3780
- }
3781
-
3782
- // inflate locally
3783
- // We loop here because what happens if many requests happen at once
3784
- // the first N requests will try to async make a worker. Other requests
3785
- // will then be on the queue. But if we fail to make workers then there
3786
- // are pending requests.
3787
- while (waitingForWorkerQueue.length) {
3788
- const {src, uncompressedSize, type, resolve} = waitingForWorkerQueue.shift();
3789
- let data = src;
3790
- if (isBlob(src)) {
3791
- data = await readBlobAsUint8Array(src);
3792
- }
3793
- inflateRawLocal(data, uncompressedSize, type, resolve);
3794
- }
3795
- }
3796
-
3797
- function setOptions(options) {
3798
- config.workerURL = options.workerURL || config.workerURL;
3799
- // there's no reason to set the workerURL if you're not going to use workers
3800
- if (options.workerURL) {
3801
- config.useWorkers = true;
3802
- }
3803
- config.useWorkers = options.useWorkers !== undefined ? options.useWorkers : config.useWorkers;
3804
- config.numWorkers = options.numWorkers || config.numWorkers;
3805
- }
3806
-
3807
- // It has to take non-zero time to put a large typed array in a Blob since the very
3808
- // next instruction you could change the contents of the array. So, if you're reading
3809
- // the zip file for images/video/audio then all you want is a Blob on which to get a URL.
3810
- // so that operation of putting the data in a Blob should happen in the worker.
3811
- //
3812
- // Conversely if you want the data itself then you want an ArrayBuffer immediately
3813
- // since the worker can transfer its ArrayBuffer zero copy.
3814
- //
3815
- // @param {Uint8Array|Blob} src
3816
- // @param {number} uncompressedSize
3817
- // @param {string} [type] falsy or mimeType string (eg: 'image/png')
3818
- // @returns {ArrayBuffer|Blob} ArrayBuffer if type is falsy or Blob otherwise.
3819
- function inflateRawAsync(src, uncompressedSize, type) {
3820
- return new Promise((resolve, reject) => {
3821
- // note: there is potential an expensive copy here. In order for the data
3822
- // to make it into the worker we need to copy the data to the worker unless
3823
- // it's a Blob or a SharedArrayBuffer.
3824
- //
3825
- // Solutions:
3826
- //
3827
- // 1. A minor enhancement, if `uncompressedSize` is small don't call the worker.
3828
- //
3829
- // might be a win period as their is overhead calling the worker
3830
- //
3831
- // 2. Move the entire library to the worker
3832
- //
3833
- // Good, Maybe faster if you pass a URL, Blob, or SharedArrayBuffer? Not sure about that
3834
- // as those are also easy to transfer. Still slow if you pass an ArrayBuffer
3835
- // as the ArrayBuffer has to be copied to the worker.
3836
- //
3837
- // I guess benchmarking is really the only thing to try.
3838
- waitingForWorkerQueue.push({src, uncompressedSize, type, resolve, reject, id: nextId++});
3839
- processWaitingForWorkerQueue();
3840
- });
3841
- }
3842
-
3843
- function clearArray(arr) {
3844
- arr.splice(0, arr.length);
3845
- }
3846
-
3847
- async function cleanup() {
3848
- for (const worker of workers) {
3849
- await workerHelper.terminate(worker);
3850
- }
3851
- clearArray(workers);
3852
- clearArray(availableWorkers);
3853
- clearArray(waitingForWorkerQueue);
3854
- currentlyProcessingIdToRequestMap.clear();
3855
- numWorkers = 0;
3856
- canUseWorkers = true;
3857
- }
3858
-
3859
- /*
3860
- class Zip {
3861
- constructor(reader) {
3862
- comment, // the comment for this entry
3863
- commentBytes, // the raw comment for this entry
3864
- }
3865
- }
3866
- */
3867
-
3868
- function dosDateTimeToDate(date, time) {
3869
- const day = date & 0x1f; // 1-31
3870
- const month = (date >> 5 & 0xf) - 1; // 1-12, 0-11
3871
- const year = (date >> 9 & 0x7f) + 1980; // 0-128, 1980-2108
3872
-
3873
- const millisecond = 0;
3874
- const second = (time & 0x1f) * 2; // 0-29, 0-58 (even numbers)
3875
- const minute = time >> 5 & 0x3f; // 0-59
3876
- const hour = time >> 11 & 0x1f; // 0-23
3877
-
3878
- return new Date(year, month, day, hour, minute, second, millisecond);
3879
- }
3880
-
3881
- class ZipEntry {
3882
- constructor(reader, rawEntry) {
3883
- this._reader = reader;
3884
- this._rawEntry = rawEntry;
3885
- this.name = rawEntry.name;
3886
- this.nameBytes = rawEntry.nameBytes;
3887
- this.size = rawEntry.uncompressedSize;
3888
- this.compressedSize = rawEntry.compressedSize;
3889
- this.comment = rawEntry.comment;
3890
- this.commentBytes = rawEntry.commentBytes;
3891
- this.compressionMethod = rawEntry.compressionMethod;
3892
- this.lastModDate = dosDateTimeToDate(rawEntry.lastModFileDate, rawEntry.lastModFileTime);
3893
- this.isDirectory = rawEntry.uncompressedSize === 0 && rawEntry.name.endsWith('/');
3894
- this.encrypted = !!(rawEntry.generalPurposeBitFlag & 0x1);
3895
- this.externalFileAttributes = rawEntry.externalFileAttributes;
3896
- this.versionMadeBy = rawEntry.versionMadeBy;
3897
- }
3898
- // returns a promise that returns a Blob for this entry
3899
- async blob(type = 'application/octet-stream') {
3900
- return await readEntryDataAsBlob(this._reader, this._rawEntry, type);
3901
- }
3902
- // returns a promise that returns an ArrayBuffer for this entry
3903
- async arrayBuffer() {
3904
- return await readEntryDataAsArrayBuffer(this._reader, this._rawEntry);
3905
- }
3906
- // returns text, assumes the text is valid utf8. If you want more options decode arrayBuffer yourself
3907
- async text() {
3908
- const buffer = await this.arrayBuffer();
3909
- return decodeBuffer(new Uint8Array(buffer));
3910
- }
3911
- // returns text with JSON.parse called on it. If you want more options decode arrayBuffer yourself
3912
- async json() {
3913
- const text = await this.text();
3914
- return JSON.parse(text);
3915
- }
3916
- }
3917
-
3918
- const EOCDR_WITHOUT_COMMENT_SIZE = 22;
3919
- const MAX_COMMENT_SIZE = 0xffff; // 2-byte size
3920
- const EOCDR_SIGNATURE = 0x06054b50;
3921
- const ZIP64_EOCDR_SIGNATURE = 0x06064b50;
3922
-
3923
- async function readAs(reader, offset, length) {
3924
- return await reader.read(offset, length);
3925
- }
3926
-
3927
- // The point of this function is we want to be able to pass the data
3928
- // to a worker as fast as possible so when decompressing if the data
3929
- // is already a blob and we can get a blob then get a blob.
3930
- //
3931
- // I'm not sure what a better way to refactor this is. We've got examples
3932
- // of multiple readers. Ideally, for every type of reader we could ask
3933
- // it, "give me a type that is zero copy both locally and when sent to a worker".
3934
- //
3935
- // The problem is the worker would also have to know the how to handle this
3936
- // opaque type. I suppose the correct solution is to register different
3937
- // reader handlers in the worker so BlobReader would register some
3938
- // `handleZeroCopyType<BlobReader>`. At the moment I don't feel like
3939
- // refactoring. As it is you just pass in an instance of the reader
3940
- // but instead you'd have to register the reader and some how get the
3941
- // source for the `handleZeroCopyType` handler function into the worker.
3942
- // That sounds like a huge PITA, requiring you to put the implementation
3943
- // in a separate file so the worker can load it or some other workaround
3944
- // hack.
3945
- //
3946
- // For now this hack works even if it's not generic.
3947
- async function readAsBlobOrTypedArray(reader, offset, length, type) {
3948
- if (reader.sliceAsBlob) {
3949
- return await reader.sliceAsBlob(offset, length, type);
3950
- }
3951
- return await reader.read(offset, length);
3952
- }
3953
-
3954
- const crc$1 = {
3955
- unsigned() {
3956
- return 0;
3957
- },
3958
- };
3959
-
3960
- function getUint16LE(uint8View, offset) {
3961
- return uint8View[offset ] +
3962
- uint8View[offset + 1] * 0x100;
3963
- }
3964
-
3965
- function getUint32LE(uint8View, offset) {
3966
- return uint8View[offset ] +
3967
- uint8View[offset + 1] * 0x100 +
3968
- uint8View[offset + 2] * 0x10000 +
3969
- uint8View[offset + 3] * 0x1000000;
3970
- }
3971
-
3972
- function getUint64LE(uint8View, offset) {
3973
- return getUint32LE(uint8View, offset) +
3974
- getUint32LE(uint8View, offset + 4) * 0x100000000;
3975
- }
3976
-
3977
- /* eslint-disable no-irregular-whitespace */
3978
- // const decodeCP437 = (function() {
3979
- // const cp437 = '\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ';
3980
- //
3981
- // return function(uint8view) {
3982
- // return Array.from(uint8view).map(v => cp437[v]).join('');
3983
- // };
3984
- // }());
3985
- /* eslint-enable no-irregular-whitespace */
3986
-
3987
- const utf8Decoder = new TextDecoder();
3988
- function decodeBuffer(uint8View, isUTF8) { /* eslint-disable-line no-unused-vars */ /* lgtm [js/superfluous-trailing-arguments] */
3989
- if (isSharedArrayBuffer(uint8View.buffer)) {
3990
- uint8View = new Uint8Array(uint8View);
3991
- }
3992
- return utf8Decoder.decode(uint8View);
3993
- /*
3994
- AFAICT the UTF8 flat is not set so it's 100% up to the user
3995
- to self decode if their file is not utf8 filenames
3996
- return isUTF8
3997
- ? utf8Decoder.decode(uint8View)
3998
- : decodeCP437(uint8View);
3999
- */
4000
- }
4001
-
4002
- async function findEndOfCentralDirector(reader, totalLength) {
4003
- const size = Math.min(EOCDR_WITHOUT_COMMENT_SIZE + MAX_COMMENT_SIZE, totalLength);
4004
- const readStart = totalLength - size;
4005
- const data = await readAs(reader, readStart, size);
4006
- for (let i = size - EOCDR_WITHOUT_COMMENT_SIZE; i >= 0; --i) {
4007
- if (getUint32LE(data, i) !== EOCDR_SIGNATURE) {
4008
- continue;
4009
- }
4010
-
4011
- // 0 - End of central directory signature
4012
- const eocdr = new Uint8Array(data.buffer, data.byteOffset + i, data.byteLength - i);
4013
- // 4 - Number of this disk
4014
- const diskNumber = getUint16LE(eocdr, 4);
4015
- if (diskNumber !== 0) {
4016
- throw new Error(`multi-volume zip files are not supported. This is volume: ${diskNumber}`);
4017
- }
4018
-
4019
- // 6 - Disk where central directory starts
4020
- // 8 - Number of central directory records on this disk
4021
- // 10 - Total number of central directory records
4022
- const entryCount = getUint16LE(eocdr, 10);
4023
- // 12 - Size of central directory (bytes)
4024
- const centralDirectorySize = getUint32LE(eocdr, 12);
4025
- // 16 - Offset of start of central directory, relative to start of archive
4026
- const centralDirectoryOffset = getUint32LE(eocdr, 16);
4027
- // 20 - Comment length
4028
- const commentLength = getUint16LE(eocdr, 20);
4029
- const expectedCommentLength = eocdr.length - EOCDR_WITHOUT_COMMENT_SIZE;
4030
- if (commentLength !== expectedCommentLength) {
4031
- throw new Error(`invalid comment length. expected: ${expectedCommentLength}, actual: ${commentLength}`);
4032
- }
4033
-
4034
- // 22 - Comment
4035
- // the encoding is always cp437.
4036
- const commentBytes = new Uint8Array(eocdr.buffer, eocdr.byteOffset + 22, commentLength);
4037
- const comment = decodeBuffer(commentBytes);
4038
-
4039
- if (entryCount === 0xffff || centralDirectoryOffset === 0xffffffff) {
4040
- return await readZip64CentralDirectory(reader, readStart + i, comment, commentBytes);
4041
- } else {
4042
- return await readEntries(reader, centralDirectoryOffset, centralDirectorySize, entryCount, comment, commentBytes);
4043
- }
4044
- }
4045
-
4046
- throw new Error('could not find end of central directory. maybe not zip file');
4047
- }
4048
-
4049
- const END_OF_CENTRAL_DIRECTORY_LOCATOR_SIGNATURE = 0x07064b50;
4050
-
4051
- async function readZip64CentralDirectory(reader, offset, comment, commentBytes) {
4052
- // ZIP64 Zip64 end of central directory locator
4053
- const zip64EocdlOffset = offset - 20;
4054
- const eocdl = await readAs(reader, zip64EocdlOffset, 20);
4055
-
4056
- // 0 - zip64 end of central dir locator signature
4057
- if (getUint32LE(eocdl, 0) !== END_OF_CENTRAL_DIRECTORY_LOCATOR_SIGNATURE) {
4058
- throw new Error('invalid zip64 end of central directory locator signature');
4059
- }
4060
-
4061
- // 4 - number of the disk with the start of the zip64 end of central directory
4062
- // 8 - relative offset of the zip64 end of central directory record
4063
- const zip64EocdrOffset = getUint64LE(eocdl, 8);
4064
- // 16 - total number of disks
4065
-
4066
- // ZIP64 end of central directory record
4067
- const zip64Eocdr = await readAs(reader, zip64EocdrOffset, 56);
4068
-
4069
- // 0 - zip64 end of central dir signature 4 bytes (0x06064b50)
4070
- if (getUint32LE(zip64Eocdr, 0) !== ZIP64_EOCDR_SIGNATURE) {
4071
- throw new Error('invalid zip64 end of central directory record signature');
4072
- }
4073
- // 4 - size of zip64 end of central directory record 8 bytes
4074
- // 12 - version made by 2 bytes
4075
- // 14 - version needed to extract 2 bytes
4076
- // 16 - number of this disk 4 bytes
4077
- // 20 - number of the disk with the start of the central directory 4 bytes
4078
- // 24 - total number of entries in the central directory on this disk 8 bytes
4079
- // 32 - total number of entries in the central directory 8 bytes
4080
- const entryCount = getUint64LE(zip64Eocdr, 32);
4081
- // 40 - size of the central directory 8 bytes
4082
- const centralDirectorySize = getUint64LE(zip64Eocdr, 40);
4083
- // 48 - offset of start of central directory with respect to the starting disk number 8 bytes
4084
- const centralDirectoryOffset = getUint64LE(zip64Eocdr, 48);
4085
- // 56 - zip64 extensible data sector (variable size)
4086
- return readEntries(reader, centralDirectoryOffset, centralDirectorySize, entryCount, comment, commentBytes);
4087
- }
4088
-
4089
- const CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE = 0x02014b50;
4090
-
4091
- async function readEntries(reader, centralDirectoryOffset, centralDirectorySize, rawEntryCount, comment, commentBytes) {
4092
- let readEntryCursor = 0;
4093
- const allEntriesBuffer = await readAs(reader, centralDirectoryOffset, centralDirectorySize);
4094
- const rawEntries = [];
4095
-
4096
- for (let e = 0; e < rawEntryCount; ++e) {
4097
- const buffer = allEntriesBuffer.subarray(readEntryCursor, readEntryCursor + 46);
4098
- // 0 - Central directory file header signature
4099
- const signature = getUint32LE(buffer, 0);
4100
- if (signature !== CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE) {
4101
- throw new Error(`invalid central directory file header signature: 0x${signature.toString(16)}`);
4102
- }
4103
- const rawEntry = {
4104
- // 4 - Version made by
4105
- versionMadeBy: getUint16LE(buffer, 4),
4106
- // 6 - Version needed to extract (minimum)
4107
- versionNeededToExtract: getUint16LE(buffer, 6),
4108
- // 8 - General purpose bit flag
4109
- generalPurposeBitFlag: getUint16LE(buffer, 8),
4110
- // 10 - Compression method
4111
- compressionMethod: getUint16LE(buffer, 10),
4112
- // 12 - File last modification time
4113
- lastModFileTime: getUint16LE(buffer, 12),
4114
- // 14 - File last modification date
4115
- lastModFileDate: getUint16LE(buffer, 14),
4116
- // 16 - CRC-32
4117
- crc32: getUint32LE(buffer, 16),
4118
- // 20 - Compressed size
4119
- compressedSize: getUint32LE(buffer, 20),
4120
- // 24 - Uncompressed size
4121
- uncompressedSize: getUint32LE(buffer, 24),
4122
- // 28 - File name length (n)
4123
- fileNameLength: getUint16LE(buffer, 28),
4124
- // 30 - Extra field length (m)
4125
- extraFieldLength: getUint16LE(buffer, 30),
4126
- // 32 - File comment length (k)
4127
- fileCommentLength: getUint16LE(buffer, 32),
4128
- // 34 - Disk number where file starts
4129
- // 36 - Internal file attributes
4130
- internalFileAttributes: getUint16LE(buffer, 36),
4131
- // 38 - External file attributes
4132
- externalFileAttributes: getUint32LE(buffer, 38),
4133
- // 42 - Relative offset of local file header
4134
- relativeOffsetOfLocalHeader: getUint32LE(buffer, 42),
4135
- };
4136
-
4137
- if (rawEntry.generalPurposeBitFlag & 0x40) {
4138
- throw new Error('strong encryption is not supported');
4139
- }
4140
-
4141
- readEntryCursor += 46;
4142
-
4143
- const data = allEntriesBuffer.subarray(readEntryCursor, readEntryCursor + rawEntry.fileNameLength + rawEntry.extraFieldLength + rawEntry.fileCommentLength);
4144
- rawEntry.nameBytes = data.slice(0, rawEntry.fileNameLength);
4145
- rawEntry.name = decodeBuffer(rawEntry.nameBytes);
4146
-
4147
- // 46+n - Extra field
4148
- const fileCommentStart = rawEntry.fileNameLength + rawEntry.extraFieldLength;
4149
- const extraFieldBuffer = data.slice(rawEntry.fileNameLength, fileCommentStart);
4150
- rawEntry.extraFields = [];
4151
- let i = 0;
4152
- while (i < extraFieldBuffer.length - 3) {
4153
- const headerId = getUint16LE(extraFieldBuffer, i + 0);
4154
- const dataSize = getUint16LE(extraFieldBuffer, i + 2);
4155
- const dataStart = i + 4;
4156
- const dataEnd = dataStart + dataSize;
4157
- if (dataEnd > extraFieldBuffer.length) {
4158
- throw new Error('extra field length exceeds extra field buffer size');
4159
- }
4160
- rawEntry.extraFields.push({
4161
- id: headerId,
4162
- data: extraFieldBuffer.slice(dataStart, dataEnd),
4163
- });
4164
- i = dataEnd;
4165
- }
4166
-
4167
- // 46+n+m - File comment
4168
- rawEntry.commentBytes = data.slice(fileCommentStart, fileCommentStart + rawEntry.fileCommentLength);
4169
- rawEntry.comment = decodeBuffer(rawEntry.commentBytes);
4170
-
4171
- readEntryCursor += data.length;
4172
-
4173
- if (rawEntry.uncompressedSize === 0xffffffff ||
4174
- rawEntry.compressedSize === 0xffffffff ||
4175
- rawEntry.relativeOffsetOfLocalHeader === 0xffffffff) {
4176
- // ZIP64 format
4177
- // find the Zip64 Extended Information Extra Field
4178
- const zip64ExtraField = rawEntry.extraFields.find(e => e.id === 0x0001);
4179
- if (!zip64ExtraField) {
4180
- throw new Error('expected zip64 extended information extra field');
4181
- }
4182
- const zip64EiefBuffer = zip64ExtraField.data;
4183
- let index = 0;
4184
- // 0 - Original Size 8 bytes
4185
- if (rawEntry.uncompressedSize === 0xffffffff) {
4186
- if (index + 8 > zip64EiefBuffer.length) {
4187
- throw new Error('zip64 extended information extra field does not include uncompressed size');
4188
- }
4189
- rawEntry.uncompressedSize = getUint64LE(zip64EiefBuffer, index);
4190
- index += 8;
4191
- }
4192
- // 8 - Compressed Size 8 bytes
4193
- if (rawEntry.compressedSize === 0xffffffff) {
4194
- if (index + 8 > zip64EiefBuffer.length) {
4195
- throw new Error('zip64 extended information extra field does not include compressed size');
4196
- }
4197
- rawEntry.compressedSize = getUint64LE(zip64EiefBuffer, index);
4198
- index += 8;
4199
- }
4200
- // 16 - Relative Header Offset 8 bytes
4201
- if (rawEntry.relativeOffsetOfLocalHeader === 0xffffffff) {
4202
- if (index + 8 > zip64EiefBuffer.length) {
4203
- throw new Error('zip64 extended information extra field does not include relative header offset');
4204
- }
4205
- rawEntry.relativeOffsetOfLocalHeader = getUint64LE(zip64EiefBuffer, index);
4206
- index += 8;
4207
- }
4208
- // 24 - Disk Start Number 4 bytes
4209
- }
4210
-
4211
- // check for Info-ZIP Unicode Path Extra Field (0x7075)
4212
- // see https://github.com/thejoshwolfe/yauzl/issues/33
4213
- const nameField = rawEntry.extraFields.find(e =>
4214
- e.id === 0x7075 &&
4215
- e.data.length >= 6 && // too short to be meaningful
4216
- e.data[0] === 1 && // Version 1 byte version of this extra field, currently 1
4217
- getUint32LE(e.data, 1), crc$1.unsigned(rawEntry.nameBytes)); // NameCRC32 4 bytes File Name Field CRC32 Checksum
4218
- // > If the CRC check fails, this UTF-8 Path Extra Field should be
4219
- // > ignored and the File Name field in the header should be used instead.
4220
- if (nameField) {
4221
- // UnicodeName Variable UTF-8 version of the entry File Name
4222
- rawEntry.fileName = decodeBuffer(nameField.data.slice(5));
4223
- }
4224
-
4225
- // validate file size
4226
- if (rawEntry.compressionMethod === 0) {
4227
- let expectedCompressedSize = rawEntry.uncompressedSize;
4228
- if ((rawEntry.generalPurposeBitFlag & 0x1) !== 0) {
4229
- // traditional encryption prefixes the file data with a header
4230
- expectedCompressedSize += 12;
4231
- }
4232
- if (rawEntry.compressedSize !== expectedCompressedSize) {
4233
- throw new Error(`compressed size mismatch for stored file: ${rawEntry.compressedSize} != ${expectedCompressedSize}`);
4234
- }
4235
- }
4236
- rawEntries.push(rawEntry);
4237
- }
4238
- const zip = {
4239
- comment,
4240
- commentBytes,
4241
- };
4242
- return {
4243
- zip,
4244
- entries: rawEntries.map(e => new ZipEntry(reader, e)),
4245
- };
4246
- }
4247
-
4248
- async function readEntryDataHeader(reader, rawEntry) {
4249
- if (rawEntry.generalPurposeBitFlag & 0x1) {
4250
- throw new Error('encrypted entries not supported');
4251
- }
4252
- const buffer = await readAs(reader, rawEntry.relativeOffsetOfLocalHeader, 30);
4253
- // note: maybe this should be passed in or cached on entry
4254
- // as it's async so there will be at least one tick (not sure about that)
4255
- const totalLength = await reader.getLength();
4256
-
4257
- // 0 - Local file header signature = 0x04034b50
4258
- const signature = getUint32LE(buffer, 0);
4259
- if (signature !== 0x04034b50) {
4260
- throw new Error(`invalid local file header signature: 0x${signature.toString(16)}`);
4261
- }
4262
-
4263
- // all this should be redundant
4264
- // 4 - Version needed to extract (minimum)
4265
- // 6 - General purpose bit flag
4266
- // 8 - Compression method
4267
- // 10 - File last modification time
4268
- // 12 - File last modification date
4269
- // 14 - CRC-32
4270
- // 18 - Compressed size
4271
- // 22 - Uncompressed size
4272
- // 26 - File name length (n)
4273
- const fileNameLength = getUint16LE(buffer, 26);
4274
- // 28 - Extra field length (m)
4275
- const extraFieldLength = getUint16LE(buffer, 28);
4276
- // 30 - File name
4277
- // 30+n - Extra field
4278
- const localFileHeaderEnd = rawEntry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength;
4279
- let decompress;
4280
- if (rawEntry.compressionMethod === 0) {
4281
- // 0 - The file is stored (no compression)
4282
- decompress = false;
4283
- } else if (rawEntry.compressionMethod === 8) {
4284
- // 8 - The file is Deflated
4285
- decompress = true;
4286
- } else {
4287
- throw new Error(`unsupported compression method: ${rawEntry.compressionMethod}`);
4288
- }
4289
- const fileDataStart = localFileHeaderEnd;
4290
- const fileDataEnd = fileDataStart + rawEntry.compressedSize;
4291
- if (rawEntry.compressedSize !== 0) {
4292
- // bounds check now, because the read streams will probably not complain loud enough.
4293
- // since we're dealing with an unsigned offset plus an unsigned size,
4294
- // we only have 1 thing to check for.
4295
- if (fileDataEnd > totalLength) {
4296
- throw new Error(`file data overflows file bounds: ${fileDataStart} + ${rawEntry.compressedSize} > ${totalLength}`);
4297
- }
4298
- }
4299
- return {
4300
- decompress,
4301
- fileDataStart,
4302
- };
4303
- }
4304
-
4305
- async function readEntryDataAsArrayBuffer(reader, rawEntry) {
4306
- const {decompress, fileDataStart} = await readEntryDataHeader(reader, rawEntry);
4307
- if (!decompress) {
4308
- const dataView = await readAs(reader, fileDataStart, rawEntry.compressedSize);
4309
- // make copy?
4310
- //
4311
- // 1. The source is a Blob/file. In this case we'll get back TypedArray we can just hand to the user
4312
- // 2. The source is a TypedArray. In this case we'll get back TypedArray that is a view into a larger buffer
4313
- // but because ultimately this is used to return an ArrayBuffer to `someEntry.arrayBuffer()`
4314
- // we need to return copy since we need the `ArrayBuffer`, not the TypedArray to exactly match the data.
4315
- // Note: We could add another API function `bytes()` or something that returned a `Uint8Array`
4316
- // instead of an `ArrayBuffer`. This would let us skip a copy here. But this case only happens for uncompressed
4317
- // data. That seems like a rare enough case that adding a new API is not worth it? Or is it? A zip of jpegs or mp3s
4318
- // might not be compressed. For now that's a TBD.
4319
- return isTypedArraySameAsArrayBuffer(dataView) ? dataView.buffer : dataView.slice().buffer;
4320
- }
4321
- // see comment in readEntryDateAsBlob
4322
- const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize);
4323
- const result = await inflateRawAsync(typedArrayOrBlob, rawEntry.uncompressedSize);
4324
- return result;
4325
- }
4326
-
4327
- async function readEntryDataAsBlob(reader, rawEntry, type) {
4328
- const {decompress, fileDataStart} = await readEntryDataHeader(reader, rawEntry);
4329
- if (!decompress) {
4330
- const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize, type);
4331
- if (isBlob(typedArrayOrBlob)) {
4332
- return typedArrayOrBlob;
4333
- }
4334
- return new Blob([isSharedArrayBuffer(typedArrayOrBlob.buffer) ? new Uint8Array(typedArrayOrBlob) : typedArrayOrBlob], {type});
4335
- }
4336
- // Here's the issue with this mess (should refactor?)
4337
- // if the source is a blob then we really want to pass a blob to inflateRawAsync to avoid a large
4338
- // copy if we're going to a worker.
4339
- const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize);
4340
- const result = await inflateRawAsync(typedArrayOrBlob, rawEntry.uncompressedSize, type);
4341
- return result;
4342
- }
4343
-
4344
- function setOptions$1(options) {
4345
- setOptions(options);
4346
- }
4347
-
4348
- async function unzipRaw(source) {
4349
- let reader;
4350
- if (typeof Blob !== 'undefined' && source instanceof Blob) {
4351
- reader = new BlobReader(source);
4352
- } else if (source instanceof ArrayBuffer || (source && source.buffer && source.buffer instanceof ArrayBuffer)) {
4353
- reader = new ArrayBufferReader(source);
4354
- } else if (isSharedArrayBuffer(source) || isSharedArrayBuffer(source.buffer)) {
4355
- reader = new ArrayBufferReader(source);
4356
- } else if (typeof source === 'string') {
4357
- const req = await fetch(source);
4358
- if (!req.ok) {
4359
- throw new Error(`failed http request ${source}, status: ${req.status}: ${req.statusText}`);
4360
- }
4361
- const blob = await req.blob();
4362
- reader = new BlobReader(blob);
4363
- } else if (typeof source.getLength === 'function' && typeof source.read === 'function') {
4364
- reader = source;
4365
- } else {
4366
- throw new Error('unsupported source type');
4367
- }
4368
-
4369
- const totalLength = await reader.getLength();
4370
-
4371
- if (totalLength > Number.MAX_SAFE_INTEGER) {
4372
- throw new Error(`file too large. size: ${totalLength}. Only file sizes up 4503599627370496 bytes are supported`);
4373
- }
4374
-
4375
- return await findEndOfCentralDirector(reader, totalLength);
4376
- }
4377
-
4378
- // If the names are not utf8 you should use unzipitRaw
4379
- async function unzip(source) {
4380
- const {zip, entries} = await unzipRaw(source);
4381
- return {
4382
- zip,
4383
- entries: Object.fromEntries(entries.map(v => [v.name, v])),
4384
- };
4385
- }
4386
-
4387
- function cleanup$1() {
4388
- cleanup();
4389
- }
4390
-
4391
- var unzipit_module = /*#__PURE__*/Object.freeze({
4392
- __proto__: null,
4393
- HTTPRangeReader: HTTPRangeReader,
4394
- cleanup: cleanup$1,
4395
- setOptions: setOptions$1,
4396
- unzip: unzip,
4397
- unzipRaw: unzipRaw
4398
- });
4399
-
4400
- export { AckType, CrcGenerator, DeviceBoundPacket, DisableDashH2DPacket, DisableDashReplyD2HPacket, EnableDashH2DPacket, EnableDashReplyD2HPacket, EraseFileH2DPacket, EraseFileReplyD2HPacket, ExitFileTransferH2DPacket, ExitFileTransferReplyD2HPacket, FactoryEnableH2DPacket, FactoryEnableReplyD2HPacket, FactoryStatusH2DPacket, FactoryStatusReplyD2HPacket, FileClearUpH2DPacket, FileClearUpReplyD2HPacket, FileControlH2DPacket, FileControlReplyD2HPacket, FileDownloadTarget, FileExitAction, FileFormatH2DPacket, FileFormatReplyD2HPacket, FileInitAction, FileInitOption, FileLoadAction, FileVendor, GetDeviceStatusH2DPacket, GetDeviceStatusReplyD2HPacket, GetDirectoryEntryH2DPacket, GetDirectoryEntryReplyD2HPacket, GetDirectoryFileCountH2DPacket, GetDirectoryFileCountReplyD2HPacket, GetFdtStatusH2DPacket, GetFdtStatusReplyD2HPacket, GetFileMetadataH2DPacket, GetFileMetadataReplyD2HPacket, GetLogCountH2DPacket, GetLogCountReplyD2HPacket, GetMatchStatusH2DPacket, GetProgramSlotInfoH2DPacket, GetProgramSlotInfoReplyD2HPacket, GetRadioModeH2DPacket, GetRadioStatusH2DPacket, GetRadioStatusReplyD2HPacket, GetSlot1to4InfoH2DPacket, GetSlot1to4InfoReplyD2HPacket, GetSlot5to8InfoH2DPacket, GetSlot5to8InfoReplyD2HPacket, GetSystemFlagsH2DPacket, GetSystemFlagsReplyD2HPacket, GetSystemStatusH2DPacket, GetSystemStatusReplyD2HPacket, GetUserDataH2DPacket, GetUserDataReplyD2HPacket, HostBoundPacket, InitFileTransferH2DPacket, InitFileTransferReplyD2HPacket, LinkFileH2DPacket, LinkFileReplyD2HPacket, LoadFileActionH2DPacket, LoadFileActionReplyD2HPacket, MatchModeReplyD2HPacket, MatchStatusReplyD2HPacket, Packet, PacketEncoder, PacketView, ProgramIniConfig, Query1H2DPacket, Query1ReplyD2HPacket, RadioChannelType, ReadFileH2DPacket, ReadFileReplyD2HPacket, ReadKeyValueH2DPacket, ReadKeyValueReplyD2HPacket, ReadLogPageH2DPacket, ReadLogPageReplyD2HPacket, ScreenCaptureH2DPacket, ScreenCaptureReplyD2HPacket, SelectDashH2DPacket, SelectDashReplyD2HPacket, SelectDashScreen, SendDashTouchH2DPacket, SendDashTouchReplyD2HPacket, SerialDeviceType, SetFileMetadataH2DPacket, SetFileMetadataReplyD2HPacket, SmartDeviceType, SystemVersionH2DPacket, SystemVersionReplyD2HPacket, USER_FLASH_END, USER_FLASH_END_B, USER_FLASH_END_C, USER_FLASH_MAX_FILE_SIZE, USER_FLASH_START, USER_FLASH_START_B, USER_FLASH_START_C, USER_FLASH_SYS_CODE_START, USER_FLASH_USR_CODE_START, USER_PROG_CHUNK_SIZE, UpdateMatchModeH2DPacket, V5Battery, V5Brain, V5BrainButton, V5BrainSettings, V5Controller, V5Radio, V5SerialConnection, V5SerialDevice, V5SmartDevice, VexEventEmitter, VexEventTarget, VexFirmwareVersion, VexSerialConnection, VexSerialDevice, WriteFileH2DPacket, WriteFileReplyD2HPacket, WriteKeyValueH2DPacket, WriteKeyValueReplyD2HPacket, downloadFileFromInternet, sleep, sleepUntil, sleepUntilAsync };
4401
- //# sourceMappingURL=v5-serial-protocol.es.js.map