Firebase how to know specific client is offline?

混江龙づ霸主 提交于 2019-12-10 12:15:22

问题


I am developing a device/product using raspberry pi and Firebase...

System flows like this: user buys device on my website and she can use same credentials to login mobile app.

Currently, I am relying on an some how generated uniuqe id put by me in to device to interact to db from device and device to Firebase Realtime Database...

Now I need to know if device is online or offline. Answers should be on possibble two solutions. Because I want to notify user: "Your device is offline"...

1- on current code(relying on unique id): if it's possible, how can I achive this.

2- changing system in to user based: if I implement this how I must think system. Device will have no display input nor keyboard. For example what happens when user changed her password?

Thank you..


回答1:


What you want is onDisconnect

When your device starts you setup an onDisconnect to change its status or even fire a time:

var lastOnlineRef = firebase.database().ref("devices/1234/lastOnline");
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);

var isOnlineRef = firebase.database().ref("devices/1234/isOnline");
isOnlineRef.onDisconnect().set(false);

As to the user thing I'm not totally sure I understand. If you isolate your devices with your UID in a path like: /devices/UID they exist independently of the users.

For your users you would simply create a list of all of their devices: /users/UID/devices

{
    1234: 1234,
    5678: 5678
}

Then in your app you just first get their list of devices, then create references to them.

In Angular that would look like:

// in the ts
public userDevices = this.db.list('/users/UID/devices').valueChanges();

public getDeviceObservable(deviceId: string) {
    return this.db.object('/devices/' + deviceId).valueChanges();
}

//in the template
<div *ngFor="let deviceId of userDevices | async">
    <ng-container *ngIf="getDeviceObservable(deviceId) | async as device">
    {{ device | json }}
    </ng-container>
</div>

It's not totally best practice to put a getObservable in the template, you could do it in the component too but thats a whole other talk with switchMap etc.



来源:https://stackoverflow.com/questions/48303327/firebase-how-to-know-specific-client-is-offline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!