All files / sportident/src/SiStation BaseSiStation.ts

98.61% Statements 71/72
83.33% Branches 10/12
100% Functions 28/28
98.61% Lines 71/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 2864x 4x 4x 4x 4x                                                                       4x                 6x     6x                 12x                                                 4x             4x                 11x 11x 4x   7x   7x   7x       16x 16x   16x       8x 8x 8x               17x                 7x         7x             1x           66x             14x       1x 1x   1x 1x         3x   3x 3x 3x 3x               4x 4x 512x   4x           512x 500x   12x 12x 12x 8x         4x             4x 4x 8x 4x   4x 4x       4x         4x 4x 4x     4x 4x     4x       1x       1x         1x       1x         2x 2x         2x 1x             1x            
import {proto} from '../constants';
import * as storage from '../storage';
import * as siProtocol from '../siProtocol';
import {ISiStation, SiStationMode, SiStationModel} from './ISiStation';
import {ISiTargetMultiplexer, SiTargetMultiplexerTarget} from './ISiTargetMultiplexer';
 
export interface ISiStationStorageFields {
    code: number;
    mode: keyof typeof SiStationMode,
    beeps: boolean;
    flashes: boolean;
    autoSend: boolean;
    extendedProtocol: boolean;
    serialNumber: number;
    firmwareVersion: number;
    buildDate: Date;
    deviceModel: keyof typeof SiStationModel;
    memorySize: number;
    batteryDate: Date;
    batteryCapacity: number;
    batteryState: number;
    backupPointer: number;
    siCard6Mode: number;
    memoryOverflow: number;
    lastWriteDate: Date;
    autoOffTimeout: number;
    refreshRate: number;
    powerMode: number;
    interval: number;
    wtf: number;
    program: number;
    handshake: boolean;
    sprint4ms: boolean;
    passwordOnly: boolean;
    stopOnFullBackup: boolean;
    autoReadout: boolean;
    sleepDay: number;
    sleepSeconds: number;
    workingMinutes: number;
}
export const siStationStorageLocations: storage.ISiStorageLocations<ISiStationStorageFields> = {
    code: new storage.SiInt([[0x72], [0x73, 6, 8]]),
    mode: new storage.SiEnum([[0x71]], SiStationMode),
    beeps: new storage.SiBool(0x73, 2),
    flashes: new storage.SiBool(0x73, 0),
    autoSend: new storage.SiBool(0x74, 1),
    extendedProtocol: new storage.SiBool(0x74, 0),
    serialNumber: new storage.SiInt([[0x03], [0x02], [0x01], [0x00]]),
    firmwareVersion: new storage.SiInt([[0x07], [0x06], [0x05]]),
    buildDate: new siProtocol.SiDate(3, (i) => 0x08 + i),
    deviceModel: new storage.SiEnum([[0x0C], [0x0B]], SiStationModel),
    memorySize: new storage.SiInt([[0x0D]]),
    batteryDate: new siProtocol.SiDate(3, (i) => 0x15 + i),
    batteryCapacity: new storage.SiInt([[0x1A], [0x19]]),
    batteryState: new storage.SiInt([[0x37], [0x36], [0x35], [0x34]]),
    // 2000mAh: 000000=0%, 6E0000=100%, 1000mAh:000000=0%, 370000=100%
    backupPointer: new storage.SiInt([[0x22], [0x21], [0x1D], [0x1C]]),
    siCard6Mode: new storage.SiInt([[0x33]]),
    // 08 or FF = 192 punches, 00 or C1 normal
    memoryOverflow: new storage.SiInt([[0x3D]]),
    // overflow if != 00
    lastWriteDate: new siProtocol.SiDate(6, (i) => 0x75 + i),
    autoOffTimeout: new storage.SiInt([[0x7F], [0x7E]]),
    refreshRate: new storage.SiInt([[0x10]]),
    // in 3/sec ???
    powerMode: new storage.SiInt([[0x11]]),
    // 06 low power, 08 standard/sprint
    interval: new storage.SiInt([[0x49], [0x48]]),
    // in 32*ms
    wtf: new storage.SiInt([[0x4B], [0x4A]]),
    // in 32*ms
    program: new storage.SiInt([[0x70]]),
    // xx0xxxxxb competition, xx1xxxxxb training
    handshake: new storage.SiBool(0x74, 2),
    sprint4ms: new storage.SiBool(0x74, 3),
    passwordOnly: new storage.SiBool(0x74, 4),
    stopOnFullBackup: new storage.SiBool(0x74, 5),
    autoReadout: new storage.SiBool(0x74, 7),
    // depends on autoSend
    sleepDay: new storage.SiInt([[0x7B]]),
    //   xxxxxxx0b - seconds relative to midnight/midday: 0 = am, 1 = pm
    //   xxxx000xb - day of week: 000 = Sunday, 110 = Saturday
    //   xx00xxxxb - week counter 0..3, relative to programming date
    sleepSeconds: new storage.SiInt([[0x7D], [0x7C]]),
    workingMinutes: new storage.SiInt([[0x7F], [0x7E]]),
};
export const siStationStorageDefinition = storage.defineStorage(
    0x80,
    siStationStorageLocations,
);
// export type ISiStationStorageFields = storage.FieldsFromStorageDefinition<typeof siStationStorageDefinition>;
// export type ISiStationStorageFields = storage.FieldsFromStorageLocations<typeof siStationStorageLocations>;
 
export abstract class BaseSiStation<T extends SiTargetMultiplexerTarget> {
    public storage: storage.ISiStorage<ISiStationStorageFields>;
 
    protected static fromSiTargetMultiplexerWithGivenTarget<U extends SiTargetMultiplexerTarget>(
        multiplexer: ISiTargetMultiplexer,
        multiplexerTarget: U,
        createNewInstance: () => ISiStation<U>,
    ): ISiStation<U> {
        const existingStationObject =
            multiplexer.stations[multiplexerTarget] as ISiStation<U>|undefined;
        if (existingStationObject) {
            return existingStationObject;
        }
        const instance = createNewInstance();
        // @ts-ignore
        multiplexer.stations[multiplexerTarget] = instance;
        // TODO: deregister/close
        return instance;
    }
 
    constructor(
                public siTargetMultiplexer: ISiTargetMultiplexer,
                public readonly multiplexerTarget: T,
    ) {
        this.storage = siStationStorageDefinition();
    }
 
    get ident(): string {
        const multiplexerTargetString = SiTargetMultiplexerTarget[this.multiplexerTarget];
        const deviceIdentString = this.siTargetMultiplexer.siDevice.ident;
        return `${multiplexerTargetString}-${deviceIdentString}`;
    }
 
    sendMessage(
        message: siProtocol.SiMessage,
        numResponses = 0,
        timeoutInMiliseconds = 10000,
    ): Promise<number[][]> {
        return this.siTargetMultiplexer.sendMessage(
            this.multiplexerTarget,
            message,
            numResponses,
            timeoutInMiliseconds,
        );
    }
 
    readInfo(): Promise<void> {
        return this.sendMessage({
            command: proto.cmd.GET_SYS_VAL,
            parameters: [0x00, 0x80],
        }, 1)
            .then((data) => {
                this.storage.splice(0x00, 0x80, ...data[0].slice(3));
            });
    }
 
    getField<Field extends keyof ISiStationStorageFields>(
        infoName: Field,
    ): storage.ISiStorageLocations<ISiStationStorageFields>[Field] {
        return this.storage.locations[infoName];
    }
 
    getInfo<Field extends keyof ISiStationStorageFields>(
        infoName: Field,
    ): storage.ISiFieldValue<ISiStationStorageFields[Field]>|undefined {
        return this.storage.get(infoName);
    }
 
    setInfo<Field extends keyof ISiStationStorageFields>(
        infoName: Field,
        newValue: storage.ISiFieldValue<ISiStationStorageFields[Field]>|ISiStationStorageFields[Field],
    ): void {
        this.storage.set(infoName, newValue);
    }
 
    writeChanges(): Promise<void> {
        const newStorage = this.storage.data;
        return this.readInfo()
            .then(() => {
                const oldStorage = this.storage.data;
                return this.writeDiff(oldStorage, newStorage);
            });
    }
 
    atomically(doThings: () => void): Promise<void> {
        return this.readInfo()
            .then(() => {
                const oldStorage = this.storage.data;
                doThings();
                const newStorage = this.storage.data;
                return this.writeDiff(oldStorage, newStorage);
            });
    }
 
    writeDiff(
        oldStorage: storage.ISiStorageData,
        newStorage: storage.ISiStorageData,
    ): Promise<void> {
        const zippedStorageBytes = oldStorage.zip(newStorage);
        const isByteDirty = zippedStorageBytes.map(
            (oldAndNew: [unknown, unknown]) => oldAndNew[0] !== oldAndNew[1],
        );
        const dirtyRanges = isByteDirty.reduce(
            (
                ranges: [number, number][],
                isDirty: boolean,
                byteIndex: number,
            ): [number, number][] => {
                if (!isDirty) {
                    return ranges;
                }
                const numRanges = ranges.length;
                const lastRange = ranges[numRanges - 1];
                if (lastRange && lastRange[1] === byteIndex) {
                    return [
                        ...ranges.slice(0, numRanges - 1),
                        [lastRange[0], byteIndex + 1],
                    ];
                }
                return [
                    ...ranges,
                    [byteIndex, byteIndex + 1],
                ];
            },
            [] as [number, number][],
        );
        let dirtyRangeIndex = 0;
        const processDirtyRanges = (): Promise<void> => {
            if (dirtyRangeIndex >= dirtyRanges.length) {
                return Promise.resolve();
            }
            const dirtyRange = dirtyRanges[dirtyRangeIndex];
            const parameters = [
                dirtyRange[0],
                ...newStorage.slice(dirtyRange[0], dirtyRange[1]),
            ] as number[];
            return this.sendMessage({
                command: proto.cmd.SET_SYS_VAL,
                parameters: parameters,
            }, 1)
                .then((d) => {
                    const data = d[0];
                    data.splice(0, 2);
                    Iif (data[0] !== parameters[0]) {
                        console.warn(`SET_SYS_VAL error: ${data[0]} (expected ${parameters[0]})`);
                    }
                    dirtyRangeIndex += 1;
                    return processDirtyRanges();
                });
        };
        return processDirtyRanges();
    }
 
    getTime(): Promise<Date|undefined> {
        return this.sendMessage({
            command: proto.cmd.GET_TIME,
            parameters: [],
        }, 1)
            .then((d) => siProtocol.arr2date(d[0].slice(2)));
    }
 
    setTime(newTime: Date): Promise<Date|undefined> {
        // TODO: compensate for waiting time
        return this.sendMessage({
            command: proto.cmd.SET_TIME,
            parameters: [...siProtocol.date2arr(newTime)],
        }, 1)
            .then((d) => siProtocol.arr2date(d[0].slice(2)));
 
    }
 
    signal(countArg: number): Promise<void> {
        const count = countArg < 1 ? 1 : countArg;
        return this.sendMessage({
            command: proto.cmd.SIGNAL,
            parameters: [count],
        }, 1)
            .then((data) => {
                if (data[0][2] !== count) {
                    throw new Error('NUM BEEPS');
                }
            });
    }
 
    powerOff(): Promise<number[][]> {
        // Does not power off BSM8 (USB powered), though
        return this.sendMessage({
            command: proto.cmd.OFF,
            parameters: [],
        }, 0);
    }
}