究極のハウツー:ハードウェアを備えたBluetoothSwiftアプリを20分で構築する

前のチュートリアルでは、BluetoothをParticleXenonアプリケーションに追加する方法を学びました。そうすれば、nRFConnectやLightBlueExplorerなどのテストアプリからオンボードRGBLEDを制御できます。

この投稿では、さらに一歩進んでいきます。パーティクルメッシュRGBLEDを制御するSwiftアプリを開発します。すべてがうまくいけば、約20分で動作するアプリができあがります。

始めましょう。

今、記事全文を読む時間がありませんか?

こちらからPDF版をダウンロードしてください。

セットアップ

  • Xcodeをインストールします。こちらのAppStoreからダウンロードできます。
  • Appleログインも必要です。iCloudメールを使用しています。まだアカウントを持っていない場合は、Xcode内に新しいアカウントを作成できます。
  • RGBサンプルコードをパーティクルメッシュボードにインストールします。

プロジェクトを作成する

すべてがインストールされたら、楽しいものに取り掛かりましょう!

Xcodeを開き、[ファイル]→[新しいプロジェクト]に移動します。

Xcodeの新しいプロジェクト

シングルビューアプリを選択します。

新しいプロジェクト情報

次に、プロジェクト名を好みに合わせて更新します。また、組織IDをに変更しましたcom.jaredwolff。必要に応じて変更してください。

保存する場所を選択します。

次に、Info.plistを見つけます

XcocdeのInfo.plist

info.plist追加して更新Privacy - Bluetooth Peripheral Usage Description

私が使用することになった説明は App uses Bluetooth to connect to the Particle Xenon RGB Example

これにより、Bluetoothをリリースしたい場合に、アプリでBluetoothを使用できます。

それでは、すべてを最小限の機能にしましょう!

最小限の機能

新しい断面画像

次に、接続してサービス検出を行うための最小限の機能を備えたアプリを入手します。アクションのほとんどはで発生しますViewController.swift

最初にインポートしましょう CoreBluetooth

 import CoreBluetooth 

これにより、iOSのBluetooth LowEnergy機能を制御できます。その後のは、両方追加してみましょうCBPeripheralDelegateCBCentralManagerDelegateするViewControllerクラス。

 class ViewController: UIViewController, CBPeripheralDelegate, CBCentralManagerDelegate { 

次に、実際の中央マネージャーと周辺機器を格納するためのローカルプライベート変数を作成しましょう。それらをさらにすぐに設定します。

 // Properties private var centralManager: CBCentralManager! private var peripheral: CBPeripheral! 

あなたのviewDidLoad関数で、初期化しましょうcentralManager

 centralManager = CBCentralManager(delegate: self, queue: nil) 

設定delegate: selfは重要です。それ以外の場合、中央の状態は起動時に変更されません。

先に進む前に、別のファイルを作成してそれを呼び出しましょうParticlePeripheral.swift。どこにでも配置できますが、後で使用するために、Modelsという別の「グループ」に配置しました。

内部では、パーティクルボードのUUIDを含むいくつかのパブリック変数を作成します。彼らは見覚えがあるはずです!

 import UIKit import CoreBluetooth class ParticlePeripheral: NSObject { /// MARK: - Particle LED services and charcteristics Identifiers public static let particleLEDServiceUUID = CBUUID.init(string: "b4250400-fb4b-4746-b2b0-93f0e61122c6") public static let redLEDCharacteristicUUID = CBUUID.init(string: "b4250401-fb4b-4746-b2b0-93f0e61122c6") public static let greenLEDCharacteristicUUID = CBUUID.init(string: "b4250402-fb4b-4746-b2b0-93f0e61122c6") public static let blueLEDCharacteristicUUID = CBUUID.init(string: "b4250403-fb4b-4746-b2b0-93f0e61122c6") } 

戻っViewController.swiftて、Bluetoothビットをつなぎ合わせましょう。

Bluetoothビット

iOSでのBluetoothSwiftのフロー図

Bluetoothに関係することはすべて、イベントベースです。これらのイベントを処理するいくつかの関数を定義します。重要なものは次のとおりです。

centralManagerDidUpdateStateBluetoothペリフェラルがオンまたはオフに切り替えられると更新されます。アプリが最初に起動したときに起動するので、Bluetoothの状態を知ることができます。ここからもスキャンを開始します。

このcentralManagerdidDiscoverイベントは、スキャン結果を受け取ったときに発生します。これを使用して接続を開始します。

centralManagerdidConnectデバイスが接続されると、イベントが発生します。ここからデバイス検出を開始します。注:デバイス検出は、使用可能なサービスと特性を判別する方法です。これは、接続しているデバイスの種類を確認するための良い方法です。

peripheraldidDiscoverServicesイベントはまず、すべてのサービスが発見された後。接続されたので、centralManagerからperipheral今に切り替えたことに注意してください。ここから特徴的な発見を始めましょう。ターゲットとしてRGBサービスUUIDを使用します。

peripheraldidDiscoverCharacteristicsForイベントは、提供されるサービスのUUIDを使用して、すべての特性を提供します。これは、完全なデバイス検出を行うチェーンの最後のステップです。毛深いですが、接続フェーズ中に一度だけ実行する必要があります!

すべてのBluetooth機能を定義します。

これで、トリガーされる関数イベントがわかりました。接続サイクル中に発生する論理的な順序でそれらを定義します。

First, we'll define centralManagerDidUpdateState to start scanning for a device with our Particle RGB LED Service. If Bluetooth is not enabled, it will not do anything.

 // If we're powered on, start scanning func centralManagerDidUpdateState(_ central: CBCentralManager) { print("Central state update") if central.state != .poweredOn { print("Central is not powered on") } else { print("Central scanning for", ParticlePeripheral.particleLEDServiceUUID); centralManager.scanForPeripherals(withServices: [ParticlePeripheral.particleLEDServiceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey : true]) } } 

Defining the centralManagerdidDiscover is our next step in the process. We know we've found a device if this event has occurred.

 // Handles the result of the scan func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // We've found it so stop scan self.centralManager.stopScan() // Copy the peripheral instance self.peripheral = peripheral self.peripheral.delegate = self // Connect! self.centralManager.connect(self.peripheral, options: nil) } 

So, we stop scanning using self.centralManager.stopScan(). We set the peripheral so it persists through the app. Then we connect to that device using self.centralManager.connect

Once connected, we need to double check if we're working with the right device.

 // The handler if we do connect succesfully func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { if peripheral == self.peripheral { print("Connected to your Particle Board") peripheral.discoverServices([ParticlePeripheral.particleLEDServiceUUID]) } } 

By comparing the two peripherals we'll know its the device we found earlier. We'll kick off a services discovery using peripheral.discoverService. We can use ParticlePeripheral.particleLEDServiceUUID as a parameter. That way we don't pick up any services we don't care about.

Once we finish the discovering services, we'll get a didDiscoverServices event. We iterate through all the "available" services. (Though there will only be one!)

 // Handles discovery event func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if let services = peripheral.services { for service in services { if service.uuid == ParticlePeripheral.particleLEDServiceUUID { print("LED service found") //Now kick off discovery of characteristics peripheral.discoverCharacteristics([ParticlePeripheral.redLEDCharacteristicUUID, ParticlePeripheral.greenLEDCharacteristicUUID, ParticlePeripheral.blueLEDCharacteristicUUID], for: service) return } } } } 

By this point this is the third time we're checking to make sure we have the correct service. This becomes more handy later when there are many characteristics and many services.

We call peripheral.discoverCharacteristics with an array of UUIDs for the characteristics we're looking for. They're all the UUIDs that we defined in ParticlePeripheral.swift.

Finally, we handle the didDiscoverCharacteriscsFor event. We iterate through all the available characteristics. As we iterate we compare with the ones we're looking for.

 // Handling discovery of characteristics func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let characteristics = service.characteristics { for characteristic in characteristics { if characteristic.uuid == ParticlePeripheral.redLEDCharacteristicUUID { print("Red LED characteristic found") } else if characteristic.uuid == ParticlePeripheral.greenLEDCharacteristicUUID { print("Green LED characteristic found") } else if characteristic.uuid == ParticlePeripheral.blueLEDCharacteristicUUID { print("Blue LED characteristic found"); } } } } 

At this point we're ready to do a full device discovery of our Particle Mesh device. In the next section we'll test what we have to make sure things are working ok.

Testing our minimal example

テストに関する断面画像

Before we get started, if you run into trouble I've put some troubleshooting steps in the footnotes.

To test, you'll have to have an iPhone with Bluetooth Low Energy. Most modern iPhones have it. The last iPhone not to have it I believe was either the iPhone 4 or 3Gs. (so you're likely good)

First, plug it into your computer.

Go to the top by the play and stop buttons. Select your target device. In my case I chose my phone (Jared's iPhone). You can also use an iPad.

デバイスタイプを選択します

Then you can hit Command + R or hit that Play button to load the app to your phone.

Make sure you have your log tab open. Enable it by clicking the bottom pane button in the top right corner.

ログ用のXcodeの下部ペイン

Make sure you have a mesh device setup and running the example code. You can go to this post to get it. Remember your Particle Mesh board needs to be running device OS 1.3.0 or greater for Bluetooth to work!

Once both the firmware and app is loaded, let's check the log output.

It should look something like this:

View loaded Central state update Central scanning for B4250400-FB4B-4746-B2B0-93F0E61122C6 Connected to your Particle Board LED service found Red LED characteristic found Green LED characteristic found Blue LED characteristic found 

This means that your Phone has connected, found the LED service! The characteristics also being discovered is important here. Without those we wouldn't be able to send data to the mesh device.

Next step is to create some sliders so we can update the RGB values on the fly.

Slide to the left. Slide to the right.

Next we're going to add some elements to our Main.storyboard. Open Main.storyboard and click on the View underneath View Controller.

Xcodeでビューを更新しています

Then click on the Library button. (It looks like the old art Apple used for the home button)

Library button in Xcode

You'll get a pop-up with all the choices that you can insert into your app.

Library pane in Xcode

Drag three Labels and copy three Sliders to your view.

Dragging Labels to Xcode View

You can double click on the labels and rename them as you go.

Dragging Slider to Xcode View

If you click and hold, some handy alignment tools will popup. They'll even snap to center!

Alignment tools in Xcode

You can also select them all and move them together. We'll align them vertically and horizontally.

In order for them to stay in the middle, let's remove the autoresizing property. Click the Ruler icon on the top right. Then click each of the red bars. This will ensure that your labels and sliders stay on the screen!

Ruler pane in Xcode

Next let's click the Show Assistant Editor button. (Looks like a Venn diagram)

Show Assistant Editor button in Xcode

Note: make sure that ViewController.swift is open in your Assistant Editor.

Automatic option in Assistant Editor

Then underneath the /properties section, Control-click and dragthe Red Slider into your code.

Drag slider to code

Repeat with all the other ones. Make sure you name them something different. Your code should look like this when you're done:

 // Properties private var centralManager: CBCentralManager! private var peripheral: CBPeripheral! // Sliders @IBOutlet weak var redSlider: UISlider! @IBOutlet weak var greenSlider: UISlider! @IBOutlet weak var blueSlider: UISlider! 

This allow us to access the value of the sliders.

Next, let's attach the Value Changed event to each of the sliders. Right click on the Red Slider in the folder view.

Drag value changed event to code

It should give you some options for events. Click and drag the Value Changed event to your code. Make sure you name it something that makes sense. I used RedSliderChanged for the Red Slider.

Repeat two more times. Your code should look like this at the end of this step:

 @IBAction func RedSliderChanged(_ sender: Any) { } @IBAction func GreenSliderChanged(_ sender: Any) { } @IBAction func BlueSliderChanged(_ sender: Any) { } 

I've also selected each of the sliders to and un-checked Enabled. That way you can't move them. We'll enable them later on in code.

Disable slider by default

Also, this is a great time to change the maximum value to 255. Also set the default value from 0.5 to 0.

Set default value and max value of slider

Back at the top of the file. Let's create some local variables for each of the characteristics. We'll use these so we can write the slider variables to the Particle Mesh board.

 // Characteristics private var redChar: CBCharacteristic? private var greenChar: CBCharacteristic? private var blueChar: CBCharacteristic? 

Now, let's tie everything together!

In the didDiscoverCharacteristicsFor callback function. Let's assign those characteristics. For example

 if characteristic.uuid == ParticlePeripheral.redLEDCharacteristicUUID { print("Red LED characteristic found") redChar = characteristic 

As we find each characteristic, we can also enable each of the sliders in the same spot.

 // Unmask red slider redSlider.isEnabled = true 

In the end your didDiscoverCharacteristicsFor should look like:

 // Handling discovery of characteristics func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let characteristics = service.characteristics { for characteristic in characteristics { if characteristic.uuid == ParticlePeripheral.redLEDCharacteristicUUID { print("Red LED characteristic found") redChar = characteristic redSlider.isEnabled = true } else if characteristic.uuid == ParticlePeripheral.greenLEDCharacteristicUUID { print("Green LED characteristic found") greenChar = characteristic greenSlider.isEnabled = true } else if characteristic.uuid == ParticlePeripheral.blueLEDCharacteristicUUID { print("Blue LED characteristic found"); blueChar = characteristic blueSlider.isEnabled = true } } } } 

Now, let's update the RedSliderChangedGreenSliderChanged and BlueSliderChanged functions. What we want to do here is update the characteristic associated with the Changed function. I created a separate function called writeLEDValueToChar. We'll pass in the characteristic and the data.

 private func writeLEDValueToChar( withCharacteristic characteristic: CBCharacteristic, withValue value: Data) { // Check if it has the write property if characteristic.properties.contains(.writeWithoutResponse) && peripheral != nil { peripheral.writeValue(value, for: characteristic, type: .withoutResponse) } } 

Now add a call to writeLEDValueToChar to each of the Changed functions. You will have to cast the value to a Uint8. (The Particle Mesh device expects an unsigned 8-bit number.)

 @IBAction func RedSliderChanged(_ sender: Any) { print("red:",redSlider.value); let slider:UInt8 = UInt8(redSlider.value) writeLEDValueToChar( withCharacteristic: redChar!, withValue: Data([slider])) } 

Repeat this for GreenSliderChanged and BlueSliderChanged. Make sure you changed red to green and blue for each!

Finally, to keep things clean, i've also added a function that handles Bluetooth disconnects.

 func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { 

Inside, we should reset the state of the sliders to 0 and disable them.

 if peripheral == self.peripheral { print("Disconnected") redSlider.isEnabled = false greenSlider.isEnabled = false blueSlider.isEnabled = false redSlider.value = 0 greenSlider.value = 0 blueSlider.value = 0 

It's a good idea to reset self.peripheral to nil that way we're not ever trying to write to a phantom device.

 self.peripheral = nil 

Finally, because we've disconnected, start scanning again!

 // Start scanning again print("Central scanning for", ParticlePeripheral.particleLEDServiceUUID); centralManager.scanForPeripherals(withServices: [ParticlePeripheral.particleLEDServiceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey : true]) } 

Alright! We just about ready to test. Let's move on to the next (and final) step.

Test the sliders.

Next section test!

The hard work is done. Now it's time to play!

The easiest way to test everything is to click the Play button in the top left or the Command + R keyboard shortcut. Xcode will load the app to your phone. You should see a white screen proceeded by a screen with your sliders!

The sliders should stay greyed out until connected to your Particle Mesh board. You can check your log output if the connection has been established.

View loaded Central state update Central scanning for B4250400-FB4B-4746-B2B0-93F0E61122C6 Connected to your Particle Board LED service found Red LED characteristic found Green LED characteristic found Blue LED characteristic found 

(Look familiar? We're connected!)

If you followed everything perfectly, you should be able to move the sliders. Better yet, the RGB LED on the Particle Mesh board should change color.

Final test results

Conclusion

この記事では、Bluetooth経由でパーティクルメッシュボードとiOSデバイスを接続する方法を学びました。利用可能な各特性に接続する方法を学びました。さらに、何よりも、すべてを実行するためのクリーンなインターフェイスを作成します。

ご想像のとおり、iOSのBluetoothでうさぎの穴を掘り下げることができます。今後のガイドには、さらに多くの情報が含まれています。パーティクルメッシュの究極のガイドです。私のリストの購読者は、リリース前のコンテンツにアクセスでき、リリースされると割引が適用されます。サインアップするには、ここをクリックしてください。

コード

完全なソースコードはGithubで入手できます。便利な場合は、スターボタンを押してください。⭐️