Merge pull request #110 from jostrander/main

Fix multiple vehicles in account, add namePrefix for MQTT sensors
This commit is contained in:
Michael Woods 2022-01-09 23:23:51 -05:00 committed by GitHub
commit 4fe7b7978c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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,