Add Android BLE mesh client and project website
This commit is contained in:
44
android/app/build.gradle.kts
Normal file
44
android/app/build.gradle.kts
Normal file
@@ -0,0 +1,44 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.schoolmesh.messenger"
|
||||
compileSdk = 34
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.schoolmesh.messenger"
|
||||
minSdk = 26
|
||||
targetSdk = 34
|
||||
versionCode = 2
|
||||
versionName = "0.1.1"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.core:core-ktx:1.13.1")
|
||||
implementation("androidx.appcompat:appcompat:1.7.0")
|
||||
implementation("com.google.android.material:material:1.12.0")
|
||||
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
|
||||
}
|
||||
1
android/app/proguard-rules.pro
vendored
Normal file
1
android/app/proguard-rules.pro
vendored
Normal file
@@ -0,0 +1 @@
|
||||
# Project specific ProGuard rules go here.
|
||||
44
android/app/src/main/AndroidManifest.xml
Normal file
44
android/app/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.bluetooth_le"
|
||||
android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
|
||||
<uses-permission
|
||||
android:name="android.permission.BLUETOOTH_SCAN"
|
||||
android:usesPermissionFlags="neverForLocation" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@android:drawable/sym_def_app_icon"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@android:drawable/sym_def_app_icon"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.SchoolMeshMessenger">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".mesh.MeshForegroundService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="connectedDevice" />
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.schoolmesh.messenger
|
||||
|
||||
import android.Manifest
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.widget.Button
|
||||
import android.widget.TextView
|
||||
import android.widget.Toast
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.schoolmesh.messenger.mesh.MeshForegroundService
|
||||
import com.schoolmesh.messenger.mesh.MeshServiceContract
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
private lateinit var statusText: TextView
|
||||
private lateinit var peersText: TextView
|
||||
private lateinit var logsText: TextView
|
||||
|
||||
private val peers = linkedSetOf<String>()
|
||||
private val logs = ArrayDeque<String>()
|
||||
|
||||
private val meshEventReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
if (intent?.action != MeshServiceContract.ACTION_EVENT) return
|
||||
val eventType = intent.getStringExtra(MeshServiceContract.EXTRA_EVENT_TYPE) ?: return
|
||||
val value = intent.getStringExtra(MeshServiceContract.EXTRA_EVENT_VALUE) ?: return
|
||||
|
||||
when (eventType) {
|
||||
MeshServiceContract.EVENT_STATUS -> updateStatus(value)
|
||||
MeshServiceContract.EVENT_PEER -> addPeer(value)
|
||||
MeshServiceContract.EVENT_LOG -> appendLog(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val permissionLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { result ->
|
||||
val allGranted = result.values.all { it }
|
||||
if (allGranted) {
|
||||
startMesh()
|
||||
} else {
|
||||
updateStatus("Нет BLE-разрешений")
|
||||
appendLog("Permissions denied by user")
|
||||
Toast.makeText(this, "Разрешения отклонены", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_main)
|
||||
|
||||
statusText = findViewById(R.id.statusText)
|
||||
peersText = findViewById(R.id.peersText)
|
||||
logsText = findViewById(R.id.logsText)
|
||||
|
||||
findViewById<Button>(R.id.btnStartMesh).setOnClickListener {
|
||||
ensurePermissionsAndStart()
|
||||
}
|
||||
findViewById<Button>(R.id.btnStopMesh).setOnClickListener {
|
||||
MeshForegroundService.stop(this)
|
||||
updateStatus("Mesh остановлен")
|
||||
appendLog("Mesh service stop requested")
|
||||
}
|
||||
|
||||
renderPeers()
|
||||
renderLogs()
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
registerMeshReceiver()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
unregisterReceiver(meshEventReceiver)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
private fun registerMeshReceiver() {
|
||||
val filter = IntentFilter(MeshServiceContract.ACTION_EVENT)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
registerReceiver(meshEventReceiver, filter, RECEIVER_NOT_EXPORTED)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
registerReceiver(meshEventReceiver, filter)
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensurePermissionsAndStart() {
|
||||
val missing = requiredPermissions().filter { permission ->
|
||||
ContextCompat.checkSelfPermission(this, permission) != android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
if (missing.isEmpty()) {
|
||||
startMesh()
|
||||
} else {
|
||||
permissionLauncher.launch(missing.toTypedArray())
|
||||
}
|
||||
}
|
||||
|
||||
private fun requiredPermissions(): List<String> {
|
||||
val permissions = mutableListOf<String>()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
permissions += Manifest.permission.BLUETOOTH_SCAN
|
||||
permissions += Manifest.permission.BLUETOOTH_CONNECT
|
||||
permissions += Manifest.permission.BLUETOOTH_ADVERTISE
|
||||
} else {
|
||||
permissions += Manifest.permission.ACCESS_FINE_LOCATION
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
permissions += Manifest.permission.POST_NOTIFICATIONS
|
||||
}
|
||||
return permissions
|
||||
}
|
||||
|
||||
private fun startMesh() {
|
||||
MeshForegroundService.start(this)
|
||||
updateStatus("Запуск foreground service")
|
||||
appendLog("Mesh service start requested")
|
||||
Toast.makeText(this, "Mesh запускается", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
private fun updateStatus(text: String) {
|
||||
statusText.text = text
|
||||
}
|
||||
|
||||
private fun addPeer(address: String) {
|
||||
if (peers.add(address)) {
|
||||
renderPeers()
|
||||
}
|
||||
}
|
||||
|
||||
private fun appendLog(message: String) {
|
||||
if (logs.size >= MAX_LOG_ENTRIES) {
|
||||
logs.removeFirst()
|
||||
}
|
||||
logs.addLast(message)
|
||||
renderLogs()
|
||||
}
|
||||
|
||||
private fun renderPeers() {
|
||||
peersText.text = if (peers.isEmpty()) {
|
||||
"Узлы не найдены"
|
||||
} else {
|
||||
peers.joinToString(separator = "\n")
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderLogs() {
|
||||
logsText.text = if (logs.isEmpty()) {
|
||||
"Лог пуст"
|
||||
} else {
|
||||
logs.joinToString(separator = "\n")
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val MAX_LOG_ENTRIES = 20
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
package com.schoolmesh.messenger.mesh
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.bluetooth.BluetoothAdapter
|
||||
import android.bluetooth.BluetoothDevice
|
||||
import android.bluetooth.BluetoothGatt
|
||||
import android.bluetooth.BluetoothGattCallback
|
||||
import android.bluetooth.BluetoothGattCharacteristic
|
||||
import android.bluetooth.BluetoothProfile
|
||||
import android.bluetooth.BluetoothGattServer
|
||||
import android.bluetooth.BluetoothGattServerCallback
|
||||
import android.bluetooth.BluetoothGattService
|
||||
import android.bluetooth.BluetoothManager
|
||||
import android.bluetooth.le.AdvertiseCallback
|
||||
import android.bluetooth.le.AdvertiseData
|
||||
import android.bluetooth.le.AdvertiseSettings
|
||||
import android.bluetooth.le.BluetoothLeAdvertiser
|
||||
import android.bluetooth.le.BluetoothLeScanner
|
||||
import android.bluetooth.le.ScanCallback
|
||||
import android.bluetooth.le.ScanFilter
|
||||
import android.bluetooth.le.ScanResult
|
||||
import android.bluetooth.le.ScanSettings
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.ParcelUuid
|
||||
import android.util.Log
|
||||
import androidx.core.content.ContextCompat
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
class BleMeshManager(
|
||||
private val context: Context,
|
||||
private val onPeerDiscovered: (String) -> Unit = {},
|
||||
private val onStatusChanged: (String) -> Unit = {},
|
||||
private val onError: (String) -> Unit = {},
|
||||
private val onLog: (String) -> Unit = {},
|
||||
private val seenPacketCache: SeenPacketCache = SeenPacketCache()
|
||||
) {
|
||||
private val bluetoothManager = context.getSystemService(BluetoothManager::class.java)
|
||||
private val bluetoothAdapter = bluetoothManager?.adapter
|
||||
private val scanner: BluetoothLeScanner?
|
||||
get() = bluetoothAdapter?.bluetoothLeScanner
|
||||
private val advertiser: BluetoothLeAdvertiser?
|
||||
get() = bluetoothAdapter?.bluetoothLeAdvertiser
|
||||
|
||||
private val activeConnections = ConcurrentHashMap<String, BluetoothGatt>()
|
||||
private var gattServer: BluetoothGattServer? = null
|
||||
private var inboundCharacteristic: BluetoothGattCharacteristic? = null
|
||||
private var isRunning = false
|
||||
|
||||
private val localNodeId: String by lazy {
|
||||
bluetoothAdapter?.address ?: "android-${UUID.randomUUID()}"
|
||||
}
|
||||
|
||||
private val scanCallback = object : ScanCallback() {
|
||||
override fun onScanResult(callbackType: Int, result: ScanResult) {
|
||||
val device = result.device ?: return
|
||||
val address = device.address ?: return
|
||||
onPeerDiscovered(address)
|
||||
if (address == localNodeId || activeConnections.containsKey(address)) {
|
||||
return
|
||||
}
|
||||
log("Discovered BLE node: $address")
|
||||
connectToPeer(device)
|
||||
}
|
||||
|
||||
override fun onScanFailed(errorCode: Int) {
|
||||
fail("BLE scan failed: $errorCode")
|
||||
}
|
||||
}
|
||||
|
||||
private val advertiseCallback = object : AdvertiseCallback() {
|
||||
override fun onStartSuccess(settingsInEffect: AdvertiseSettings) {
|
||||
log("BLE advertising started")
|
||||
}
|
||||
|
||||
override fun onStartFailure(errorCode: Int) {
|
||||
fail("BLE advertising failed: $errorCode")
|
||||
}
|
||||
}
|
||||
|
||||
private val gattServerCallback = object : BluetoothGattServerCallback() {
|
||||
override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) {
|
||||
log("GATT server connection ${device.address}: state=$newState status=$status")
|
||||
}
|
||||
|
||||
override fun onCharacteristicWriteRequest(
|
||||
device: BluetoothDevice,
|
||||
requestId: Int,
|
||||
characteristic: BluetoothGattCharacteristic,
|
||||
preparedWrite: Boolean,
|
||||
responseNeeded: Boolean,
|
||||
offset: Int,
|
||||
value: ByteArray
|
||||
) {
|
||||
if (characteristic.uuid != CHARACTERISTIC_PACKET_UUID) {
|
||||
if (responseNeeded) {
|
||||
gattServer?.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, offset, null)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val rawPacket = value.toString(StandardCharsets.UTF_8)
|
||||
log("Packet received from ${device.address}: $rawPacket")
|
||||
handleIncomingPacket(rawPacket)
|
||||
|
||||
if (responseNeeded) {
|
||||
gattServer?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private inner class MeshGattCallback(
|
||||
private val device: BluetoothDevice
|
||||
) : BluetoothGattCallback() {
|
||||
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
|
||||
val address = device.address ?: return
|
||||
if (status != BluetoothGatt.GATT_SUCCESS) {
|
||||
log("GATT client error for $address: status=$status")
|
||||
closeConnection(address)
|
||||
return
|
||||
}
|
||||
|
||||
when (newState) {
|
||||
BluetoothProfile.STATE_CONNECTED -> {
|
||||
log("Connected to peer $address")
|
||||
activeConnections[address] = gatt
|
||||
gatt.discoverServices()
|
||||
}
|
||||
|
||||
BluetoothProfile.STATE_DISCONNECTED -> {
|
||||
log("Disconnected from peer $address")
|
||||
closeConnection(address)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
|
||||
if (status != BluetoothGatt.GATT_SUCCESS) {
|
||||
log("Service discovery failed for ${device.address}: $status")
|
||||
return
|
||||
}
|
||||
log("Services discovered for ${device.address}")
|
||||
sendPresence(gatt)
|
||||
}
|
||||
|
||||
override fun onCharacteristicWrite(
|
||||
gatt: BluetoothGatt,
|
||||
characteristic: BluetoothGattCharacteristic,
|
||||
status: Int
|
||||
) {
|
||||
val address = device.address ?: return
|
||||
if (status == BluetoothGatt.GATT_SUCCESS) {
|
||||
log("Packet sent to $address")
|
||||
} else {
|
||||
log("Packet send failed to $address: status=$status")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onPacketReceived(packet: MeshPacket): MeshAction {
|
||||
val isNew = seenPacketCache.markSeen(packet.messageId)
|
||||
if (!isNew) {
|
||||
return MeshAction.DropDuplicate
|
||||
}
|
||||
|
||||
if (packet.isExpired()) {
|
||||
return MeshAction.DropExpired
|
||||
}
|
||||
|
||||
return when (packet.type) {
|
||||
PacketType.ACK -> MeshAction.ConsumeAck(packet.messageId)
|
||||
PacketType.PRESENCE -> MeshAction.ConsumePresence(packet.senderId)
|
||||
PacketType.MESSAGE -> MeshAction.ProcessAndRelay(packet.decrementedTtl())
|
||||
}
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (isRunning) return
|
||||
if (!hasRequiredRuntimePermissions()) {
|
||||
fail("BLE permissions are missing")
|
||||
return
|
||||
}
|
||||
|
||||
val adapter = bluetoothAdapter
|
||||
if (adapter == null || !adapter.isEnabled) {
|
||||
fail("Bluetooth adapter is unavailable or disabled")
|
||||
return
|
||||
}
|
||||
|
||||
startGattServer()
|
||||
startScanning()
|
||||
startAdvertising()
|
||||
isRunning = true
|
||||
onStatusChanged("Mesh активен, идет discovery и GATT transport")
|
||||
log("BLE mesh manager started with nodeId=$localNodeId")
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
if (!isRunning) return
|
||||
|
||||
runCatching { scanner?.stopScan(scanCallback) }
|
||||
.onFailure { Log.w(TAG, "Failed to stop scan", it) }
|
||||
runCatching { advertiser?.stopAdvertising(advertiseCallback) }
|
||||
.onFailure { Log.w(TAG, "Failed to stop advertising", it) }
|
||||
runCatching { gattServer?.close() }
|
||||
.onFailure { Log.w(TAG, "Failed to close GATT server", it) }
|
||||
|
||||
activeConnections.keys.toList().forEach(::closeConnection)
|
||||
inboundCharacteristic = null
|
||||
gattServer = null
|
||||
isRunning = false
|
||||
onStatusChanged("Mesh остановлен")
|
||||
log("BLE mesh manager stopped")
|
||||
}
|
||||
|
||||
private fun handleIncomingPacket(rawPacket: String) {
|
||||
val packet = runCatching { MeshPacketCodec.decode(rawPacket) }
|
||||
.getOrElse {
|
||||
fail("Packet decode failed: ${it.message}")
|
||||
return
|
||||
}
|
||||
|
||||
when (val action = onPacketReceived(packet)) {
|
||||
MeshAction.DropDuplicate -> log("Duplicate packet dropped: ${packet.messageId}")
|
||||
MeshAction.DropExpired -> log("Expired packet dropped: ${packet.messageId}")
|
||||
is MeshAction.ConsumeAck -> log("ACK consumed: ${action.messageId}")
|
||||
is MeshAction.ConsumePresence -> {
|
||||
onPeerDiscovered(action.senderId)
|
||||
onStatusChanged("Presence from ${action.senderId}")
|
||||
log("Presence consumed from ${action.senderId}")
|
||||
}
|
||||
|
||||
is MeshAction.ProcessAndRelay -> {
|
||||
onStatusChanged("Message from ${packet.senderId}")
|
||||
log("Relaying packet ${packet.messageId}")
|
||||
broadcastPacket(action.packetToRelay)
|
||||
sendAck(packet)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun startGattServer() {
|
||||
val manager = bluetoothManager ?: run {
|
||||
fail("BluetoothManager unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
val server = manager.openGattServer(context, gattServerCallback)
|
||||
if (server == null) {
|
||||
fail("Failed to open GATT server")
|
||||
return
|
||||
}
|
||||
|
||||
val characteristic = BluetoothGattCharacteristic(
|
||||
CHARACTERISTIC_PACKET_UUID,
|
||||
BluetoothGattCharacteristic.PROPERTY_WRITE or BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE,
|
||||
BluetoothGattCharacteristic.PERMISSION_WRITE
|
||||
)
|
||||
|
||||
val service = BluetoothGattService(
|
||||
MESH_SERVICE_UUID,
|
||||
BluetoothGattService.SERVICE_TYPE_PRIMARY
|
||||
).apply {
|
||||
addCharacteristic(characteristic)
|
||||
}
|
||||
|
||||
server.addService(service)
|
||||
gattServer = server
|
||||
inboundCharacteristic = characteristic
|
||||
log("GATT server started")
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun startScanning() {
|
||||
val filter = ScanFilter.Builder()
|
||||
.setServiceUuid(ParcelUuid(MESH_SERVICE_UUID))
|
||||
.build()
|
||||
val settings = ScanSettings.Builder()
|
||||
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
|
||||
.build()
|
||||
scanner?.startScan(listOf(filter), settings, scanCallback)
|
||||
log("BLE scanning started")
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun startAdvertising() {
|
||||
val settings = AdvertiseSettings.Builder()
|
||||
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
|
||||
.setConnectable(true)
|
||||
.setTimeout(0)
|
||||
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
|
||||
.build()
|
||||
|
||||
val data = AdvertiseData.Builder()
|
||||
.setIncludeDeviceName(false)
|
||||
.addServiceUuid(ParcelUuid(MESH_SERVICE_UUID))
|
||||
.build()
|
||||
|
||||
advertiser?.startAdvertising(settings, data, advertiseCallback)
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun connectToPeer(device: BluetoothDevice) {
|
||||
val address = device.address ?: return
|
||||
if (activeConnections.containsKey(address)) return
|
||||
log("Connecting to peer $address")
|
||||
val gatt = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
device.connectGatt(context, false, MeshGattCallback(device), BluetoothDevice.TRANSPORT_LE)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
device.connectGatt(context, false, MeshGattCallback(device))
|
||||
}
|
||||
if (gatt != null) {
|
||||
activeConnections[address] = gatt
|
||||
}
|
||||
}
|
||||
|
||||
private fun sendPresence(gatt: BluetoothGatt) {
|
||||
val packet = MeshPacket(
|
||||
senderId = localNodeId,
|
||||
targetId = gatt.device.address ?: "broadcast",
|
||||
type = PacketType.PRESENCE,
|
||||
payload = "presence:$localNodeId"
|
||||
)
|
||||
writePacket(gatt, packet)
|
||||
}
|
||||
|
||||
private fun sendAck(packet: MeshPacket) {
|
||||
val ack = MeshPacket(
|
||||
senderId = localNodeId,
|
||||
targetId = packet.senderId,
|
||||
type = PacketType.ACK,
|
||||
payload = packet.messageId
|
||||
)
|
||||
broadcastPacket(ack)
|
||||
}
|
||||
|
||||
private fun broadcastPacket(packet: MeshPacket) {
|
||||
activeConnections.values.forEach { gatt ->
|
||||
writePacket(gatt, packet)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun writePacket(gatt: BluetoothGatt, packet: MeshPacket) {
|
||||
val characteristic = gatt
|
||||
.getService(MESH_SERVICE_UUID)
|
||||
?.getCharacteristic(CHARACTERISTIC_PACKET_UUID)
|
||||
|
||||
if (characteristic == null) {
|
||||
log("Remote characteristic missing on ${gatt.device.address}")
|
||||
return
|
||||
}
|
||||
|
||||
val payload = MeshPacketCodec.encode(packet).toByteArray(StandardCharsets.UTF_8)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
gatt.writeCharacteristic(
|
||||
characteristic,
|
||||
payload,
|
||||
BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
||||
@Suppress("DEPRECATION")
|
||||
characteristic.value = payload
|
||||
@Suppress("DEPRECATION")
|
||||
gatt.writeCharacteristic(characteristic)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun closeConnection(address: String) {
|
||||
val gatt = activeConnections.remove(address) ?: return
|
||||
runCatching {
|
||||
gatt.disconnect()
|
||||
gatt.close()
|
||||
}.onFailure {
|
||||
Log.w(TAG, "Failed to close connection for $address", it)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hasRequiredRuntimePermissions(): Boolean {
|
||||
val requiredPermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
listOf(
|
||||
Manifest.permission.BLUETOOTH_SCAN,
|
||||
Manifest.permission.BLUETOOTH_CONNECT,
|
||||
Manifest.permission.BLUETOOTH_ADVERTISE
|
||||
)
|
||||
} else {
|
||||
listOf(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
}
|
||||
|
||||
return requiredPermissions.all { permission ->
|
||||
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
}
|
||||
|
||||
private fun fail(message: String) {
|
||||
Log.e(TAG, message)
|
||||
onError(message)
|
||||
onLog(message)
|
||||
}
|
||||
|
||||
private fun log(message: String) {
|
||||
Log.d(TAG, message)
|
||||
onLog(message)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "BleMeshManager"
|
||||
private val MESH_SERVICE_UUID: UUID = UUID.fromString("8fa8f9f0-e755-4c1d-9ac2-4f0a02e07f8b")
|
||||
private val CHARACTERISTIC_PACKET_UUID: UUID =
|
||||
UUID.fromString("f9629b10-9d60-4d95-bc6a-6fdb4d4f5a4a")
|
||||
}
|
||||
}
|
||||
|
||||
sealed interface MeshAction {
|
||||
data object DropDuplicate : MeshAction
|
||||
data object DropExpired : MeshAction
|
||||
data class ConsumeAck(val messageId: String) : MeshAction
|
||||
data class ConsumePresence(val senderId: String) : MeshAction
|
||||
data class ProcessAndRelay(val packetToRelay: MeshPacket) : MeshAction
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.schoolmesh.messenger.mesh
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.schoolmesh.messenger.R
|
||||
|
||||
class MeshForegroundService : Service() {
|
||||
private lateinit var bleMeshManager: BleMeshManager
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
createNotificationChannel()
|
||||
bleMeshManager = BleMeshManager(
|
||||
context = applicationContext,
|
||||
onPeerDiscovered = { address ->
|
||||
sendEvent(MeshServiceContract.EVENT_PEER, address)
|
||||
sendEvent(MeshServiceContract.EVENT_LOG, "Peer discovered: $address")
|
||||
},
|
||||
onStatusChanged = { status ->
|
||||
sendEvent(MeshServiceContract.EVENT_STATUS, status)
|
||||
updateNotification(status)
|
||||
},
|
||||
onError = { message ->
|
||||
sendEvent(MeshServiceContract.EVENT_STATUS, "Ошибка: $message")
|
||||
sendEvent(MeshServiceContract.EVENT_LOG, "Error: $message")
|
||||
updateNotification("Ошибка mesh")
|
||||
},
|
||||
onLog = { message ->
|
||||
sendEvent(MeshServiceContract.EVENT_LOG, message)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
MeshServiceContract.ACTION_STOP -> stopMesh()
|
||||
else -> startMesh()
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
bleMeshManager.stop()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private fun startMesh() {
|
||||
startForeground(NOTIFICATION_ID, buildNotification("Mesh запускается"))
|
||||
bleMeshManager.start()
|
||||
}
|
||||
|
||||
private fun stopMesh() {
|
||||
bleMeshManager.stop()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private fun buildNotification(contentText: String): Notification {
|
||||
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle(getString(R.string.notification_title))
|
||||
.setContentText(contentText)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun updateNotification(contentText: String) {
|
||||
val notificationManager = getSystemService(NotificationManager::class.java)
|
||||
notificationManager.notify(NOTIFICATION_ID, buildNotification(contentText))
|
||||
}
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
getString(R.string.notification_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
)
|
||||
manager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private fun sendEvent(type: String, value: String) {
|
||||
sendBroadcast(
|
||||
Intent(MeshServiceContract.ACTION_EVENT)
|
||||
.setPackage(packageName)
|
||||
.putExtra(MeshServiceContract.EXTRA_EVENT_TYPE, type)
|
||||
.putExtra(MeshServiceContract.EXTRA_EVENT_VALUE, value)
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "mesh_status"
|
||||
private const val NOTIFICATION_ID = 1001
|
||||
|
||||
fun start(context: Context) {
|
||||
val intent = Intent(context, MeshForegroundService::class.java).apply {
|
||||
action = MeshServiceContract.ACTION_START
|
||||
}
|
||||
androidx.core.content.ContextCompat.startForegroundService(context, intent)
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
val intent = Intent(context, MeshForegroundService::class.java).apply {
|
||||
action = MeshServiceContract.ACTION_STOP
|
||||
}
|
||||
context.startService(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.schoolmesh.messenger.mesh
|
||||
|
||||
import java.util.UUID
|
||||
|
||||
data class MeshPacket(
|
||||
val messageId: String = UUID.randomUUID().toString(),
|
||||
val senderId: String,
|
||||
val targetId: String,
|
||||
val ttl: Int = DEFAULT_TTL,
|
||||
val timestamp: Long = System.currentTimeMillis(),
|
||||
val type: PacketType,
|
||||
val payload: String
|
||||
) {
|
||||
fun isExpired(): Boolean = ttl <= 0
|
||||
|
||||
fun decrementedTtl(): MeshPacket = copy(ttl = ttl - 1)
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_TTL = 6
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.schoolmesh.messenger.mesh
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
object MeshPacketCodec {
|
||||
fun encode(packet: MeshPacket): String {
|
||||
return JSONObject()
|
||||
.put("messageId", packet.messageId)
|
||||
.put("senderId", packet.senderId)
|
||||
.put("targetId", packet.targetId)
|
||||
.put("ttl", packet.ttl)
|
||||
.put("timestamp", packet.timestamp)
|
||||
.put("type", packet.type.name)
|
||||
.put("payload", packet.payload)
|
||||
.toString()
|
||||
}
|
||||
|
||||
fun decode(raw: String): MeshPacket {
|
||||
val json = JSONObject(raw)
|
||||
return MeshPacket(
|
||||
messageId = json.getString("messageId"),
|
||||
senderId = json.getString("senderId"),
|
||||
targetId = json.getString("targetId"),
|
||||
ttl = json.getInt("ttl"),
|
||||
timestamp = json.getLong("timestamp"),
|
||||
type = PacketType.valueOf(json.getString("type")),
|
||||
payload = json.getString("payload")
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.schoolmesh.messenger.mesh
|
||||
|
||||
object MeshServiceContract {
|
||||
const val ACTION_START = "com.schoolmesh.messenger.mesh.START"
|
||||
const val ACTION_STOP = "com.schoolmesh.messenger.mesh.STOP"
|
||||
const val ACTION_EVENT = "com.schoolmesh.messenger.mesh.EVENT"
|
||||
|
||||
const val EXTRA_EVENT_TYPE = "event_type"
|
||||
const val EXTRA_EVENT_VALUE = "event_value"
|
||||
|
||||
const val EVENT_STATUS = "status"
|
||||
const val EVENT_PEER = "peer"
|
||||
const val EVENT_LOG = "log"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.schoolmesh.messenger.mesh
|
||||
|
||||
enum class PacketType {
|
||||
MESSAGE,
|
||||
ACK,
|
||||
PRESENCE
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.schoolmesh.messenger.mesh
|
||||
|
||||
class SeenPacketCache(
|
||||
private val maxSize: Int = 512
|
||||
) {
|
||||
private val packetIds = LinkedHashSet<String>()
|
||||
|
||||
@Synchronized
|
||||
fun markSeen(packetId: String): Boolean {
|
||||
if (packetIds.contains(packetId)) return false
|
||||
|
||||
packetIds.add(packetId)
|
||||
if (packetIds.size > maxSize) {
|
||||
val oldest = packetIds.firstOrNull()
|
||||
if (oldest != null) {
|
||||
packetIds.remove(oldest)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
101
android/app/src/main/res/layout/activity_main.xml
Normal file
101
android/app/src/main/res/layout/activity_main.xml
Normal file
@@ -0,0 +1,101 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".MainActivity">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="24dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/titleText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="School Mesh Messenger"
|
||||
android:textAppearance="@style/TextAppearance.Material3.HeadlineMedium" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/subtitleText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="Debug-экран BLE mesh: foreground service, найденные узлы и журнал событий." />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnStartMesh"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:text="Запустить mesh" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnStopMesh"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="12dp"
|
||||
android:layout_weight="1"
|
||||
android:text="Остановить mesh" />
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/statusLabel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:text="Статус"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/statusText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="Ожидание запуска" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/peersLabel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:text="Найденные узлы"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/peersText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:background="#EAF3F7"
|
||||
android:padding="12dp"
|
||||
android:text="Узлы не найдены" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/logsLabel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:text="Журнал событий"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/logsText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:background="#101820"
|
||||
android:padding="12dp"
|
||||
android:text="Лог пуст"
|
||||
android:textColor="#EAF7F2"
|
||||
android:textIsSelectable="true" />
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
5
android/app/src/main/res/values/colors.xml
Normal file
5
android/app/src/main/res/values/colors.xml
Normal file
@@ -0,0 +1,5 @@
|
||||
<resources>
|
||||
<color name="teal_primary">#1E6E54</color>
|
||||
<color name="teal_container">#A4F3D5</color>
|
||||
<color name="blue_secondary">#1150B4</color>
|
||||
</resources>
|
||||
5
android/app/src/main/res/values/strings.xml
Normal file
5
android/app/src/main/res/values/strings.xml
Normal file
@@ -0,0 +1,5 @@
|
||||
<resources>
|
||||
<string name="app_name">School Mesh Messenger</string>
|
||||
<string name="notification_title">School Mesh Messenger</string>
|
||||
<string name="notification_channel_name">Mesh status</string>
|
||||
</resources>
|
||||
7
android/app/src/main/res/values/themes.xml
Normal file
7
android/app/src/main/res/values/themes.xml
Normal file
@@ -0,0 +1,7 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<style name="Theme.SchoolMeshMessenger" parent="Theme.Material3.DayNight.NoActionBar">
|
||||
<item name="colorPrimary">#1E6E54</item>
|
||||
<item name="colorPrimaryContainer">#A4F3D5</item>
|
||||
<item name="colorSecondary">#1150B4</item>
|
||||
</style>
|
||||
</resources>
|
||||
2
android/app/src/main/res/xml/backup_rules.xml
Normal file
2
android/app/src/main/res/xml/backup_rules.xml
Normal file
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<full-backup-content />
|
||||
2
android/app/src/main/res/xml/data_extraction_rules.xml
Normal file
2
android/app/src/main/res/xml/data_extraction_rules.xml
Normal file
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<data-extraction-rules />
|
||||
Reference in New Issue
Block a user