Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to Upload Location Data to Custom Server Using Background Geolocation #141

Open
ZhenzeMo opened this issue Jul 11, 2024 · 0 comments

Comments

@ZhenzeMo
Copy link

Description:
I am using the react-native-background-geolocation library to track and upload location data to a custom server. The setup seems to be configured correctly, as the BackgroundGeolocation.ready method indicates readiness in the logs. However, the data is not being uploaded to my AWS server or the public server provided by transistorsoft. Below are the details of my setup, configurations, and log outputs.

Setup:
Environment: AWS m5.large
Project: background-geolocation-console
Installed and started using npm install and npm start
Configured with Google Maps API key and JWT key
React Native Code:

`import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import BackgroundGeolocation from 'react-native-background-geolocation';
import * as Device from 'expo-device';
import * as Location from 'expo-location';

const TestBackgroundGeo = () => {
console.log('start recording..');
useEffect(() => {
const configureBackgroundGeolocation = async () => {
// Request location permissions
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
console.error('Permission to access location was denied');
return;
}

  let { status: backgroundStatus } = await Location.requestBackgroundPermissionsAsync();
  if (backgroundStatus !== 'granted') {
    console.error('Permission to access background location was denied');
    return;
  }

  // Get device parameters
  const deviceParams = {
    uuid: Device.osInternalBuildId || Device.deviceId,
    model: Device.modelName,
    platform: Device.osName,
    manufacturer: Device.manufacturer,
    version: Device.osVersion,
    framework: 'ReactNative',
  };

  // Get JSON Web Token
  let token = await BackgroundGeolocation.findOrCreateTransistorAuthorizationToken(
    'socitydao', // Organization name
    'socity'    // Username
  );

  // Manually set token URLs
  token.url = 'http://3.134.85.0:9000/locations';
  token.refreshUrl = 'http://3.134.85.0:9000/locations/api/refresh_token';

  // Configure BackgroundGeolocation
  BackgroundGeolocation.ready(
    {
      url: 'http://3.134.85.0:9000/locations', // Custom server URL
      params: BackgroundGeolocation.transistorTrackerParams(deviceParams),
      autoSync: true,
      debug: true,
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
      stopOnTerminate: false,
      startOnBoot: true,
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10, // Update distance in meters
      locationUpdateInterval: 10000, // Update interval in milliseconds
      fastestLocationUpdateInterval: 5000, // Fastest update interval in milliseconds
      foregroundService: true,
      transistorAuthorizationToken: token, // Provided token
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token.accessToken}`, // Provided token
      },
    },
    state => {
      console.log('BackgroundGeolocation is ready:', state);
      if (!state.enabled) {
        BackgroundGeolocation.start();
      }
    },
  );

  const refreshToken = async () => {
    try {
      const response = await fetch(token.refreshUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token.accessToken}`,
        },
        body: JSON.stringify({
          refresh_token: token.refreshToken,
        }),
      });
      const newToken = await response.json();
      if (response.ok) {
        token.accessToken = newToken.accessToken;
        console.log('Token refreshed successfully:', newToken);
      } else {
        console.error('Failed to refresh token:', newToken);
      }
    } catch (error) {
      console.error('Error refreshing token:', error);
    }
  };

  // Check token expiration and refresh if necessary
  BackgroundGeolocation.onLocation(async location => {
    console.log('[location] -', location);

    const expirationDate = new Date(token.expires * 1000);
    const currentDate = new Date();
    if (expirationDate - currentDate < 60000) {
      await refreshToken();
    }

    fetch('http://3.134.85.0:9000/locations', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token.accessToken}`, // Use the new token
      },
      body: JSON.stringify(location),
    })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        console.log('Data sent to server:', data);
      })
      .catch(error => {
        console.error('Error sending data to server:', error);
      });
  });

  // Listen for errors
  BackgroundGeolocation.onError(error => {
    console.error('[error] -', error);
  });
};

configureBackgroundGeolocation();

return () => {
  BackgroundGeolocation.removeListeners();
};

}, []);

return (

Background Geolocation App

);
};

export default TestBackgroundGeo;
**Log Output:**LOG start recording..
LOG BackgroundGeolocation is ready: {
"activityRecognitionInterval": 10000,
"activityType": 1,
"authorization": {
"accessToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21wYW55SWQiOjIwNDU4LCJkZXZCI6NzY0NzcsIm1vZGVsIjoiaVBob25lMTQsNSIsIm9yZyI6InNvv39jV8F6BlmrdrA_gTwh7z5E3eARCySH4liOOPkMw8R-RBueMX5mtJ",
"expires": -1,
"refreshHeaders": {
"Authorization": "Bearer {accessToken}"
},
"refreshPayload": {
"refresh_token": "{refreshToken}"
},
"refreshToken": "89ae8305c2d7bb70e54a5",
"refreshUrl": "http://3.134.85.0:9000/locations/api/refresh_token",
"strategy": "JWT"
},
"autoSync": true,
"autoSyncThreshold": 0,
"batchSync": false,
"debug": true,
"desiredAccuracy": -1,
"desiredOdometerAccuracy": 100,
"didDeviceReboot": false,
"didLaunchInBackground": false,
"didRequestUpgradeLocationAuthorization": false,
"disableAutoSyncOnCellular": false,
"disableElasticity": false,
"disableLocationAuthorizationAlert": false,
"disableMotionActivityUpdates": false,
"disableStopDetection": false,
"distanceFilter": 10,
"elasticityMultiplier": 1,
"enableTimestampMeta": false,
"enabled": true,
"extras": {},
"geofenceInitialTriggerEntry": true,
"geofenceProximityRadius": 2000,
"geofenceTemplate": "",
"headers": {
"Authorization": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21wYW55SWQiOjIwNDU4LCJkZXZpY2VJZCI6NzY0NzcsIm1vZGVsIjoiaVBob25lMTQsNSIsIm9yZyI6EjINB77iav39jV8F6BlmrdrA_gTwh7z5E3eARCySH4liOOPkMw8R-RBueMX5mtJR4LVk4T_PhkSA_lbXKsN9GYb1gAGt2ORGX7A9lVCVIN7wpKH0fXcH9rRJxiSaU2-rZ38COvM_tx",
"Content-Type": "application/json"
},
"heartbeatInterval": 60,
"httpRootProperty": "location",
"httpTimeout": 60000,
"iOSHasWarnedLocationServicesOff": false,
"isFirstBoot": false,
"isMoving": false,
"lastLocationAuthorizationStatus": 3,
"locationAuthorizationAlert": {
"cancelButton": "Cancel",
"instructions": "To use background location, you must enable '{locationAuthorizationRequest}' in the Location Services settings",
"settingsButton": "Settings",
"titleWhenNotEnabled": "Background location is not enabled",
"titleWhenOff": "Location services are off"
},
"locationAuthorizationRequest": "Always",
"locationTemplate": "",
"locationTimeout": 60,
"locationsOrderDirection": "ASC",
"logLevel": 5,
"logMaxDays": 3,
"maxBatchSize": -1,
"maxDaysToPersist": 1,
"maxRecordsToPersist": -1,
"method": "POST",
"minimumActivityRecognitionConfidence": 70,
"odometer": 0,
"params": {
"_h": 0,
"_i": 0,
"_j": null,
"_k": null,
"catch": null,
"finally": null,
"then": null
},
"pausesLocationUpdatesAutomatically": true,
"persistMode": 2,
"preventSuspend": false,
"schedule": [],
"schedulerEnabled": false,
"showsBackgroundLocationIndicator": true,
"startOnBoot": true,
"stationaryRadius": 25,
"stopAfterElapsedMinutes": -1,
"stopDetectionDelay": 0,
"stopOnStationary": false,
"stopOnTerminate": false,
"stopTimeout": 5,
"trackingMode": 1,
"url": "http://3.134.85.0:9000/locations",
"useSignificantChangesOnly": false
}
`

Issue:
Despite the configuration indicating that BackgroundGeolocation is ready, the recorded location data is not being uploaded to my custom AWS server or the public server provided by transistorsoft.

Questions:

Why is the location data not being uploaded to the specified server?
Are there any additional configurations or steps needed to ensure successful data upload?
Is there a way to further debug or log the upload process to identify where the failure occurs?
Any help or guidance would be greatly appreciated. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant