2017年2月15日 星期三

swift3 字元轉換

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        if characteristic.uuid.uuidString == "FFF4" {
            guard let data = characteristic.value else {
                return
            }
            let dataString = String(data: data, encoding: String.Encoding.unicode)
            var uintData = [UInt8](repeating:0, count:data.count)
            data.copyBytes(to: &uintData, count: data.count)
            print ("uintData = \(uintData)")
            print ("data = \(data)")
            print ("unicode: \(dataString)")
            print ("characteristic = \(characteristic)")

        }

uintData = [6]
data = 1 bytes
unicode: Optional("")
characteristic = <CBCharacteristic: 0x1700b2300, UUID = FFF4, properties = 0x10, value = <06>, notifying = YES>

The 12 Steps of Bluetooth (Swift)

note from 

http://www.kevinhoyt.com/2016/05/20/the-12-steps-of-bluetooth-swift/

The 12 Steps of Bluetooth (Swift)

 on swift, ble, bluetooth

There are a lot of tutorials out there for using Bluetooth (Low Energy) on iOS. Many of those are written using Swift. Some of them cover the mechanics of Bluetooth, while others focus on just the code. This post will definitely be of the later variety.
Why this post if it is already thoroughly covered in other areas? Mostly because I recently ran across I project on which I needed BLE, had to really get my head around it, and now want to write it down in case I need it again. And, hey, maybe it will be valuable to others.

(1) Import

Unlike beacons, which use Core Location, if you are communicating to a BLE device, you will use CoreBluetooth.
import CoreBluetooth  

(2) Delegates

Eventually you are going to want to get callbacks from some functionality. There are two delegates to implement: CBCentralManagerDelegate, and CBPeripheralDelegate.
class ViewController:  
  UIViewController, 
  CBCentralManagerDelegate, 
  CBPeripheralDelegate {

  // Moar code

}

(3) Declare Manager and Peripheral

The CBCentralManager install will be what you use to find, connect, and manage BLE devices. Once you are connected, and are working with a specific service, the peripheral will help you iterate characteristics and interacting with them.
var manager:CBCentralManager!  
var peripheral:CBPeripheral!  

(4) UUID and Service Name

You will need UUID for the BLE service, and a UUID for the specific characteristic. In some cases, you will need additional UUIDs. They get used repeatedly throughout the code, so having constants for them will keep the code cleaner, and easier to maintain. There are also many service/characteristic pairs called out in the specification.
let BEAN_NAME = "Robu"  
let BEAN_SCRATCH_UUID =  
  CBUUID(string: "a495ff21-c5b1-4b44-b512-1370f02d74de")
let BEAN_SERVICE_UUID =  
  CBUUID(string: "a495ff20-c5b1-4b44-b512-1370f02d74de")

(5) Instantiate Manager

One-liner to create an instance of CBCentralManager. It takes the delegate as an argument, and options, which in most cases are not needed. This is also the jumping off point for what effectively becomes a chain of the remaining seven waterfall steps.
override func viewDidLoad() {  
  super.viewDidLoad()        
  manager = CBCentralManager(delegate: self, queue: nil)
}

(6) Scan for Devices

Once the CBCentralManager instance is finished creating, it will call centralManagerDidUpdateState on the delegate class. From there, if Bluetooth is available (as in "turned on"), you can start scanning for devices.
func centralManagerDidUpdateState(central: CBCentralManager) {  
  if central.state == CBCentralManagerState.PoweredOn {
    central.scanForPeripheralsWithServices(nil, options: nil)
  } else {
    print("Bluetooth not available.")
  }
}

(7) Connect to a Device

When you find the device you are interested in interacting with, you will want to connect to it. This is the only place where the device name shows up in the code, but I still like to declare it as a constant with the UUIDs.
func centralManager(  
  central: CBCentralManager, 
  didDiscoverPeripheral peripheral: CBPeripheral, 
  advertisementData: [String : AnyObject], 
  RSSI: NSNumber) {
  let device = (advertisementData as NSDictionary)
    .objectForKey(CBAdvertisementDataLocalNameKey) 
    as? NSString

  if device?.containsString(BEAN_NAME) == true {
    self.manager.stopScan()

    self.peripheral = peripheral
    self.peripheral.delegate = self

    manager.connectPeripheral(peripheral, options: nil)
  }
}

(8) Get Services

Once you are connected to a device, you can get a list of services on that device.
func centralManager(  
  central: CBCentralManager, 
  didConnectPeripheral peripheral: CBPeripheral) {
  peripheral.discoverServices(nil)
}

(9) Get Characteristics

Once you get a list of the services offered by the device, you will want to get a list of the characteristics. You can get crazy here, or limit listing of characteristics to just a specific service. If you go crazy watch for threading issues.
func peripheral(  
  peripheral: CBPeripheral, 
  didDiscoverServices error: NSError?) {
  for service in peripheral.services! {
    let thisService = service as CBService

    if service.UUID == BEAN_SERVICE_UUID {
      peripheral.discoverCharacteristics(
        nil, 
        forService: thisService
      )
    }
  }
}

(10) Setup Notifications

There are different ways to approach getting data from the BLE device. One approach would be to read changes incrementally. Another approach, the approach I used in my application, would be to have the BLE device notify you whenever a characteristic value has changed.
func peripheral(  
  peripheral: CBPeripheral, 
  didDiscoverCharacteristicsForService service: CBService, 
  error: NSError?) {
  for characteristic in service.characteristics! {
    let thisCharacteristic = characteristic as CBCharacteristic

    if thisCharacteristic.UUID == BEAN_SCRATCH_UUID {
      self.peripheral.setNotifyValue(
        true, 
        forCharacteristic: thisCharacteristic
      )
    }
  }
}

(11) Changes Are Coming

Any characteristic changes you have setup to receive notifications for will call this delegate method. You will want to be sure and filter them out to take the appropriate action for the specific change.
func peripheral(  
  peripheral: CBPeripheral, 
  didUpdateValueForCharacteristic characteristic: CBCharacteristic, 
  error: NSError?) {
  var count:UInt32 = 0;

  if characteristic.UUID == BEAN_SCRATCH_UUID {
    characteristic.value!.getBytes(&count, length: sizeof(UInt32))
    labelCount.text = 
      NSString(format: "%llu", count) as String
  }
}

(12) Disconnect and Try Again

This is an optional step, but hey, let us be good programmers and clean up after ourselves. Also a good place to start scanning all over again.
func centralManager(  
  central: CBCentralManager, 
  didDisconnectPeripheral peripheral: CBPeripheral, 
  error: NSError?) {
  central.scanForPeripheralsWithServices(nil, options: nil)
}

Next Steps

Yes, twelve, count them, twelve steps to working with BLE devices - and this is just a single service and single characteristic. What makes them particularly tricky is that they cascade. After step #5 the everything is one long chain. Watch your ... step (ha!).

2017年2月13日 星期一

iOS BLE 藍牙應用注意事項

- BLE 設置 參考
http://canoxcode.blogspot.tw/2016/01/ios-ble_18.html


-Zero to BLE
https://www.cloudcity.io/blog/2016/09/09/zero-to-ble-on-ios--part-two---swift-edition/

2017年2月10日 星期五

iOS BLE使用SWIFT#3

新增framework
https://dotblogs.com.tw/clark/2015/11/13/153918

[XCODE]ViewController基本應用 - 點選換畫面(ViewController > ViewController)

http://nigeljucodefarmercooltw.blogspot.tw/2015/06/xcodeviewcontroller-viewcontroller.html

swift不需要.m了,因此我們在VC.swift裡面新增

    @IBAction func close(segue:UIStoryboardSegue){
        
    }

就可以了


- 無法將table view controller與code關聯起來
要選到對應的storyboard區域才可以選對應的custom class(BLEScanTableViewCell)

- initializer for conditional binding must have optional type
發問至 stackoverflow 
http://stackoverflow.com/questions/42151095/initializer-for-conditional-binding-must-have-optional-type

guard類似於if 或者是exception

-Table view controller 參考官網教學
https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/CreateATableView.html

- Int to String
        let x : Int = member.rssi
        let myString = String(x)

http://www.cnblogs.com/lovecode/archive/2011/12/02/2272764.html
http://blog.changyy.org/2013/12/ios-terminating-app-due-to-uncaught.html

記得要在identify裡面輸入相對應的label
例如  let cellIdentifier = "BLEScanTableViewCell"

-模擬器視窗大小
command + 1~6


2017年2月6日 星期一

CC2541 低功耗運作電流參考

CC2541 CC2540 实现超低功耗是非常重要的:
我们来总结一下实现方法:

1,有定时器在跑时会一直跑在  PM2  电流在  300uA左右。
   没有定时器跑后会到 PM3 , 电流会少于10uA 。
   这个定时器是指 osal 的定时器,
例如:
   启动 了      
   osal_start_timerEx( keyfobapp_TaskID, KFD_TOGGLE_BUZZER_EVT, 2000 );
   但没到时间:
需要说明的是 keyfob 中的 低功耗一直都是进不去 PM3 的, 这是由于有一个查询电量的定时器一直在跑:
   osal_start_timerEx( keyfobapp_TaskID, KFD_BATTERY_CHECK_EVT, BATTERY_CHECK_PERIOD );
   把它注释掉 就会进 PM3 了。
   电流 小于 10uA 。
   因此, 如果你想低功耗到但是又想启用定时器是不现实的。
2, 如果有外部中断,比如开关量如按键, 一定,一定,一定需要用下降沿中断, 目前我上升沿中断调不出来, 并且,常态时如果是低电平输入, 会比较耗电。实测,低电平输入会比高电平输入多200uA 左右。
  
总结一下:
常态下是PM1  
要进入 PM2, 首先,确认你的option的编译宏设置了   POWER_SAVING
             然后代码中, 需要执行 osal_pwrmgr_device( PWRMGR_BATTERY );
             即可, 电流还有200uA 呀, 怎么办?
要进入 Pm3, 需要你没有 osal的定时器在跑。  
详见我们提供的例程。
附件例程上电就广播 30s, 电流 500uA,使用AmoBleTool.apk 连接后, 电流在小于10uA
此时,已经开通了3个电平中断, 分别是 P0.0, p0.1 与p0.4
任意一个中断产生, AmoBleTool.apk  都键收到 数据, 请注意观察。
  
电流测试方法为在供电电路上串一个电流表即可。


获取资料地址:

链接:http://pan.baidu.com/s/1pJ7IpQj 密码:cy6z


获取源码与简明教程:
阿莫单片机蓝牙开发板网店

來自
http://blog.csdn.net/mzy202/article/details/42091537

2017年1月16日 星期一

CC2541 與 BLE 名詞提示

http://gogoprivateryan.blogspot.tw/2014/09/cc2540-bluetooth-low-energy-3.html

Bluetooth 4.0 區分為 Basic Rate (BR) 與 Bluetooth Low Energy (BLE). BR 是我們過往認知的藍牙, BLE 則設計成每次傳送很小的封包資料, 相比 BR 裝置很省電, 適合用在穿戴裝置與物聯網. 能同時支援 BR 與 BLE 的裝置叫做雙模 (dual-mode), 例如智慧手機, 筆電等. 僅能支援 BLE 的則為單模 (single-mode).

BLE Protocol Stack architecture 長這樣..


Physical Layer, Link Layer 和 HCI 三層合稱做 Controller.


Physical Layer

實體層, 最底層.

Link Layer

主要處理底層網路連線狀態, 會有六種可能的狀態: 
  - Standby
  - Advertiser
  - Scanner
  - Initiator
  - Master
  - Slave 

Host/Controller Interface (HCI)

做上下層之間通信用途, 讓 Host 可以透過 UART, USB, SDIO 之類的標準介面和 Controller 溝通. 

GAP, GATT, SMP, ATT, L2CP 合稱做 Host.

Generic Access Profile (GAP)
負責連線相關的服務, 包括: 
  - Device Discovery (裝置搜尋)
  - Link Establishment/Management/Termination (連線 建立/維護/終止)
  - Initiation of security features

這邊定義了四種 profile roles (角色), 包括: 

  - Broadcaster (廣播者)
    只發送數據, 不能被連線的裝置. 例如溫度感測器.
  - Observer (觀察者)
    會接收數據, 但不會啟動連線的裝置. 例如溫度顯示面版.
  - Peripheral (週邊)
    會發送數據, 也能做為 slave 被連線的裝置. 例如智慧手錶. 
  - Central (中控)
    能接收數據, 也能做為 master 來啟動連線. 例如智慧手機.

然後, 一個裝置是可以同時具有不同 profile roles 的. 例如 

  - Peripheral (週邊) + Broadcaster (廣播者)
  - Peripheral (週邊) + Observer (觀察者)
  - Central (中控) + Broadcaster (廣播者)

另外, GAP 這邊還定義了三種裝置搜尋模式, 包括:

  - Non-discoverable Mode (不可被搜尋)
    裝置不會發送廣告封包出來.
  - Limited Discoverable Mode (有限度被搜尋)
    裝置會在一定時限內發送廣告封包, 若沒進一步發生什麼事的話, 就進入 standby 模式.
  - General Discoverable Mode (不限制)
    裝置會持續發送廣告封包.

Security Manager Protocol (SMP)
負責加密與認證. 這邊定義了裝置之間會有三種關係: 
  - Pairing
  - Authentication
  - Bonding

Logical Link Control and Adaptation Protocol (L2CAP)

萊恩大兵不知該怎麼形容這部份.

Attribute Protocol (ATT)

這邊有定義了 client/server 的角色與兩邊資料傳遞讀寫機制.

Generic Attribute Profile (GATT)
萊恩大兵也不知該怎麼形容這部份, 只知道這邊有個叫做 Characteristic 的, 會在稍後的程式碼裡面有用到. 

再來要說一下 TI 原廠的 BLE stack, 從官方的文件說明可以知道, 這 CC2540 是一顆整合了 8051 MCU, RF Transceiver, 8KB RAM 與 flash 的 SoC (System on chip). 官方有提供完整的 framework, 建議開發者儘量遵循 framework 的架構來做開發, 會比較少問題. 

一隻 CC2540 應用程式, 可分成五大模塊:

  - Operating System Abstraction layer (OSAL)
  - Hardwar Abstraction Layer (HAL)
  - KeyFobDemo Application, 例如, SimpleBLEPeripheral.
  - BLE Protocol Stack
  - Profiles: GAP Role, GAP Security 和 GATT Services

萊恩大兵對這些模塊的功能用途還模模糊糊的, 就不強作解釋了. 


值得一提的還有 training slides 的 agenda: 


  - CC2540 Hardware Overview

  - CC2540 BLE Software Architecture and Structure
  - SimpleBLEPeripheral Project / Framework for Custom Applications
  - GAP Role Profiles and Bond Manager
  - GATT Profiles and Services
  - CC2540DK-MINI Kit Overview

應該這些項目 (GAP Role Profiles, Bond Manager, GATT Profiles..) 就是未來在開發 BLE 程式時, 要重點關注的項目吧.


=-=-=-=- 分隔線 -=-=-=-=-=


找阿立聊一下才了解. 這研究會暫訂的走向, 是要把 SimpleBLECentral 放手機上執行, 來操控 SimpleBLEPeripheral 的裝置. 所以我們大家才需要深入了解 SimpleBLEPeripheral 的架構. 


來看 SimpleBLEPeripheral 的 code.


(1) 程式裡面會用 compiler settings 的 symbol 來開關某些功能




(2) 初始值
這邊可以設定裝置預設的 discoverable mode.

也可以更改裝置的名稱.




(3) Profile callbacks

這邊可以填入自訂的 function, 讓某些狀況發生時, 會自動呼叫該 function.

順道說一下, GAP Peripheral Role Profile 會處理 advertisements, scan requests, connections 與 connection parameters. 而 GAP Peripheral Bond Manager 則是去回應  pairing 或 bonding requests, 以及 security keys 的儲存與維護.


(4) Events
這邊以後會有機會自訂 event 來處理某些狀況.



(5) Characteristic

這 characteristic, 我們可以拿 LightBlue 去連接一個 SimpleBLEPeripheral 裝置, 然後直接寫值給它.

CC2541 耗電與省電

參考
http://www.itdadao.com/articles/c15a543513p0.html

实验结果

电阻状态\模式PowerMode 1PowerMode 2PowerMode 3
上拉254.2μA1.2μA0.4μA
下拉254.4μA1.2μA0.37μA
高阻601.3μA182.4μA398.9μA

实验结论

  • 在PIN脚没有外设的情况下,应该把PIN脚配置成确定的状态,非确定的状态(高阻状态)会带来高功耗的电流。
  • PIN脚有外设连接的情况下,需要根据实际的情况作出相应的配置,以达到最低功耗的效果。


完整概念, 參考:
https://takako042.wordpress.com/2008/09/11/%E9%9B%BB%E8%B7%AF%E5%B8%B8%E8%AD%98%E6%80%A7%E6%A6%82%E5%BF%B5%EF%BC%885%EF%BC%89-%E4%B8%8A%E6%8B%89%E9%9B%BB%E9%98%BB%E3%80%81%E4%B8%8B%E6%8B%89%E9%9B%BB%E9%98%BB-%E6%8B%89%E9%9B%BB%E6%B5%81/