Skip to content

Commit

Permalink
Minot code changes
Browse files Browse the repository at this point in the history
  • Loading branch information
glodanif committed Mar 30, 2018
1 parent 92e93a0 commit 2b9cc01
Showing 1 changed file with 18 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ import kotlin.concurrent.thread

class BluetoothConnectionService : Service() {

private val TAG = "BCS"

private val binder = ConnectionBinder()
private val handler = Handler()
private val adapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()

private val APP_NAME = "BluetoothChat"
private val APP_UUID = UUID.fromString("220da3b2-41f5-11e7-a919-92ebcb67fe33")

enum class ConnectionState { CONNECTED, CONNECTING, NOT_CONNECTED, REJECTED, PENDING, LISTENING }
enum class ConnectionType { INCOMING, OUTCOMING }
Expand All @@ -42,13 +45,6 @@ class BluetoothConnectionService : Service() {
private var messageListener: OnMessageListener? = null
private var fileListener: OnFileListener? = null

private val adapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()

private val APP_NAME = "BluetoothChat"
private val APP_UUID = UUID.fromString("220da3b2-41f5-11e7-a919-92ebcb67fe33")

private val handler: Handler = Handler()

private var acceptThread: AcceptThread? = null
private var connectThread: ConnectThread? = null
private var dataTransferThread: DataTransferThread? = null
Expand Down Expand Up @@ -82,7 +78,6 @@ class BluetoothConnectionService : Service() {

override fun onCreate() {
super.onCreate()
Log.e(TAG, "CREATED")
application = getApplication() as ChatApplication
settings = SettingsManagerImpl(this)
preferences = UserPreferences(this)
Expand Down Expand Up @@ -129,11 +124,7 @@ class BluetoothConnectionService : Service() {

@Synchronized
private fun prepareForAccept() {

Log.d(TAG, "start")

cancelConnections()

acceptThread = AcceptThread()
acceptThread?.start()
showNotification(getString(R.string.notification__ready_to_connect))
Expand All @@ -142,8 +133,6 @@ class BluetoothConnectionService : Service() {
@Synchronized
fun connect(device: BluetoothDevice) {

log("connect to: ${device.name}")

if (connectionState == ConnectionState.CONNECTING) {
connectThread?.cancel()
connectThread = null
Expand All @@ -168,7 +157,6 @@ class BluetoothConnectionService : Service() {
cancelConnections()

connectionType = type

currentSocket = socket

acceptThread?.cancel()
Expand Down Expand Up @@ -379,25 +367,17 @@ class BluetoothConnectionService : Service() {
dataTransferThread?.start()

handler.post { connectionListener?.onConnected(socket.remoteDevice) }

log("connected")
}

@Synchronized
fun stop() {

cancelConnections()

acceptThread?.cancel()
acceptThread = null

connectionState = ConnectionState.NOT_CONNECTED

log("stop")
}

private fun cancelConnections() {
log("cancelConnections")
connectThread?.cancel()
connectThread = null
dataTransferThread?.cancel()
Expand Down Expand Up @@ -454,12 +434,10 @@ class BluetoothConnectionService : Service() {
notificationView.dismissFileTransferNotification()
}

private fun onMessageSent(messageBody: String) {

if (currentSocket == null) return
private fun onMessageSent(messageBody: String) = currentSocket?.let {

val message = Message(messageBody)
val sentMessage = ChatMessage(currentSocket!!.remoteDevice.address, Date(), true, message.body)
val sentMessage = ChatMessage(it.remoteDevice.address, Date(), true, message.body)

if (message.type == Message.Type.MESSAGE) {
sentMessage.seenHere = true
Expand All @@ -475,8 +453,6 @@ class BluetoothConnectionService : Service() {

private fun onMessageReceived(messageBody: String) {

log("Message received: $messageBody")

val message = Message(messageBody)

if (message.type == Message.Type.MESSAGE && currentSocket != null) {
Expand Down Expand Up @@ -517,9 +493,9 @@ class BluetoothConnectionService : Service() {
}
}

private fun handleReceivedMessage(text: String) {
private fun handleReceivedMessage(text: String) = currentSocket?.let {

val device: BluetoothDevice = currentSocket!!.remoteDevice
val device: BluetoothDevice = it.remoteDevice

val receivedMessage = ChatMessage(device.address, Date(), false, text)

Expand All @@ -539,9 +515,9 @@ class BluetoothConnectionService : Service() {
}
}

private fun handleConnectionRequest(message: Message) {
private fun handleConnectionRequest(message: Message) = currentSocket?.let {

val device: BluetoothDevice = currentSocket!!.remoteDevice
val device: BluetoothDevice = it.remoteDevice

val parts = message.body.split("#")
val conversation = Conversation(device.address, device.name, parts[0], parts[1].toInt())
Expand All @@ -561,9 +537,9 @@ class BluetoothConnectionService : Service() {
}
}

private fun handleConnectionApproval(message: Message) {
private fun handleConnectionApproval(message: Message) = currentSocket?.let {

val device: BluetoothDevice = currentSocket!!.remoteDevice
val device: BluetoothDevice = it.remoteDevice

val parts = message.body.split("#")
val conversation = Conversation(device.address, device.name, parts[0], parts[1].toInt())
Expand All @@ -581,7 +557,6 @@ class BluetoothConnectionService : Service() {
}

private fun connectionFailed() {
log("connectionFailed")
currentSocket = null
currentConversation = null
handler.post { connectionListener?.onConnectionFailed() }
Expand All @@ -591,26 +566,20 @@ class BluetoothConnectionService : Service() {

private fun connectionLost() {

log("connectionLost")

currentSocket = null
currentConversation = null
if (isConnectedOrPending()) {
handler.post {
if (isPending() && connectionType == ConnectionType.INCOMING) {
connectionState = ConnectionState.NOT_CONNECTED
connectionListener?.onConnectionWithdrawn()
log("onConnectionWithdrawn")
} else {
connectionState = ConnectionState.NOT_CONNECTED
connectionListener?.onConnectionLost()
log("onConnectionLost")
}
log("connectionLost - connected - prepareForAccept")
prepareForAccept()
}
} else {
log("connectionLost - not connected - prepareForAccept")
prepareForAccept()
}
}
Expand Down Expand Up @@ -647,7 +616,6 @@ class BluetoothConnectionService : Service() {
try {
serverSocket = adapter?.listenUsingRfcommWithServiceRecord(APP_NAME, APP_UUID)
} catch (e: IOException) {
log("Socket listen() failed: ${e.message}")
e.printStackTrace()
}

Expand All @@ -656,42 +624,35 @@ class BluetoothConnectionService : Service() {

override fun run() {

log("BEGIN acceptThread")

var socket: BluetoothSocket?

while (!isConnectedOrPending()) {
try {
socket = serverSocket?.accept()
} catch (e: IOException) {
log("Socket accept() failed")
e.printStackTrace()
break
}

if (socket != null) {
when (connectionState) {
ConnectionState.LISTENING, ConnectionState.CONNECTING -> {
log("Connected in AcceptThread")
connected(socket, ConnectionType.INCOMING)
}
ConnectionState.NOT_CONNECTED, ConnectionState.CONNECTED, ConnectionState.PENDING, ConnectionState.REJECTED -> try {
socket.close()
} catch (e: IOException) {
log("Could not close unwanted socket: ${e.message}")
e.printStackTrace()
}
}
}
}

log("END acceptThread")
}

fun cancel() {
log("cancel() AcceptThread")
try {
serverSocket?.close()
} catch (e: IOException) {
log("cancel() AcceptThread failed: ${e.message}")
e.printStackTrace()
}
}
Expand All @@ -703,12 +664,9 @@ class BluetoothConnectionService : Service() {

override fun run() {

log("BEGIN connectThread")

try {
socket = bluetoothDevice.createRfcommSocketToServiceRecord(APP_UUID)
} catch (e: IOException) {
log("unable to create socket in ConnectThread: ${e.message}")
e.printStackTrace()
}
connectionState = ConnectionState.CONNECTING
Expand All @@ -720,7 +678,7 @@ class BluetoothConnectionService : Service() {
try {
socket?.close()
} catch (e: IOException) {
log("unable to close() socket during connection failure: ${e.message}")
e.printStackTrace()
}
connectionFailed()
return
Expand All @@ -731,19 +689,15 @@ class BluetoothConnectionService : Service() {
}

if (socket != null) {
log("connect thread - connected")
connected(socket!!, ConnectionType.OUTCOMING)
}

log("END connectThread")
}

fun cancel() {
try {
socket?.close()
} catch (e: IOException) {
e.printStackTrace()
log("cancel() of connect thread failed: ${e.message}")
}
}
}
Expand All @@ -760,8 +714,8 @@ class BluetoothConnectionService : Service() {

var isRunning = false

var FOREGROUND_SERVICE = 101
var ACTION_STOP = "action.stop"
private const val FOREGROUND_SERVICE = 101
const val ACTION_STOP = "action.stop"

fun start(context: Context) {
val intent = Intent(context, BluetoothConnectionService::class.java)
Expand All @@ -777,11 +731,4 @@ class BluetoothConnectionService : Service() {
context.bindService(intent, connection, AppCompatActivity.BIND_ABOVE_CLIENT)
}
}

private fun log(text: String) {
if (BuildConfig.DEBUG) {
val logBody = "$text - (State: ${connectionState.name}, Type: ${connectionType?.name}, Conversation: $currentConversation, Threads: A: $acceptThread (running: ${acceptThread?.isAlive}), C: $connectThread (running: ${connectThread?.isAlive}), CD: $dataTransferThread (running: ${dataTransferThread?.isAlive}))"
Log.e(TAG, logBody)
}
}
}

0 comments on commit 2b9cc01

Please sign in to comment.