0

I tried send my struct parameters to remote device with swift CoreBluetooth library but I stack into copy struct parameters to array. Actually did the same thing in Windows application in c# but swift syntax and code style is very different and I couldn't make it.

You can find My code below

struct Test_Struct {
    var value1 : UInt32
    var value2 : UInt32
    var value3 : UInt8

}

    var data : [Test_Struct]=[]

    data.append(Test_Struct(value1: 1000, value2: 2000, value3: 02))

I also tried something like below

    var data = Test_Struct.init(value1: <UInt32>, value2: <UInt32>, value3: <UInt8>)

    data.value1 = 1000
    data.value2 = 1000
    data.value3 = 1000

both code give me no error but when I tried to add "my var" to peripheral.writeValue(data, for: myChractaristic, type: CBCharacteristicWriteType.withoutResponse) I get an error. I also tried to add "var data" to Data or NSData but never worked for me.

For the summarize I need copy to struct some array like Byte[] array=data_struct and I send array value with BLE write value command.

Thanks in Advance.

1 Answers1

0

You need to convert your structure to data. You a few options: Make your structure Codable and encode your Data using JSONEncoder() or even better create your own encoding method to make sure you send your data with the minimum bytes required:

struct TestStruct {
    let value1: UInt32
    let value2: UInt32
    let value3: UInt8
}

To convert your numeric properties to data check this:

extension Numeric {
    var data: Data {
        var source = self
        return Data(bytes: &source, count: MemoryLayout<Self>.size)
    }
}
extension TestStruct {
    var data: Data {
        return value1.data + value2.data + value3.data
    }
}

To initialise your struct from the data you can check this answer for reference:

extension TestStruct {
    init(data: Data) {
        value1 = data[0...3].withUnsafeBytes { $0.pointee }
        value2 = data[4...7].withUnsafeBytes { $0.pointee }
        value3 = data[8...8].withUnsafeBytes { $0.pointee }
    }
}

let test = TestStruct(value1: 10, value2: 20, value3: 30)

let data = test.data
print(data)            // "9 bytes\n"
print(data as NSData)  // "<0a000000 14000000 1e>\n"

let objectFromData = TestStruct(data: data)

print(objectFromData.value1) // 10
print(objectFromData.value2) // 20
print(objectFromData.value3) // 30
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571