iosswiftbluetooth-lowenergycore-bluetoothobd-ii

Swift Core Bluetooth communication with OBD2


I'm trying to observe velocity of my car using an OBD2, to try if the hardware works i had use the app "Auto Doctor" and it works. But i need some more features and so i started to create my own application

To send 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 characteristic found

Independently which command i send to the characteristic i receive every time the same amount of byte and i can't decode it using utf8 or ascii.

I hope I have supply you enough information.


Solution

  • The answers from (almost all) OBD2 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, 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 OBD2 library that does all the heavy lifting for you. As a matter of fact, I wrote one, which you can download at https://github.com/mickeyl/LTSupportAutomotive.

    Update: And since then I rewrote something similar in Swift, which might be even more interesting for you. Please have a look at https://github.com/Cornucopia-Swift/CornucopiaUDS