-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWatchPatProtocol.cs
More file actions
305 lines (272 loc) · 9.45 KB
/
Copy pathWatchPatProtocol.cs
File metadata and controls
305 lines (272 loc) · 9.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
using System;
namespace WatchPatBLE;
/// <summary>
/// WatchPAT BLE Protocol Constants
/// Based on reverse-engineered protocol from ITAMAR Medical WatchPAT device
/// </summary>
public static class WatchPatProtocol
{
// GATT Service UUIDs (Nordic UART Service)
public static readonly Guid ServiceUuid = Guid.Parse("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
public static readonly Guid TxCharacteristicUuid = Guid.Parse("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // Write
public static readonly Guid RxCharacteristicUuid = Guid.Parse("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // Notify
public static readonly Guid ClientCharacteristicConfigDescriptorUuid = Guid.Parse("00002902-0000-1000-8000-00805f9b34fb");
// Device name prefix
public const string DeviceNamePrefix = "ITAMAR_";
public const string DeviceNameSuffixNew = "N"; // New device marker
// Session mode constants
public enum SessionMode : byte
{
Sleep = 0x01, // Start sleep session
Recording = 0x02, // Recording mode
Prepare = 0x04 // Prepare mode
}
// Connection states
public enum ConnectionState
{
Disconnected = 0,
Connecting = 1,
Connected = 2
}
// Device discovery states
public enum DiscoveryState
{
NotFound = 0,
SingleDevice = 1,
MultipleDevices = 2
}
/// <summary>
/// Create START SESSION command packet
/// From DeviceCommands.java SessionStartCommandPacket
/// </summary>
public static WatchPatPacket CreateStartSessionCommand(int mobileId, SessionMode mode, string androidVersion)
{
var versionBytes = System.Text.Encoding.ASCII.GetBytes(androidVersion);
// Payload: mobileId (4 bytes) + mode (1 byte) + version (variable) + null terminator (1 byte)
var payload = new List<byte>();
payload.AddRange(BitConverter.GetBytes(mobileId));
payload.Add((byte)mode);
payload.AddRange(versionBytes);
payload.Add(0x00); // Null terminator
// Get current timestamp with timezone offset (milliseconds -> seconds)
var now = DateTimeOffset.Now;
long timestamp = now.ToUnixTimeSeconds();
return new WatchPatPacket(
WatchPatPacket.CommandId.StartSession,
payload.ToArray(),
flags: 0,
timestamp: timestamp
);
}
/// <summary>
/// Create STOP ACQUISITION command
/// From DeviceCommands.java line 542-546
/// </summary>
public static WatchPatPacket CreateStopSessionCommand()
{
return new WatchPatPacket(
WatchPatPacket.CommandId.StopAcquisition,
payload: null
);
}
/// <summary>
/// Create TECHNICAL STATUS REQUEST command
/// From DeviceCommands.java line 470-474
/// </summary>
public static WatchPatPacket CreateGetStatusCommand()
{
return new WatchPatPacket(
WatchPatPacket.CommandId.TechnicalStatusRequest,
payload: null
);
}
/// <summary>
/// Create START ACQUISITION command
/// </summary>
public static WatchPatPacket CreateStartAcquisitionCommand()
{
return new WatchPatPacket(
WatchPatPacket.CommandId.StartAcquisition,
payload: null
);
}
/// <summary>
/// Create SEND STORED DATA command
/// </summary>
public static WatchPatPacket CreateSendStoredDataCommand()
{
return new WatchPatPacket(
WatchPatPacket.CommandId.SendStoredData,
payload: null
);
}
/// <summary>
/// Create SET LEDs command
/// From DeviceCommands.java line 512-516
/// </summary>
/// <param name="ledByte">LED control byte (0x00=off, 0xFF=all on, or bit pattern)</param>
public static WatchPatPacket CreateSetLEDsCommand(byte ledByte)
{
return new WatchPatPacket(
WatchPatPacket.CommandId.SetLEDs,
payload: new byte[] { ledByte }
);
}
/// <summary>
/// Create SET LEDs OFF command (convenience)
/// </summary>
public static WatchPatPacket CreateSetLEDsOffCommand()
{
return CreateSetLEDsCommand(0x00);
}
/// <summary>
/// Create SET LEDs ON command (convenience)
/// </summary>
public static WatchPatPacket CreateSetLEDsOnCommand()
{
return CreateSetLEDsCommand(0xFF);
}
/// <summary>
/// Create IS_DEVICE_PAIRED command (required after connection)
/// From DeviceCommands.java line 476-480
/// </summary>
public static WatchPatPacket CreateIsDevicePairedCommand()
{
return new WatchPatPacket(
WatchPatPacket.CommandId.IsDevicePaired,
payload: null
);
}
/// <summary>
/// Create ACK command to acknowledge received packets
/// From DeviceCommands.java line 499-508 (AckPacket)
/// ACK Status Codes:
/// 0 = ACK_OK
/// 1 = ACK_CRC_ERR
/// 2 = ACK_ILLEGAL_OP_CODE
/// 3 = ACK_NON_UNIQ_ID
/// 4 = ACK_INVALID_PARAM
/// </summary>
/// <param name="ackedCommandId">The command ID being acknowledged</param>
/// <param name="status">ACK status (0 = OK)</param>
/// <param name="transactionId">Transaction ID from the packet being acknowledged</param>
public static WatchPatPacket CreateAckCommand(ushort ackedCommandId, byte status, int transactionId)
{
// ACK payload: [AckedCmdId:2 bytes][Status:1 byte][Reserved:2 bytes]
// AckedCmdId needs byte reversal (like we do for all command IDs)
ushort reversedCmdId = (ushort)((ackedCommandId >> 8) | (ackedCommandId << 8));
var payload = new byte[5];
payload[0] = (byte)(reversedCmdId & 0xFF);
payload[1] = (byte)(reversedCmdId >> 8);
payload[2] = status;
payload[3] = 0; // Reserved
payload[4] = 0; // Reserved
return new WatchPatPacket(
WatchPatPacket.CommandId.Ack,
payload,
transactionId: transactionId
);
}
/// <summary>
/// Create RESET DEVICE command
/// From DeviceCommands.java line 482-486 (ResetCommandPacket)
/// </summary>
/// <param name="resetType">0 = soft reset, 1 = hard reset</param>
public static WatchPatPacket CreateResetDeviceCommand(byte resetType = 0)
{
return new WatchPatPacket(
WatchPatPacket.CommandId.ResetDevice,
payload: new byte[] { resetType }
);
}
/// <summary>
/// Create START FINGER DETECTION command
/// From DeviceCommands.java line 530-534
/// </summary>
public static WatchPatPacket CreateStartFingerDetectionCommand()
{
return new WatchPatPacket(
WatchPatPacket.CommandId.StartFingerDetection,
payload: null
);
}
/// <summary>
/// Create GET LOG FILE command
/// From DeviceCommands.java GetLogFilePacket
/// Downloads device log in 2048-byte chunks
/// </summary>
/// <param name="offset">Byte offset to start reading from (increments by 2048)</param>
public static WatchPatPacket CreateGetLogFileCommand(int offset)
{
// Payload: [Offset:4 bytes][ChunkSize:4 bytes]
// Java uses Integer.reverseBytes() before writing, so we do the same
var payload = new byte[8];
// Reverse bytes for offset (matches Java Integer.reverseBytes)
byte[] offsetBytes = BitConverter.GetBytes(offset);
payload[0] = offsetBytes[3];
payload[1] = offsetBytes[2];
payload[2] = offsetBytes[1];
payload[3] = offsetBytes[0];
// Reverse bytes for chunk size (always 2048)
byte[] sizeBytes = BitConverter.GetBytes(2048);
payload[4] = sizeBytes[3];
payload[5] = sizeBytes[2];
payload[6] = sizeBytes[1];
payload[7] = sizeBytes[0];
return new WatchPatPacket(
WatchPatPacket.CommandId.GetLogFile,
payload
);
}
/// <summary>
/// Parse serial number from device name
/// Device name format: ITAMAR_[HEX]N or ITAMAR_[HEX]
/// </summary>
public static string ParseSerialNumber(string deviceName)
{
if (!deviceName.StartsWith(DeviceNamePrefix))
return null;
var hexPart = deviceName.Substring(DeviceNamePrefix.Length).Replace("N", "");
try
{
// Convert hex to decimal and format as 9-digit serial
int serialInt = Convert.ToInt32(hexPart, 16);
return serialInt.ToString("D9");
}
catch
{
return null;
}
}
/// <summary>
/// Convert serial number to hex format for device name
/// </summary>
public static string SerialToHex(string serial)
{
if (int.TryParse(serial, out int serialInt))
{
return serialInt.ToString("X");
}
return null;
}
/// <summary>
/// Generate mobile ID from Bluetooth adapter MAC address
/// </summary>
public static int GenerateMobileId(string macAddress)
{
// Take first 4 bytes of MAC address
var bytes = System.Text.Encoding.ASCII.GetBytes(macAddress);
if (bytes.Length >= 4)
{
return BitConverter.ToInt32(bytes, 0);
}
return Environment.TickCount; // Fallback to timestamp-based ID
}
/// <summary>
/// Format byte array as hex string for logging
/// </summary>
public static string ByteArrayToHex(byte[] data)
{
return BitConverter.ToString(data).Replace("-", " ");
}
}