mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-22 22:02:38 +03:00
feat(new tools): 4-20 mA, 0-10 V and analog scaling converters (#596)
Add an Automation category with three tools for PLC programmers and instrumentation technicians, built on a shared AnalogSignalConverter component and a tested src/utils/analog-signal.ts module: - 4-20 mA converter: current <-> engineering value, 4-20 / 0-20 mA, with the NAMUR NE 43 loop diagnostic (failure, undefined zone, under/over-range) - 0-10 V converter: 0-10, 2-10, 0-5, 1-5 and ±10 V, warns below the live zero (broken wire) - Analog scaling calculator: raw PLC values (Siemens 0-27648 / ±27648, Schneider 0-10000, 12/15/16 bits) <-> engineering value, with the rounded raw value Three-column layout: input, parameters and output, each side with a gauge and a coloured status. A swap button inverts the conversion direction and keeps the operating point. Also shows the y = gain × x + offset formula for the PLC and a 0-25-50-75-100 % reference table. Ranges are validated (min < max). English and French translations.
This commit is contained in:
1 parent
e7758934a8
commit
b5eace85db
15 files changed
+1137
No files matched your search
@@ -5177,6 +5177,7 @@ tools:
|
||||
RAID 0 splits data evenly across 2 or more disks without redunancy or
|
||||
fault tolerance creating one large storage space.
|
||||
categories:
|
||||
automation: Automation
|
||||
favorite-tools: Your favorite tools
|
||||
crypto: Crypto
|
||||
converter: Converter
|
||||
@@ -5207,6 +5208,27 @@ tools:
|
||||
finance: Finance
|
||||
default: Default
|
||||
toml: TOML
|
||||
current-loop-4-20ma-converter:
|
||||
title: 4-20 mA converter
|
||||
description: Convert a 4-20 mA (or 0-20 mA) current into an engineering value and back, with NAMUR NE 43 loop diagnostic.
|
||||
texts:
|
||||
signal-label: Current
|
||||
voltage-0-10v-converter:
|
||||
title: 0-10 V converter
|
||||
description: Convert a 0-10 V, 2-10 V, 0-5 V, 1-5 V or ±10 V voltage into an engineering value and back.
|
||||
texts:
|
||||
signal-label: Voltage
|
||||
analog-scaling-calculator:
|
||||
title: Analog scaling calculator
|
||||
description: Scale a raw PLC analog value (Siemens 0-27648, Schneider 0-10000, 12/15/16 bits...) into an engineering value and back.
|
||||
texts:
|
||||
signal-label: Raw value
|
||||
preset-siemens-unipolar: Siemens S7 unipolar (0 to 27648)
|
||||
preset-siemens-bipolar: Siemens S7 bipolar (-27648 to 27648)
|
||||
preset-schneider: Schneider M340/M580 (0 to 10000)
|
||||
preset-12-bits: 12 bits (0 to 4095)
|
||||
preset-15-bits: 15 bits (0 to 32767)
|
||||
preset-16-bits: 16 bits (0 to 65535)
|
||||
websocket-tester:
|
||||
title: Websocket tester
|
||||
description: Allows to test WebSocket connections
|
||||
@@ -10108,6 +10130,39 @@ tools:
|
||||
description: Test your speakers and headphones by playing test sounds. Adjust
|
||||
volume and check for audio clarity.
|
||||
externalAccess: "null"
|
||||
analogSignalConverter:
|
||||
texts:
|
||||
title-input: Input
|
||||
title-parameters: Parameters
|
||||
title-output: Output
|
||||
swap-direction: Swap direction
|
||||
status-ok: In range
|
||||
copy-output: Copy the output value
|
||||
title-reference-points: Reference points
|
||||
label-signal-type: Signal type
|
||||
preset-custom: Custom
|
||||
label-engineering-range: Engineering min / max
|
||||
label-engineering-unit: Engineering unit
|
||||
placeholder-unit: Unit
|
||||
error-signal-range: The signal min must be lower than the signal max.
|
||||
error-engineering-range: The engineering min must be lower than the engineering max.
|
||||
label-engineering-value: Engineering value
|
||||
label-rounded-signal: Rounded (integer)
|
||||
status-below-range: The signal is below the range.
|
||||
status-above-range: The signal is above the range.
|
||||
status-below-live-zero: The signal is below the live zero, check for a broken wire or a faulty sensor.
|
||||
engineering-below-range: The value is below the engineering range, the signal will be out of range.
|
||||
engineering-above-range: The value is above the engineering range, the signal will be out of range.
|
||||
loop-status-failure-low: "Low failure (≤ 3.6 mA, NAMUR NE 43): broken loop, unpowered or faulty transmitter."
|
||||
loop-status-uncertain-low: "Between 3.6 and 3.8 mA: undefined zone, a failure is likely (NAMUR NE 43)."
|
||||
loop-status-under-range: "Under-range (3.8 to 4 mA): the measurement is saturated at the bottom of the range."
|
||||
loop-status-over-range: "Over-range (20 to 20.5 mA): the measurement is saturated at the top of the range."
|
||||
loop-status-uncertain-high: "Between 20.5 and 21 mA: undefined zone, a failure is likely (NAMUR NE 43)."
|
||||
loop-status-failure-high: "High failure (≥ 21 mA, NAMUR NE 43): faulty transmitter or short circuit."
|
||||
label-formula: Formula
|
||||
formula-value: value
|
||||
formula-signal: signal
|
||||
column-percent: Range
|
||||
collapsibleToolMenu:
|
||||
text:
|
||||
expanding: Expanding...
|
||||
|
||||
@@ -147,6 +147,7 @@ tools:
|
||||
label-jpeg: JPEG
|
||||
label-webp: WebP
|
||||
categories:
|
||||
automation: Automatisme
|
||||
favorite-tools: Vos outils favoris
|
||||
crypto: Cryptographie
|
||||
converter: Convertisseur
|
||||
@@ -177,6 +178,27 @@ tools:
|
||||
finance: Finance
|
||||
default: Défaut
|
||||
toml: TOML
|
||||
current-loop-4-20ma-converter:
|
||||
title: Convertisseur 4-20 mA
|
||||
description: Convertir un courant 4-20 mA (ou 0-20 mA) en valeur physique et inversement, avec le diagnostic de boucle NAMUR NE 43.
|
||||
texts:
|
||||
signal-label: Courant
|
||||
voltage-0-10v-converter:
|
||||
title: Convertisseur 0-10 V
|
||||
description: Convertir une tension 0-10 V, 2-10 V, 0-5 V, 1-5 V ou ±10 V en valeur physique et inversement.
|
||||
texts:
|
||||
signal-label: Tension
|
||||
analog-scaling-calculator:
|
||||
title: Mise à l'échelle analogique
|
||||
description: Convertir une valeur brute d'entrée analogique d'automate (Siemens 0-27648, Schneider 0-10000, 12/15/16 bits...) en valeur physique et inversement.
|
||||
texts:
|
||||
signal-label: Valeur brute
|
||||
preset-siemens-unipolar: Siemens S7 unipolaire (0 à 27648)
|
||||
preset-siemens-bipolar: Siemens S7 bipolaire (-27648 à 27648)
|
||||
preset-schneider: Schneider M340/M580 (0 à 10000)
|
||||
preset-12-bits: 12 bits (0 à 4095)
|
||||
preset-15-bits: 15 bits (0 à 32767)
|
||||
preset-16-bits: 16 bits (0 à 65535)
|
||||
token-generator:
|
||||
title: Générateur de token
|
||||
description: Génère une chaîne aléatoire avec les caractères que vous voulez,
|
||||
@@ -10558,6 +10580,39 @@ textareaCopyable:
|
||||
download: Télécharger
|
||||
locale-selector:
|
||||
select-a-language: Sélectionnez une langue
|
||||
analogSignalConverter:
|
||||
texts:
|
||||
title-input: Entrée
|
||||
title-parameters: Paramètres
|
||||
title-output: Sortie
|
||||
swap-direction: Inverser le sens
|
||||
status-ok: Dans la plage
|
||||
copy-output: Copier la valeur de sortie
|
||||
title-reference-points: Points de référence
|
||||
label-signal-type: Type de signal
|
||||
preset-custom: Personnalisé
|
||||
label-engineering-range: Plage physique min / max
|
||||
label-engineering-unit: Unité physique
|
||||
placeholder-unit: Unité
|
||||
error-signal-range: Le min du signal doit être inférieur au max du signal.
|
||||
error-engineering-range: Le min de la plage physique doit être inférieur au max.
|
||||
label-engineering-value: Valeur physique
|
||||
label-rounded-signal: Arrondi (entier)
|
||||
status-below-range: Le signal est sous la plage.
|
||||
status-above-range: Le signal est au-dessus de la plage.
|
||||
status-below-live-zero: Le signal est sous le zéro décalé, vérifier une rupture de fil ou un capteur en défaut.
|
||||
engineering-below-range: La valeur est sous la plage physique, le signal sera hors plage.
|
||||
engineering-above-range: La valeur est au-dessus de la plage physique, le signal sera hors plage.
|
||||
loop-status-failure-low: "Défaut bas (≤ 3,6 mA, NAMUR NE 43) : boucle coupée, transmetteur non alimenté ou en défaut."
|
||||
loop-status-uncertain-low: "Entre 3,6 et 3,8 mA : zone indéterminée, défaut probable (NAMUR NE 43)."
|
||||
loop-status-under-range: "Sous-échelle (3,8 à 4 mA) : mesure saturée en bas de plage."
|
||||
loop-status-over-range: "Sur-échelle (20 à 20,5 mA) : mesure saturée en haut de plage."
|
||||
loop-status-uncertain-high: "Entre 20,5 et 21 mA : zone indéterminée, défaut probable (NAMUR NE 43)."
|
||||
loop-status-failure-high: "Défaut haut (≥ 21 mA, NAMUR NE 43) : transmetteur en défaut ou court-circuit."
|
||||
label-formula: Formule
|
||||
formula-value: valeur
|
||||
formula-signal: signal
|
||||
column-percent: Plage
|
||||
collapsibleToolMenu:
|
||||
text:
|
||||
expanding: Réduire...
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
<script setup lang="ts">
|
||||
import { useThemeVars } from 'naive-ui';
|
||||
import { formatSignalNumber } from '@/utils/analog-signal';
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
min: number;
|
||||
max: number;
|
||||
value: number;
|
||||
unit?: string;
|
||||
status?: 'ok' | 'warning' | 'error';
|
||||
}>(),
|
||||
{
|
||||
unit: '',
|
||||
status: 'ok',
|
||||
},
|
||||
);
|
||||
|
||||
const themeVars = useThemeVars();
|
||||
|
||||
const isValid = computed(() => Number.isFinite(props.min) && Number.isFinite(props.max) && props.min !== props.max);
|
||||
|
||||
// Position in the range, in percent; may go outside of 0-100 when the value is out of range.
|
||||
const percent = computed(() =>
|
||||
isValid.value && Number.isFinite(props.value)
|
||||
? ((props.value - props.min) / (props.max - props.min)) * 100
|
||||
: Number.NaN,
|
||||
);
|
||||
const clampedPercent = computed(() => (Number.isFinite(percent.value) ? Math.min(100, Math.max(0, percent.value)) : 0));
|
||||
const isOutOfRange = computed(() => percent.value < 0 || percent.value > 100);
|
||||
|
||||
const fillColor = computed(
|
||||
() =>
|
||||
({
|
||||
ok: themeVars.value.primaryColor,
|
||||
warning: themeVars.value.warningColor,
|
||||
error: themeVars.value.errorColor,
|
||||
})[props.status],
|
||||
);
|
||||
|
||||
const withUnit = (value: number) => `${formatSignalNumber(value)}${props.unit ? ` ${props.unit}` : ''}`;
|
||||
const middle = computed(() => (props.min + props.max) / 2);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="analog-gauge" :class="{ 'out-of-range': isOutOfRange }" data-test-id="gauge">
|
||||
<div class="scale">
|
||||
<span>{{ withUnit(max) }}</span>
|
||||
<span>{{ withUnit(middle) }}</span>
|
||||
<span>{{ withUnit(min) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="tube" role="meter" :aria-valuemin="min" :aria-valuemax="max" :aria-valuenow="value">
|
||||
<div class="fill" :style="{ height: `${clampedPercent}%`, backgroundColor: fillColor }" />
|
||||
<div class="tick" style="bottom: 25%" />
|
||||
<div class="tick" style="bottom: 50%" />
|
||||
<div class="tick" style="bottom: 75%" />
|
||||
</div>
|
||||
|
||||
<div class="marker-track">
|
||||
<div v-if="Number.isFinite(percent)" class="marker" :style="{ bottom: `${clampedPercent}%`, color: fillColor }">
|
||||
◄ {{ formatSignalNumber(percent, 1) }} %
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.analog-gauge {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
height: 200px;
|
||||
margin: 16px 0;
|
||||
|
||||
.scale {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
align-items: flex-end;
|
||||
font-size: 12px;
|
||||
opacity: 0.7;
|
||||
white-space: nowrap;
|
||||
// Labels sit on the top, middle and bottom lines of the tube
|
||||
margin: -8px 0;
|
||||
}
|
||||
|
||||
.tube {
|
||||
position: relative;
|
||||
width: 28px;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
background-color: v-bind('themeVars.buttonColor2');
|
||||
border: 1px solid v-bind('themeVars.borderColor');
|
||||
|
||||
.fill {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
transition:
|
||||
height 0.25s ease-out,
|
||||
background-color 0.25s;
|
||||
}
|
||||
|
||||
.tick {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
width: 8px;
|
||||
height: 1px;
|
||||
background-color: v-bind('themeVars.textColor3');
|
||||
}
|
||||
}
|
||||
|
||||
.marker-track {
|
||||
position: relative;
|
||||
width: 72px;
|
||||
|
||||
.marker {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
transform: translateY(50%);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
transition: bottom 0.25s ease-out;
|
||||
}
|
||||
}
|
||||
|
||||
&.out-of-range .tube {
|
||||
border-color: v-bind('fillColor');
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,468 @@
|
||||
<script setup lang="ts">
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import { useThemeVars } from 'naive-ui';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import AnalogGauge from './AnalogGauge.vue';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
import {
|
||||
type SignalRange,
|
||||
formatSignalNumber,
|
||||
getCurrentLoopStatus,
|
||||
getLinearTransform,
|
||||
getSignalRangeStatus,
|
||||
scaleValue,
|
||||
} from '@/utils/analog-signal';
|
||||
|
||||
export interface SignalPreset {
|
||||
label: string;
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
type Direction = 'signal-to-value' | 'value-to-signal';
|
||||
type Side = 'signal' | 'engineering';
|
||||
interface SideStatus {
|
||||
type: 'ok' | 'warning' | 'error';
|
||||
message: string;
|
||||
}
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
storageKey: string;
|
||||
signalLabel: string;
|
||||
signalUnit?: string;
|
||||
presets: SignalPreset[];
|
||||
defaultEngineering?: SignalRange & { unit: string };
|
||||
// The signal is an integer register (raw PLC value): also show the rounded value.
|
||||
integerSignal?: boolean;
|
||||
// Apply the NAMUR NE 43 diagnostic when the signal range is 4-20 mA.
|
||||
currentLoopDiagnostic?: boolean;
|
||||
}>(),
|
||||
{
|
||||
signalUnit: '',
|
||||
defaultEngineering: () => ({ min: 0, max: 100, unit: '%' }),
|
||||
integerSignal: false,
|
||||
currentLoopDiagnostic: false,
|
||||
},
|
||||
);
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const themeVars = useThemeVars();
|
||||
|
||||
const defaultPreset = props.presets[0] ?? { label: '', min: 0, max: 10 };
|
||||
|
||||
const signalMin = useStorage<number | null>(`${props.storageKey}:signal-min`, defaultPreset.min);
|
||||
const signalMax = useStorage<number | null>(`${props.storageKey}:signal-max`, defaultPreset.max);
|
||||
const engineeringMin = useStorage<number | null>(`${props.storageKey}:engineering-min`, props.defaultEngineering.min);
|
||||
const engineeringMax = useStorage<number | null>(`${props.storageKey}:engineering-max`, props.defaultEngineering.max);
|
||||
const engineeringUnit = useStorage(`${props.storageKey}:engineering-unit`, props.defaultEngineering.unit);
|
||||
const direction = useStorage<Direction>(`${props.storageKey}:direction`, 'signal-to-value');
|
||||
|
||||
const toNumber = (value: number | null | undefined) => (typeof value === 'number' ? value : Number.NaN);
|
||||
|
||||
const signalRange = computed<SignalRange>(() => ({ min: toNumber(signalMin.value), max: toNumber(signalMax.value) }));
|
||||
const engineeringRange = computed<SignalRange>(() => ({
|
||||
min: toNumber(engineeringMin.value),
|
||||
max: toNumber(engineeringMax.value),
|
||||
}));
|
||||
const rangeOf = (side: Side) => (side === 'signal' ? signalRange.value : engineeringRange.value);
|
||||
const unitOf = (side: Side) => (side === 'signal' ? props.signalUnit : engineeringUnit.value);
|
||||
const labelOf = (side: Side) =>
|
||||
side === 'signal' ? props.signalLabel : t('analogSignalConverter.texts.label-engineering-value');
|
||||
|
||||
const inputSide = computed<Side>(() => (direction.value === 'signal-to-value' ? 'signal' : 'engineering'));
|
||||
const outputSide = computed<Side>(() => (direction.value === 'signal-to-value' ? 'engineering' : 'signal'));
|
||||
|
||||
const midpoint = ({ min, max }: SignalRange) => (min + max) / 2;
|
||||
const inputValue = ref<number | null>(midpoint(rangeOf(inputSide.value)));
|
||||
|
||||
// Min must be strictly lower than max: an inverted range is almost always a typo.
|
||||
const isRangeValid = (range: SignalRange) =>
|
||||
Number.isFinite(range.min) && Number.isFinite(range.max) && range.min < range.max;
|
||||
|
||||
const isSignalRangeInvalid = computed(() => !isRangeValid(signalRange.value));
|
||||
const isEngineeringRangeInvalid = computed(() => !isRangeValid(engineeringRange.value));
|
||||
|
||||
const rangesError = computed(() => {
|
||||
if (!isRangeValid(signalRange.value)) {
|
||||
return t('analogSignalConverter.texts.error-signal-range');
|
||||
}
|
||||
if (!isRangeValid(engineeringRange.value)) {
|
||||
return t('analogSignalConverter.texts.error-engineering-range');
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
const outputValue = computed(() => {
|
||||
const value = toNumber(inputValue.value);
|
||||
if (rangesError.value || !Number.isFinite(value)) {
|
||||
return Number.NaN;
|
||||
}
|
||||
return scaleValue({ value, from: rangeOf(inputSide.value), to: rangeOf(outputSide.value) });
|
||||
});
|
||||
|
||||
const valueOf = (side: Side) => (side === inputSide.value ? toNumber(inputValue.value) : outputValue.value);
|
||||
|
||||
// Swapping keeps the current operating point: the output becomes the new input.
|
||||
function swapDirection() {
|
||||
const previousOutput = outputValue.value;
|
||||
direction.value = direction.value === 'signal-to-value' ? 'value-to-signal' : 'signal-to-value';
|
||||
inputValue.value = Number.isFinite(previousOutput)
|
||||
? Number(formatSignalNumber(previousOutput))
|
||||
: midpoint(rangeOf(inputSide.value));
|
||||
}
|
||||
|
||||
const CUSTOM_PRESET = 'custom';
|
||||
const presetOptions = computed(() => [
|
||||
...props.presets.map(({ label }, index) => ({ label, value: String(index) })),
|
||||
{ label: t('analogSignalConverter.texts.preset-custom'), value: CUSTOM_PRESET },
|
||||
]);
|
||||
|
||||
const selectedPreset = computed({
|
||||
get() {
|
||||
const index = props.presets.findIndex(({ min, max }) => min === signalMin.value && max === signalMax.value);
|
||||
return index === -1 ? CUSTOM_PRESET : String(index);
|
||||
},
|
||||
set(value: string) {
|
||||
const preset = props.presets[Number(value)];
|
||||
if (preset) {
|
||||
signalMin.value = preset.min;
|
||||
signalMax.value = preset.max;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const isCurrentLoop = computed(
|
||||
() => props.currentLoopDiagnostic && signalRange.value.min === 4 && signalRange.value.max === 20,
|
||||
);
|
||||
|
||||
function getSignalStatus(value: number): SideStatus {
|
||||
if (isCurrentLoop.value) {
|
||||
const status = getCurrentLoopStatus(value);
|
||||
if (status === 'ok') {
|
||||
return { type: 'ok', message: t('analogSignalConverter.texts.status-ok') };
|
||||
}
|
||||
return {
|
||||
type: status.startsWith('failure') ? 'error' : 'warning',
|
||||
message: t(`analogSignalConverter.texts.loop-status-${status}`),
|
||||
};
|
||||
}
|
||||
|
||||
const status = getSignalRangeStatus({ value, range: signalRange.value });
|
||||
if (status === 'ok') {
|
||||
return { type: 'ok', message: t('analogSignalConverter.texts.status-ok') };
|
||||
}
|
||||
// A live zero (e.g. 2-10 V) lets a value under the minimum reveal a broken wire.
|
||||
const hasLiveZero = Math.min(signalRange.value.min, signalRange.value.max) > 0;
|
||||
return {
|
||||
type: 'warning',
|
||||
message:
|
||||
status === 'below-range' && hasLiveZero
|
||||
? t('analogSignalConverter.texts.status-below-live-zero')
|
||||
: t(`analogSignalConverter.texts.status-${status}`),
|
||||
};
|
||||
}
|
||||
|
||||
function getEngineeringStatus(value: number): SideStatus {
|
||||
const status = getSignalRangeStatus({ value, range: engineeringRange.value });
|
||||
return status === 'ok'
|
||||
? { type: 'ok', message: t('analogSignalConverter.texts.status-ok') }
|
||||
: { type: 'warning', message: t(`analogSignalConverter.texts.engineering-${status}`) };
|
||||
}
|
||||
|
||||
function statusOf(side: Side): SideStatus | null {
|
||||
const value = valueOf(side);
|
||||
if (rangesError.value || !Number.isFinite(value)) {
|
||||
return null;
|
||||
}
|
||||
return side === 'signal' ? getSignalStatus(value) : getEngineeringStatus(value);
|
||||
}
|
||||
|
||||
const inputStatus = computed(() => statusOf(inputSide.value));
|
||||
const outputStatus = computed(() => statusOf(outputSide.value));
|
||||
|
||||
const formatWithUnit = (value: number, unit: string) =>
|
||||
Number.isFinite(value) ? `${formatSignalNumber(value)}${unit ? ` ${unit}` : ''}` : '';
|
||||
const withUnit = (label: string, unit: string) => (unit ? `${label} (${unit})` : label);
|
||||
|
||||
const outputText = computed(() => formatWithUnit(outputValue.value, unitOf(outputSide.value)));
|
||||
const roundedOutputText = computed(() =>
|
||||
props.integerSignal && outputSide.value === 'signal' && Number.isFinite(outputValue.value)
|
||||
? formatWithUnit(Math.round(outputValue.value), props.signalUnit)
|
||||
: '',
|
||||
);
|
||||
const { copy: copyOutput } = useCopy({ source: () => formatSignalNumber(outputValue.value) });
|
||||
|
||||
// Significant digits rather than decimals: Siemens gains such as 100 / 27648 are tiny.
|
||||
const formatCoefficient = (value: number) => String(Number(value.toPrecision(10)));
|
||||
|
||||
const formula = computed(() => {
|
||||
if (rangesError.value) {
|
||||
return '';
|
||||
}
|
||||
const { gain, offset } = getLinearTransform({ from: rangeOf(inputSide.value), to: rangeOf(outputSide.value) });
|
||||
const names = {
|
||||
signal: t('analogSignalConverter.texts.formula-signal'),
|
||||
engineering: t('analogSignalConverter.texts.formula-value'),
|
||||
};
|
||||
const product = `${names[outputSide.value]} = ${formatCoefficient(gain)} × ${names[inputSide.value]}`;
|
||||
return formatCoefficient(offset) === '0'
|
||||
? product
|
||||
: `${product} ${offset < 0 ? '-' : '+'} ${formatCoefficient(Math.abs(offset))}`;
|
||||
});
|
||||
|
||||
const referencePoints = computed(() => {
|
||||
if (rangesError.value) {
|
||||
return [];
|
||||
}
|
||||
return [0, 25, 50, 75, 100].map((percent) => {
|
||||
const signal = scaleValue({ value: percent, from: { min: 0, max: 100 }, to: signalRange.value });
|
||||
const value = scaleValue({ value: percent, from: { min: 0, max: 100 }, to: engineeringRange.value });
|
||||
return {
|
||||
percent: `${percent} %`,
|
||||
signal: formatWithUnit(props.integerSignal ? Math.round(signal) : signal, props.signalUnit),
|
||||
value: formatWithUnit(value, engineeringUnit.value),
|
||||
};
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div flex flex-col gap-3>
|
||||
<div class="converter-columns">
|
||||
<!-- Input -->
|
||||
<c-card class="column" :title="t('analogSignalConverter.texts.title-input')">
|
||||
<div class="side-label">
|
||||
{{ withUnit(labelOf(inputSide), unitOf(inputSide)) }}
|
||||
</div>
|
||||
<n-input-number-i18n v-model:value="inputValue" size="large" data-test-id="converter-input" />
|
||||
|
||||
<AnalogGauge
|
||||
v-if="!rangesError"
|
||||
:min="rangeOf(inputSide).min"
|
||||
:max="rangeOf(inputSide).max"
|
||||
:value="valueOf(inputSide)"
|
||||
:unit="unitOf(inputSide)"
|
||||
:status="inputStatus?.type"
|
||||
data-test-id="input-gauge"
|
||||
/>
|
||||
|
||||
<div v-if="inputStatus" class="status" :class="inputStatus.type" data-test-id="input-status">
|
||||
<icon-mdi-check-circle v-if="inputStatus.type === 'ok'" />
|
||||
<icon-mdi-alert v-else />
|
||||
<span>{{ inputStatus.message }}</span>
|
||||
</div>
|
||||
</c-card>
|
||||
|
||||
<!-- Parameters -->
|
||||
<c-card class="column" :title="t('analogSignalConverter.texts.title-parameters')">
|
||||
<!-- c-select keeps the label it was mounted with: remount it when the language changes -->
|
||||
<c-select
|
||||
:key="locale"
|
||||
v-model:value="selectedPreset"
|
||||
:options="presetOptions"
|
||||
:label="t('analogSignalConverter.texts.label-signal-type')"
|
||||
data-test-id="signal-preset"
|
||||
/>
|
||||
|
||||
<div class="side-label" mt-3>
|
||||
{{ withUnit(`${signalLabel} min / max`, signalUnit) }}
|
||||
</div>
|
||||
<div flex gap-2>
|
||||
<n-input-number-i18n
|
||||
v-model:value="signalMin"
|
||||
:status="isSignalRangeInvalid ? 'error' : undefined"
|
||||
flex-1
|
||||
:show-button="false"
|
||||
data-test-id="signal-min"
|
||||
/>
|
||||
<n-input-number-i18n
|
||||
v-model:value="signalMax"
|
||||
:status="isSignalRangeInvalid ? 'error' : undefined"
|
||||
flex-1
|
||||
:show-button="false"
|
||||
data-test-id="signal-max"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="swap" my-4>
|
||||
<c-button
|
||||
round
|
||||
:title="t('analogSignalConverter.texts.swap-direction')"
|
||||
data-test-id="swap-direction"
|
||||
@click="swapDirection"
|
||||
>
|
||||
<icon-mdi-swap-horizontal text-20px />
|
||||
<span ml-2>{{ t('analogSignalConverter.texts.swap-direction') }}</span>
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<div class="side-label">
|
||||
{{ t('analogSignalConverter.texts.label-engineering-range') }}
|
||||
</div>
|
||||
<div flex gap-2>
|
||||
<n-input-number-i18n
|
||||
v-model:value="engineeringMin"
|
||||
:status="isEngineeringRangeInvalid ? 'error' : undefined"
|
||||
flex-1
|
||||
:show-button="false"
|
||||
data-test-id="engineering-min"
|
||||
/>
|
||||
<n-input-number-i18n
|
||||
v-model:value="engineeringMax"
|
||||
:status="isEngineeringRangeInvalid ? 'error' : undefined"
|
||||
flex-1
|
||||
:show-button="false"
|
||||
data-test-id="engineering-max"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<c-input-text
|
||||
v-model:value="engineeringUnit"
|
||||
:label="t('analogSignalConverter.texts.label-engineering-unit')"
|
||||
:placeholder="t('analogSignalConverter.texts.placeholder-unit')"
|
||||
mt-3
|
||||
data-test-id="engineering-unit"
|
||||
/>
|
||||
|
||||
<c-alert v-if="rangesError" type="error" mt-3>
|
||||
{{ rangesError }}
|
||||
</c-alert>
|
||||
|
||||
<input-copyable
|
||||
v-else
|
||||
:label="t('analogSignalConverter.texts.label-formula')"
|
||||
:value="formula"
|
||||
mt-3
|
||||
data-test-id="formula"
|
||||
/>
|
||||
</c-card>
|
||||
|
||||
<!-- Output -->
|
||||
<c-card class="column" :title="t('analogSignalConverter.texts.title-output')">
|
||||
<div class="side-label">
|
||||
{{ withUnit(labelOf(outputSide), unitOf(outputSide)) }}
|
||||
</div>
|
||||
<div class="output-value">
|
||||
<span data-test-id="converter-output">{{ outputText || '—' }}</span>
|
||||
<c-button
|
||||
v-if="outputText"
|
||||
variant="text"
|
||||
circle
|
||||
:title="t('analogSignalConverter.texts.copy-output')"
|
||||
@click="copyOutput()"
|
||||
>
|
||||
<icon-mdi-content-copy />
|
||||
</c-button>
|
||||
</div>
|
||||
<div v-if="roundedOutputText" class="rounded-output" data-test-id="converter-output-rounded">
|
||||
{{ t('analogSignalConverter.texts.label-rounded-signal') }} : {{ roundedOutputText }}
|
||||
</div>
|
||||
|
||||
<AnalogGauge
|
||||
v-if="!rangesError"
|
||||
:min="rangeOf(outputSide).min"
|
||||
:max="rangeOf(outputSide).max"
|
||||
:value="outputValue"
|
||||
:unit="unitOf(outputSide)"
|
||||
:status="outputStatus?.type"
|
||||
data-test-id="output-gauge"
|
||||
/>
|
||||
|
||||
<div v-if="outputStatus" class="status" :class="outputStatus.type" data-test-id="output-status">
|
||||
<icon-mdi-check-circle v-if="outputStatus.type === 'ok'" />
|
||||
<icon-mdi-alert v-else />
|
||||
<span>{{ outputStatus.message }}</span>
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
|
||||
<c-card v-if="!rangesError" :title="t('analogSignalConverter.texts.title-reference-points')">
|
||||
<n-table size="small" data-test-id="reference-points">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ t('analogSignalConverter.texts.column-percent') }}</th>
|
||||
<th>{{ signalLabel }}</th>
|
||||
<th>{{ t('analogSignalConverter.texts.label-engineering-value') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="point of referencePoints" :key="point.percent">
|
||||
<td>{{ point.percent }}</td>
|
||||
<td>{{ point.signal }}</td>
|
||||
<td>{{ point.value }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</n-table>
|
||||
</c-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.converter-columns {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1.2fr 1fr;
|
||||
gap: 12px;
|
||||
align-items: stretch;
|
||||
|
||||
// Narrow screens: input, parameters and output stacked
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.column {
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.side-label {
|
||||
font-size: 13px;
|
||||
opacity: 0.75;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.swap {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.output-value {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
min-height: 40px;
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.rounded-output {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
|
||||
svg {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
&.ok {
|
||||
color: v-bind('themeVars.successColor');
|
||||
}
|
||||
&.warning {
|
||||
color: v-bind('themeVars.warningColor');
|
||||
}
|
||||
&.error {
|
||||
color: v-bind('themeVars.errorColor');
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test.describe('Tool - Analog scaling calculator', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/analog-scaling-calculator');
|
||||
});
|
||||
|
||||
test('Has correct title', async ({ page }) => {
|
||||
await expect(page).toHaveTitle('Analog scaling calculator - IT Tools');
|
||||
});
|
||||
|
||||
test('Scales a Siemens raw value', async ({ page }) => {
|
||||
await page.getByTestId('converter-input').locator('input').fill('20736');
|
||||
await page.getByTestId('converter-input').locator('input').press('Enter');
|
||||
await expect(page.getByTestId('converter-output')).toHaveText('75 %');
|
||||
await expect(page.getByTestId('formula').locator('input')).toHaveValue('value = 0.003616898148 × signal');
|
||||
});
|
||||
|
||||
test('Gives the rounded raw value in the other direction', async ({ page }) => {
|
||||
await page.getByTestId('swap-direction').click();
|
||||
await page.getByTestId('converter-input').locator('input').fill('33.3');
|
||||
await page.getByTestId('converter-input').locator('input').press('Enter');
|
||||
await expect(page.getByTestId('converter-output')).toHaveText('9206.784');
|
||||
await expect(page.getByTestId('converter-output-rounded')).toContainText('9207');
|
||||
});
|
||||
|
||||
test('Rejects a range whose min is not lower than its max', async ({ page }) => {
|
||||
const min = page.getByTestId('engineering-min').locator('input');
|
||||
await min.fill('200');
|
||||
await min.press('Enter');
|
||||
await expect(page.getByText('The engineering min must be lower than the engineering max.')).toBeVisible();
|
||||
await expect(page.getByTestId('converter-output')).toHaveText('—');
|
||||
await expect(page.getByTestId('output-gauge')).toHaveCount(0);
|
||||
|
||||
await min.fill('-50');
|
||||
await min.press('Enter');
|
||||
await expect(page.getByTestId('converter-output')).not.toHaveText('—');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import AnalogSignalConverter from '@/components/AnalogSignalConverter.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const presets = computed(() => [
|
||||
{ label: t('tools.analog-scaling-calculator.texts.preset-siemens-unipolar'), min: 0, max: 27648 },
|
||||
{ label: t('tools.analog-scaling-calculator.texts.preset-siemens-bipolar'), min: -27648, max: 27648 },
|
||||
{ label: t('tools.analog-scaling-calculator.texts.preset-schneider'), min: 0, max: 10000 },
|
||||
{ label: t('tools.analog-scaling-calculator.texts.preset-12-bits'), min: 0, max: 4095 },
|
||||
{ label: t('tools.analog-scaling-calculator.texts.preset-15-bits'), min: 0, max: 32767 },
|
||||
{ label: t('tools.analog-scaling-calculator.texts.preset-16-bits'), min: 0, max: 65535 },
|
||||
]);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AnalogSignalConverter
|
||||
storage-key="analog-scaling-calculator"
|
||||
:signal-label="t('tools.analog-scaling-calculator.texts.signal-label')"
|
||||
:presets="presets"
|
||||
:default-engineering="{ min: 0, max: 100, unit: '%' }"
|
||||
integer-signal
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,25 @@
|
||||
import { defineTool } from '../tool';
|
||||
import { translate as t } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: t('tools.analog-scaling-calculator.title'),
|
||||
path: '/analog-scaling-calculator',
|
||||
description: t('tools.analog-scaling-calculator.description'),
|
||||
keywords: [
|
||||
'analog',
|
||||
'scaling',
|
||||
'raw',
|
||||
'plc',
|
||||
'siemens',
|
||||
'27648',
|
||||
'schneider',
|
||||
'norm_x',
|
||||
'scale_x',
|
||||
'engineering',
|
||||
'unit',
|
||||
],
|
||||
component: () => import('./analog-scaling-calculator.vue'),
|
||||
icon: defineAsyncComponent(() => import('@vicons/tabler/es/AdjustmentsHorizontal')),
|
||||
createdAt: new Date('2026-11-03'),
|
||||
category: 'Automation',
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test.describe('Tool - 4-20 mA converter', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/current-loop-4-20ma-converter');
|
||||
});
|
||||
|
||||
test('Has correct title', async ({ page }) => {
|
||||
await expect(page).toHaveTitle('4-20 mA converter - IT Tools');
|
||||
});
|
||||
|
||||
test('Converts a current into an engineering value', async ({ page }) => {
|
||||
await page.getByTestId('converter-input').locator('input').fill('8');
|
||||
await page.getByTestId('converter-input').locator('input').press('Enter');
|
||||
await expect(page.getByTestId('converter-output')).toHaveText('2.5 bar');
|
||||
await expect(page.getByTestId('input-status')).toContainText('In range');
|
||||
});
|
||||
|
||||
test('Swaps the direction and keeps the operating point', async ({ page }) => {
|
||||
await page.getByTestId('converter-input').locator('input').fill('16');
|
||||
await page.getByTestId('converter-input').locator('input').press('Enter');
|
||||
await expect(page.getByTestId('converter-output')).toHaveText('7.5 bar');
|
||||
|
||||
await page.getByTestId('swap-direction').click();
|
||||
await expect(page.getByTestId('converter-input').locator('input')).toHaveValue('7.5');
|
||||
await expect(page.getByTestId('converter-output')).toHaveText('16 mA');
|
||||
await expect(page.getByTestId('formula').locator('input')).toHaveValue('signal = 1.6 × value + 4');
|
||||
|
||||
await page.getByTestId('swap-direction').click();
|
||||
});
|
||||
|
||||
test('Reports a NAMUR NE 43 loop failure', async ({ page }) => {
|
||||
await page.getByTestId('converter-input').locator('input').fill('2');
|
||||
await page.getByTestId('converter-input').locator('input').press('Enter');
|
||||
await expect(page.getByTestId('input-status')).toContainText('Low failure');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import AnalogSignalConverter from '@/components/AnalogSignalConverter.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const presets = [
|
||||
{ label: '4-20 mA', min: 4, max: 20 },
|
||||
{ label: '0-20 mA', min: 0, max: 20 },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AnalogSignalConverter
|
||||
storage-key="current-loop-4-20ma-converter"
|
||||
:signal-label="t('tools.current-loop-4-20ma-converter.texts.signal-label')"
|
||||
signal-unit="mA"
|
||||
:presets="presets"
|
||||
:default-engineering="{ min: 0, max: 10, unit: 'bar' }"
|
||||
current-loop-diagnostic
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,26 @@
|
||||
import { defineTool } from '../tool';
|
||||
import { translate as t } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: t('tools.current-loop-4-20ma-converter.title'),
|
||||
path: '/current-loop-4-20ma-converter',
|
||||
description: t('tools.current-loop-4-20ma-converter.description'),
|
||||
keywords: [
|
||||
'4-20',
|
||||
'ma',
|
||||
'milliampere',
|
||||
'current',
|
||||
'loop',
|
||||
'analog',
|
||||
'sensor',
|
||||
'transmitter',
|
||||
'namur',
|
||||
'ne43',
|
||||
'plc',
|
||||
'scaling',
|
||||
],
|
||||
component: () => import('./current-loop-4-20ma-converter.vue'),
|
||||
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Gauge')),
|
||||
createdAt: new Date('2026-11-03'),
|
||||
category: 'Automation',
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineTool } from '../tool';
|
||||
import { translate as t } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: t('tools.voltage-0-10v-converter.title'),
|
||||
path: '/voltage-0-10v-converter',
|
||||
description: t('tools.voltage-0-10v-converter.description'),
|
||||
keywords: ['0-10', 'volt', 'voltage', 'analog', 'sensor', '1-5', '2-10', 'plc', 'scaling'],
|
||||
component: () => import('./voltage-0-10v-converter.vue'),
|
||||
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Bolt')),
|
||||
createdAt: new Date('2026-11-03'),
|
||||
category: 'Automation',
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test.describe('Tool - 0-10 V converter', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/voltage-0-10v-converter');
|
||||
});
|
||||
|
||||
test('Has correct title', async ({ page }) => {
|
||||
await expect(page).toHaveTitle('0-10 V converter - IT Tools');
|
||||
});
|
||||
|
||||
test('Converts a voltage into an engineering value', async ({ page }) => {
|
||||
await page.getByTestId('converter-input').locator('input').fill('2.5');
|
||||
await page.getByTestId('converter-input').locator('input').press('Enter');
|
||||
await expect(page.getByTestId('converter-output')).toHaveText('25 %');
|
||||
});
|
||||
|
||||
test('Warns below the live zero of a 2-10 V signal', async ({ page }) => {
|
||||
await page.getByTestId('signal-min').locator('input').fill('2');
|
||||
await page.getByTestId('signal-min').locator('input').press('Enter');
|
||||
await page.getByTestId('converter-input').locator('input').fill('1');
|
||||
await page.getByTestId('converter-input').locator('input').press('Enter');
|
||||
await expect(page.getByTestId('input-status')).toContainText('live zero');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import AnalogSignalConverter from '@/components/AnalogSignalConverter.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const presets = [
|
||||
{ label: '0-10 V', min: 0, max: 10 },
|
||||
{ label: '2-10 V', min: 2, max: 10 },
|
||||
{ label: '0-5 V', min: 0, max: 5 },
|
||||
{ label: '1-5 V', min: 1, max: 5 },
|
||||
{ label: '±10 V', min: -10, max: 10 },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AnalogSignalConverter
|
||||
storage-key="voltage-0-10v-converter"
|
||||
:signal-label="t('tools.voltage-0-10v-converter.texts.signal-label')"
|
||||
signal-unit="V"
|
||||
:presets="presets"
|
||||
:default-engineering="{ min: 0, max: 100, unit: '%' }"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
formatSignalNumber,
|
||||
getCurrentLoopStatus,
|
||||
getLinearTransform,
|
||||
getSignalRangeStatus,
|
||||
scaleValue,
|
||||
toPercentOfRange,
|
||||
} from './analog-signal';
|
||||
|
||||
describe('analog-signal', () => {
|
||||
describe('scaleValue', () => {
|
||||
it('maps a 4-20 mA current onto an engineering range', () => {
|
||||
const from = { min: 4, max: 20 };
|
||||
const to = { min: 0, max: 10 };
|
||||
|
||||
expect(scaleValue({ value: 4, from, to })).toBe(0);
|
||||
expect(scaleValue({ value: 12, from, to })).toBe(5);
|
||||
expect(scaleValue({ value: 20, from, to })).toBe(10);
|
||||
});
|
||||
|
||||
it('maps the other way round, from engineering value to current', () => {
|
||||
expect(scaleValue({ value: 2.5, from: { min: 0, max: 10 }, to: { min: 4, max: 20 } })).toBe(8);
|
||||
});
|
||||
|
||||
it('handles negative and inverted ranges', () => {
|
||||
expect(scaleValue({ value: 0, from: { min: -27648, max: 27648 }, to: { min: -10, max: 10 } })).toBe(0);
|
||||
expect(scaleValue({ value: 27648, from: { min: -27648, max: 27648 }, to: { min: -10, max: 10 } })).toBe(10);
|
||||
expect(scaleValue({ value: 4, from: { min: 4, max: 20 }, to: { min: 100, max: 0 } })).toBe(100);
|
||||
});
|
||||
|
||||
it('scales Siemens raw values', () => {
|
||||
expect(scaleValue({ value: 13824, from: { min: 0, max: 27648 }, to: { min: 0, max: 100 } })).toBe(50);
|
||||
});
|
||||
|
||||
it('extrapolates outside of the range', () => {
|
||||
expect(scaleValue({ value: 0, from: { min: 4, max: 20 }, to: { min: 0, max: 16 } })).toBe(-4);
|
||||
});
|
||||
|
||||
it('throws on an empty input range', () => {
|
||||
expect(() => scaleValue({ value: 1, from: { min: 4, max: 4 }, to: { min: 0, max: 10 } })).toThrow();
|
||||
expect(() => scaleValue({ value: 1, from: { min: Number.NaN, max: 4 }, to: { min: 0, max: 10 } })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getLinearTransform', () => {
|
||||
it('returns gain and offset of y = gain * x + offset', () => {
|
||||
expect(getLinearTransform({ from: { min: 4, max: 20 }, to: { min: 0, max: 16 } })).toEqual({
|
||||
gain: 1,
|
||||
offset: -4,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('toPercentOfRange', () => {
|
||||
it('gives the position in the range', () => {
|
||||
expect(toPercentOfRange({ value: 8, range: { min: 4, max: 20 } })).toBe(25);
|
||||
expect(toPercentOfRange({ value: 2, range: { min: 2, max: 10 } })).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSignalRangeStatus', () => {
|
||||
it('detects values outside of the range', () => {
|
||||
expect(getSignalRangeStatus({ value: 5, range: { min: 0, max: 10 } })).toBe('ok');
|
||||
expect(getSignalRangeStatus({ value: -0.1, range: { min: 0, max: 10 } })).toBe('below-range');
|
||||
expect(getSignalRangeStatus({ value: 10.1, range: { min: 0, max: 10 } })).toBe('above-range');
|
||||
expect(getSignalRangeStatus({ value: 5, range: { min: 10, max: 0 } })).toBe('ok');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCurrentLoopStatus', () => {
|
||||
it('follows NAMUR NE 43 limits', () => {
|
||||
expect(getCurrentLoopStatus(0)).toBe('failure-low');
|
||||
expect(getCurrentLoopStatus(3.6)).toBe('failure-low');
|
||||
expect(getCurrentLoopStatus(3.7)).toBe('uncertain-low');
|
||||
expect(getCurrentLoopStatus(3.8)).toBe('under-range');
|
||||
expect(getCurrentLoopStatus(4)).toBe('ok');
|
||||
expect(getCurrentLoopStatus(20)).toBe('ok');
|
||||
expect(getCurrentLoopStatus(20.5)).toBe('over-range');
|
||||
expect(getCurrentLoopStatus(20.8)).toBe('uncertain-high');
|
||||
expect(getCurrentLoopStatus(21)).toBe('failure-high');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatSignalNumber', () => {
|
||||
it('removes float noise', () => {
|
||||
expect(formatSignalNumber(0.1 + 0.2)).toBe('0.3');
|
||||
expect(formatSignalNumber(12.345678)).toBe('12.3457');
|
||||
expect(formatSignalNumber(-0.00001)).toBe('0');
|
||||
expect(formatSignalNumber(Number.NaN)).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
export interface SignalRange {
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export interface LinearTransform {
|
||||
gain: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export type CurrentLoopStatus =
|
||||
| 'ok'
|
||||
| 'under-range'
|
||||
| 'over-range'
|
||||
| 'uncertain-low'
|
||||
| 'uncertain-high'
|
||||
| 'failure-low'
|
||||
| 'failure-high';
|
||||
|
||||
export type SignalRangeStatus = 'ok' | 'below-range' | 'above-range';
|
||||
|
||||
function assertNonEmptyRange(range: SignalRange) {
|
||||
if (!Number.isFinite(range.min) || !Number.isFinite(range.max) || range.min === range.max) {
|
||||
throw new Error('Invalid range: min and max must be finite and different');
|
||||
}
|
||||
}
|
||||
|
||||
// y = gain * x + offset, mapping `from` onto `to` (what PLC scaling blocks compute).
|
||||
export function getLinearTransform({ from, to }: { from: SignalRange; to: SignalRange }): LinearTransform {
|
||||
assertNonEmptyRange(from);
|
||||
|
||||
const gain = (to.max - to.min) / (from.max - from.min);
|
||||
return { gain, offset: to.min - gain * from.min };
|
||||
}
|
||||
|
||||
export function scaleValue({ value, from, to }: { value: number; from: SignalRange; to: SignalRange }): number {
|
||||
const { gain, offset } = getLinearTransform({ from, to });
|
||||
return gain * value + offset;
|
||||
}
|
||||
|
||||
export function toPercentOfRange({ value, range }: { value: number; range: SignalRange }): number {
|
||||
return scaleValue({ value, from: range, to: { min: 0, max: 100 } });
|
||||
}
|
||||
|
||||
export function getSignalRangeStatus({ value, range }: { value: number; range: SignalRange }): SignalRangeStatus {
|
||||
const low = Math.min(range.min, range.max);
|
||||
const high = Math.max(range.min, range.max);
|
||||
|
||||
if (value < low) {
|
||||
return 'below-range';
|
||||
}
|
||||
if (value > high) {
|
||||
return 'above-range';
|
||||
}
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
// NAMUR NE 43 limits for 4-20 mA transmitters.
|
||||
export const NAMUR_NE43 = {
|
||||
failureLowMax: 3.6,
|
||||
measurementMin: 3.8,
|
||||
measurementMax: 20.5,
|
||||
failureHighMin: 21,
|
||||
} as const;
|
||||
|
||||
export function getCurrentLoopStatus(current: number): CurrentLoopStatus {
|
||||
if (current <= NAMUR_NE43.failureLowMax) {
|
||||
return 'failure-low';
|
||||
}
|
||||
if (current < NAMUR_NE43.measurementMin) {
|
||||
return 'uncertain-low';
|
||||
}
|
||||
if (current < 4) {
|
||||
return 'under-range';
|
||||
}
|
||||
if (current <= 20) {
|
||||
return 'ok';
|
||||
}
|
||||
if (current <= NAMUR_NE43.measurementMax) {
|
||||
return 'over-range';
|
||||
}
|
||||
if (current < NAMUR_NE43.failureHighMin) {
|
||||
return 'uncertain-high';
|
||||
}
|
||||
return 'failure-high';
|
||||
}
|
||||
|
||||
// Avoids float noise such as 0.30000000000000004 in displayed results.
|
||||
export function formatSignalNumber(value: number, maxDecimals = 4): string {
|
||||
if (!Number.isFinite(value)) {
|
||||
return '';
|
||||
}
|
||||
const rounded = Number(value.toFixed(maxDecimals));
|
||||
return Object.is(rounded, -0) ? '0' : String(rounded);
|
||||
}
|
||||
Reference in new issue
Block a user