iosswiftbluetooth-lowenergycore-bluetoothobd-ii

Swift Core Bluetooth communication with OBD-II


I'm trying to observe the velocity of my car using an OBD-II device. To try if the hardware works, I had use the app "Auto Doctor", and it works.

But I needed some more features, and so I started to create my own application.

To send a command to the characteristic, I use the following code:

var commandSended = String() {
    didSet {
        if let peripheral = self.peripheralConnected {
            for char in characteristicConnected {
                peripheral.writeValue(self.commandSended.data(using: .utf8)!, for: char, type: .withoutResponse)
                peripheral.writeValue(self.commandSended.data(using: .ascii)!, for: char, type: .withoutResponse)
                peripheral.readValue(for: char)
            }
        } else {
            self.myTerminal.printToTerminalCommand("You are not connected to the peripheral")
        }
    }
}

characteristicConnected: are all the characteristics found

Independently of which command I send to the characteristic, I receive the same amount of bytes every time, and I can't decode it using UTF-8 or ASCII.


Solution

  • The answers from (almost all) OBD-II adapters are ASCII string responses, so you need to decode the NSData into ASCII. To extract the actual payload for your responses, you need to learn about decoding the various car protocols. A lot of this information is freely available on the web, and for some things you might want to buy the official SAE standards.

    That said, even though you are using Swift, you might be interested in using an OBD-II library that does all the heavy lifting for you. As a matter of fact, I wrote one, which you can download at LTSupportAutomotive.

    P.S. Since then I rewrote something much more comprehensive in Swift, but it's not open source, so I can't link from here.