chore(miio): Add tests for the miio socket local msgId generation

This commit is contained in:
Sören Beye 2022-02-28 17:14:43 +01:00
parent 3d65458c5d
commit 374f00cd54
2 changed files with 35 additions and 4 deletions

View File

@ -164,7 +164,7 @@ class MiioSocket {
Unexpectedly, it is not required for the next msgId to be larger than the previous one
It just needs to be different
*/
msg["id"] = MiioSocket.calculateMsgId();
msg["id"] = MiioSocket.calculateMsgId(new Date());
}
}
@ -239,10 +239,11 @@ class MiioSocket {
/**
* @private
* @param {Date} date
* @return {number} must be less than MAX_INT32
*/
static calculateMsgId() {
const now = new Date().getTime();
static calculateMsgId(date) {
const now = date.getTime();
if (now > FEB_1970_UNIXTIME_MS) { // If we're not in january 1970, assume that time is synced
/*
@ -278,7 +279,7 @@ class MiioSocket {
}
}
const FEB_1970_UNIXTIME_MS = 2674800 * 1000;
const FEB_1970_UNIXTIME_MS = new Date("1970-02-01T00:00:00.000Z").getTime();
const MAX_INT32 = 0x7fffffff;
/** The default remote port. @const {int} */

View File

@ -0,0 +1,30 @@
const should = require("should");
const MiioSocket = require("../../../lib/miio/MiioSocket");
should.config.checkProtoEql = false;
describe("MiioSocket", function () {
it("Should generate MessageIds correctly", async function() {
//Jan 1970 means no synced time => 1 msgId per second
MiioSocket.calculateMsgId(new Date("1970-01-01T00:00:01.000Z")).should.equal(1);
// Up until 1970-01-02, IDs are collision-free to allow the ntp sync to take some time
MiioSocket.calculateMsgId(new Date("1970-01-01T23:59:59.000Z")).should.equal(86399);
MiioSocket.calculateMsgId(new Date("1970-01-02T00:00:00.000Z")).should.equal(86400);
MiioSocket.calculateMsgId(new Date("1970-01-31T23:59:59.000Z")).should.equal(2678399);
MiioSocket.calculateMsgId(new Date("1970-02-01T00:00:00.000Z")).should.equal(2678400);
// >= Feb 1970 means synced time => 1 msgId every 10ms
MiioSocket.calculateMsgId(new Date("1970-02-01T00:00:01.000Z")).should.equal(267926500);
//wrapping occurs every ~5965 hours
MiioSocket.calculateMsgId(new Date("1972-09-21T03:58:09.870Z")).should.equal(2147483646);
MiioSocket.calculateMsgId(new Date("1972-09-21T03:58:09.880Z")).should.equal(86400);
MiioSocket.calculateMsgId(new Date("1973-05-27T16:57:42.340Z")).should.equal(2147483646);
MiioSocket.calculateMsgId(new Date("1973-05-27T16:57:42.350Z")).should.equal(86400);
});
});