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

Refactor item state presentation format pattern regexp #652

Merged
merged 1 commit into from
Feb 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
}