Skip to content

Commit

Permalink
prefer "unknown" over "any", fix eslint warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
mathertel committed Jun 17, 2024
1 parent 15197b6 commit 1f0c896
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 53 deletions.
18 changes: 9 additions & 9 deletions server/ConfigCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,24 @@ export class ConfigCache {
public router = express.Router();

private defaultOptions: unknown = { timeout: 4000 };
private options: unknown = {};
private options: { [key: string]: any } = {};

private dService = DeviceDiscovery.getInstance();

// cache for device configurations
private netConfigs: { [hostname: string]: unknown } = {};
private netConfigs: { [hostname: string]: any } = {};


constructor(options: unknown = {}) {
this.options = Object.assign({}, this.defaultOptions, options);

// express function: list all found devices.
this.router.get('/', async(req, res) => {
this.router.get('/', async (req, res) => {
res.json({});
});

// express function: list all found devices.
this.router.get('/:hostname', async(req, res) => {
this.router.get('/:hostname', async (req, res) => {
let cnf = {};
if (req.params.hostname) {
cnf = await this.get(req.params.hostname);
Expand All @@ -55,30 +55,30 @@ export class ConfigCache {
this.netConfigs = {};
}

async get(hostname: string) {
async get(hostname: string): Promise<{ [key: string]: any }> {
const host: string = hostname.replace(/\.local/, '');
if (!this.dService.isOnline(host)) {
Logger.error(`not online: ${host}`); // , err
} else if (!this.netConfigs[host]) {
try {
let eObj: unknown = {}, cObj: unknown = {};
let eObj: { [key: string]: any } = {}, cObj: { [key: string]: any } = {};

const eReq = await fetch(`http://${hostname}/env.json`, { signal: timeoutSignal(this.options.timeout) });
if (eReq.status === 200) {
eObj = await eReq.json();
eObj = await eReq.json() as { [key: string]: any };
}

const cReq = await fetch(`http://${hostname}/config.json`, { signal: timeoutSignal(this.options.timeout) });
if (eReq.status === 200) {
cObj = await cReq.json();
cObj = await cReq.json() as { [key: string]: any };
}

// use device.title as default on all elements
const conf = { ...eObj, ...cObj };
const title = conf.device[0].title;

for (const t in conf) for (const i in conf[t]) {
if (!conf[t][i].title) conf[t][i].title = title;
if (!conf[t][i].title) conf[t][i].title = title;
}


Expand Down
6 changes: 3 additions & 3 deletions server/Discover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class DeviceDiscovery {
public router = express.Router();

private defaultOptions: unknown = { refresh: 1 * 60 };
private options: unknown = {};
private options: { [key: string]: any } = {};

private mdns: mDNS.MulticastDNS;

Expand Down Expand Up @@ -96,7 +96,7 @@ export class DeviceDiscovery {
Logger.trace('Device:', response);
// Logger.trace('Device:', JSON.stringify(response));

const hdd = {
const hdd : { [key: string]: any } = {
host: '',
target: '',
room: '',
Expand Down Expand Up @@ -130,7 +130,7 @@ export class DeviceDiscovery {
.split(',')
.forEach(e => {
const p = e.split('=');
(<unknown>hdd)[p[0]] = p[1];
hdd[p[0]] = p[1];
});
});

Expand Down
14 changes: 7 additions & 7 deletions server/EventBus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class EventBusClass {
this._registry = registry;
}

addElement(typeName: string, id: string, conf: unknown) {
addElement(typeName: string, id: string, conf: { [key: string]: any }) {
Logger.trace(`add ${typeName}/${id}: ${conf}`);
const elem = this._registry?.newElement(typeName, id);
if (elem) {
Expand All @@ -26,13 +26,13 @@ export class EventBusClass {
} // addElement()

/** Activate virtual elements for all configured elements. */
startup(allConfig: unknown) {
startup(allConfig: { [key: string]: any }) {
Object.entries(allConfig).forEach(([typeName, elements]) => {
Object.entries(elements as unknown).forEach(([id, conf]) => {
this.addElement(typeName, id, conf);
Object.entries(elements as any).forEach(([id, conf]) => {
this.addElement(typeName, id, conf as { [key: string]: any });
});
});
Object.entries(this.activeVirtuals).forEach(([_id, _v]) => {
Object.entries(this.activeVirtuals).forEach(([_id, v]) => {
v.doAction({});
});
} // startup()
Expand All @@ -55,7 +55,7 @@ export class EventBusClass {
const e = this.activeVirtuals[typeId];
Logger.trace("execute:", e, args);
if (e) {
const actions = {} as unknown;
const actions:{ [key: string]: any } = {};
args.split('&').forEach(a => {
const [key, val] = a.split('=');
actions[key] = val;
Expand Down Expand Up @@ -92,7 +92,7 @@ export class EventBusClass {

/** return the state of all virtual elements */
async allState() {
const all: unknown = {};
const all: { [key: string]: any } = {};

for (const eId in this.activeVirtuals) {
all[eId] = await this.activeVirtuals[eId].getState();
Expand Down
30 changes: 16 additions & 14 deletions server/HomeDingServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ export class HomeDingServer {
};

// file based settings
private _settings = {} as unknown;
private _settings: { [key: string]: any } = {};
private _boardFileName = '';

/** The current config & state for mocked elements. */
private _allConfig: { [e: string]: unknown; } = {};
private _boardState: unknown = null;
private _allConfig: { [key: string]: any; } = {};
private _boardState: { [key: string]: any } | undefined = undefined;

private _caseFolder?: string;

Expand Down Expand Up @@ -165,11 +165,11 @@ export class HomeDingServer {
JSON.parse(fs.readFileSync(this._caseFolder + 'env.json', 'utf8')),
JSON.parse(fs.readFileSync(this._caseFolder + 'config.json', 'utf8'))
);
this._boardState = null;
this._boardState = undefined;

// ===== watch for changes of $board
fs.watch(this._boardFileName, (_eventName, _filename) => {
this._boardState = null;
this._boardState = undefined;
});
mock.register(this.registry);

Expand Down Expand Up @@ -253,7 +253,7 @@ export class HomeDingServer {
res.send();
/* no await */ this.eventBus.dispatch(id, req.query);
this.eventBus.executeEvents();
} else {
} else if (this._boardState) {
// Update and return status of a single element
this._boardState[id] = Object.assign(this._boardState[id], this.eventBus.state(id));
res.json(this._boardState[id]);
Expand All @@ -270,10 +270,10 @@ export class HomeDingServer {
this._app.get(/^\/api\/elements/, this.expressNoCache, handleElements);

const handleScan = async (_req: express.Request, res: express.Response) => {
const elems = [{"id": "net01"}, {"id": "net02"}, {"id": "net03"}];
const elems = [{ "id": "net01" }, { "id": "net02" }, { "id": "net03" }];
res.json(elems);
}; // handleScan

this._app.get(/^\/api\/scan/, this.expressNoCache, handleScan);


Expand All @@ -292,13 +292,15 @@ export class HomeDingServer {
}
}

// Update status of all elements
const vState = await this.eventBus.allState();
this._boardState = Object.assign(this._boardState, vState);
if (this._boardState) {
// Update status of all elements
const vState = await this.eventBus.allState();
this._boardState = Object.assign(this._boardState, vState);

// debugSend('send:' , boardStatus);
res.type('application/json');
res.send(JSON.stringify(this._boardState, null, 2));
// debugSend('send:' , boardStatus);
res.type('application/json');
res.send(JSON.stringify(this._boardState, null, 2));
}
}; // handleState


Expand Down
28 changes: 14 additions & 14 deletions server/MockElements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { RegistryClass } from './Registry.js';
import { VirtualBaseElement } from './VirtualBaseElement.js';

export class MockSwitch extends VirtualBaseElement {
async doAction(action: unknown) {
async doAction(action: { [key: string]: any }) {
if (action.value != null) { this.state.value = action.value; }
if (action.toggle != null) { this.state.value = (this.state.value ? 0 : 1); }
super.doAction(action);
Expand All @@ -17,7 +17,7 @@ export class MockSwitch extends VirtualBaseElement {
export class MockReference extends VirtualBaseElement {
private _lastState = { reference: undefined, invalue: undefined, value: 0 };

async doAction(action: unknown) {
async doAction(action: { [key: string]: any }) {
if (action.value != null) { this.state.invalue = Number(action.value); }
if (action.reference != null) { this.state.reference = Number(action.reference); }
super.doAction(action);
Expand All @@ -41,7 +41,7 @@ export class MockDHT extends VirtualBaseElement {
private _defaultConfig = { readtime: 60 };
private _lastState = { temperature: undefined, humidity: undefined };

setConfig(bus: EventBusClass, config: unknown) {
setConfig(bus: EventBusClass, config: { [key: string]: any }) {
super.setConfig(bus, config, this._defaultConfig);
// this.state = Object.assign(this.state, {
// temperature: this.config.temperature,
Expand Down Expand Up @@ -83,14 +83,14 @@ export class MockDHT extends VirtualBaseElement {
export class MockValue extends VirtualBaseElement {
private _defaultConfig = { step: 1, value: 0 };

setConfig(bus: EventBusClass, config: unknown) {
setConfig(bus: EventBusClass, config: { [key: string]: any }) {
super.setConfig(bus, config, this._defaultConfig);
this.state = Object.assign(this.state, {
value: this.config.value
});
}

async doAction(action: unknown) {
async doAction(action: { [key: string]: any }) {
const step = this.config.step;
const v = this.state.value;
if (action.value != null) { this.state.value = action.value; }
Expand All @@ -114,15 +114,15 @@ export class MockDevice extends VirtualBaseElement {
return (this.state);
}

async doAction(action: unknown) {
async doAction(action: { [key: string]: any }) {
if (action.log !== null) { Logger.info('>>', action.log); }
super.doAction(action);
}
} // MockDevice


export class MockTime extends VirtualBaseElement {
async getState(): Promise<unknown> {
async getState(): Promise<{ [key: string]: any }> {
const now = new Date().toISOString();
this.state.now =
this.state.value = now.substring(0, 19).replace(/T/, ' ');
Expand All @@ -133,7 +133,7 @@ export class MockTime extends VirtualBaseElement {
export class MockBL0937 extends VirtualBaseElement {
private _defaultConfig = { step: 1, value: 0 };

setConfig(bus: EventBusClass, config: unknown) {
setConfig(bus: EventBusClass, config: { [key: string]: any }) {
super.setConfig(bus, config, this._defaultConfig);
}

Expand All @@ -152,7 +152,7 @@ export class MockBL0937 extends VirtualBaseElement {
return (this.state);
}

async doAction(action: unknown) {
async doAction(action: { [key: string]: any }) {
if ((action.mode === 'current') || (action.mode === 'voltage')) {
this.state.mode = action.mode;
}
Expand All @@ -168,12 +168,12 @@ export class MockStandard extends VirtualBaseElement {
super(typeName, id);
}

setConfig(bus: EventBusClass, config: unknown) {
setConfig(bus: EventBusClass, config: { [key: string]: any }) {
super.setConfig(bus, config);
this.state.value = config.value || 0;
}

async doAction(action: unknown) {
async doAction(action: { [key: string]: any }) {
super.doAction(action);
if (action.value != null) { this.state.value = action.value; }
if (action.mode != null) { this.state.mode = action.mode; }
Expand All @@ -187,14 +187,14 @@ export class MockTimer extends VirtualBaseElement {
restart = false;
startTime = Date.now();

setConfig(bus: EventBusClass, config: unknown) {
setConfig(bus: EventBusClass, config: { [key: string]: any }) {
super.setConfig(bus, config);
this.restart = Boolean(config.restart);
this.state.value = config.value || 0;
this.state.mode = config.mode || 'timer';
}

async doAction(action: unknown) {
async doAction(action: { [key: string]: any }) {
super.doAction(action);
if (action.mode != null) { this.state.mode = action.mode; }
if (action.start != null) {
Expand All @@ -203,7 +203,7 @@ export class MockTimer extends VirtualBaseElement {
}
}

async getState(): Promise<unknown> {
async getState(): Promise<{ [key: string]: any }> {
if (this.state.mode === 'on') {
this.state.value = 1;
} else if (this.state.mode === 'off') {
Expand Down
6 changes: 3 additions & 3 deletions server/ProxyElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class ProxyElement extends VirtualBaseElement {
private TIMEOUT_MS = 3 * 1000; // timeout for getting resaults from a device.
private NEXT_TRY_MS = 8 * 1000; // duration for next data from device

setConfig(_bus: EventBusClass, config: unknown, _default = {}) {
setConfig(_bus: EventBusClass, config: { [key: string]: any }, _default = {}) {
this.eventBus = _bus;
this.config = Object.assign({}, _default, config);

Expand Down Expand Up @@ -77,7 +77,7 @@ export class ProxyElement extends VirtualBaseElement {
} else {
try {
const r = await fetch(this.url, { signal: timeoutSignal(this.TIMEOUT_MS) });
const j = await r.json() as unknown;
const j = await r.json() as { [key: string]: any };
const rs = j[`${this.type}/${this.id}`];
this.state = Object.assign(this.state, rs);
} catch (e) {
Expand All @@ -92,7 +92,7 @@ export class ProxyElement extends VirtualBaseElement {


// pass action to real element
async doAction(action: unknown) {
async doAction(action: { [key: string]: any }) {
for (const a in action) {
await fetch(this.url + '?' + a + '=' + action[a], { signal: timeoutSignal(this.TIMEOUT_MS) });
this.nextTry = 0; // asap.
Expand Down
6 changes: 3 additions & 3 deletions server/VirtualBaseElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@ export class VirtualBaseElement {

protected eventBus!: EventBusClass;

config: unknown;
state: unknown = { active: true };
config: { [key: string]: any } = {};
state: { [key: string]: any } = { active: true };

constructor(type: string, id: string) {
this.type = type;
this.id = id;
this.typeId = `${type}/${id}`;
}

setConfig(_bus: EventBusClass, config: unknown, _default = {}) {
setConfig(_bus: EventBusClass, config: { [key: string]: any }, _default = {}) {
this.eventBus = _bus;
this.config = Object.assign({}, _default, config);
}
Expand Down

0 comments on commit 1f0c896

Please sign in to comment.