エンプラ系エンジニアの地獄
一週間前、Delphiで開発するアプリのプロジェクトにアサインされた。私はC#erにもかかわらず。大規模な法改正により人月が足りないそう泣
年末年始でDelphiを学ぶことに...
むかし、Delphiで簡単なiOSアプリを作ったのだが、文法とかとかが古めかしかったのをおぼえている。年の瀬にあらためて学んでみるとやっぱり書きづらい。とはいえ、Delphiにもいい点があると思っている。ネイティブに近いため、C#より速く動くし、WindowsのAPIと親和性が高いイメージがある。まずは軽いアプリを作って勉強したいなーと思った。
AirPodsをツールから接続するアプリを作成することに
業務中のWEB会議ではもっぱらAirPodsをイヤホンとして使っています。自動的に接続されないため、Windowsの設定画面から手動でつなぐ必要があるのです。これがまたダルいのでツール叩けばつながる感じのアプリを作ろうって算段です★
全体像
- ペアリングされたデバイス(AirPods)を取得
- Bluetoothとのコネクションを作成
- BluetoothのサービスのUUIDを探す
- デバイス(AirPods)と接続
ペアリングされたデバイス(AirPods)を取得
↓みたいな感じで実装。引数には「AirPods」を指定すればOKかと。
function TBluetoothGetter.FindAirPodsDevice(ADeviceName: string)
: TBluetoothDevice;
var
BluetoothManager: TBluetoothManager;
BluetoothAdapter: TBluetoothAdapter;
BluetoothDeviceObj: TObject;
BluetoothDevice: TBluetoothDevice;
begin
BluetoothManager := TBluetoothManager.Current;
BluetoothAdapter := BluetoothManager.CurrentAdapter;
for BluetoothDeviceObj in BluetoothAdapter.PairedDevices do begin
BluetoothDevice := BluetoothDeviceObj as TBluetoothDevice;
if BluetoothDevice.DeviceName.Contains(ADeviceName) then begin
Result := BluetoothDevice;
end;
end;
end;
Bluetoothとのコネクションを作成
↑で取得したデバイス(TBluetoothDevice)のCreateClientSocket関数を使えばOKっぽいが、第一引数のUUIDが分からんかった。調べてもいまいち的を射た答えがない。つーかBluetoothって何?
どうやら、BluetoothのサービスのUUID?を入力すればOKっぽいので自力で探す旅に。
BluetoothのサービスのUUIDを探す
TBluetoothDeviceにGetServices関数が入っていたので、この中のUUIDを使えばいいと予想。まずは全部リストアップし、対象のUUIDを探す。
procedure TBluetoothGetter.ListupBluetoothServiceUUID;
var
BluetoothDevice: TBluetoothDevice;
BluetoothService: TBluetoothService;
begin
BluetoothDevice := FindAirPodsDevice('AirPods');
if BluetoothDevice = nil then begin
raise Exception.Create('デバイスが見つかりませんでした。');
end;
for BluetoothService in BluetoothDevice.GetServices() do begin
Writeln('Name:' + BluetoothService.Name + ' ' + 'UUID:' +
BluetoothService.UUID.ToString);
end;
end;
デバイス(AirPods)と接続
↑で取得したGUIDを元にSocketを開き、Connect関数を呼ぶ。すると、なんとAirPodsにつながりました。ただ、EBluetoothSocketExceptionが出てきたため、こいつは無視するようにします。
procedure TBluetoothGetter.Connect();
var
BluetoothDevice: TBluetoothDevice;
BluetoothSocket: TBluetoothSocket;
begin
BluetoothDevice := FindAirPodsDevice('AirPods');
if BluetoothDevice = nil then begin
raise Exception.Create('デバイスが見つかりませんでした。');
end;
BluetoothSocket := BluetoothDevice.CreateClientSocket
(BluetoothServiceUUID, True);
try
BluetoothSocket.Connect;
except
on E: EBluetoothSocketException do begin
end;
end;
end;
成果物
参考にしたURL
- https://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_Classic_Bluetooth
- http://izawa-web.com/bt60/bt60delphi.html
- https://note.com/liuk_net/n/nc25a4b5cf2a4
最後に
- Delphi、サンプル少ないよぉ...
- Bluetoothもとい、DDDのサンプルコードとかほとんどない。
- 学習のハードル高くないかえ...
- type,interface,implementationとかとか、おまじないを覚えるのが大変
- Bluetoothの実装は楽だった(と思う)
- 最初はC#で実装しようとしたが、WinRTがどうのこうのと、ConsoleAppで作んのがダルそうだった。
- DelphiならSystem.BluetoothをusesすればOKなのでよきよき