iOS BT Mesh 環境介紹與架設(下)

前言

前一篇文章「iOS BT Mesh 環境介紹與架設(上)」講解基本使用到的Mesh架構及配置入網流程,讓裝置順利成為Mesh網路的Node,本篇介紹Group建立流程及Node發布訊息流程。

BT Mesh Group流程

下圖為新增Group流程,輸入名稱後,選取欲加入Group的Node,預設訂閱的Model ID為GENERIC_OnOff_Server (0x1000),按下新增按鈕,進行訂閱流程,當完成訂閱後,將資訊儲存。建立Group可以控制內部Node的開關功能,因為是訂閱GENERIC_OnOff_Server (0x1000),建立Group不需要使用者個別控制Node。




BT Mesh 新增Group說明

下圖為Group主頁面,下方點選右邊Groups圖示,即可顯示Group主頁面,右上方「+」為新增Group按鈕。




點選右上角「+」跳轉至新增Group頁面,輸入名稱及選取加入Group的Node,範例中Group名稱為test,選擇Node1,按下Save按鈕,執行 [[QmeshDatabase sharedInstance]getNextFreeGroupAddress]取得下一個Group ID,再透過QTIEditGroupViewController.m內的 [[QmeshDatabase sharedInstance]addGroup:group devices:_devices] 將Group進行建立並進行訂閱,接著跳轉至QTIGroupProgress,顯示訂閱程序進度,部分Swift代碼及圖如下:

 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return devices.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "nodeCell") as! AddGroupNodeTableViewCell
let device = devices[indexPath.row]

cell.setNode(node: device)

if device.selected {
cell.accessoryType = UITableViewCell.AccessoryType.checkmark
}else{
cell.accessoryType = UITableViewCell.AccessoryType.none
}
return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let device = devices[indexPath.row]
//選取欲新增至Group的Node
if device.selected {
devices[indexPath.row].selected = false

}else{
devices[indexPath.row].selected = true
}
self.tableView.reloadData()
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}

// 文字變動,搜尋資料庫查看是否已新增
@objc func textFieldDidChange(_ textField:UITextField){
groupName = textField.text
print("text changed = \(groupName!)")
isGroupEqual = false
for gp in groups {
if groupName == gp.name {
self.group = gp
isGroupEqual = true
for node in devices {
for subscripName in node.subscriptions {
if gp.address == (subscripName as! String) {
for device in devices {
if node.elementAddress == device.elementAddress {
device.selected = true
break
}
}
break
}
}
}
}
}
if isGroupEqual == false {
for device in devices {
device.selected = false
}
}
self.tableView.reloadData()
}
// 查詢資料庫,如果已新增則做更新,若無資料則新增Group
@IBAction func saveAction(_ sender: Any) {
if isGroupEqual {

}else {
self.group = QmeshGroup()
let groupAddress = QmeshDatabase.sharedInstance()?.getNextFreeGroupAddress()
self.group?.address = QmeshUtilities.number(toHexString: groupAddress as! UInt32)
if nameTextField.text?.count == 0 {
self.group?.name = String(format: "Group %@", (group?.address)!)
}else {
self.group?.name = nameTextField.text
}
}
QmeshDatabase.sharedInstance()?.add(self.group, devices: self.devices)
//跳轉至訂閱畫面
self.performSegue(withIdentifier: "GROUP_PROGRESS", sender: self)
}


下圖為完成訂閱的頁面及部分代碼,在QTIGroupProgress.m內顯示訂閱服務流程,下面的程式碼是取得目前已經訂閱的Model ID,預設使用GENERIC_OnOff_Server (0x1000),點選「OK」按鈕回到Group主畫面。

groups = [NSMutableArray array];
if ([[QmeshDatabase sharedInstance] groupsToSubscribe].count)
[groups addObjectsFromArray:[[QmeshDatabase sharedInstance] groupsToSubscribe]];
if ([[QmeshDatabase sharedInstance] groupsToUnSubscribe].count)
[groups addObjectsFromArray:[[QmeshDatabase sharedInstance] groupsToUnSubscribe]];




如下圖,回到Group主畫面後,可以看到已經新增的Group及開關案妞,按下按鈕可以操控Group內的Node開關功能,下面指令程式碼部分,內部參數onOffSet設定為selectedGroup.groupAddress及networkInfo設定為selectedGroup.networkInfo,就能針對該Group進行開關操作。

[[QmeshGenericApi sharedInstance] qmeshGenericOnOffSet:selectedGroup.groupAddress networkInfo:selectedGroup.networkInfo onOff:@(powerState) TID:[[QmeshDatabase sharedInstance]getTid] transitionTime:@0 delay:@0 result:nil]




發佈(Publish)流程圖

下圖為Publish流程圖,參考程式碼QTIPublishViewController.m。




QTIPublishViewController頁面,Groups上方為初始直及QmeshNetworkInfo內的資訊,Groups List內增加0x0000讓Publish指向0的位置,表示取消Publish功能,Models列出該Node內所有的Model ID,範例為「Node 1」內的全部Model ID,讓使用者選取透過哪個Model ID操控的功能,部分代碼及圖如下:

NSNumber *publishAddress;
publishAddress = _selectedGroup.groupAddress;

[[QmeshConfigApi sharedInstance]
qmeshConfigModelPublicationSet:selectedDevice.elementAddress // Node 1
networkKeyIndex:@0 //初始使用Key index = 0
ttl:selectedDevice.networkInfo.ttl
publishAddress:publishAddress
applicationKeyIndex:applicationKeyNumber
credentialFlag:credentialFlag
publishTTL:publishTTLNumber
publishPeriod:publishPeriodNumber
sigOrVendor:_selectedModel.type //Model ID是SIG標準或自定義
publishModelId:_selectedModel.modelID // 選擇的Model ID
retransmissions:retriesNumber
retransmissionInterval:retryIntervalNumber
result:nil];




透過qmeshConfigModelPublicationSet將資訊進行Publish程序, qmeshConfigModelPublicationResponse回傳至UI畫面,判斷是否完成並跳出Alert通知使用者狀況,部分代碼及圖如下:

func qmeshConfigModelPublicationResponse(_ modelId: NSNumber, sigOrVendor: QmeshSigOrVendor, elementAddress: NSNumber, publishAddress: NSNumber, applicationKeyIndex: NSNumber, credentialFlag: NSNumber, publishTTL: NSNumber, publishPeriod: NSNumber, retransmitCount: NSNumber, retransmitInterval: NSNumber, messageStatus: QMESH_RESULT) {
//成功
if messageStatus == QMESH_RESULT.QMESHRESULT_SUCCESS {
DispatchQueue.main.async {
let alertController = UIAlertController(title: "Message",
message: "Model publish complete.",
preferredStyle: .alert)
alertController.addAction( UIAlertAction( title: "Ok", style: UIAlertAction.Style.destructive) {
(action: UIAlertAction!) -> Void in
self.dismiss(animated: false, completion: nil)
})
self.present( alertController, animated: true, completion: nil)
}
}else{
//失敗
DispatchQueue.main.async {
self.showAlert("Message", body: "Model publish error.")
}
}
}





Group名稱修改

Group Item向左滑,顯示編輯名稱及刪除,若按下Delete會跳出Alert提醒使用者,點選確認則會執行[[QmeshDatabase sharedInstance]deleteGroup:group]做刪除的動作,如下圖:



按下編輯名稱,跳出Alert Group名稱輸入視窗,輸入修改名稱後,點選確認按鈕,透過[[QmeshDatabase sharedInstance]renameGroup:group]更改資料庫內對應Group的名稱。



小結

以上為本篇Group及Publish介紹,透過iOS BT Mesh 環境介紹與架設(上)及本篇介紹BT Mesh基本功能及觀念,建立群組可以控制群組內的全部裝置,例如將兩個燈設置一個Group,Group名稱叫「Test Lights」,Switch設定Publish指定「Test Lights」,設定完成後,按下Switch就可以控制「Test Lights」Group內全部Lights的開關功能。對於BT Mesh有興趣可以找「詮鼎科技Qualcomm Team」聯繫,官方版本別Qmesh_iOS_20191123,希望透過這兩篇博文能幫助開發者。

 

資料參考:

Bluetooth® Technology Website

https://www.bluetooth.com/learn-about-bluetooth/bluetooth-technology/topology-options/

解密藍牙mesh系列

https://www.eettaiwan.com/20170822nt41-intro-to-bluetooth-mesh-part1/

BLE-Mesh技術揭秘

http://doc.iotxx.com/BLE-Mesh%E6%8A%80%E6%9C%AF%E6%8F%AD%E7%A7%98

★博文內容均由個人提供,與平台無關,如有違法或侵權,請與網站管理員聯繫。

★文明上網,請理性發言。內容一周內被舉報5次,發文人進小黑屋喔~

評論