-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBLEController.cs
427 lines (363 loc) · 13.8 KB
/
BLEController.cs
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
using UnityEngine;
using System;
using ITiles;
using System.Collections.Generic;
public class BLEController : MonoBehaviour
{
private AndroidJavaObject bleManager;
#region Subscribable itile events
public delegate void DataReceivedEventHandler(string data);
public event DataReceivedEventHandler DataReceived;
public delegate void MasterTilesDiscoveredEventHandler(List<string> discovered_itiles);
public event MasterTilesDiscoveredEventHandler MasterTilesDiscovered;
public delegate void ConnectionStateChangedEventHandler(CONNECTION_STATE connectionState);
public event ConnectionStateChangedEventHandler ConnectionStateChanged;
public delegate void ITileTouchedEventHandler(TOUCH_RESPONSE touch_response);
public event ITileTouchedEventHandler ITileTouched;
public delegate void ITileShakedEventHandler(SHAKE_RESPONSE shake_response);
public event ITileShakedEventHandler ITileShaked;
public delegate void ITileSidePairedEventHandler(SIDE_PAIR_RESPONSE side_pair_response);
public event ITileSidePairedEventHandler ITileSidePaired;
public delegate void ITileStepChangedEventHandler(STEP_CHANGE_RESPONSE step_change_response);
public event ITileStepChangedEventHandler ITileStepChanged;
public delegate void ITileTimedOutEventHandler();
public event ITileTimedOutEventHandler ITileTimedOut;
public delegate void PairedITileListReceivedEventHandler(PAIRED_TILES_RESPONSE paired_tile_response);
public event PairedITileListReceivedEventHandler PairedITileListReceived;
public delegate void OnlineITileStatusReceivedEventHandler(ONLINE_TILES_RESPONSE online_tile_response);
public event OnlineITileStatusReceivedEventHandler OnlineITileStatusReceived;
public delegate void BatteryStatusReceivedEventHandler(BATTERY_STATUS_RESPONSE battery_status_response);
public event BatteryStatusReceivedEventHandler BatteryStatusReceived;
#endregion
public static BLEController itile;
private void Awake()
{
DontDestroyOnLoad(this.gameObject);
itile = this;
}
void Start()
{
try
{
using (AndroidJavaClass javaClass = new AndroidJavaClass(CONFIG_STRINGS.UNITY_PLAYER_CLASS))
{
AndroidJavaObject unityActivity = javaClass.GetStatic<AndroidJavaObject>("currentActivity");
bleManager = new AndroidJavaObject(CONFIG_STRINGS.ANDROID_LIBRARY_MAIN_CLASS, unityActivity);
BLEDataCallbackProxy dataCallback = new BLEDataCallbackProxy(this);
bleManager.Call(ANDROID_ITILE_METHOD.SET_CALLBACK, dataCallback);
}
}
catch (Exception e) {
Debug.LogError(e.Message);
}
}
#region Event Invoker methods
public void OnConnectionStateChanged(CONNECTION_STATE connectionState)
{
ConnectionStateChanged?.Invoke(connectionState);
}
public void DiscoveredMasterTiles(string deviceIds)
{
string preProcessedJson = "{\"discoveredItileIds\": #}".Replace("#", deviceIds);
TileIdList jsonData = JsonUtility.FromJson<TileIdList>(preProcessedJson);
List<string> masterTileIds = new List<string>();
foreach (string id in jsonData.discoveredItileIds)
{
masterTileIds.Add(id);
}
MasterTilesDiscovered?.Invoke(masterTileIds);
}
public void ReceiveData(string value)
{
DataReceived?.Invoke(value);
DecodeMessage(value);
}
#endregion
#region Main iTile methods
public void StartScan() {
bleManager.Call(ANDROID_ITILE_METHOD.START_SCAN);
}
public void StopScan()
{
bleManager.Call(ANDROID_ITILE_METHOD.STOP_SCAN);
}
public void Connect(string deviceAddress)
{
bleManager.Call(ANDROID_ITILE_METHOD.CONNECT,
deviceAddress,
CONFIG_STRINGS.ITILES_BLE_SERVICE_UUID,
CONFIG_STRINGS.CHARACTERISTIC_UUID_RX,
CONFIG_STRINGS.CHARACTERISTIC_UUID_TX
);
}
public void Read()
{
bleManager.Call(ANDROID_ITILE_METHOD.START_READ);
}
public void Write(byte[] data)
{
bleManager.Call(ANDROID_ITILE_METHOD.WRITE, data);
}
// Method to send the specific command with parameters to the BLE device
private void SendCommand(TX_COMMAND command, byte[] parameters, SELECT_ITILE tileId = SELECT_ITILE.ALL)
{
// Command packet format: [Start Byte][Tile ID][Command][Length][Parameters][End Byte]
byte[] commandPacket = new byte[5 + parameters.Length];
commandPacket[0] = (byte)TX_COMMAND.START_BYTE;
commandPacket[1] = (byte)tileId;
commandPacket[2] = (byte)command;
commandPacket[3] = (byte)parameters.Length;
Array.Copy(parameters, 0, commandPacket, 4, parameters.Length);
commandPacket[^1] = (byte)TX_COMMAND.END_BYTE;
string byteCmdString = string.Join(", ", commandPacket);
Console.WriteLine("Sending message to iTile: " + byteCmdString);
// Convert the byte array to sbyte array
sbyte[] sbyteCmd = new sbyte[commandPacket.Length];
for (int i = 0; i < commandPacket.Length; i++)
{
sbyteCmd[i] = (sbyte)commandPacket[i];
}
// Send the command packet to the BLE device
string sbyteCmdString = string.Join(", ", sbyteCmd);
bleManager.Call("write", sbyteCmd);
}
private void DecodeMessage(string message)
{
byte[] byteMessage = HexStringToByteArray(message);
// Command packet format: [Start Byte][Tile ID][Command][Length][Parameters][End Byte]
switch ((RX_COMMAND)byteMessage[2]) {
case RX_COMMAND.REPLY_PAIRED_TILES:
PairedITileListReceived?.Invoke(new PAIRED_TILES_RESPONSE(byteMessage));
break;
case RX_COMMAND.REPLY_ONLINE_TILES:
OnlineITileStatusReceived?.Invoke(new ONLINE_TILES_RESPONSE(byteMessage));
break;
case RX_COMMAND.SHAKE:
ITileShaked?.Invoke(new SHAKE_RESPONSE(byteMessage));
break;
case RX_COMMAND.SIDE_UPDATE:
ITileSidePaired?.Invoke(new SIDE_PAIR_RESPONSE(byteMessage));
break;
case RX_COMMAND.STEP_CHANGE:
ITileStepChanged?.Invoke(new STEP_CHANGE_RESPONSE(byteMessage));
break;
case RX_COMMAND.TILE_TIMEOUT:
ITileTimedOut?.Invoke();
break;
case RX_COMMAND.TOUCH:
ITileTouched?.Invoke(new TOUCH_RESPONSE(byteMessage));
break;
case RX_COMMAND.REPLY_BATTERY_LEVEL:
BatteryStatusReceived?.Invoke(new BATTERY_STATUS_RESPONSE(byteMessage));
break;
}
}
public void PairTiles(byte[] masterTileMacAddress)
{
SendCommand(TX_COMMAND.BROADCAST, masterTileMacAddress);
}
public void UnpairTile(SELECT_ITILE tileID)
{
SendCommand(TX_COMMAND.UNPAIR, new byte[0], tileID);
}
public void ClearMacList() {
SendCommand(TX_COMMAND.CLEAR_MAC_LIST, new byte[0]);
}
public void QueryPairedTiles()
{
SendCommand(TX_COMMAND.QUERY_PAIRED_TILES, new byte[0]);
}
public void QueryOnlineTiles(SELECT_ITILE tileId = SELECT_ITILE.ALL)
{
SendCommand(TX_COMMAND.QUERY_ONLINE_TILES, new byte[0], tileId);
}
public void TriggerLight(
TILE_COLOR color,
TIMEOUT_DELAY offAfterSeconds,
LOG_REACTION_TIME logReactionTime,
TIMEOUT_RESPONSE timeoutResponse,
SELECT_ITILE tileId
)
{
byte[] parameters = new byte[] { color.R, color.G, color.B, (byte)offAfterSeconds, (byte)logReactionTime, (byte)timeoutResponse };
SendCommand(TX_COMMAND.TRIGGER_LIGHT, parameters, tileId);
}
public void TriggerSound(
SOUND_TRACK soundTrackID,
REPEAT_COUNT repeatCount,
LOG_REACTION_TIME logReactionTime,
TIMEOUT_RESPONSE timeoutResponse,
SELECT_ITILE tileId
)
{
byte[] parameters = new byte[] { (byte)soundTrackID, (byte)repeatCount, (byte)logReactionTime, (byte)timeoutResponse };
SendCommand(TX_COMMAND.TRIGGER_SOUND, parameters, tileId);
}
public void TriggerVibration(
VIBRATION_PATTERN vibrationPatternID,
REPEAT_COUNT repeatCount,
LOG_REACTION_TIME logReactionTime,
TIMEOUT_RESPONSE timeoutResponse,
SELECT_ITILE tileId)
{
byte[] parameters = new byte[] { (byte)vibrationPatternID, (byte)repeatCount, (byte)logReactionTime, (byte)timeoutResponse };
SendCommand(TX_COMMAND.TRIGGER_VIBRATE, parameters, tileId);
}
// Method to light up tile sides
public void TriggerLight(
SIDE_COLORS sideColors,
TIMEOUT_DELAY offAfterSeconds,
LOG_REACTION_TIME logReactionTime,
TIMEOUT_RESPONSE timeoutResponse,
SELECT_ITILE tileId
)
{
byte[] colors = sideColors.GET_BYTES();
byte[] parameters = new byte[colors.Length + 3];
Array.Copy(colors, 0, parameters, 0, colors.Length);
parameters[^3] = (byte)offAfterSeconds;
parameters[^2] = (byte)logReactionTime;
parameters[^1] = (byte)timeoutResponse;
SendCommand(TX_COMMAND.TRIGGER_SIDE, parameters, tileId);
}
public void TriggerEffect() {
throw new NotImplementedException();
}
public void TriggerLightSoundVibration(
TILE_COLOR lightColor,
TIMEOUT_DELAY timeoutDelay,
SOUND_TRACK soundTrackId,
VIBRATION_PATTERN vibrationPattern,
REPEAT_COUNT repeatCount,
LOG_REACTION_TIME logReactionTime,
TIMEOUT_RESPONSE timeoutResponse,
SELECT_ITILE tileId
) {
byte[] parameters = new byte[] {
lightColor.R,
lightColor.G,
lightColor.B,
(byte)timeoutDelay,
(byte)soundTrackId,
0x00, // not implemented
(byte)vibrationPattern,
(byte)repeatCount,
(byte)logReactionTime,
(byte)timeoutResponse,
};
SendCommand(TX_COMMAND.ADVANCE_TRIGGER, parameters, tileId);
}
public void TurnOffLight(SELECT_ITILE tileId)
{
SendCommand(TX_COMMAND.OFF_LIGHT, new byte[0], tileId);
}
public void StopEffect(SELECT_ITILE tileId)
{
SendCommand(TX_COMMAND.STOP_EFFECT, new byte[0], tileId);
}
public void TriggerLightSoundVibration(
SIDE_COLORS sideColor,
TIMEOUT_DELAY timeoutDelay,
SOUND_TRACK soundTrackId,
VIBRATION_PATTERN vibrationPattern,
REPEAT_COUNT repeatCount,
LOG_REACTION_TIME logReactionTime,
TIMEOUT_RESPONSE timeoutResponse,
SELECT_ITILE tileId
)
{
byte[] parameters = new byte[] {
sideColor.SIDE_1.R, sideColor.SIDE_1.G, sideColor.SIDE_1.B,
sideColor.SIDE_2.R, sideColor.SIDE_2.G, sideColor.SIDE_2.B,
sideColor.SIDE_3.R, sideColor.SIDE_3.G, sideColor.SIDE_3.B,
sideColor.SIDE_4.R, sideColor.SIDE_4.G, sideColor.SIDE_4.B,
sideColor.SIDE_5.R, sideColor.SIDE_5.G, sideColor.SIDE_5.B,
sideColor.SIDE_6.R, sideColor.SIDE_6.G, sideColor.SIDE_6.B,
(byte)timeoutDelay,
(byte)soundTrackId,
0x00, // not implemented
(byte)vibrationPattern,
(byte)repeatCount,
(byte)logReactionTime,
(byte)timeoutResponse,
};
SendCommand(TX_COMMAND.SUPER_TRIGGER, parameters, tileId);
}
public void ToggleShakeSensor(
TOGGLE_SENSOR toggle,
SELECT_ITILE tileId
)
{
SendCommand(TX_COMMAND.ENABLE_DISABLE_ACCEL, new byte[] { (byte)toggle}, tileId);
}
public void SetShakeThreshold(
byte accelerationThreshold,
SELECT_ITILE tileId
)
{
SendCommand(TX_COMMAND.SET_ACCEL_THRESHOLD, new byte[] { accelerationThreshold }, tileId);
}
public void ToggleTouchSensor(
TOGGLE_SENSOR toggle,
SELECT_ITILE tileId
)
{
SendCommand(TX_COMMAND.ENABLE_DISABLE_TOUCH, new byte[] { (byte)toggle}, tileId);
}
public void ConfirmAssignement(
SELECT_ITILE tileId
)
{
SendCommand(TX_COMMAND.CONFIRM_ASSIGNMENT, new byte[0], tileId);
}
public void GameInProgress(
GAME_STATUS gameStatus,
SELECT_ITILE tileId
)
{
SendCommand(TX_COMMAND.GAME_IN_PROGRESS, new byte[] {(byte)gameStatus }, tileId);
}
public void AssignFeedback(
FEEDBACK_STATUS feedbackStatus,
TILE_COLOR color,
SOUND_TRACK soundTrackId,
VIBRATION_PATTERN vibrationPattern,
TIMEOUT_DELAY timeoutDelay,
SELECT_ITILE tileId
) {
SendCommand(TX_COMMAND.ASSIGN_FEEDBACK, new byte[] {(byte)feedbackStatus, (byte)color.R, color.G, color.B, (byte)soundTrackId, (byte)vibrationPattern, (byte)timeoutDelay }, tileId);
}
public void GetBattery(
SELECT_ITILE tileId
) {
SendCommand(TX_COMMAND.GET_BATTERY_LEVEL, new byte[0], tileId);
}
public void SetVolume(byte[] parameters, SELECT_ITILE tileId)
{
throw new NotImplementedException();
}
#endregion
#region Utility methods
public static byte[] HexStringToByteArray(string hex)
{
Debug.Log(hex);
hex = hex.Replace(":", "");
if (hex.Length % 2 != 0)
{
throw new ArgumentException("Hex string length must be even.");
}
byte[] byteArray = new byte[hex.Length / 2];
for (int i = 0; i < byteArray.Length; i++)
{
string byteValue = hex.Substring(i * 2, 2);
byteArray[i] = Convert.ToByte(byteValue, 16);
}
return byteArray;
}
#endregion
}
[System.Serializable]
public class TileIdList
{
public string[] discoveredItileIds;
}