Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON response not converting to single numeric value #713

Open
Abubakar506 opened this issue Jan 14, 2025 · 0 comments
Open

JSON response not converting to single numeric value #713

Abubakar506 opened this issue Jan 14, 2025 · 0 comments

Comments

@Abubakar506
Copy link

Description of the issue

The Problem is I'm not able to convert the JSON object into single numeric value:
The code is attached.
`// tuya_water_meter.js

const fz = require('zigbee-herdsman-converters/converters/fromZigbee');
const tz = require('zigbee-herdsman-converters/converters/toZigbee');
const exposes = require('zigbee-herdsman-converters/lib/exposes');
const e = exposes.presets;
const ea = exposes.access;
const tuya = require('zigbee-herdsman-converters/lib/tuya');

const converters = {
month_consumption: {
key: ['month_consumption'],
convert: (model, msg, publish, options, meta) => {
try {
// Assuming msg.data is a JSON string
const parsedData = JSON.parse(msg.data);
const totalLiters = Object.values(parsedData).reduce((sum, num) => sum + parseFloat(num), 0);
const totalM3 = totalLiters / 1000;
console.log('Month Consumption (m³):', totalM3);
return totalM3;
} catch (err) {
console.error('Error processing month consumption:', err);
return 0;
}
},
},
daily_consumption: {
key: ['daily_consumption'],
convert: (model, msg, publish, options, meta) => {
try {
const parsedData = JSON.parse(msg.data);
const totalLiters = Object.values(parsedData).reduce((sum, num) => sum + parseFloat(num), 0);
const daysCount = Object.keys(parsedData).length;
const averageDailyM3 = (totalLiters / 1000) / daysCount;
console.log('Daily Consumption (m³):', averageDailyM3);
return averageDailyM3;
} catch (err) {
console.error('Error processing daily consumption:', err);
return 0;
}
},
},
reverse_water_consumption: {
key: ['reverse_water_consumption'],
convert: (model, msg, publish, options, meta) => {
try {
const parsedData = JSON.parse(msg.data);
const totalLiters = Object.values(parsedData).reduce((sum, num) => sum + parseFloat(num), 0);
const totalM3 = totalLiters / 1000;
console.log('Reverse Water Consumption (m³):', totalM3);
return totalM3;
} catch (err) {
console.error('Error processing reverse water consumption:', err);
return 0;
}
},
},
instant_flow_rate: {
key: ['instant_flow_rate'],
convert: (model, msg, publish, options, meta) => {
try {
const parsedData = JSON.parse(msg.data);
const totalLiters = Object.values(parsedData).reduce((sum, num) => sum + parseFloat(num), 0);
const daysCount = Object.keys(parsedData).length || 1; // Prevent division by zero
const averageFlowRate = (totalLiters / 1000) / daysCount;
console.log('Instant Flow Rate (m³/hr):', averageFlowRate);
return averageFlowRate;
} catch (err) {
console.error('Error processing instant flow rate:', err);
return 0;
}
},
},
};

// Device Definition
const definition = {
fingerprint: [
{
modelID: 'TS0601',
manufacturerName: '_TZE200_vuwtqx0t',
},
],
model: 'TS0601',
vendor: 'TuYa',
description: 'Tuya water meter with valve',
fromZigbee: [
tuya.fz.datapoints,
converters.month_consumption,
converters.daily_consumption,
converters.reverse_water_consumption,
converters.instant_flow_rate,
],
toZigbee: [tuya.tz.datapoints],
onEvent: tuya.onEventSetTime,
configure: tuya.configureMagicPacket,
exposes: [
e.numeric('total_water_usage', ea.STATE).withUnit('m³').withDescription('Всего использовано'),
e.numeric('month_consumption', ea.STATE).withUnit('m³').withDescription('Месячное использование'),
e.numeric('daily_consumption', ea.STATE).withUnit('m³').withDescription('Дневное использование'),
e.numeric('month_and_daily_frozen_set', ea.STATE).withDescription('Month Daily Frozen Set'),
e.enum('report_period', ea.STATE_SET, ['1h', '2h', '3h', '4h', '6h', '8h', '12h', '24h']).withDescription('Период отчетов'),
e.text('warning', ea.STATE).withDescription('Предупреждения'), // FIX THIS - BITMAP -> fault types
e.binary('valve_state', ea.STATE_SET, 'ON', 'OFF').withDescription('Управление клапаном'),
e.binary('auto_clean', ea.STATE_SET, 'ON', 'OFF').withDescription('Автоочистка клапана'),
e.text('meter_id', ea.STATE).withDescription('ID счетчика'),
e.numeric('reverse_water_consumption', ea.STATE).withUnit('L').withDescription('Обратное использование воды'),
e.numeric('instant_flow_rate', ea.STATE).withUnit('L/hr').withDescription('Мгновенный поток воды'),
e.temperature().withDescription('Температура воды'),
e.numeric('battery_voltage', ea.STATE).withUnit('V').withDescription('Напряжение батареи'),
],
meta: {
tuyaDatapoints: [
[1, 'total_water_usage', tuya.valueConverter.raw], // dtype number
[2, 'month_consumption', 'month_consumption'], // Reference to custom converter
[3, 'daily_consumption', 'daily_consumption'], // Reference to custom converter
[4, 'report_period', tuya.valueConverterBasic.lookup({
'1h': tuya.enum(0),
'2h': tuya.enum(1),
'3h': tuya.enum(2),
'4h': tuya.enum(3),
'6h': tuya.enum(4),
'8h': tuya.enum(5),
'12h': tuya.enum(6),
'24h': tuya.enum(7),
})],
[5, 'warning', tuya.dataTypes.enum], // bitmap
[6, 'month_and_daily_frozen_set', tuya.valueConverter.raw], // dtype 0 - raw
[13, 'valve_state', tuya.valueConverter.onOff], // Bool - VALVE OPEN CLOSE
[14, 'auto_clean', tuya.valueConverter.onOff], // Bool - AUTOCLEAN SW
[16, 'meter_id', tuya.valueConverter.raw], // dtype 3 - raw METER ID
[18, 'reverse_water_consumption', 'reverse_water_consumption'], // Reference to custom converter
[21, 'instant_flow_rate', 'instant_flow_rate'], // Reference to custom converter
[22, 'temperature', tuya.valueConverter.divideBy100],
[26, 'battery_voltage', tuya.valueConverter.divideBy100],
],
},
};

module.exports = definition;
`
Any help highly appreciated.
Thanks

Addon version

v2.0.0-2

Platform

HassOS

Logs of the issue (if applicable)

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant