/
SwiftQuickBluePlugin.swift
236 lines (213 loc) · 9.48 KB
/
SwiftQuickBluePlugin.swift
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
import CoreBluetooth
import Flutter
import UIKit
let GATT_HEADER_LENGTH = 3
let GSS_SUFFIX = "0000-1000-8000-00805f9b34fb"
extension CBUUID {
public var uuidStr: String {
get {
uuidString.lowercased()
}
}
}
extension CBPeripheral {
// FIXME https://forums.developer.apple.com/thread/84375
public var uuid: UUID {
get {
value(forKey: "identifier") as! NSUUID as UUID
}
}
public func getCharacteristic(_ characteristic: String, of service: String) -> CBCharacteristic {
let s = self.services?.first {
$0.uuid.uuidStr == service || "0000\($0.uuid.uuidStr)-\(GSS_SUFFIX)" == service
}
let c = s?.characteristics?.first {
$0.uuid.uuidStr == characteristic || "0000\($0.uuid.uuidStr)-\(GSS_SUFFIX)" == characteristic
}
return c!
}
public func setNotifiable(_ bleInputProperty: String, for characteristic: String, of service: String) {
setNotifyValue(bleInputProperty != "disabled", for: getCharacteristic(characteristic, of: service))
}
}
public class SwiftQuickBluePlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let method = FlutterMethodChannel(name: "quick_blue/method", binaryMessenger: registrar.messenger())
let eventScanResult = FlutterEventChannel(name: "quick_blue/event.scanResult", binaryMessenger: registrar.messenger())
let messageConnector = FlutterBasicMessageChannel(name: "quick_blue/message.connector", binaryMessenger: registrar.messenger())
let instance = SwiftQuickBluePlugin()
registrar.addMethodCallDelegate(instance, channel: method)
eventScanResult.setStreamHandler(instance)
instance.messageConnector = messageConnector
}
private var manager: CBCentralManager!
private var discoveredPeripherals: Dictionary<String, CBPeripheral>!
private var scanResultSink: FlutterEventSink?
private var messageConnector: FlutterBasicMessageChannel!
override init() {
super.init()
manager = CBCentralManager(delegate: self, queue: nil)
discoveredPeripherals = Dictionary()
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "startScan":
manager.scanForPeripherals(withServices: nil)
result(nil)
case "stopScan":
manager.stopScan()
result(nil)
case "connect":
let arguments = call.arguments as! Dictionary<String, Any>
let deviceId = arguments["deviceId"] as! String
guard let peripheral = discoveredPeripherals[deviceId] else {
result(FlutterError(code: "IllegalArgument", message: "Unknown deviceId:\(deviceId)", details: nil))
return
}
peripheral.delegate = self
manager.connect(peripheral)
result(nil)
case "disconnect":
let arguments = call.arguments as! Dictionary<String, Any>
let deviceId = arguments["deviceId"] as! String
guard let peripheral = discoveredPeripherals[deviceId] else {
result(FlutterError(code: "IllegalArgument", message: "Unknown deviceId:\(deviceId)", details: nil))
return
}
if (peripheral.state != .disconnected) {
manager.cancelPeripheralConnection(peripheral)
}
result(nil)
case "discoverServices":
let arguments = call.arguments as! Dictionary<String, Any>
let deviceId = arguments["deviceId"] as! String
guard let peripheral = discoveredPeripherals[deviceId] else {
result(FlutterError(code: "IllegalArgument", message: "Unknown deviceId:\(deviceId)", details: nil))
return
}
peripheral.discoverServices(nil)
result(nil)
case "setNotifiable":
let arguments = call.arguments as! Dictionary<String, Any>
let deviceId = arguments["deviceId"] as! String
let service = arguments["service"] as! String
let characteristic = arguments["characteristic"] as! String
let bleInputProperty = arguments["bleInputProperty"] as! String
guard let peripheral = discoveredPeripherals[deviceId] else {
result(FlutterError(code: "IllegalArgument", message: "Unknown deviceId:\(deviceId)", details: nil))
return
}
peripheral.setNotifiable(bleInputProperty, for: characteristic, of: service)
result(nil)
case "requestMtu":
let arguments = call.arguments as! Dictionary<String, Any>
let deviceId = arguments["deviceId"] as! String
guard let peripheral = discoveredPeripherals[deviceId] else {
result(FlutterError(code: "IllegalArgument", message: "Unknown deviceId:\(deviceId)", details: nil))
return
}
result(nil)
let mtu = peripheral.maximumWriteValueLength(for: .withoutResponse)
print("peripheral.maximumWriteValueLengthForType:CBCharacteristicWriteWithoutResponse \(mtu)")
messageConnector.sendMessage(["mtuConfig": mtu + GATT_HEADER_LENGTH])
case "writeValue":
let arguments = call.arguments as! Dictionary<String, Any>
let deviceId = arguments["deviceId"] as! String
let service = arguments["service"] as! String
let characteristic = arguments["characteristic"] as! String
let value = arguments["value"] as! FlutterStandardTypedData
let bleOutputProperty = arguments["bleOutputProperty"] as! String
guard let peripheral = discoveredPeripherals[deviceId] else {
result(FlutterError(code: "IllegalArgument", message: "Unknown deviceId:\(deviceId)", details: nil))
return
}
let type = bleOutputProperty == "withoutResponse" ? CBCharacteristicWriteType.withoutResponse : CBCharacteristicWriteType.withResponse
peripheral.writeValue(value.data, for: peripheral.getCharacteristic(characteristic, of: service), type: type)
result(nil)
default:
result(FlutterMethodNotImplemented)
}
}
}
extension SwiftQuickBluePlugin: CBCentralManagerDelegate {
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
print("centralManagerDidUpdateState \(central.state.rawValue)")
}
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
print("centralManager:didDiscoverPeripheral \(peripheral.name) \(peripheral.uuid.uuidString)")
discoveredPeripherals[peripheral.uuid.uuidString] = peripheral
let manufacturerData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data
scanResultSink?([
"name": peripheral.name ?? "",
"deviceId": peripheral.uuid.uuidString,
"manufacturerData": FlutterStandardTypedData(bytes: manufacturerData ?? Data()),
"rssi": RSSI,
])
}
public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("centralManager:didConnect \(peripheral.uuid.uuidString)")
messageConnector.sendMessage([
"deviceId": peripheral.uuid.uuidString,
"ConnectionState": "connected",
])
}
public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("centralManager:didDisconnectPeripheral: \(peripheral.uuid.uuidString) error: \(error)")
messageConnector.sendMessage([
"deviceId": peripheral.uuid.uuidString,
"ConnectionState": "disconnected",
])
}
}
extension SwiftQuickBluePlugin: FlutterStreamHandler {
open func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
guard let args = arguments as? Dictionary<String, Any>, let name = args["name"] as? String else {
return nil
}
print("QuickBlueMacosPlugin onListenWithArguments:\(name)")
if name == "scanResult" {
scanResultSink = events
}
return nil
}
open func onCancel(withArguments arguments: Any?) -> FlutterError? {
guard let args = arguments as? Dictionary<String, Any>, let name = args["name"] as? String else {
return nil
}
print("QuickBlueMacosPlugin onCancelWithArguments:\(name)")
if name == "scanResult" {
scanResultSink = nil
}
return nil
}
}
extension SwiftQuickBluePlugin: CBPeripheralDelegate {
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
print("peripheral: \(peripheral.uuid.uuidString) didDiscoverServices: \(error)")
for service in peripheral.services! {
peripheral.discoverCharacteristics(nil, for: service)
}
}
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics! {
print("peripheral:didDiscoverCharacteristicsForService (\(service.uuid.uuidStr), \(characteristic.uuid.uuidStr)")
}
self.messageConnector.sendMessage([
"deviceId": peripheral.uuid.uuidString,
"ServiceState": "discovered",
"services": [service.uuid.uuidStr],
])
}
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
print("peripheral:didWriteValueForCharacteristic \(characteristic.uuid.uuidStr) \(characteristic.value as? NSData) error: \(error)")
}
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("peripheral:didUpdateValueForForCharacteristic \(characteristic.uuid) \(characteristic.value as! NSData) error: \(error)")
self.messageConnector.sendMessage([
"characteristicValue": [
"characteristic": characteristic.uuid.uuidStr,
"value": FlutterStandardTypedData(bytes: characteristic.value!)
]
])
}
}