forked from incrementing/react-native-ntp-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
188 lines (174 loc) · 5.02 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import BackgroundTimer from "react-native-background-timer";
setInterval = (fn, ms = 0) => {
const numberMs = Number(ms);
if (isNaN(numberMs)) return BackgroundTimer.setInterval(fn, 0);
return BackgroundTimer.setInterval(fn, numberMs);
};
let NTPSync = function (config) {
this.client = require("./client");
if (!config) {
config = {};
}
this.ntpServers = [];
if (config.hasOwnProperty('servers')) {
config.servers.forEach(function (s, i) {
if (typeof s === 'string' && s.length > 0) {
this.ntpServers.push({
server: s,
port: 123
});
} else if (typeof s === 'object') {
if (s.server && typeof s.server === 'string' && s.port && typeof s.port === 'number' && s.port > 0) {
this.ntpServers.push({
server: s.server,
port: s.port
});
}
}
}, this);
}
if(this.ntpServers.length == 0){
this.ntpServers = [
{ server: "time.cloudflare.com", port: 123 },
{ server: "time.google.com", port: 123 },
{ server: "0.pool.ntp.org", port: 123 },
{ server: "1.pool.ntp.org", port: 123 },
];
}
this.limit = 10;
if(parseInt(config.history) > 0){
this.limit = parseInt(config.history);
}
this.tickRate = 300;
if(parseFloat(config.syncDelay) > 0){
this.tickRate = parseFloat(config.syncDelay);
}
this.currentIndex = 0;
this.tickId = null;
this.tickRate = this.tickRate * 1000;
this.historyDetails = {
currentConsecutiveErrorCount: 0,
currentServer: this.ntpServers[this.currentIndex],
deltas: [],
errors: [],
isInErrorState: false,
lastSyncTime: null,
lastNtpTime: null,
lastError: null,
lifetimeErrorCount: 0,
maxConsecutiveErrorCount: 0,
};
this.syncTime();
this.startTick();
};
/**
* @private
*/
NTPSync.prototype.computeAndUpdate = function (ntpDate) {
let tempServerTime = ntpDate.getTime();
let tempLocalTime = Date.now();
let dt = tempServerTime - tempLocalTime;
if (this.historyDetails.deltas.length === this.limit) {
this.historyDetails.deltas.shift();
}
this.historyDetails.deltas.push({
dt: dt,
ntp: tempServerTime,
});
this.historyDetails.lastSyncTime = tempLocalTime;
this.historyDetails.lastNtpTime = tempServerTime;
return dt;
};
/**
* @private
*/
NTPSync.prototype.getDelta = function (callback) {
let fetchingServer = Object.assign({}, this.historyDetails.currentServer);
this.client.getNetworkTime(
this.historyDetails.currentServer.server,
this.historyDetails.currentServer.port,
function (err, date) {
if (err) {
this.shiftServer();
let ex = err;
if (!ex) {
ex = new Error("unknown error");
} else if (!(ex instanceof Error)) {
if (typeof ex === "string") {
ex = new Error(ex);
} else {
ex = new Error(ex.toString());
}
}
if (callback) {
callback(ex, fetchingServer);
}
} else {
let delta = this.computeAndUpdate(date);
if (callback) {
callback(delta, fetchingServer);
}
}
}.bind(this)
);
};
NTPSync.prototype.getHistory = function () {
return JSON.parse(JSON.stringify(this.historyDetails));
};
NTPSync.prototype.getTime = function () {
let sum = this.historyDetails.deltas.reduce((a, b) => {
return a + b.dt;
}, 0);
let avg = Math.round(sum / this.historyDetails.deltas.length) || 0;
return Date.now() + avg;
};
NTPSync.prototype.shiftServer = function () {
if (this.ntpServers.length > 1) {
this.currentIndex++;
this.currentIndex %= this.ntpServers.length;
}
this.historyDetails.currentServer = this.ntpServers[this.currentIndex];
};
NTPSync.prototype.startTick = function () {
if (!this.tickId) {
this.tickId = setInterval(
function () {
this.syncTime();
}.bind(this),
this.tickRate
);
}
};
NTPSync.prototype.syncTime = function () {
function internalCallback(result, server) {
var success = false;
if (typeof result === "number") {
success = true;
this.historyDetails.currentConsecutiveErrorCount = 0;
this.historyDetails.isInErrorState = false;
} else if (result instanceof Error) {
// extract Error data
var ed = {
name: result.name,
message: result.message,
server: server,
stack: result.stack,
time: Date.now(),
};
this.historyDetails.currentConsecutiveErrorCount++;
if (this.historyDetails.errors.length === this.limit) {
this.historyDetails.errors.shift();
}
this.historyDetails.errors.push(ed);
this.historyDetails.isInErrorState = true;
this.historyDetails.lastError = ed;
this.historyDetails.lifetimeErrorCount++;
this.historyDetails.maxConsecutiveErrorCount = Math.max(
this.historyDetails.maxConsecutiveErrorCount,
this.historyDetails.currentConsecutiveErrorCount
);
}
}
this.getDelta(internalCallback.bind(this));
};
module.exports = NTPSync;