or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdbluetooth-communication.mdcore-protocol.mdgui-components.mdindex.mdmessage-handling.mdserial-communication.md

bluetooth-communication.mddocs/

0

# Bluetooth Communication

1

2

Android Bluetooth communication enabling Arduino control from mobile applications. The Bluetooth module provides seamless Arduino communication over Bluetooth connections with automatic device pairing, connection management, and the same reliable messaging protocol used in serial communication.

3

4

## Capabilities

5

6

### Android Bluetooth Arduino Connection

7

8

Main class for Bluetooth communication with Arduino from Android applications, implementing the observer pattern for asynchronous message handling.

9

10

```java { .api }

11

class AndroidBluetooth4JArduino implements JArduinoClientObserver, JArduinoSubject, Runnable {

12

// Message framing constants (same as serial)

13

static final byte START_BYTE = 0x12;

14

static final byte STOP_BYTE = 0x13;

15

static final byte ESCAPE_BYTE = 0x7D;

16

17

// Constructors

18

AndroidBluetooth4JArduino(AndroidBluetoothConfiguration myConf);

19

AndroidBluetooth4JArduino(ProtocolConfiguration myConf);

20

21

// Configuration methods

22

void setAndroidBluetoothSocket(BluetoothSocket socket);

23

24

// Communication methods

25

void receiveMsg(byte[] msg);

26

void register(JArduinoObserver observer);

27

void unregister(JArduinoObserver observer);

28

void run();

29

void close();

30

}

31

```

32

33

### Bluetooth Configuration

34

35

Configuration class for Android Bluetooth connection setup.

36

37

```java { .api }

38

class AndroidBluetoothConfiguration extends ProtocolConfiguration {

39

AndroidBluetoothConfiguration(BluetoothSocket socket);

40

BluetoothSocket getmSocket();

41

}

42

43

class ProtocolConfiguration {

44

// Base configuration class

45

}

46

```

47

48

## Usage Examples

49

50

### Basic Android Bluetooth Setup

51

52

```java

53

import org.sintef.jarduino.comm.AndroidBluetooth4JArduino;

54

import org.sintef.jarduino.comm.AndroidBluetoothConfiguration;

55

import org.sintef.jarduino.observer.JArduinoObserver;

56

import org.sintef.jarduino.*;

57

import android.bluetooth.BluetoothSocket;

58

import android.bluetooth.BluetoothAdapter;

59

import android.bluetooth.BluetoothDevice;

60

61

public class AndroidBluetoothExample extends Activity {

62

private AndroidBluetooth4JArduino arduino;

63

private BluetoothSocket socket;

64

65

private void connectToArduino() {

66

try {

67

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

68

BluetoothDevice device = adapter.getRemoteDevice("00:11:22:33:44:55"); // Arduino Bluetooth MAC

69

70

// Create Bluetooth socket

71

UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Serial Port Profile

72

socket = device.createRfcommSocketToServiceRecord(uuid);

73

socket.connect();

74

75

// Create configuration and Arduino connection

76

AndroidBluetoothConfiguration config = new AndroidBluetoothConfiguration(socket);

77

arduino = new AndroidBluetooth4JArduino(config);

78

79

// Register observer for Arduino responses

80

arduino.register(new JArduinoObserver() {

81

@Override

82

public void receiveMsg(byte[] msg) {

83

FixedSizePacket packet = JArduinoProtocol.createMessageFromPacket(msg);

84

Log.d("Arduino", "Response: " + packet.toString());

85

86

// Handle specific message types

87

if (packet instanceof AnalogReadResultMsg) {

88

AnalogReadResultMsg result = (AnalogReadResultMsg) packet;

89

// Update UI with sensor value

90

}

91

}

92

});

93

94

// Start communication thread

95

Thread bluetoothThread = new Thread(arduino);

96

bluetoothThread.start();

97

98

} catch (IOException e) {

99

Log.e("Bluetooth", "Connection failed", e);

100

}

101

}

102

103

private void controlArduino() {

104

// Set pin mode

105

FixedSizePacket pinMode = JArduinoProtocol.createPinMode(DigitalPin.PIN_13, PinMode.OUTPUT);

106

arduino.receiveMsg(pinMode.getPacket());

107

108

// Blink LED

109

FixedSizePacket on = JArduinoProtocol.createDigitalWrite(DigitalPin.PIN_13, DigitalState.HIGH);

110

arduino.receiveMsg(on.getPacket());

111

112

// Read sensor

113

FixedSizePacket analogRead = JArduinoProtocol.createAnalogRead(AnalogPin.A_0);

114

arduino.receiveMsg(analogRead.getPacket());

115

}

116

117

@Override

118

protected void onDestroy() {

119

super.onDestroy();

120

if (arduino != null) {

121

arduino.close();

122

}

123

if (socket != null) {

124

try {

125

socket.close();

126

} catch (IOException e) {

127

Log.e("Bluetooth", "Error closing socket", e);

128

}

129

}

130

}

131

}

132

```

133

134

### Android Bluetooth Device Discovery

135

136

```java

137

import android.bluetooth.BluetoothAdapter;

138

import android.bluetooth.BluetoothDevice;

139

import android.content.BroadcastReceiver;

140

import android.content.Context;

141

import android.content.Intent;

142

import android.content.IntentFilter;

143

144

public class BluetoothDeviceDiscovery {

145

private BluetoothAdapter bluetoothAdapter;

146

private List<BluetoothDevice> discoveredDevices = new ArrayList<>();

147

148

public void startDiscovery() {

149

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

150

151

// Register broadcast receiver for device discovery

152

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

153

registerReceiver(deviceDiscoveryReceiver, filter);

154

155

// Start discovery

156

if (bluetoothAdapter.isDiscovering()) {

157

bluetoothAdapter.cancelDiscovery();

158

}

159

bluetoothAdapter.startDiscovery();

160

}

161

162

private final BroadcastReceiver deviceDiscoveryReceiver = new BroadcastReceiver() {

163

@Override

164

public void onReceive(Context context, Intent intent) {

165

String action = intent.getAction();

166

if (BluetoothDevice.ACTION_FOUND.equals(action)) {

167

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

168

169

// Look for Arduino devices (typically named "HC-05", "HC-06", etc.)

170

String deviceName = device.getName();

171

if (deviceName != null && (deviceName.contains("HC-") || deviceName.contains("Arduino"))) {

172

discoveredDevices.add(device);

173

// Update UI with found Arduino device

174

}

175

}

176

}

177

};

178

}

179

```

180

181

### Socket Configuration with Existing Connection

182

183

```java

184

// If you already have a BluetoothSocket from elsewhere

185

BluetoothSocket existingSocket = // ... obtained from your Bluetooth setup

186

187

// Create Arduino communication directly

188

AndroidBluetooth4JArduino arduino = new AndroidBluetooth4JArduino(

189

new AndroidBluetoothConfiguration(existingSocket)

190

);

191

192

// Or set socket after creation

193

arduino.setAndroidBluetoothSocket(existingSocket);

194

```

195

196

## Android Integration

197

198

### Permissions Required

199

200

Add these permissions to your Android manifest:

201

202

```xml

203

<uses-permission android:name="android.permission.BLUETOOTH" />

204

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

205

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

206

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

207

```

208

209

### Sample Android Application

210

211

The JArduino project includes complete Android sample applications:

212

213

- **jarduino.samples.android**: Basic Android Arduino control

214

- **jarduino.samples.android.gui**: Full GUI Arduino controller with visual pin layout

215

216

These samples demonstrate:

217

- Bluetooth device discovery and pairing

218

- Arduino connection management

219

- Real-time sensor reading

220

- Interactive pin control

221

- Command history and logging

222

223

## Message Framing Protocol

224

225

Bluetooth communication uses the same reliable binary framing protocol as serial communication:

226

227

- **START_BYTE (0x12)**: Marks beginning of message

228

- **STOP_BYTE (0x13)**: Marks end of message

229

- **ESCAPE_BYTE (0x7D)**: Escapes special bytes in payload

230

231

This ensures consistent message handling across all communication transports.

232

233

## Threading Model

234

235

The `AndroidBluetooth4JArduino` class implements `Runnable` for background communication:

236

237

- **Main Thread**: Send commands via `receiveMsg()` method

238

- **Background Thread**: Continuously listens for Arduino responses

239

- **Observer Callbacks**: Delivered on background thread (use Handler for UI updates)

240

241

## Error Handling

242

243

Common Bluetooth issues handled by the implementation:

244

245

- **Connection failures**: IOException handling with automatic cleanup

246

- **Device not found**: Proper error reporting through observer pattern

247

- **Connection lost**: Automatic detection and notification

248

- **Message corruption**: Framing protocol enables recovery

249

- **Android lifecycle**: Proper cleanup in activity destruction

250

251

## Dependencies

252

253

- **JArduino Core**: `org.sintef.jarduino.core` for protocol and message classes

254

- **Android Bluetooth API**: `android.bluetooth.*` for Bluetooth socket communication

255

- **RXTX Library**: `org.kevoree.extra.osgi.rxtx` for additional serial port utilities