BeautifulFragment.kt 4.71 KB
Newer Older
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
/*
 * 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.sparkle

import android.bluetooth.*
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import de.ccc.events.badge.card10.CARD10_BLUETOOTH_MAC_PREFIX
import de.ccc.events.badge.card10.CARD10_SERVICE_UUID
import de.ccc.events.badge.card10.LEDS_ABOVE_CHARACTERISTIC_UUID
import de.ccc.events.badge.card10.R
import java.util.concurrent.CountDownLatch
import kotlin.random.Random

class BeautifulFragment : Fragment(), Runnable {

    private val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    private lateinit var gatt: BluetoothGatt
    private var ledsAboveCharacteristic: BluetoothGattCharacteristic? = null
    private @Volatile var writeLatch: CountDownLatch? = null
    private val handler = Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val callback = object : BluetoothGattCallback() {
            override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
                println("===== onConnectionStateChange ${gatt} ${if (status == BluetoothGatt.GATT_SUCCESS) "SUCCESS" else status} ${if (newState == BluetoothProfile.STATE_CONNECTED) "CONNECTED" else if (newState == BluetoothProfile.STATE_DISCONNECTED) "DISCONNECTED" else newState}")
                if (newState == BluetoothGatt.STATE_CONNECTED)
                    gatt.requestMtu(64)
            }

            override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
                println("===== onMtuChanged ${gatt} ${if (status == BluetoothGatt.GATT_SUCCESS) "SUCCESS" else status} ${mtu}")
                gatt.discoverServices()
            }

            override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
                println("===== onServicesDiscovered ${gatt} ${if (status == BluetoothGatt.GATT_SUCCESS) "SUCCESS" else status}")
                val card10Service = gatt.getService(CARD10_SERVICE_UUID)
                ledsAboveCharacteristic = card10Service.getCharacteristic(LEDS_ABOVE_CHARACTERISTIC_UUID)
                handler.post(this@BeautifulFragment)
            }

            override fun onCharacteristicWrite(
                gatt: BluetoothGatt,
                characteristic: BluetoothGattCharacteristic,
                status: Int
            ) {
                println("=== onCharacteristicWrite ${gatt} ${if (status == BluetoothGatt.GATT_SUCCESS) "SUCCESS" else status} ${characteristic.uuid} ${characteristic.value}")
                writeLatch?.countDown();
            }
        }

        val remoteDevices =
            bluetoothAdapter.bondedDevices.filter { it.address.startsWith(CARD10_BLUETOOTH_MAC_PREFIX, true) }
        if (remoteDevices.isEmpty())
            activity!!.finish()
        gatt = remoteDevices.get(0).connectGatt(activity, false, callback)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.beautiful_fragment, container, false)
    }

    override fun run() {
        ledsAboveCharacteristic!!.value = Random.nextBytes(33);
        writeLatch = CountDownLatch(1)
        val init = gatt.writeCharacteristic(ledsAboveCharacteristic)
        if (!init)
            println("=== Failed to initiate writing GATT attribute")
        writeLatch!!.await();
        handler.postDelayed(this, 100)
    }

    override fun onDestroy() {
        handler.removeCallbacksAndMessages(null)
        gatt.close();
        super.onDestroy()
    }
}