transistorsoft / cordova-background-geolocation-lt

The most sophisticated background location-tracking & geofencing module with battery-conscious motion-detection intelligence for iOS and Android.
http://www.transistorsoft.com/shop/products/cordova-background-geolocation
Other
655 stars 277 forks source link

Runaway http Updates #1354

Closed TARJr closed 1 month ago

TARJr commented 1 year ago

Your Environment

type TProviderStatus = 'on' | 'off' | null;

type TProviderState = { status: TProviderStatus, changeEvent: ProviderChangeEvent, phoneMac: string, };

@Injectable() export class BackgroundGeolocationProvider { public $providerState: ReplaySubject<TProviderState | null> = new ReplaySubject(1); public $providerChanged: Subject = new Subject(); private _providerState: TProviderState | null; private phoneMac: string;

private set providerState(value: Partial<TProviderState> | null) {
    this._providerState = {
        ...this._providerState,
        ...value,
    };

    this.$providerState.next(this._providerState);
}

get hasBEAccess() {
    return;
}

constructor(
    private utilsProvider: UtilsService,
    private platform: Platform,
    private toastCtrl: ToastController,
    private logger: Logger,
    private settingsProvider: Settings,
) {
    if (!this.platform.is('cordova')) {
        console.log('skip BackgroundGeolocation');

        return;
    }

    this.utilsProvider.phoneMac().then((mac) => {
        this.phoneMac = mac;

        if (!BackgroundGeolocation || !mac) return;

        BackgroundGeolocation.onActivityChange((event) => {
            console.error('[onActivityChange] ', event);
        });

        BackgroundGeolocation.onMotionChange((event) => {
            if (event.isMoving) {
                console.error('[onMotionChange] Device has just started MOVING ', event.location);
                this.logger.info(`BackgroundGeolocationProvider:: MOVING`);
                BackgroundGeolocation.getCurrentPosition({
                    samples: 1,
                    persist: true
                }).then((location) => {
                    console.log('[getCurrentPosition] ', location);
                });

            } else {
               console.log('[onMotionChange] Device has just STOPPED:  ', event.location);
            }
        });

        const subscription = BackgroundGeolocation.onHeartbeat((event) => {
            console.log('[onHeartbeat] ', event);
        });

        BackgroundGeolocation.onProviderChange(async (event) => {
            this.$providerChanged.next(event);

            try {
                const state = await BackgroundGeolocation.getState();
                const status = this.getStatus(state.enabled, event);

                this.providerState = {
                    status,
                    changeEvent: event,
                    phoneMac: this.phoneMac,
                };
            } catch (error) {
                this.settingsProvider.updateSettings({
                    trackThisPhone: false
                });

                this.providerState = {
                    status: null,
                    changeEvent: event,
                    phoneMac: this.phoneMac,
                }
            }
        });

        BackgroundGeolocation.ready({
            reset: true,
            debug: false,
            locationAuthorizationRequest: 'Always',
            backgroundPermissionRationale: {
                title: "Allow access to this device's location in the background?",
                message: "Please enable 'Allow all the time permission",
                positiveAction: "Change to Allow all the time"
            },
            /* iOS only */
            locationAuthorizationAlert: {
                titleWhenNotEnabled: 'Yo, location-services not enabled',
                titleWhenOff: 'Location-services are OFF',
                instructions: "You must enable 'Always' in location-services",
                cancelButton: 'Cancel',
                settingsButton: 'Settings'
            },
            stationaryRadius: 50,
            /* Common */
            logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
            desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
            distanceFilter: this.platform.is('ios') ? 300 : 0,
            desiredOdometerAccuracy: 10,
            /* android only */
            foregroundService: true,
            locationUpdateInterval: 15 * 1000,
            fastestLocationUpdateInterval: 120000,
            allowIdenticalLocations: false,
            /* **** */
            stopOnTerminate: false,
            startOnBoot: true,
            url: `${API_INFO.DEVICE_API}/v1/devices/tracks`,
            method: 'PUT',
            autoSync: true,
            httpRootProperty: 'PHS_LOCATION'
        });
    });
}

public sendLogs() {
    console.log('sending log');
    const Logger = BackgroundGeolocation.logger;
    Logger.emailLog('support@email.com').then((success) => {
        this.logger.info(`[emailLog] SUCCESS`);
      }).catch((error) => {
        this.logger.info(`[emailLog] FAILURE: ${error}`);
      });

}

public start() {
    BackgroundGeolocation.getState((state) => {
        this.logger.info(`BackgroundGeolocationProvider::start: enabled? ${state.enabled}`);
        this.providerState = {
            status: this.getStatus(state.enabled, get(this._providerState, 'changeEvent', false)),
            phoneMac: this.phoneMac
        };

        if (!state.enabled) {
            BackgroundGeolocation.start(() => {
                console.log(`BackgroundGeolocationProvider::start: OK`);

                this.providerState = {
                    status: this.getStatus(true, get(this._providerState, 'changeEvent', false)),
                    phoneMac: this.phoneMac
                };

            }, (err) => {
                this.logger.error(`BackgroundGeolocationProvider::start: error ${err}`);
            });
        }
    });
}

public stop() {
    BackgroundGeolocation.getState((state) => {
        this.logger.info(`BackgroundGeolocationProvider::stop: enabled? ${state.enabled}`);
        this.providerState = {
            status: this.getStatus(state.enabled, get(this._providerState, 'changeEvent', false)),
            phoneMac: this.phoneMac
        };

        if (state.enabled) {
            BackgroundGeolocation.removeListeners();
            BackgroundGeolocation.stop(() => {
                console.log(`BackgroundGeolocationProvider::stop: OK`);

                this.providerState = {
                    status: this.getStatus(false, get(this._providerState, 'changeEvent', false)),
                    phoneMac: this.phoneMac
                };
            }, (err) => {
                this.logger.error(`BackgroundGeolocationProvider::stop: error ${err}`);
            });
        }
    });
}

private getStatus(BGEnabled: boolean, event: ProviderChangeEvent | false): TProviderStatus {
    let status: 'on' | 'off' | null = null;

    if (this.phoneMac) {
        if (BGEnabled) { 
            status = 'on';
        } else {
            status = 'off';
        }
    }

    return status;
}

}


## Expected Behavior
<!--- Tell us what should happen -->
plugin posting updates continuously

## Actual Behavior
<!--- Tell us what happens instead -->

I'm seeing non-stop updates on my phone and a customer's phone:

my phone showed is_moving: 1   (wasn't moving all night) (Pixel 4a, my
verbose logs attached)
cust phone showed is_movng: 0  (his geo never changed) (Galaxy A51,
unable to get logs)

(both phones stuck on opposite moving states, yet plugin continued to
send updates)

## Steps to Reproduce
<!--- reproduce this issue; include code to reproduce, if relevant -->
1.
Pixel 4a attached verbose BG Log significant times:

05-31 22:21:25.857 ->  our http service was fixed to return 201 and
accept all records

...http updates every 2 minutes, non-stop, phone never moved

06-01 04:47:25.153 ->  I stopped BG service (in the app)

06-01 05:17:23.325 ->  I restarted BG service (in the app)

...updates and tracking returned to normal

2.
3.
4.

## Context
<!--- What were you trying to do? -->

## Debug logs
<!-- include iOS / Android logs
- ios XCode logs,
- use #getLog #emailLog methods (@see docs)
- Android: $ adb logcat
-->
<details>
    <summary>Logs</summary>

```<!-- Syntax highlighting:  DO NOT REMOVE -->
PASTE_YOUR_LOGS_HERE

background-geolocation (4).log

christocracy commented 1 year ago

What is the start timestamp where this behaviour begins?

TARJr commented 1 year ago

Continuous posts start here:

05-31 22:23:26.908

On Wed, Jun 1, 2022 at 10:23 AM Chris Scott @.***> wrote:

What is the start timestamp where this behaviour begins?

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/cordova-background-geolocation-lt/issues/1354#issuecomment-1143678254, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAL5JMURNNQJLNMKTCSHZNLVM5W4ZANCNFSM5XRLAR6Q . You are receiving this because you authored the thread.Message ID: <transistorsoft/cordova-background-geolocation-lt/issues/1354/1143678254@ github.com>

christocracy commented 1 year ago

Have you been using a Mock Location app on that device?

christocracy commented 1 year ago

Plugin version: 4.4.2

I've been making a lot of changes wrt Android 12 lately. I suggest you test Android 12 on the latest version 4.7.1.

TARJr commented 1 year ago

Not sure what a Mock location app would be.

On Wed, Jun 1, 2022 at 10:53 AM Chris Scott @.***> wrote:

Have you been using a Mock Location app on that device?

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/cordova-background-geolocation-lt/issues/1354#issuecomment-1143713194, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAL5JMTY43TZCLDUZ4SYCZDVM52NHANCNFSM5XRLAR6Q . You are receiving this because you authored the thread.Message ID: <transistorsoft/cordova-background-geolocation-lt/issues/1354/1143713194@ github.com>

christocracy commented 1 year ago

Why are you doing this? the onMotionChange delivers a high-quality location to event.location. Doing a getCurrentPosition() there is probably just going to give you the exact location that was delivered to event.location.

BackgroundGeolocation.onMotionChange((event) => {
                if (event.isMoving) {
                    console.error('[onMotionChange] Device has just started MOVING ', event.location);
                    this.logger.info(`BackgroundGeolocationProvider:: MOVING`);
                    BackgroundGeolocation.getCurrentPosition({
                        samples: 1,
                        persist: true
                    }).then((location) => {
                        console.log('[getCurrentPosition] ', location);
                    });

                } else {
                   console.log('[onMotionChange] Device has just STOPPED:  ', event.location);
                }
            });
christocracy commented 1 year ago

Show me your platforms/android/project.properties

TARJr commented 1 year ago

This file was originally created by the Android Tools, but is now

used by cordova-android to manage the state of the various third party

libraries used in your application

This is the Library Module that contains the Cordova Library, this is not

required when using an AAR

This is the application project. This is only required for Android

Studio Gradle projects

Project target.

target=android-29 android.library.reference.1=CordovaLib android.library.reference.2=app cordova.gradle.include.1=cordova-plugin-background-fetch/txxxx-build.gradle cordova.system.library.1=com.google.android.gms:play-services-location:18.+ cordova.system.library.2=androidx.appcompat:appcompat:1.2.0 cordova.system.library.3=com.squareup.okhttp3:okhttp:3.12.+ cordova.system.library.4=org.greenrobot:eventbus:3.2.0 cordova.system.library.5=io.github.nishkarsh:android-permissions:0.1.8 cordova.system.library.6=org.slf4j:slf4j-api:1.7.25 cordova.system.library.7=com.github.tony19:logback-android:2.0.0 cordova.gradle.include.2=cordova-background-geolocation-lt/xxxxx-build.gradle cordova.system.library.8=com.google.android.play:core:1.8.0 cordova.gradle.include.3=cordova-support-google-services/xxxxx-build.gradle cordova.gradle.include.4=phonegap-plugin-multidex/xxxxx-multidex.gradle cordova.system.library.9=androidx.legacy:legacy-support-v13:1.0.0 @.*** cordova.system.library.11=com.google.firebase:firebase-messaging:17.0.+

On Wed, Jun 1, 2022 at 11:07 AM Chris Scott @.***> wrote:

Show me your platforms/android/project.properties

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/cordova-background-geolocation-lt/issues/1354#issuecomment-1143730775, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAL5JMQYO43DLPOZAZSFCBTVM54C5ANCNFSM5XRLAR6Q . You are receiving this because you authored the thread.Message ID: <transistorsoft/cordova-background-geolocation-lt/issues/1354/1143730775@ github.com>

TARJr commented 1 year ago

I'm going to take that out, it was put in for testing.

On Wed, Jun 1, 2022 at 11:01 AM Chris Scott @.***> wrote:

Why are you doing this? the onMotionChange delivers a high-quality location to event.location. Doing a getCurrentPosition() there is probably just going to give you the exact location that was delivered to event.location.

BackgroundGeolocation.onMotionChange((event) => { if (event.isMoving) { console.error('[onMotionChange] Device has just started MOVING ', event.location); this.logger.info(BackgroundGeolocationProvider:: MOVING); BackgroundGeolocation.getCurrentPosition({ samples: 1, persist: true }).then((location) => { console.log('[getCurrentPosition] ', location); });

            } else {
               console.log('[onMotionChange] Device has just STOPPED:  ', event.location);
            }
        });

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/cordova-background-geolocation-lt/issues/1354#issuecomment-1143722991, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAL5JMSRGDARDO5O7JFOJVLVM53M3ANCNFSM5XRLAR6Q . You are receiving this because you authored the thread.Message ID: <transistorsoft/cordova-background-geolocation-lt/issues/1354/1143722991@ github.com>

christocracy commented 1 year ago

I believe the issue started here:

  1. App is terminated.

    05-31 13:06:01.065 INFO [TSScheduleManager oneShot] 
    ⏰ Scheduled OneShot: TERMINATE_EVENT in 10000ms (jobID: -1708771588)
    05-31 13:06:01.131 DEBUG [BackgroundGeolocation a] 
    🔴  Cleared callbacks
    05-31 13:06:01.140 INFO [BackgroundGeolocation$m0 run] 
    ╔═════════════════════════════════════════════
    ║ MainActivity was destroyed
    ╠═════════════════════════════════════════════
    ╟─ stopOnTerminate: false
    ╟─ enabled: true
  2. Location updates are turned ON:

    05-31 13:06:05.596 INFO [TSLocationManager requestLocationUpdates] 
    🎾  Location-services: ON
  3. Motion Transition STILL occurs:

    05-31 13:06:05.777 INFO [ActivityRecognitionService a] 
    ╔═════════════════════════════════════════════
    ║ Motion Transition Result
    ╠═════════════════════════════════════════════
    ╟─ 🎾  ENTER: still
    ╚═════════════════════════════════════════════
  4. TrackingService receives motionchange: false event:

    05-31 13:06:07.417 INFO [TrackingService h] 
    ╔═════════════════════════════════════════════
    ║ TrackingService motionchange: false
    ╠═════════════════════════════════════════════

But there is no 🔴 Location-services: OFF message, therefore, Location-updates remain updating.

I believe there is a bug here related to Android 12 and the new long-lived foreground-services. I will guard against this case. Though it may work better in latest version.

TARJr commented 1 year ago

Thanks. I'll wait for the updated fix.

On Wed, Jun 1, 2022 at 12:46 PM Chris Scott @.***> wrote:

I believe the issue started here:

05-31 13:06:01.065 INFO [TSScheduleManager oneShot] ⏰ Scheduled OneShot: TERMINATE_EVENT in 10000ms (jobID: -1708771588) 05-31 13:06:01.131 DEBUG [BackgroundGeolocation a] 🔴 Cleared callbacks 05-31 13:06:01.140 INFO [BackgroundGeolocation$m0 run] ╔═════════════════════════════════════════════ ║ MainActivity was destroyed ╠═════════════════════════════════════════════ ╟─ stopOnTerminate: false ╟─ enabled: true

Location updates are turned ON:

05-31 13:06:05.596 INFO [TSLocationManager requestLocationUpdates] 🎾 Location-services: ON

Motion Transition STILL occurs:

05-31 13:06:05.777 INFO [ActivityRecognitionService a] ╔═════════════════════════════════════════════ ║ Motion Transition Result ╠═════════════════════════════════════════════ ╟─ 🎾 ENTER: still ╚═════════════════════════════════════════════

TrackingService receives motionchange: false event:

05-31 13:06:07.417 INFO [TrackingService h] ╔═════════════════════════════════════════════ ║ TrackingService motionchange: false ╠═════════════════════════════════════════════

But there is no 🔴 Location-services: OFF message, therefore, Location-updates remain updating.

I believe there is a bug here related to Android 12 and the new long-lived foreground-services. I will guard against this case. Though it may work better in latest version.

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/cordova-background-geolocation-lt/issues/1354#issuecomment-1143864238, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAL5JMULM6XDT2SVD7ILEH3VM6HU3ANCNFSM5XRLAR6Q . You are receiving this because you authored the thread.Message ID: <transistorsoft/cordova-background-geolocation-lt/issues/1354/1143864238@ github.com>

christocracy commented 1 year ago

It will arrive first in the private repo, not the public npm version you’re using.

TARJr commented 1 year ago

Not sure this is related, but location was not updating for several hours, should have (same phone), had to reset BG: last update was 17:11:32

╔═════════════════════════════════════════════ ║ Motion Transition Result ╠═════════════════════════════════════════════ ╟─ 🎾 ENTER: still ╚═════════════════════════════════════════════ 06-06 17:11:32.273 DEBUG [AbstractService a] ⚙️︎ finish ActivityRecognitionService [eventCount: 0, sticky: false] 06-06 17:11:32.339 INFO [HttpService$i onResponse] 🔵 Response: 201 06-06 17:11:32.340 DEBUG [b destroy] ✅ DESTROY: 534f7811-e9d7-42ab-b34a-61ddec5d5222 06-06 17:11:32.344 INFO [BackgroundTaskManager$Task stop] ⏳ stopBackgroundTask: 181 06-06 17:11:32.345 DEBUG [AbstractService a] ⚙️︎ finish BackgroundTaskService [eventCount: 0, sticky: false] 06-06 17:11:32.346 DEBUG [AbstractService onDestroy] 🔴 BackgroundTaskService destroyed 06-06 17:11:32.435 DEBUG [AbstractService onDestroy] 🔴 LocationRequestService destroyed 06-06 17:11:32.531 DEBUG [AbstractService onDestroy] 🔴 ActivityRecognitionService destroyed 06-06 17:11:39.691 INFO [TSScheduleManager oneShot] ⏰ Scheduled OneShot: TERMINATE_EVENT in 10000ms (jobID: -1708771588) 06-06 17:11:49.916 INFO [ScheduleEvent onOneShot] ╔═════════════════════════════════════════════ ║ ⏰ OneShot event fired: TERMINATE_EVENT ╠═════════════════════════════════════════════

06-06 17:11:49.920 DEBUG [TerminateEvent ] ℹ️ TERMINATE_EVENT ignored (MainActivity is still active). 06-06 17:24:52.310 INFO [TSScheduleManager oneShot] ⏰ Scheduled OneShot: TERMINATE_EVENT in 10000ms (jobID: -1708771588) 06-06 17:25:10.873 INFO [ScheduleEvent onOneShot] ╔═════════════════════════════════════════════ ║ ⏰ OneShot event fired: TERMINATE_EVENT ╠═════════════════════════════════════════════

06-06 17:25:10.875 DEBUG [TerminateEvent ] ℹ️ TERMINATE_EVENT ignored (MainActivity is still active). 06-06 17:40:31.340 INFO [TSScheduleManager oneShot] ⏰ Scheduled OneShot: TERMINATE_EVENT in 10000ms (jobID: -1708771588) 06-06 17:40:46.308 INFO [ScheduleEvent onOneShot] ╔═════════════════════════════════════════════ ║ ⏰ OneShot event fired: TERMINATE_EVENT ╠═════════════════════════════════════════════

06-06 17:40:46.312 DEBUG [TerminateEvent ] ℹ️ TERMINATE_EVENT ignored (MainActivity is still active). 06-06 17:49:12.338 INFO [TSScheduleManager oneShot] ⏰ Scheduled OneShot: TERMINATE_EVENT in 10000ms (jobID: -1708771588) 06-06 17:49:30.876 INFO [ScheduleEvent onOneShot] ╔═════════════════════════════════════════════ ║ ⏰ OneShot event fired: TERMINATE_EVENT ╠═════════════════════════════════════════════

06-06 17:49:30.879 DEBUG [TerminateEvent ] ℹ️ TERMINATE_EVENT ignored (MainActivity is still active). 06-06 18:12:54.582 INFO [TSScheduleManager oneShot] ⏰ Scheduled OneShot: TERMINATE_EVENT in 10000ms (jobID: -1708771588) 06-06 18:18:54.323 INFO [ScheduleEvent onOneShot] ╔═════════════════════════════════════════════ ║ ⏰ OneShot event fired: TERMINATE_EVENT ╠═════════════════════════════════════════════ 06-06 22:35:10.597 DEBUG [TerminateEvent ] ℹ️ TERMINATE_EVENT ignored (MainActivity is still active). 06-06 22:42:45.053 INFO [TSScheduleManager oneShot] ⏰ Scheduled OneShot: TERMINATE_EVENT in 10000ms (jobID: -1708771588) 06-06 22:43:02.580 INFO [ScheduleEvent onOneShot] ╔═════════════════════════════════════════════ ║ ⏰ OneShot event fired: TERMINATE_EVENT ╠═════════════════════════════════════════════

06-06 22:43:02.583 DEBUG [TerminateEvent ] ℹ️ TERMINATE_EVENT ignored (MainActivity is still active).

christocracy commented 1 year ago

Are you doing something in the app pause / resume events?

TARJr commented 1 year ago

Just logging events, nothing else being done:

this.resumeSubscription = this.platform.resume.subscribe(async () => {
  logger.info('App:onResume');

On Tue, Jun 7, 2022 at 10:04 AM Chris Scott @.***> wrote:

Are you doing something in the app pause / resume events?

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/cordova-background-geolocation-lt/issues/1354#issuecomment-1148722528, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAL5JMV3YQNFKDVIEO7BD63VN5JH7ANCNFSM5XRLAR6Q . You are receiving this because you authored the thread.Message ID: <transistorsoft/cordova-background-geolocation-lt/issues/1354/1148722528@ github.com>

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. You may also mark this issue as a "discussion" and I will leave this open.

github-actions[bot] commented 1 month ago

This issue was closed because it has been inactive for 14 days since being marked as stale.