I am working on arduino project which involves it sending/receiving data from the iPhone to to an arduino through a BLE board. I am struggling with receiving data from the arduino back to the iPhone.
I have this function:
func readPosition() -> NSString? {
if self.positionCharacteristic == nil {
return nil
}
self.peripheral?.readValue(for: self.positionCharacteristic!)
if ((self.positionCharacteristic?.value) != nil) {
return NSString(data: self.positionCharacteristic!.value!, encoding:
String.Encoding.utf8.rawValue) }
return nil
}
My problem with it is that I don't understand how to use it in a way that it will immediately read and use what was sent from the arduino. How would I code my project to accomplish this? I need to receive constant data from a sensor that is attached to the arduino
The receiving UUID if needed:
let PositionCharUUID = CBUUID(string: "A9CD2F86-8661-4EB1-B132-367A3434BC90")
It is likely (but you need to check) that your characteristic supports Notify operations. In this case you can use
self.peripheral.setNotifyValue(true, for: self.positionCharacteristic)
You will then get a call to your peripheral delegate's didUpdateValue:for: method
Related
I am developing an iOS app using BLE, I have the BLE comms working but I do not seem to receive any data. The plan is to use multiple BLE UUID characteristics to send data from our ECU to the iOS mobile app. I know the BLE ECU is working as I have checked it with a BLE scanner.
I have followed this example, but still cannot get the BLE read to work correctly. Oddly if read the bytes back one by one I get the required data, but I cannot seem to find a solution to read the complete string in one go? I could use a loop to read all the data back, but surely there must be a way to read back the BLE receive buffer in one go?
https://www.freecodecamp.org/news/ultimate-how-to-bluetooth-swift-with-hardware-in-20-minutes/
Any help would be highly appreciated.
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
var characteristicASCIIValue = NSString()
guard characteristic == rxCharacteristic,
let characteristicValue = characteristic.value,
let ASCIIstring = NSString(data: characteristicValue, encoding: String.Encoding.utf8.rawValue) else { return }
print("Value Recieved: \((characteristicASCIIValue as String))")
if(characteristic.uuid.isEqual(CBUUIDs.ECU_UUID_A)
{
print ("Found ECU_UUID_A")
Extract_ECU_UUID_A(ASCIIstring)
}
else if(characteristic.uuid.isEqual(CBUUIDs.ECU_UUID_B)
{
print ("Found ECU_UUID_B")
Extract_ECU_UUID_B(ASCIIstring)
}
}
I'm developing and app for iOS which needs to connect to a Bluetooth Device. I've been able to find and connect to devices near me using CoreBluetooth and GATT profile. The writing and reading of characteristics worked as well. These values will eventually be written when a slider is moved. However, now I also need to be able to stream audio to the Bluetooth Device.
When I looked around for streaming audio over bluetooth I noticed this could be done with AVFoundation by allowing output over bluetooth. However, then the device has to use A2DP profile. But this causes the app to be unable to read/write characteristics?
I got this piece of code to read, notify and write to specific characteristics.
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService,
error: Error?) {
guard let characteristics = service.characteristics else { return }
for characteristic in characteristics {
print(characteristic)
if characteristic.properties.contains(.read) {
print("\(characteristic.uuid): properties contains .read")
if characteristic.uuid == batteryLevelCharacteristicCBUUID { peripheral.readValue(for: characteristic) }
}
if characteristic.properties.contains(.notify) {
print("\(characteristic.uuid): properties contains .notify")
if characteristic.uuid == batteryLevelCharacteristicCBUUID {
peripheral.setNotifyValue(true, for: characteristic)
}
}
if characteristic.properties.contains(.write) {
print("\(characteristic.uuid): properties contains .write")
if characteristic.uuid == writeTestCharacteristicCBUUID {
print("Writing characteristic found! Trying to write now.")
let string = "Hello World!"
let data = string.data(using: .utf8)!
peripheral.writeValue(data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
}
}
}
}
This question seems similar but it is mentioned that it's not possible. Is possible send hexadecimal data to A2DP Bluetooth Device in swift?
However, I was thinking. If you look at a headset for example when you press buttons there has to be some data transfer. Can this somehow be used for what I want to do? But I can't seem to find any information about these signals or how to use those in my code.
So what I want is to be able to stream the audio and also send small values like percentages.
If you know any information that might help me please let me know. Thanks in advance!
I am writing an app that needs to write a byte value to a CBPeripheral using iOS CoreBluetooth. I am able to read values, and the write is successful and triggers the didWriteValueFor delegate like it should. Basically, it does work, BUT, it takes a long time (about 3 seconds and reports of over 10). When I test the write process in another app (nRF Connect), the write is almost instantaneous. Here's the code I am using to write to the Characteristic:
func setConfigurationValue(_ i:UInt8){
guard peripheral != nil, configurationStateCharacteristic != nil else { return }
var vint:UInt8 = i
let intData = Data(bytes: &vint, count: MemoryLayout<UInt8>.size)
isWriting = true
peripheral?.writeValue(intData, for: configurationStateCharacteristic!, type: CBCharacteristicWriteType.withResponse)
// Notify any views that they should show a progress overlay
NotificationName.showProgressOverlay.post(userInfo: ["message":"Device configuring".localized], object: self)
}
Note, that peripheral is a stored reference to the CBPeripheral object, and configurationStateCharacteristic is a reference to the CBCharacteristic I am writing to. This code does work, but what is causing the peripheral BLE device to take so long in writing the data and sending a response?
Any ideas?
I have connected to two iPhones and found the services and characteristics in it. I am facing problems in sending write requests from central and receiving response from peripheral. I have written the code below to write data in central and received data in Peripheral. But the function didReceiveWriteRequests didn't execute. I don't know Why didn't work.
In central view write, the data code:
func writeValue(data:NSData){
if let discoveredPeripheral = discoveredPeripheral{
if let deviceCharacteristics = deviceCharacteristics{
discoveredPeripheral.writeValue(data, forCharacteristic: deviceCharacteristics, type: CBCharacteristicWriteType.WithResponse)
}
}
}
and in peripheral view, the receive code:
func peripheralManager(peripheral: CBPeripheralManager!, didReceiveWriteRequests requests: [AnyObject]!) {
println("didReceiveWriteRequests")
println("\(requests.count)")
}
Does anybody know how to receive messages through uBudu Mesh Network?
I'm working on an app using uBudu beacons and the general idea is to allow users to send messages to each other through these beacons. I've successfully hooked up iOS-Mesh-SDK as described here: https://github.com/Ubudu/IOS-Mesh-SDK.
There is an example of how to send mesh message to another beacon and it works perfectly, but as for retrieving these messages from beacon to user app I have no idea.
There are methods in MeshBeacon class:
- (void)abortMeshMessage;
- (void)clearMeshMessageQueue;
- (void)setMeshNotification:(BOOL)enable withCompletionBlock:(UMeshBeaconSuccessBlock)completionBlock;
but nothing about retrieving the message.
Any suggestions are highly appreciated!
As you correctly pointed out, the SDK doesn't yet have the method for receiving messages but there is an update of the library coming with support of this feature.
I found maybe brute, but working solution for this problem.
First we need to set ourselves as delegate of BeaconManager
UBUMeshBeaconManager.sharedInstance().delegate = self
In implementation of delegate method, connect to closest beacon and reset its peripheral delegate to self.
func meshManager(meshManager: UBUMeshBeaconManager!, didUpdateVisibleAndConnectableNodes meshNodes: [AnyObject]!) {
UBUMeshBeaconManager.sharedInstance().connectToClosestBeacon({ (meshManager, meshBeacon, userInfo) -> Void in
meshBeacon.peripheral.delegate = self
}, progressBlock: { (meshManager, userInfo) -> Void in
}, failedBlock: { (meshManager, meshBeacon, userInfo, error) -> Void in
})
}
And waiting for characteristics updates in Peripheral Delegate method. All services and characteristics will be set behind the scene by UbuduSDK.
func peripheral(peripheral: CBPeripheral!,
didUpdateValueForCharacteristic characteristic: CBCharacteristic!,
error: NSError!) {
var string = NSString(data: characteristic.value, encoding: NSASCIIStringEncoding)
println(string)
}