iOS Bluetooth Performing Write Long - ios

I'm working on a project with an iPhone connecting to an ESP32 using BLE. I'm trying to write a 528 byte long blob to a characteristic. Since the blob is longer than the max 512 allowed per write I'm trying to do a Write Long.
I'ved tried a couple things
1 - If I just try to write the blob I see the first chunk go through with Prepare Write set but there are no subsequent writes.
Why is it stopping after the first chunk?
2 - If I try to chuck it manually based on the size returned from maximumWriteValueLengthForType I see all the data is sent correctly but Prepare Write is not set so they aren't handled correctly.
How do I specify Prepare Write / Execute Write requests?
Here's a code snippet covering the implementation #2
NSData *blob = [request value];
NSUInteger localLength = 0;
NSUInteger totalLength = [blob length];
NSUInteger chunkSize = [peripheral maximumWriteValueLengthForType:type];
uint8_t localBytes[chunkSize];
NSData *localData;
do
{
if(totalLength > chunkSize) {
NSLog(#"BIGGER THAN CHUNK!!!!!!!!!!!!!!!!!!!!!");
NSLog(#"%tu", chunkSize);
for ( int i = 0; i < chunkSize; i++) {
localBytes[i] = ((uint8_t *)blob.bytes)[localLength + i];
}
localData = [NSMutableData dataWithBytes:localBytes length:chunkSize];
totalLength -= chunkSize;
localLength += chunkSize;
}
else {
NSLog(#"Smaller than chunk");
uint8_t lastBytes[totalLength];
for (int i = 0 ; i < totalLength; i++) {
lastBytes[i] = ((uint8_t *)blob.bytes)[localLength + i];
}
localData = [NSMutableData dataWithBytes:lastBytes length:totalLength];
totalLength = 0;
}
// Write to characteristic
[peripheral writeValue: localData forCharacteristic:characteristic type:type];
} while( totalLength > 0);

Long writes are affected by the same limit of 512 bytes maximum for the characteristic value. Long writes are only useful when MTU is too short to write the full value in one packet. Maybe you're trying to write out of this allowed range or something.
Newer iOS versions communicating with BLE 5 devices use a large enough MTU to fit a characteristic value of 512 in one packet (if the remote device also supports such a big MTU).
If you want to write bigger values than 512 bytes, you will need to split it up into multiple writes, so that the second write "overwrites" the first value sent, rather than appending to it. You can also use L2CAP CoC instead which eliminates this arbitrary 512 byte limit.

You have the right general approach but you can't just send the chunks sequentially. There is a limited buffer for sending Bluetooth data and your loop will write data into that buffer more quickly than the Bluetooth hardware can send it.
The exact approach you need to take depends on whether your characteristic supports write with response or write without response.
If your characteristic uses write with response, you should send a chunk and then wait until you get a call to the didWriteValueFor delegate method. You can then write the next chunk. The advantage of this approach is essentially guaranteed delivery of the data. The disadvantage is it is relatively slow.
If your characteristic uses write without response then you call write repeatedly until you get a call to didWriteValueFor with an error. At this point you have to wait until you get a call to peripheralIsReady. At this point you can start writing again, beginning with the last failed write.
With this approach there is the potential for lost data, but it is faster.
If you have to move large amounts of data, an L2Cap stream might be better, but you need to handle data framing.

Related

midi packet list dose not change timestamp

i have this code from here(Using MIDIPacketList in swift) but i can't pm the user or comment on that question, so i will ask my question.
#ephemer dude if you see my question, i love your code on midi list and it work so well, but when i change the time stamp, nothing happens, it must create some delay but it will be the same as 0 time stamp.
do anyone know how to fix this?
and how i can have the time stamp out of this extension to have that in midi event, i want to be able to change time stamp for every midi event,
to have it here:
var packets = MIDIPacketList(midiEvents: [[0x90, 60, 100]])
public typealias MidiEvent = [UInt8]
extension MIDIPacketList {
init(midiEvents: [MidiEvent]) {
let timestamp = MIDITimeStamp(0) // do it now
let totalBytesInAllEvents = midiEvents.reduce(0) { total, event in
return total + event.count
}
// Without this, we'd run out of space for the last few MidiEvents
let listSize = MemoryLayout<MIDIPacketList>.size + totalBytesInAllEvents
// CoreMIDI supports up to 65536 bytes, but in practical tests it seems
// certain devices accept much less than that at a time. Unless you're
// turning on / off ALL notes at once, 256 bytes should be plenty.
assert(totalBytesInAllEvents < 256,
"The packet list was too long! Split your data into multiple lists.")
// Allocate space for a certain number of bytes
let byteBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: listSize)
// Use that space for our MIDIPacketList
self = byteBuffer.withMemoryRebound(to: MIDIPacketList.self, capacity: 1) { packetList -> MIDIPacketList in
var packet = MIDIPacketListInit(packetList)
midiEvents.forEach { event in
packet = MIDIPacketListAdd(packetList, listSize, packet, timestamp, event.count, event)
}
return packetList.pointee
}
byteBuffer.deallocate() // release the manually managed memory
}
}
// to send use this
var packets = MIDIPacketList(midiEvents: [[0x90, 60, 100]])
MIDISend(clientOutputPort, destination, &packetList)
i figure it out, how it should work, but not quite right.
according to apple documentation, it must use mach_absolute_time() .
so i used that but i don't know how to work properly with mach_absolute_time().if anyone knows please tell me too.
if i use var timestamp = mach_absolute_time()+1000000000 it will delay like 1 min or so.if i change the 1000000000 with any number lower than this ,will not make a delay.
do anyone know how to work with mach_absolute_time()?
i saw some code on mach_absolute_time() but they use that as timer, it is acutely a timer that give time from the fist boot ,but how to give a time as a mach_absolute_time() to work with midi timestamp.
I found the answer.
set the timestamp to :
var delay = 0.2
var timestamp: MIDITimeStamp = mach_absolute_time() + MIDITimeStamp(delay * 1_000_000_000)
the delay is the time you want the midi message age to have delay.

Sending few values at the same time over bluetooth

I am working on a Bluetooth based application and I am having problems when I try to send data from the iPhone to the other device.
I have no problem when I have to send just one value, using something like this:
- (void)sendData:(NSInteger)mel {
NSData *myData = [NSData dataWithBytes:&mel length:sizeof(mel)];
[self.myDevice writeValue:myData forCharacteristic:self.myCharacteristic type:CBCharacteristicWriteWithoutResponse];
}
But, for some characteristics I need send 2 or more values at the same time (for example in this case, variable mel and another one) but I haven’t been able yet to do it.
Does somebody know how to do this? Thanks in advance.
UPDATE 1
What I tried to send two values is
unsigned char bytes[] = {mel, interval};
NSMutableData *myData = [NSMutableData new];
[myData appendBytes:&bytes length:sizeof(bytes)];
[self.myDevice writeValue:myData forCharacteristic:self.myCharacteristic type:CBCharacteristicWriteWithoutResponse];
But this works like if the second value didn't exist
You can't use sizeof(bytes) to get the number of bytes in the array. It's simply going to return 4 since that is the size of a char *.
One options would be to use sizeof(mel) + sizeof(interval) instead of sizeof(bytes).

Best way to read Beacon Manufacture Data in iOS

I am trying to Read Beacon(BLE Device) manufacture Data which is in below image
And I am getting response as,
and my code is,
id manufactureData = [advertisementData objectOrNilForKey:#"kCBAdvDataManufacturerData"];
if ([manufactureData isKindOfClass:[NSData class]]) {
int8_t measuredPower = 0;
NSUInteger dataLength = [manufactureData length];
for (int i = 0; i < dataLength; i++) {
NSRange powerRange = NSMakeRange(i, 1);
[manufactureData getBytes:&measuredPower range:powerRange];
NSLog(#"index :%# info :%hhd", [NSString stringWithFormat:#"%d", i+1],measuredPower);
}
}
Is this is correct way to read the manufacture data, Here i am trying to read Battery Address value. which i have to show.
This is a correct way of reading through the returned NSData.
Given this, your information is returning 32 for battery value, does that seem correct?
If not, can you find out if your manufacturer device is little endian or big endian? Link to explanation here if you do not know what that means.
The short version of the endianness question is if your info is coming from a big endian processor then your NSData will be backwards. making your battery value 77
One quick note: This does not sound like an iBeacon implementation. iBeacons are NOT the same as BLE enabled devices. This is most likely a BLE enabled device and not an iBeacon.

Extract and Convert NSData from BLE to Float in Swift

I'm developing an IOS App that handles a BlueTooth SensorTag.
That SensorTag is based on the TI BLE SensorTag, but we had some of the Sensors removed.
In the sourcecode of the original IOS App from TI the XYZ-Values are calculated like follows
with KXTJ9_RANGE defined as 1.0 in my implementation and KXTJ9 is the Accelerometer built on the SensorTag
+(float) calcXValue:(NSData *)data {
char scratchVal[data.length];
[data getBytes:&scratchVal length:3];
return ((scratchVal[0] * 1.0) / (64 / KXTJ9_RANGE));
}
The data comes as hexadecimal like "fe850d" and by the method will be cut in 3 parts.
Now i'm trying to convert this method to swift, but i get the wrong numbers back
e.g. fe should return something around 0.02 what the objective C Code does
My Swift Code so far
class Sensor: NSObject {
let Range: Float = 1.0
var data: NSData
var bytes: [Byte] = [0x00, 0x00, 0x00]
init(data: NSData) {
self.data = data
data.getBytes(&bytes, length: data.length)
}
func calcXValue()->Float {
return ((Float(bytes[0]) * 1.0) / (64.0 / Range))
}
...
}
I believe problem must lie around my Float(bytes[0]) because that makes 254 out of fe whereas scratchVal[0] in ObjectiveC is around 64
But my main problem is, i was all new with IOS programming when i had to begin with this project, so i chose to use Swift to learn and code the app with it.
Right now i use the original Objective C Code from TI to use with our SensorTag, but i would prefer using Swift for every part in the App.
On all current iOS and OS X platforms, char is a signed quantity,
so that the input fe is treated as a negative number.
Byte on the other hand is an alias for UInt8 which is unsigned.
Use [Int8] array instead to get the same behaviour as in your Objective-C code.
it depends on the BLE device Endianness, in relation to your device Endianness.
wiki on Endianness
To keep it simple you need to check which does two method
NSData *data4 = [completeData subdataWithRange:NSMakeRange(0, 4)];
int value = CFSwapInt32BigToHost(*(int*)([data4 bytes]));
or
NSData *data4 = [completeData subdataWithRange:NSMakeRange(0, 4)];
int value = CFSwapInt32LittleToHost(*(int*)([data4 bytes]));
And check which one make more sense when you parse the data.

Saving a very simple MusicSequence into MIDI doesn't reproduce sound

I'm trying to save a very basic one note MusicSequence (MusicSequence Reference) into a MIDI file. The file is being written right now and the duration of the note also (if I put duration 4 then the MIDI file lasts 2 secs, if I change it to 2 then it lasts 1 sec as it should) but there's no sound being reproduced and if I look at the MIDI file in Logic there's no information neither. Seems like the note duration gets written but the note's note isn't.
What could be happening?
+ (MusicSequence)getSequence
{
MusicSequence mySequence;
MusicTrack myTrack;
NewMusicSequence(&mySequence);
MusicSequenceNewTrack(mySequence, &myTrack);
MIDINoteMessage noteMessage;
MusicTimeStamp timestamp = 0;
noteMessage.channel = 0;
noteMessage.note = 4;
noteMessage.velocity = 90;
noteMessage.releaseVelocity = 0;
noteMessage.duration = 4;
if (MusicTrackNewMIDINoteEvent(myTrack, timestamp, &noteMessage) != noErr) NSLog(#"ERROR creating the note");
else NSLog(#"Note added");
return mySequence;
}
Try writing a note that is > 20 and < 109 (midi note range). While 4 may be technically valid, it is outside the range of normal midi notes.
Also, a useful function working with Core Audio/MusicPlayer etc. is CAShow() - so try CAShow(sequence) to view the sequence data.

Resources