Fix multiple vehicles in account, add namePrefix for MQTT sensors

This commit is contained in:
Jesse Ostrander 2022-01-08 20:17:35 -05:00
parent 973988b984
commit 523a4f3a8f
2 changed files with 25 additions and 4 deletions

View File

@ -28,6 +28,7 @@ const mqttConfig = {
port: parseInt(process.env.MQTT_PORT) || 1883,
tls: process.env.MQTT_TLS || false,
prefix: process.env.MQTT_PREFIX || 'homeassistant',
namePrefix: process.env.MQTT_NAME_PREFIX || '',
};
logger.info('MQTT Config', {mqttConfig});
@ -45,6 +46,15 @@ const getVehicles = async commands => {
return vehicles;
}
const getCurrentVehicle = async commands => {
const vehicles = await getVehicles(commands);
const currentVeh = _.find(vehicles, v => v.vin.toLowerCase() === onstarConfig.vin.toLowerCase());
if (!currentVeh) {
throw new Error(`Configured vehicle VIN ${onstarConfig.vin} not available in account vehicles`);
}
return currentVeh;
}
const connectMQTT = async availabilityTopic => {
const url = `${mqttConfig.tls ? 'mqtts' : 'mqtt'}://${mqttConfig.host}:${mqttConfig.port}`;
const config = {
@ -97,9 +107,9 @@ const configureMQTT = async (commands, client, mqttHA) => {
(async () => {
try {
const commands = init();
const vehicles = await getVehicles(commands);
const vehicle = await getCurrentVehicle(commands);
const mqttHA = new MQTT(vehicles[0], 'homeassistant');
const mqttHA = new MQTT(vehicle, mqttConfig.prefix, mqttConfig.namePrefix);
const availTopic = mqttHA.getAvailabilityTopic();
const client = await connectMQTT(availTopic);
client.publish(availTopic, 'true', {retain: true})
@ -109,7 +119,7 @@ const configureMQTT = async (commands, client, mqttHA) => {
const configurations = new Map();
const run = async () => {
const states = new Map();
const v = vehicles[0];
const v = vehicle;
logger.info('Requesting diagnostics');
const statsRes = await commands.diagnostics({diagnosticItem: v.getSupported()});
logger.info('Diagnostic request status', {status: _.get(statsRes, 'status')});

View File

@ -36,10 +36,11 @@ const _ = require('lodash');
* }
*/
class MQTT {
constructor(vehicle, prefix = 'homeassistant') {
constructor(vehicle, prefix = 'homeassistant', namePrefix) {
this.prefix = prefix;
this.vehicle = vehicle;
this.instance = vehicle.vin;
this.namePrefix = namePrefix
}
static convertName(name) {
@ -64,6 +65,15 @@ class MQTT {
}
}
/**
* @param {string} name
* @returns {string}
*/
addNamePrefix(name) {
if (!this.namePrefix) return name
return `${this.namePrefix} ${name}`
}
/**
* @param {'sensor'|'binary_sensor'|'device_tracker'} type
* @returns {string}
@ -143,6 +153,7 @@ class MQTT {
mapBaseConfigPayload(diag, diagEl, device_class, name, attr) {
name = name || MQTT.convertFriendlyName(diagEl.name);
name = this.addNamePrefix(name);
return {
device_class,
name,