Python(Bluetooth通信03-Bleak_GATTサーバ)
■スマホでGATTサーバを作成する。
前回は既存のアプリをスマホで実行して、PC-スマホ間でデータの送受信を行った。もう少し自由度を持たせたいので、既存のアプリの代わりにデータの受け手となるGATT(Generic Attribute Profile)サーバのアプリをスマホに作る。
AIでそれらしいコードを生成して、Android studioに張り付け実行と修正を繰り返していく。
AndroidのonCreateのコードが下のようなもの。
GATT serverの作成、Characteristic作成、Service作成の後、通信に必要なAdvertisingを始めている。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bleTextView = findViewById(R.id.BLE_text);
BluetoothManager manager =
(BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
BluetoothAdapter adapter = manager.getAdapter();
//-----------------------------------------
// GATT Server作成
//-----------------------------------------
gattServer = manager.openGattServer(this, gattServerCallback);
//-----------------------------------------
// Characteristic作成
//-----------------------------------------
characteristic = new BluetoothGattCharacteristic(
CHAR_UUID,
BluetoothGattCharacteristic.PROPERTY_READ
| BluetoothGattCharacteristic.PROPERTY_WRITE
| BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ
| BluetoothGattCharacteristic.PERMISSION_WRITE
);
characteristic.setValue("Hello".getBytes(StandardCharsets.UTF_8));
BluetoothGattDescriptor descriptor =
new BluetoothGattDescriptor(
UUID.fromString(
"00002902-0000-1000-8000-00805f9b34fb"
),
BluetoothGattDescriptor.PERMISSION_READ
| BluetoothGattDescriptor.PERMISSION_WRITE
);
characteristic.addDescriptor(descriptor);
//-----------------------------------------
// Service作成
//-----------------------------------------
BluetoothGattService service =
new BluetoothGattService(
SERVICE_UUID,
BluetoothGattService.SERVICE_TYPE_PRIMARY
);
service.addCharacteristic(characteristic);
gattServer.addService(service);
//-----------------------------------------
// Advertise開始
//-----------------------------------------
BluetoothLeAdvertiser advertiser =
adapter.getBluetoothLeAdvertiser();
AdvertiseSettings settings =
new AdvertiseSettings.Builder()
.setAdvertiseMode(
AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.setConnectable(true)
.build();
AdvertiseData data =
new AdvertiseData.Builder()
.setIncludeDeviceName(false)
.addServiceUuid(new ParcelUuid(SERVICE_UUID))
.build();
advertiser.startAdvertising(
settings,
data,
advertiseCallback
);
Log.d(TAG, "Advertising Start");
}
Advertising中にPythonのコードを実行すると、接続が試される。接続に成功した後、"Hello Android22222"を送信し、スマホで受信すると、アプリ内のTextviewを更新するとともにPCへ通知(Notify)する。
結果が下。
スマホ画面。TextviewがPythonコード内の文字列に更新されている。

Pythonのコンソール。Notifyで受信した文字列が表示されている。

android.permission.BLUETOOTH_CONNECT、android.permission.BLUETOOTH_ADVERTISEといった権限の付与も行わないといけないけど、エラーのたびに生成AIに聞くなどして割りとすんなりと上の実行までできた。
