-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (73 loc) · 1.76 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict'
const createDebug = require('debug')
const pRetry = require('p-retry')
const {Readable} = require('stream')
const sncfWifiPortal = require('sncf-wifi-portal-client')
const ouifiPortal = require('ouifi-portal-client')
const debugPortal = createDebug('record-tgv-movement:portal')
// find any portal that does not fail with `ENOTFOUND` or request timeouts
const checkIfPortalWorks = async (name, portal, checkIfWorking) => {
try {
const info = await pRetry(checkIfWorking, {minTimeout: 1000, retries: 3})
debugPortal(name + ' seems to work', info)
return portal
} catch (err) {
debugPortal(name + ' doesn\'t seem to work', err)
throw err
}
}
const createPositionsStream = (interval = 3 * 1000) => {
if (
'number' !== typeof interval ||
Number.isNaN(interval) ||
interval <= 0
) {
throw new Error('interval must be an integer > 0.')
}
let portal = null
const out = new Readable({
objectMode: true,
read: () => {}
})
const fetch = () => {
const t = Date.now()
portal.gps()
.then((_) => {
out.push({
ok: _.success === true,
speed: _.speed * 3.6, // m/s -> km/h
latitude: _.latitude,
longitude: _.longitude,
heading: _.heading,
precision: _.fix,
serverTime: _.timestamp * 1000,
clientTime: t
})
})
.catch((err) => {
out.emit('error', err)
})
}
// todo [breaking]: use async/await here
Promise.any([
checkIfPortalWorks(
'sncf-wifi-portal-client',
sncfWifiPortal,
sncfWifiPortal.connectionStatus,
),
checkIfPortalWorks(
'ouifi-portal-client',
ouifiPortal,
ouifiPortal.networkQuality,
),
])
.then((_portal) => {
portal = _portal
setInterval(fetch, interval)
})
.catch((err) => {
out.emit('error', err)
})
return out
}
module.exports = createPositionsStream