Home > front end >  How to send Data via BLE using a for loop
How to send Data via BLE using a for loop

Time:10-10

I'm pretty new to BLE and I'm making an application that requires Data objects to be transferred via BLE in rapid succession. So far I've tried a for loop to change the characteristic based on the index. It successfully changes the characteristic for the first value but fails on the rest. I'm currently working on a POC which has the code which can be seen below.

guard let characteristic = self.transferCharacteristic else { return }

for x in "Hello there" {
    let data = Data("\(x)".data(using: .utf8)!)
    let didSend = self.peripheralManager.updateValue(data, for: characteristic, onSubscribedCentrals: nil)
    if didSend {
        print("Sent: \(x)")
    } else {
        print("Couldn't send: \(x)")
    }
}

The output of this is,

Sent: H
Couldn't send: e
Couldn't send: l
Couldn't send: l
.
.
.
Couldn't send: e
Couldn't send: r
Couldn't send: e

How can I achieve what I want to? Is there a better way?

I'm aware that transaction are a few milliseconds, but have no idea how I can sync the characteristic change with the transaction speed, IF POSSIBLE.

Thank you in advance.

CodePudding user response:

If you receive false for this call, you need to store the rest of your packets and wait until peripheralManagerIsReady(toUpdateSubscribers:) is called. Then you can queue additional changes until it returns false again. You cannot just do this in a loop without dealing with back pressure.

Depending on your use case, you may find it better to throw away intermediate packets until the manager is ready, or you may queue them, or you may return an error if there are too many dropped, or many other strategies. What back pressure strategy makes sense depends on your problem.

Don't forget that it's also possible for you to lose the connection at any time. BLE is a reliable transport, so you'll never get packets out of order, or skipped or corrupted packets, but that doesn't mean the packet will be delivered.

That said, this is a very inefficient way to send lots of data. Typically you should combine your packets into chunks (up to maximumUpdateValueLength) and send them in fewer writes. There's a lot of overhead in sending a packet. Being a reliable transport comes at significant cost.

  • Related