TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Problem trying to iterate CoreBluetooth write/read requests to OBD-II BLE adapter

Forums > Swift

Hello! I am new to Swift and I'm working on my senior project for my CS degree coursework.

I am trying to continually iterate through my write/read requests to get live data from the OBD-II bus on my vehicle. I am using CoreBluetooth in Swift to connect and communicate with my OBD-II BLE adapter.

My goal is to constantly update the live data for 4 different sensors while the user is in the LiveDataView() and then stop asking if they leave the view, or the app is set to background/is closed.

I tried a timer. This appears to work, but seems janky. I noticed that as I repetitively ask for PID "0105" (Engine Coolant Temperature), everything seemed to work in the debug console.. but it wasn't actually updating my engine coolant temp in the LiveDataView().

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    for characteristic in service.characteristics ?? [] {
        if (String(describing: characteristic.uuid)) == "BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F" {
            obdSensorCharacteristic = characteristic
            peripheral.setNotifyValue(true, for: characteristic)
            print("Found \(characteristic), waiting on values:")
            print("Characteristic Value: \(String(describing: characteristic.value))")

            if stopData {
                Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
                    self.requestData()

                    if self.stopData == false {
                        timer.invalidate()
                    }
                })
            }
        }
    }
}

func requestData() {
    if ((obdSensorPeripheral?.canSendWriteWithoutResponse) != nil && sendData) {

        if sendData {
            self.write(value: commands[0], characteristic: self.obdSensorCharacteristic!)
            self.read(characteristic: self.obdSensorCharacteristic!)

        }
    }
}

Is there a better way to continually write/read information from the OBD-II BLE device? Is there a better way to control write/reads to the peripheral characteristic?

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.