ConnectionService.kt 5.26 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
29
import de.ccc.events.badge.card10.CARD10_BLUETOOTH_MAC_PREFIX
import de.ccc.events.badge.card10.R
Anon's avatar
Anon committed
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
import de.ccc.events.badge.card10.filetransfer.LowEffortService
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
    var mtu = 100

    private var connection: BluetoothGatt? = null

    private var connectionState = BluetoothGatt.STATE_DISCONNECTED
    private var gattListeners = mutableListOf<GattListener>()

    private val fileServiceUuid = UUID.fromString("42230100-2342-2342-2342-234223422342")

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

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

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

    fun isConnected() = connectionState == BluetoothGatt.STATE_CONNECTED

    fun addGattListener(listener: GattListener) {
        gattListeners.add(listener)
    }

    fun connect(context: Context) {
66
67
68
69
70
71
72
73
74
75
76
77
78
79
        // 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
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
        // 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}")

                if (service.uuid == fileServiceUuid) {
                    leService = LowEffortService(service)
                }
            }

            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

            gattListeners.map { it.onConnectionStateChange(newState) }

            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)
        }

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

            connection = gatt

            gattListeners.map { it.onCharacteristicWrite(characteristic, status) }
        }

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

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

            gattListeners.map { it.onCharacteristicChanged(characteristic) }
        }
    }

    fun writeCharacteristic(characteristic: BluetoothGattCharacteristic): Boolean {
        return connection?.writeCharacteristic(characteristic) ?: false
    }

}