Exercise: Chatting Using Bluetooth
Bluetooth was designed to allow the connecting of devices without the need for wires. It is good for relatively low powered devices and has a limited range. In this exercise we build a program that will allow two mobile devices to chat using bluetooth.
One mobile should run bluetooth 1 and another mobile should run bluetooth 2.
Bluetooth 1
This script turns on bluetooth, makes this phone discoverable and waits to be connected to. When a connection is established it waits for a message and prints it out.
import android
import time
droid = android.Android()
droid.toggleBluetoothState(True)
print "Making myself discoverable"
droid.bluetoothMakeDiscoverable()
print "Wait for bluetooth-2 to connect"
droid.bluetoothAccept()
result = droid.getInput('Chat', 'Enter a message').result
if result is None:
droid.exit()
droid.bluetoothWrite(result + '\n')
droid.toogleBluetoothState(False)
droid.exit()
Bluetooth 2
This is the other pair. It looks for someone to talk to and when it makes it a connection it sends a message.
import android
import time
droid = android.Android()
droid.toggleBluetoothState(True)
droid.bluetoothConnect()
message = droid.bluetoothReadLine().result
droid.dialogCreateAlert('Chat Received', message)
droid.dialogSetPositiveButtonText('Ok')
droid.dialogShow()
droid.dialogGetResponse()
droid.toogleBluetoothState(False)
droid.exit()
Troubleshooting
Sometimes the system gets into a state where it won't connect. You need to try turning bluetooth on and off. If that doesn't work try unpairing the clients.
Extending Program
Turn it into a pair that can bounce messages backwards and forth between each other. Note that this needs careful coordination.
Add speech to it.
Add a dialog to allow the users to agree on who sends first and who goes second.
Next
Go back to the
start.