Skip to content

Commit

Permalink
Add checks for incorrect button names/commands
Browse files Browse the repository at this point in the history
  • Loading branch information
BigThunderSR committed Apr 4, 2024
1 parent e8d9a85 commit a05cbbc
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 4 deletions.
4 changes: 4 additions & 0 deletions src/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ class Commands {
}
}

static getFunctionNames() {
return Object.getOwnPropertyNames(this.prototype).filter(name => typeof this.prototype[name] === 'function' && name !== 'constructor');
}

constructor(onstar) {
this.onstar = onstar;
}
Expand Down
20 changes: 17 additions & 3 deletions src/mqtt.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const _ = require('lodash');
//const Buttons = require('./buttons');
const commands = require('./commands');

/**
* Supports Home Assistant MQTT Discovery (https://www.home-assistant.io/docs/mqtt/discovery/)
Expand Down Expand Up @@ -80,11 +80,11 @@ class MQTT {
Icon: 'mdi:archive-lock-open',
},
Start: {
Name: 'start',
Name: 'startVehicle',
Icon: 'mdi:car-key',
},
CancelStart: {
Name: 'cancelStart',
Name: 'cancelStartVehicle',
Icon: 'mdi:car-off',
},
GetLocation: {
Expand Down Expand Up @@ -118,6 +118,18 @@ class MQTT {
}
};

static validateButtonNames() {
const buttonNames = Object.values(MQTT.CONSTANTS.BUTTONS).map(button => button.Name);
const commandNames = commands.getFunctionNames();

buttonNames.forEach(buttonName => {
if (!commandNames.includes(buttonName)) {
//console.log(`Button name "${buttonName}" does not match any command in commands.js`);
throw new Error(`Button name "${buttonName}" does not match any command in commands.js`);
}
});
}

constructor(vehicle, prefix = 'homeassistant', namePrefix) {
this.prefix = prefix;
this.vehicle = vehicle;
Expand Down Expand Up @@ -804,4 +816,6 @@ class MQTT {
}
}

MQTT.validateButtonNames();

module.exports = MQTT;
9 changes: 9 additions & 0 deletions test/commands.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ describe('Commands', () => {
commands = new Commands(onstarMock);
});

it('should return an array of function names', () => {
const functionNames = Commands.getFunctionNames();
assert(Array.isArray(functionNames));
assert(functionNames.length > 0);
functionNames.forEach(name => {
assert(typeof commands[name] === 'function');
});
});

it('should call getAccountVehicles method', async () => {
const result = await commands.getAccountVehicles();
assert.strictEqual(result, undefined);
Expand Down
2 changes: 1 addition & 1 deletion test/mqtt.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1518,4 +1518,4 @@ describe('MQTT', () => {
assert.deepStrictEqual(result, expected);
});
});
});
});

0 comments on commit a05cbbc

Please sign in to comment.