Skip to content

Commit

Permalink
Merge pull request #21371 from osmandapp/fix_obd_reconnect_review
Browse files Browse the repository at this point in the history
Fix obd reconnect review
  • Loading branch information
Chumva authored Nov 18, 2024
2 parents b429c35 + c13c53d commit ef0c8be
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 24 deletions.
8 changes: 5 additions & 3 deletions OsmAnd/src/net/osmand/plus/OsmandApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -724,9 +724,11 @@ public void onCarNavigationSessionStop(@NonNull NavigationSession carNavigationS

public void setCarNavigationSession(@Nullable NavigationSession carNavigationSession) {
this.carNavigationSession = carNavigationSession;
List<OsmandPlugin> enabledPlugins = PluginsHelper.getEnabledPlugins();
for (OsmandPlugin plugin: enabledPlugins) {
plugin.onCarNavigationSessionCreated();
if(carNavigationSession != null) {
List<OsmandPlugin> enabledPlugins = PluginsHelper.getEnabledPlugins();
for (OsmandPlugin plugin: enabledPlugins) {
plugin.onCarNavigationSessionCreated();
}
}
}

Expand Down
56 changes: 37 additions & 19 deletions OsmAnd/src/net/osmand/plus/plugins/odb/VehicleMetricsPlugin.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,21 +66,26 @@ import okio.sink
import okio.source
import org.json.JSONObject
import java.util.UUID
import kotlin.jvm.Throws

class VehicleMetricsPlugin(app: OsmandApplication) : OsmandPlugin(app), OBDReadStatusListener {
private var mapActivity: MapActivity? = null

private val handler = Handler(Looper.getMainLooper())
private val RECONNECT_DELAY = 5000L
private val RECONNECT_ATTEMPTS_COUNT = 10
private var currentReconnectAttempt = 0

private var connectionState = OBDConnectionState.DISCONNECTED

val USED_OBD_DEVICES =
registerStringPreference("used_obd_devices", "").makeGlobal().cache();
val LAST_CONNECTED_OBD_DEVICE =
registerStringPreference("last_connected_obd_device", "").makeGlobal().cache()

val TRIP_RECORDING_VEHICLE_METRICS : ListStringPreference =
registerListStringPreference("trip_recording_vehicle_metrics", null, ";").makeProfile().makeShared() as ListStringPreference
val TRIP_RECORDING_VEHICLE_METRICS: ListStringPreference =
registerListStringPreference("trip_recording_vehicle_metrics", null, ";").makeProfile()
.makeShared() as ListStringPreference

private val uuid =
UUID.fromString("00001101-0000-1000-8000-00805f9b34fb") // Standard UUID for SPP
Expand Down Expand Up @@ -260,7 +265,7 @@ class VehicleMetricsPlugin(app: OsmandApplication) : OsmandPlugin(app), OBDReadS

private val simulateOBDListener = StateChangedListener<Boolean> { enabled ->
if (!enabled) {
disconnect()
disconnect(true)
}
}

Expand Down Expand Up @@ -302,11 +307,13 @@ class VehicleMetricsPlugin(app: OsmandApplication) : OsmandPlugin(app), OBDReadS
}

@MainThread
fun disconnect() {
fun disconnect(forgetCurrentDeviceConnected: Boolean) {
obdDispatcher?.stopReading()
val lastConnectedDeviceInfo = connectedDeviceInfo
connectedDeviceInfo = null
setLastConnectedDevice(null)
if (forgetCurrentDeviceConnected) {
setLastConnectedDevice(null)
}
onDisconnected(lastConnectedDeviceInfo)
}

Expand Down Expand Up @@ -339,12 +346,23 @@ class VehicleMetricsPlugin(app: OsmandApplication) : OsmandPlugin(app), OBDReadS
}
}

@SuppressLint("MissingPermission")
@MainThread
fun connectToObd(activity: Activity, deviceInfo: BTDeviceInfo) {
currentReconnectAttempt = RECONNECT_ATTEMPTS_COUNT
connectToObdInternal(activity, deviceInfo)
}

@SuppressLint("MissingPermission")
@MainThread
private fun connectToObdInternal(activity: Activity, deviceInfo: BTDeviceInfo) {
if (connectionState != OBDConnectionState.DISCONNECTED) {
disconnect()
disconnect(false)
}
currentReconnectAttempt--
if (currentReconnectAttempt <= 0) {
return
}
LOG.debug("connectToObd $deviceInfo reconnectCount $currentReconnectAttempt")
if (BLEUtils.isBLEEnabled(activity)) {
if (AndroidUtils.hasBLEPermission(activity)) {
onConnecting(deviceInfo)
Expand Down Expand Up @@ -417,16 +435,13 @@ class VehicleMetricsPlugin(app: OsmandApplication) : OsmandPlugin(app), OBDReadS
socket = connectedDevice.createRfcommSocketToServiceRecord(uuid)
}

@Throws(IOException::class)
override fun connect(): Pair<Source, Sink>? {
try {
socket?.apply {
connect()
if (isConnected) {
return Pair(inputStream.source(), outputStream.sink())
}
socket?.apply {
connect()
if (isConnected) {
return Pair(inputStream.source(), outputStream.sink())
}
} catch (error: IOException) {
LOG.error("Can't connect to device. $error")
}
return null
}
Expand Down Expand Up @@ -499,16 +514,16 @@ class VehicleMetricsPlugin(app: OsmandApplication) : OsmandPlugin(app), OBDReadS
}

override fun onIOError() {
handler.post { disconnect() }
handler.removeCallbacksAndMessages(null)
handler.post { disconnect(false) }
handler.postDelayed({ reconnectObd() }, RECONNECT_DELAY)
}

private fun reconnectObd() {
mapActivity?.let {
val lastConnectedDevice = getLastConnectedDevice()
if (connectedDeviceInfo == null && lastConnectedDevice != null) {
connectToObd(it, lastConnectedDevice)
connectToObdInternal(it, lastConnectedDevice)
}
}
}
Expand Down Expand Up @@ -898,11 +913,13 @@ class VehicleMetricsPlugin(app: OsmandApplication) : OsmandPlugin(app), OBDReadS
override fun attachAdditionalInfoToRecordedTrack(location: Location, json: JSONObject) {
super.attachAdditionalInfoToRecordedTrack(location, json)
val mode = app.settings.applicationMode
val commandNames: List<String>? = TRIP_RECORDING_VEHICLE_METRICS.getStringsListForProfile(mode)
val commandNames: List<String>? =
TRIP_RECORDING_VEHICLE_METRICS.getStringsListForProfile(mode)
val selectedCommands: List<OBDCommand> = commandNames?.mapNotNull {
OBDCommand.getCommand(it)
} ?: emptyList()
if (!Algorithms.isEmpty(selectedCommands) && InAppPurchaseUtils.isVehicleMetricsAvailable(app)) {
if (!Algorithms.isEmpty(selectedCommands) && InAppPurchaseUtils.isVehicleMetricsAvailable(
app)) {
val rawData = obdDispatcher?.getRawData()
rawData?.let { data ->
for (command in data.keys) {
Expand All @@ -924,6 +941,7 @@ class VehicleMetricsPlugin(app: OsmandApplication) : OsmandPlugin(app), OBDReadS
super.onCarNavigationSessionCreated()
val activity = mapActivity
val lastConnectedDevice = getLastConnectedDevice()
LOG.debug("onCarNavigationSessionCreated $connectionState $lastConnectedDevice ${activity != null}")
if (connectionState == OBDConnectionState.DISCONNECTED && lastConnectedDevice != null && activity != null) {
connectToObd(activity, lastConnectedDevice)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ class OBDDevicesListFragment : OBDDevicesBaseFragment(),
}

override fun onDisconnect(device: BTDeviceInfo) {
vehicleMetricsPlugin.disconnect()
vehicleMetricsPlugin.disconnect(true)
}

override fun onConnect(device: BTDeviceInfo) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ class OBDMainFragment : OBDDevicesBaseFragment(), VehicleMetricsPlugin.Connectio
pairBtnTextColorId = connectedStateBtnTextColor
pairBtnTextId = R.string.external_device_details_disconnect
pairButton.setOnClickListener {
vehicleMetricsPlugin.disconnect()
vehicleMetricsPlugin.disconnect(true)
}
}

Expand Down

0 comments on commit ef0c8be

Please sign in to comment.