This repository has been archived by the owner on Sep 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.kt
60 lines (52 loc) · 2.22 KB
/
Connection.kt
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
package com.example.avaloncharacters.connection
import android.content.Context
import android.util.Log
import com.example.avaloncharacters.ApplicationConnectivity
import com.example.avaloncharacters.characters.Player
import com.google.android.gms.nearby.Nearby
import com.google.android.gms.nearby.connection.ConnectionLifecycleCallback
import com.google.android.gms.nearby.connection.Payload
import com.google.android.gms.nearby.connection.PayloadCallback
import java.nio.charset.StandardCharsets
abstract class Connection(context: Context) {
public val player: Player = (context.applicationContext as ApplicationConnectivity).player
protected val mConnectionsClient = Nearby.getConnectionsClient(context)!!
protected val packageName: String = context.packageName
protected var roomNumber: Long = -1
set(value) {
if (value.toString().length != ROOMNUMBER_LENGTH)
throw IllegalArgumentException(
"Length of room number must be equal to $ROOMNUMBER_LENGTH"
)
field = value
}
abstract val mConnectionLifecycleCallback: ConnectionLifecycleCallback
abstract val mPayloadCallback: PayloadCallback
fun sendJSON(endpointId: String, jsonString: String): Unit {
sendJSON(listOf(endpointId), jsonString)
}
fun sendJSON(endpointIds: List<String>, jsonString: String): Unit {
Payload.fromStream(jsonString.byteInputStream(StandardCharsets.UTF_8))
.also { payload ->
mConnectionsClient.sendPayload(endpointIds, payload)
}
}
abstract fun startConnection(roomNumber: Long)
fun stopConnection() {
if (this is ServerSideConnection) {
Log.i(ServerSideConnection.TAG, "Stop advertising")
mConnectionsClient.stopAdvertising()
} else if (this is ClientSideConnection) {
Log.i(ClientSideConnection.TAG, "Stop discovering")
mConnectionsClient.stopDiscovery()
} else
throw ClassNotFoundException("Unknown Connection type")
}
val isServer by lazy {
this is ServerSideConnection
}
companion object {
const val TAG = "Connection"
const val ROOMNUMBER_LENGTH = 6
}
}