NordicSemiconductor / IOS-CoreBluetooth-Mock

Mocking library for CoreBluetooth framework.
BSD 3-Clause "New" or "Revised" License
225 stars 51 forks source link

allow advertising data to be dynamically changed #73

Closed kscheff closed 2 years ago

kscheff commented 2 years ago

Many peripherals use advertising broadcast data with the CBMAdvertisementDataManufacturerDataKey key. This modifications allows to dynamically set new advertising data via e.g. a Timer()

Here is some excerpts form my code with dynamic advertising

private class MockDeviceCBMPeripheralSpecDelegate: CBMPeripheralSpecDelegate {
...
    var timer: Timer!

    init() {
      setup()
    }

    func setup() {
      timer = { Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(simulateDevice), userInfo: nil, repeats: true) }()
    }

    func reset() {
      setup()
    }
...
@objc
func simulateDevice() {
    let mnf = [CBMAdvertisementDataManufacturerDataKey : [
      u,
      iSolar,
      UInt32(_solCharge_Ah * 1_000),
      Int32(_solEnergy_Wh * 1_000),
      Int16(iBatt/8),
      UInt8(battSoc/10)].data()
    ] as [String : Any]
    let adv = advertising.merging(mnf) { (_,new) in new }
    mockDevice.advertisementData = adv
  }
let advertising: [String: Any] = [
  CBMAdvertisementDataLocalNameKey    : "Mock Device",
  CBMAdvertisementDataServiceUUIDsKey : [CBMUUID.mockService],
  CBMAdvertisementDataIsConnectable   : true as NSNumber,
  CBMAdvertisementDataManufacturerDataKey: Data([0,0,0,0,0,0,0,0,0,0,0,0,0,0,66])
]

let mockDevice = CBMPeripheralSpec
  .simulatePeripheral(proximity: .immediate)
    .advertising(
        advertisementData: advertising,
        withInterval: 0.250,
        alsoWhenConnected: true)
    .connectable(
        name: "Mock Device",
        services: [.devInfoService, .commsService, .mockService],
        delegate: MockDeviceCBMPeripheralSpecDelegate(),
        connectionInterval: 0.150,
        mtu: 251)
    .build()
CLAassistant commented 2 years ago

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


Kai Scheffer seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.