This repository was archived by the owner on Nov 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBluetoothClient.cs
More file actions
94 lines (77 loc) · 3.07 KB
/
BluetoothClient.cs
File metadata and controls
94 lines (77 loc) · 3.07 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
using System;
using UnityEngine;
namespace UnityAndroidBluetooth{
public class BluetoothClient: Bluetooth {
/* ========== CONSTANTS ========== */
private const string COULD_NOT_CREATE_SOCKET = "client.error.COULD_NOT_CREATE_SOCKET";
private const string COULD_NOT_CONNECT = "client.error.COULD_NOT_CONNECT";
private const string CONNECTION_LOST = "client.connection_lost";
private const string DISCONNECTED = "client.disconnected";
/* ========== EVENT HANDLING ========== */
public event EventHandler ConnectionLost;
public event EventHandler Disconnected;
public event EventHandler<DeviceInfoEventArgs> Connected;
protected virtual void OnConnectionLost()
{
ConnectionLost?.Invoke(this, EventArgs.Empty);
}
protected virtual void OnDisconnected()
{
Disconnected?.Invoke(this, EventArgs.Empty);
}
protected virtual void OnConnected(DeviceInfoEventArgs e)
{
Connected?.Invoke(this, e);
}
// JNI Interface
protected class OnAndroidClientStatus : Bluetooth.OnAndroidStatus {
BluetoothClient client;
public OnAndroidClientStatus(BluetoothClient c) : base(c) {
client = c;
}
public override void OnStatus(string message){
base.OnStatus(message);
switch(message) {
case BluetoothClient.COULD_NOT_CREATE_SOCKET:
throw new BluetoothException("The client could not create a socket");
case BluetoothClient.COULD_NOT_CONNECT:
throw new BluetoothException("The client could not connect to the server");
case BluetoothClient.CONNECTION_LOST:
client.OnConnectionLost();
break;
case BluetoothClient.DISCONNECTED:
client.OnDisconnected();
break;
}
string[] tokens = message.Split('.');
if (tokens[0] == "client" && tokens[1] == "connected")
{
DeviceInfoEventArgs e = new DeviceInfoEventArgs();
e.Device = Bluetooth.GetDevice(tokens[2]);
client.OnConnected(e);
}
}
}
public BluetoothClient() : base("com.guevara.bluetooth.BluetoothClient")
{
SetOnAndroidStatus(new OnAndroidClientStatus(this));
}
/* ========== JNI METHODS ========== */
public bool Connect(string address, string uuid)
{
return PluginInstance.Call("connect", address, uuid);
}
public bool Connect(string address)
{
return PluginInstance.Call("connect", address);
}
public void Disconnect()
{
PluginInstance.Call("disconnect");
}
public void Send(string message)
{
PluginInstance.Call("send", message);
}
}
}