Mmmh me parecía, pero no estoy seguro !!^^ lo vuelvo a verificar !!
Edición :
@pierre-gilles, encontré: Case à cochée "Ne pas enregistrer les nouvelles valeurs identiques" + Choix de durée de backup indépendant pour chaque Device Features - #2 par pierre-gilles
Me encantaría intentar ocuparme de eso lo antes posible (lo hice para el servicio Netatmo que funciona en casa y funciona perfectamente). Sería necesario que validaras el principio de funcionamiento, sin embargo, para no empezar algo y tener que volver a hacerlo.
-
Lado front :
- una casilla de verificación en cada función « Registrar solo los cambios de estado »,
- esta casilla está desmarcada de origen para mantenerse como ahora,
-
Lado server :
- si la casilla « Registrar solo los cambios de estado » está marcada, entonces :
- se agrega en la tabla t_device_feature una columna « only_keep_value_changes » que está en 0 de origen,
- o cuando está marcada se agrega un parámetro en device_param :
{
"name": "[id de la feature]:only_keep_value_changes",
"value": true
}
- si el valor de este parámetro es true y el nuevo valor es el mismo que el anterior, se pasa por un nuevo archivo server/lib/device/device.saveLastStateChanged.js para registrar en la tabla t_device_feature el
saveLastStateChanged como me lo pediste en la época del desarrollo de Netatmo :
const db = require('../../models');
const logger = require('../../utils/logger');
const { EVENTS, WEBSOCKET_MESSAGE_TYPES } = require('../../utils/constants');
/**
* @description Save new device feature state in DB.
* @param {Object} deviceFeature - A DeviceFeature object.
* @example
* saveLastValueChanged({
* id: 'fc235c88-b10d-4706-8b59-fef92a7119b2',
* selector: 'my-light'
* });
*/
async function saveLastStateChanged(deviceFeature) {
// logger.debug(`device.saveLastStateChanged of deviceFeature ${deviceFeature.selector}`);
const now = new Date();
// save local state in RAM
this.stateManager.setState('deviceFeature', deviceFeature.selector, {
last_value_changed: now,
});
await db.sequelize.transaction(async (t) => {
// update deviceFeature lastValue in DB
await db.DeviceFeature.update(
{
last_value_changed: now,
},
{
where: {
id: deviceFeature.id,
},
},
{
transaction: t,
},
);
});
// send websocket event
this.eventManager.emit(EVENTS.WEBSOCKET.SEND_ALL, {
type: WEBSOCKET_MESSAGE_TYPES.DEVICE.NEW_STATE_NO_CHANGED,
payload: {
device_feature_selector: deviceFeature.selector,
last_value_changed: now,
},
});
}
module.exports = {
saveLastStateChanged,
};
- Cuando el valor cambia de nuevo, se vuelve a pasar por la función del archivo server/lib/device/device.saveState.js que debemos modificar para volver a registrar, antes del nuevo valor, el valor anterior ya en la base de datos, para tener una curva ajustada :
const db = require('../../models');
const logger = require('../../utils/logger');
const { EVENTS, WEBSOCKET_MESSAGE_TYPES } = require('../../utils/constants');
const { BadParameters } = require('../../utils/coreErrors');
const DEFAULT_OPTIONS = {
skip: 0,
order_dir: 'DESC',
order_by: 'created_at',
};
/**
* @description Save new device feature state in DB.
* @param {Object} deviceFeature - A DeviceFeature object.
* @param {number} newValue - The new value of the deviceFeature to save.
* @example
* saveState({
* id: 'fc235c88-b10d-4706-8b59-fef92a7119b2',
* selector: 'my-light'
* }, 12);
*/
async function saveState(deviceFeature, newValue) {
if (Number.isNaN(newValue)) {
throw new BadParameters(`device.saveState of NaN value on ${deviceFeature.selector}`);
}
const optionsWithDefault = Object.assign({}, DEFAULT_OPTIONS);
// logger.debug(`device.saveState of deviceFeature ${deviceFeature.selector}`);
const now = new Date();
const previousDeviceFeature = this.stateManager.get('deviceFeature', deviceFeature.selector);
const previousDeviceFeatureValue = previousDeviceFeature ? previousDeviceFeature.last_value : null;
const previousDeviceFeatureLastValueChanged = previousDeviceFeature ? previousDeviceFeature.last_value_changed : null;
const deviceFeaturesState = await db.DeviceFeatureState.findOne({
attributes: ['device_feature_id', 'value', 'created_at'],
order: [[optionsWithDefault.order_by, optionsWithDefault.order_dir]],
where: {
device_feature_id: deviceFeature.id,
},
});
const previousDeviceFeatureStateLastValueChanged = deviceFeaturesState ? deviceFeaturesState.created_at : 0;
// save local state in RAM
this.stateManager.setState('deviceFeature', deviceFeature.selector, {
last_value: newValue,
last_value_changed: now,
});
// update deviceFeature lastValue in DB
await db.DeviceFeature.update(
{
last_value: newValue,
last_value_changed: now,
},
{
where: {
id: deviceFeature.id,
},
},
);
// if the deviceFeature should keep history, we save a new deviceFeatureState
if (deviceFeature.keep_history) {
// if the previous created deviceFeatureState is different of deviceFeature
// last value changed, we save a new deviceFeatureState of old state
if (previousDeviceFeatureLastValueChanged - previousDeviceFeatureStateLastValueChanged > 0) {
await db.DeviceFeatureState.create({
device_feature_id: deviceFeature.id,
value: previousDeviceFeatureValue,
created_at: previousDeviceFeatureLastValueChanged,
});
}
await db.DeviceFeatureState.create({
device_feature_id: deviceFeature.id,
value: newValue,
});
}
// });
// send websocket event
this.eventManager.emit(EVENTS.WEBSOCKET.SEND_ALL, {
type: WEBSOCKET_MESSAGE_TYPES.DEVICE.NEW_STATE,
payload: {
device_feature_selector: deviceFeature.selector,
last_value: newValue,
last_value_changed: now,
},
});
// check if there is a trigger matching
this.eventManager.emit(EVENTS.TRIGGERS.CHECK, {
type: EVENTS.DEVICE.NEW_STATE,
device_feature: deviceFeature.selector,
previous_value: previousDeviceFeatureValue,
last_value: newValue,
last_value_changed: now,
});
}
module.exports = {
saveState,
};
exemplo, si recibimos para una potencia consumida :
{
value: 1014.7,
created_at: 2022-04-19 04:20:13.277 +00:00
},
{
value: 1014.9,
created_at: 2022-04-19 04:30:13.277 +00:00
},
{
value: 1014.9,
created_at: 2022-04-19 04:40:13.277 +00:00
},
{
value: 1014.9,
created_at: 2022-04-19 04:50:13.277 +00:00
},
{
value: 1014.9,
created_at: 2022-04-19 05:00:13.277 +00:00
},
{
value: 1014.9,
created_at: 2022-04-19 05:10:13.277 +00:00
},
{
value: 78.0,
created_at: 2022-04-19 05:20:13.277 +00:00
}
Encontraríamos en la base de datos solo
{
value: 1014.7,
created_at: 2022-04-19 04:20:13.277 +00:00
},
{
value: 1014.9,
created_at: 2022-04-19 04:30:13.277 +00:00
},
// aquí no se guardaron los valores idénticos
{
value: 1014.9,
created_at: 2022-04-19 05:10:13.277 +00:00
},
// Después de escribir el valor de abajo, se volvió a enviar
{
value: 78.0,
created_at: 2022-04-19 05:20:13.277 +00:00
}
¿O lo ves de otra manera? En ese caso, ¿tendrías aproximadamente la línea a seguir?