Help needed - how to write accelerometer data to file


#1

HI,

I need to write the accelerometer readings at 100Hz to file.
While using Ionic native File plugin, the first write isn’t finished when the next start and the result is out of sync data in the file.
My provider that handles accelerometer reading and writes the data to file looks like this:

import {DeviceMotion, DeviceMotionAccelerationData} from '@ionic-native/device-motion';
import {Subject} from "rxjs/Subject";
import {Observable} from "rxjs/Observable";
import {Subscription} from "rxjs/Subscription";

import {Http} from '@angular/http';
import {File} from '@ionic-native/file';

@Injectable()
export class DeviceMotionProvider {
    accelerometerata$: Subject<DeviceMotionAccelerationData> = new Subject();
    subscription: Subscription;

    constructor(private deviceMotion: DeviceMotion, private http: Http,
                private file: File) {


    }

    startAccelerometer() {
        // Watch device acceleration
        this.subscription = this.deviceMotion.watchAcceleration({frequency: 100})
            .subscribe((acceleration: DeviceMotionAccelerationData) => {
                this.accelerometerata$.next(acceleration);
                this.file.writeFile(this.file.dataDirectory, 'flightData.txt', acceleration.timestamp + ',' +Math.sqrt(acceleration.x*acceleration.x+acceleration.y*acceleration.y+acceleration.z*acceleration.z)/10 + '\n' ,{ append:true})
            });
    }

    getAccelerometerData(): Observable<DeviceMotionAccelerationData> {
        return this.accelerometerata$.asObservable();
    }

    stopAccelerometer() {
        this.subscription.unsubscribe();
    }


}

Any idea on how to write the data so that it will not overlap ?

Thanks,
Ziv


#2

It looks like writeFile() returns a Promise indicating when it has completed, so perhaps you could do something like this:

writing = Promise.resolve();

startAccelerometer(): void {
  this.deviceMotion.watchAcceleration(}.subscribe((accel) => {
    this.writing.then(() => {
      this.writing = this.file.writeFile(...);
    });
  });
}