Skip to content

Commit

Permalink
Refactor item state presentation format pattern regexp (#652)
Browse files Browse the repository at this point in the history
Signed-off-by: jsetton <jeremy.setton@gmail.com>
  • Loading branch information
jsetton authored Feb 1, 2024
1 parent 53770ab commit f618a25
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lambda/openhab/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ import { ItemType, ItemValue, UnitSymbol } from './constants.js';
* Defines openHAB class
*/
export default class OpenHAB {
/**
* Defines item state presentation format pattern
* @type {RegExp}
*/
static #STATE_PRESENTATION_PATTERN =
/%\d*(?:\.(?<precision>\d+))?(?<specifier>[df])\s*(?:%unit%|[%]?(?<symbol>.+))?$/;

/**
* Constructor
* @param {Object} config
Expand Down Expand Up @@ -246,7 +253,7 @@ export default class OpenHAB {
const type = (item.groupType || item.type).split(':')[0];

if (type === ItemType.DIMMER || type === ItemType.NUMBER || type === ItemType.ROLLERSHUTTER) {
const precision = OpenHAB.getStatePresentationPrecision(item.stateDescription?.pattern);
const precision = this.getStatePresentationPrecision(item.stateDescription?.pattern);
const value = parseFloat(state);

return isNaN(precision) ? value.toString() : value.toFixed(precision);
Expand All @@ -262,7 +269,7 @@ export default class OpenHAB {
* @return {Number}
*/
static getStatePresentationPrecision(pattern) {
const { precision, specifier } = pattern?.match(/%\d*(?:\.(?<precision>\d+))?(?<specifier>[df])/)?.groups || {};
const { precision, specifier } = pattern?.match(this.#STATE_PRESENTATION_PATTERN)?.groups || {};
return specifier === 'd' ? 0 : precision <= 16 ? parseInt(precision) : NaN;
}

Expand All @@ -273,8 +280,7 @@ export default class OpenHAB {
* @return {String}
*/
static getStatePresentationUnitSymbol(pattern) {
return Object.values(UnitSymbol).find((symbol) =>
new RegExp(`%\\d*(?:\\.\\d+)?[df]\\s*[%]?${symbol}$`).test(pattern)
);
const { symbol } = pattern?.match(this.#STATE_PRESENTATION_PATTERN)?.groups || {};
return Object.values(UnitSymbol).includes(symbol) ? symbol : undefined;
}
}

0 comments on commit f618a25

Please sign in to comment.