ConnectionService.kt 5.63 KB
Newer Older
Anon's avatar
Anon committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
 * Copyright by the original author or authors.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package de.ccc.events.badge.card10.common

25
import android.bluetooth.*
Anon's avatar
Anon committed
26
27
import android.content.Context
import android.util.Log
28
import de.ccc.events.badge.card10.CARD10_BLUETOOTH_MAC_PREFIX
Anon's avatar
Anon committed
29
import de.ccc.events.badge.card10.CARD10_SERVICE_UUID
30
import de.ccc.events.badge.card10.FILE_SERVICE_UUID
31
import de.ccc.events.badge.card10.R
Anon's avatar
Anon committed
32
import de.ccc.events.badge.card10.filetransfer.LowEffortService
Anon's avatar
Anon committed
33
import de.ccc.events.badge.card10.time.Card10Service
Anon's avatar
Anon committed
34
35
36
37
38
39
40
41
42
import java.lang.IllegalStateException
import java.lang.NullPointerException
import java.util.*

private const val TAG = "ConnectionService"

object ConnectionService {
    var device: BluetoothDevice? = null
    var leService: LowEffortService? = null
Anon's avatar
Anon committed
43
    var card10Service: Card10Service? = null
Anon's avatar
Anon committed
44
45
46
47
48
    var mtu = 100

    private var connection: BluetoothGatt? = null

    private var connectionState = BluetoothGatt.STATE_DISCONNECTED
Anon's avatar
Anon committed
49
    private var gattListeners = mutableMapOf<String, GattListener>()
Anon's avatar
Anon committed
50
51
52
53
54
55
56
57
58
59
60
61
62

    val deviceName: String?
        get() = device?.name

    val deviceAddress: String?
        get() = device?.address

    fun hasDevice(): Boolean {
        return device != null
    }

    fun isConnected() = connectionState == BluetoothGatt.STATE_CONNECTED

Anon's avatar
Anon committed
63
64
    fun addGattListener(tag: String, listener: GattListener) {
        gattListeners[tag] = listener
Anon's avatar
Anon committed
65
66
67
    }

    fun connect(context: Context) {
68
69
70
71
72
73
74
75
76
77
78
79
80
81
        // Use first BLE devices that is bonded
        val bondedDevices = BluetoothAdapter.getDefaultAdapter().bondedDevices.filter {
            it.address.startsWith(
                CARD10_BLUETOOTH_MAC_PREFIX,
                true
            )
        }

        if (bondedDevices.isEmpty()) {
            throw ConnectionException(context.getString(R.string.connection_error_no_bonded_device))
        }

        device = bondedDevices[0]

Anon's avatar
Anon committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        // 1. Connect
        // 2. Discover services
        // 3. Change MTU
        // 4. ???
        // 5. Profit
        connection = device?.connectGatt(context, true, gattCallback)
    }

    private val gattCallback = object : BluetoothGattCallback() {
        override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
            if (gatt == null) {
                throw NullPointerException()
            }

            connection = gatt

            for (service in gatt.services) {
                Log.d(TAG, "Found service: ${service.uuid}")

101
                if (service.uuid == FILE_SERVICE_UUID) {
Anon's avatar
Anon committed
102
                    leService = LowEffortService(service)
Anon's avatar
Anon committed
103
104
                } else if (service.uuid == CARD10_SERVICE_UUID) {
                    card10Service = Card10Service(service)
Anon's avatar
Anon committed
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
                }
            }

            if (leService == null) {
                Log.e(TAG, "Could not find file transfer service")
                return
            }

            gatt.requestMtu(mtu)
        }

        override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
            connectionState = newState
            connection = gatt

            when (newState) {
                BluetoothGatt.STATE_CONNECTED -> {
                    gatt?.discoverServices()
                }
            }
        }

        override fun onMtuChanged(gatt: BluetoothGatt?, newMtu: Int, status: Int) {
            Log.d(TAG, "MTU changed to: $newMtu")

            if (gatt == null) {
                throw IllegalStateException()
            }

            mtu = newMtu - 3 // Very precise science

            leService?.enableNotify(gatt)
Anon's avatar
Anon committed
137
138

            gattListeners.values.map { it.onConnectionReady() }
Anon's avatar
Anon committed
139
140
141
142
143
144
145
146
147
148
149
150
151
        }

        override fun onCharacteristicWrite(
            gatt: BluetoothGatt?,
            characteristic: BluetoothGattCharacteristic?,
            status: Int
        ) {
            if (gatt == null || characteristic == null) {
                throw IllegalStateException()
            }

            connection = gatt

Anon's avatar
Anon committed
152
            gattListeners.values.map { it.onCharacteristicWrite(characteristic, status) }
Anon's avatar
Anon committed
153
154
155
156
157
158
159
160
161
        }

        override fun onCharacteristicChanged(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) {
            connection = gatt

            if (gatt == null || characteristic == null) {
                throw IllegalStateException()
            }

Anon's avatar
Anon committed
162
            gattListeners.values.map { it.onCharacteristicChanged(characteristic) }
Anon's avatar
Anon committed
163
164
165
166
        }
    }

    fun writeCharacteristic(characteristic: BluetoothGattCharacteristic): Boolean {
167
168
169
170
171
172
173
        val status = connection?.writeCharacteristic(characteristic) ?: false

        if (!status) {
            Log.d(TAG, "Write status: $status")
        }

        return status
Anon's avatar
Anon committed
174
175
176
    }

}