Week-3 App Inventor Bluetooth communications 

Part 1: Basic Bluetooth communications using App Inventor


To implement and test this sample code, you need access to two Android devices – one to act as a Bluetooth “server” and the other to act as a “Bluetooth” client.
Introduction to Bluetooth
Bluetooth is the communications technology with the goal of interconnecting different devices.  
The Designer View
There are two separate apps for Bluetooth communications – one is a “server” app that runs on one device, and the other is a “client” app that runs on a second device.
Bluetooth must be enabled on both devices, and the devices need to be paired before running these apps. (How to do this is explained near the end of this tutorial.)
The server must be run first on one device and then the client app on the 2nd device connects to the server before data can be sent between the two devices.


The server user interface is shown here:

The main components of the server interface design are:
Accept Connection Button – press this to set the server to accept a connection from another device. Connections are not possible until the AcceptConnection service is started.
Send the following text Button – the text is the following text box is sent to the other Bluetooth device.
Disconnect Button
Status messages – Status about the communications link, and any messages received from the other device are shown on the display
Non-visible components – The apps use a clock to cause activities to occur at a preset interval. The Notifier1 component is used to display error messages and BluetoothServer1 provides the Bluetooth support.
The BluetoothClient1 and BluetoothServer1 components are located in the Connectivity section of the Designer palette.
How each of the buttons and components are used to run the program are explained later, in a section on setting up Bluetooth on your devices and running the apps.
The client user interface is shown here:

The user interface is similar to the server except instead of AcceptConnection there is a Connect to device button, and instead of a BluetoothServer1 component, the BluetoothClient1 components is used.
The Connect to device button is actually a ListPicker component and not a standard button.
For both the client and server apps, the TimerInterval of the Clockproperties is set to 1000 milliseconds or 1 second. Other small values may also be used. This value determines how frequently to check the Bluetooth link for incoming data from the other device. As shown, each app will check the link once per second.

Blocks Code
Bluetooth Server app
We start with the server app implementation.  The client app is presented after the server app.
The first step is to check that Bluetooth is activated or switched on. If not, an error message is displayed reminding the user to open Android’s Settings and then switch Bluetooth to on.
The Initialize event occurs when the app is launched – and this is a good place to check whether or not Bluetooth is enabled on the device.

Assuming that Bluetooth on the device is currently “on”, the next step is to accept a connection from another device when the btnAcceptConnectionbutton has been pressed. This causes Bluetooth to begin listening for an incoming connection.
Once a connection request has been received and processed, a ConnectionAccepted event occurs. In our basic app, we update the status message on the app screen.

The Timer Event Handles Receiving of Data
Receiving data sent over Bluetooth takes place in the Clock1.Timer event handler. Remember, the clock is set so that the Timer event happens once per second. Every second, the app will check if any data has been received.
To prevent reading data when Bluetooth is not connected (this would cause an error), an if-then statement checks the IsConnected property of BluetoothServer1. This value is set to true when the devices are connected and false if the connection is not currently available.
IsConnected should be true if a connection has been accepted. But because this is a wireless connection, a device might go out of range or be turned off, breaking the connection. It is good programming practice to check that the connection is working before trying to send or receive data.
The property BytesAvailableToReceive tells us how much data is available (one text character is equal to one “byte” of data). If this value is zero, then no data is available. But if the value is greater than zero, then our app may read the incoming data and update the status and messages to the app display.

The Send Text button event handler is similar to the receive code located inside the Timer event except that data is sent using the SendText method to transmit the data to the other device.

Error  Handling
One thing to know about wireless communications is that errors happen. For most of our App Inventor apps, we ignore potential errors – if errors occur, the app stops running and Android displays an error messages.
Rather than letting that occur, our app can intercept the error condition by adding an error event handler to the main screen, Screen1. The ErrorOccurred event has four parameter values (local variables) that contain information about the error. The error handler displays the error values on the screen, rather than shutting down the app.

Bluetooth Client App
Now that the server app is complete, we present the client app that runs on the other device. In many ways, the client app is a mirror image of the server, but refers to the BlutoothClient1 component instead of the BluetoothServer1 component.
App Initialization
Same as the server, except it uses Bluetooth
Client1.

Connecting
When the two devices are running, the server app is set up first to accept connections. Then, on the client side, the user selects the Connect ListPicker button and selects the device name from a list of available Bluetooth devices.  Because the list of devices is in the form of a list, the ListPicker is a great interface component to display the device list and handle the selection.
Before the list is displayed, the list is filled with the list of Bluetooth devices (AddressesAndNames). The set lblStatus.Text block may be deleted as it was used during my testing and is not needed in the final version of the client.

After the device has been selected with the ListPicker user interface, the Connect method of BluetoothClient1 establishes the connection. The method returns a value of true if the connection was successful; in which case a message is sent to the server app.
Disconnect is self explanatory.

Receiving Data
Like with the server, the reception of data is implemented using a timer. Once per second, the client checks to see if data is available, and if it is, reads and displays the data on the app display.

While the server must be running prior to the client making a connection, once the two devices are connected, either app can send data to the other app, at any time.
Error Handling
The client’s error handling is identical to the server’s error handling.

Completed Client Side Programs

Completed Server Side Programs

Setting Up A Bluetooth Connection
Before you use the Bluetooth communications apps, do the following:
Use Build .apk or other method to obtain the server app, download and install on your first Android device. Use Build .apk or other method to obtain the client app, download and install on your second Android device.
Go in to the Android Settings and turn on the Bluetooth feature. Once your two devices see each other over Bluetooth, you may be prompted to “pair” the devices, or (depending on Android version), you may have to manually choose the device and then choose pairing. Follow the on screen instructions.
Once the two devices are “paired”, launch the Server app and select Accept Connection. On the other device, launch the Client app and select Connect. If all goes well, you should see a “client connected” message on the Server app.
Client
http://appinventor.pevest.com/source/tutorials/BTClient1.aia
Server
http://appinventor.pevest.com/source/tutorials/BTServer1.aia