@w2a-iiot/raw-javascript-parsers
Version:
This packages contain the raw built javascript parsers for WIKA's IIoT devices.
2 lines • 143 kB
JavaScript
var __commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);function _typeof(e){"@babel/helpers - typeof";return _typeof=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},_typeof(e)}function toPrimitive(e,n){if(_typeof(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,n||`default`);if(_typeof(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(e)}function toPropertyKey(e){var r=toPrimitive(e,`string`);return _typeof(r)==`symbol`?r:r+``}function _defineProperty(e,t,n){return(t=toPropertyKey(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ownKeys(Object(n),!0).forEach(function(t){_defineProperty(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function getGlobalConfig(e){return{lang:e?.lang??void 0,message:e?.message,abortEarly:e?.abortEarly??void 0,abortPipeEarly:e?.abortPipeEarly??void 0}}function _stringify(e){var t;let n=typeof e;return n===`string`?`"${e}"`:n===`number`||n===`bigint`||n===`boolean`?`${e}`:n===`object`||n===`function`?(e&&((t=Object.getPrototypeOf(e))==null||(t=t.constructor)==null?void 0:t.name))??`null`:n}function _addIssue(e,t,n,r,i){let a=i&&`input`in i?i.input:n.value,o=i?.expected??e.expects??null,s=i?.received??_stringify(a),l={kind:e.kind,type:e.type,input:a,expected:o,received:s,message:`Invalid ${t}: ${o?`Expected ${o} but r`:`R`}eceived ${s}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},u=e.kind===`schema`,d=i?.message??e.message??(e.reference,l.lang,void 0)??(u?(l.lang,void 0):null)??r.message??(l.lang,void 0);d!==void 0&&(l.message=typeof d==`function`?d(l):d),u&&(n.typed=!1),n.issues?n.issues.push(l):n.issues=[l]}function _getStandardProps(e){return{version:1,vendor:`valibot`,validate(t){return e[`~run`]({value:t},getGlobalConfig())}}}function _joinExpects(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??`never`}function getDotPath(e){if(e.path){let t=``;for(let n of e.path)if(typeof n.key==`string`||typeof n.key==`number`)t?t+=`.${n.key}`:t+=n.key;else return null;return t}return null}const HEXADECIMAL_REGEX=/^(?:0[hx])?[\da-fA-F]+$/u;function hexadecimal(e){return{kind:`validation`,type:`hexadecimal`,reference:hexadecimal,async:!1,expects:null,requirement:HEXADECIMAL_REGEX,message:e,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&_addIssue(this,`hexadecimal`,e,t),e}}}function integer(e){return{kind:`validation`,type:`integer`,reference:integer,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&_addIssue(this,`integer`,e,t),e}}}function maxValue(e,t){return{kind:`validation`,type:`max_value`,reference:maxValue,async:!1,expects:`<=${e instanceof Date?e.toJSON():_stringify(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value<=this.requirement)&&_addIssue(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():_stringify(e.value)}),e}}}function minValue(e,t){return{kind:`validation`,type:`min_value`,reference:minValue,async:!1,expects:`>=${e instanceof Date?e.toJSON():_stringify(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value>=this.requirement)&&_addIssue(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():_stringify(e.value)}),e}}}function transform(e){return{kind:`transformation`,type:`transform`,reference:transform,async:!1,operation:e,"~run"(e){return e.value=this.operation(e.value),e}}}function getFallback(e,t,n){return typeof e.fallback==`function`?e.fallback(t,n):e.fallback}function getDefault(e,t,n){return typeof e.default==`function`?e.default(t,n):e.default}function array(e,t){return{kind:`schema`,type:`array`,reference:array,expects:`Array`,async:!1,item:e,message:t,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){let n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let i=0;i<n.length;i++){let a=n[i],o=this.item[`~run`]({value:a},t);if(o.issues){let s={type:`array`,origin:`value`,input:n,key:i,value:a};for(let t of o.issues){var r;t.path?t.path.unshift(s):t.path=[s],(r=e.issues)==null||r.push(t)}if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value.push(o.value)}}else _addIssue(this,`type`,e,t);return e}}}function boolean(e){return{kind:`schema`,type:`boolean`,reference:boolean,expects:`boolean`,async:!1,message:e,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){return typeof e.value==`boolean`?e.typed=!0:_addIssue(this,`type`,e,t),e}}}function literal(e,t){return{kind:`schema`,type:`literal`,reference:literal,expects:_stringify(e),async:!1,literal:e,message:t,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){return e.value===this.literal?e.typed=!0:_addIssue(this,`type`,e,t),e}}}function number(e){return{kind:`schema`,type:`number`,reference:number,expects:`number`,async:!1,message:e,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){return typeof e.value==`number`&&!isNaN(e.value)?e.typed=!0:_addIssue(this,`type`,e,t),e}}}function object(e,t){return{kind:`schema`,type:`object`,reference:object,expects:`Object`,async:!1,entries:e,message:t,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let i in this.entries){let a=this.entries[i];if(i in n||(a.type===`exact_optional`||a.type===`optional`||a.type===`nullish`)&&a.default!==void 0){let o=i in n?n[i]:getDefault(a),s=a[`~run`]({value:o},t);if(s.issues){let a={type:`object`,origin:`value`,input:n,key:i,value:o};for(let t of s.issues){var r;t.path?t.path.unshift(a):t.path=[a],(r=e.issues)==null||r.push(t)}if(e.issues||=s.issues,t.abortEarly){e.typed=!1;break}}s.typed||(e.typed=!1),e.value[i]=s.value}else if(a.fallback!==void 0)e.value[i]=getFallback(a);else if(a.type!==`exact_optional`&&a.type!==`optional`&&a.type!==`nullish`&&(_addIssue(this,`key`,e,t,{input:void 0,expected:`"${i}"`,path:[{type:`object`,origin:`key`,input:n,key:i,value:n[i]}]}),t.abortEarly))break}}else _addIssue(this,`type`,e,t);return e}}}function optional(e,t){return{kind:`schema`,type:`optional`,reference:optional,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){return e.value===void 0&&(this.default!==void 0&&(e.value=getDefault(this,e,t)),e.value===void 0)?(e.typed=!0,e):this.wrapped[`~run`](e,t)}}}function picklist(e,t){return{kind:`schema`,type:`picklist`,reference:picklist,expects:_joinExpects(e.map(_stringify),`|`),async:!1,options:e,message:t,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:_addIssue(this,`type`,e,t),e}}}function string(e){return{kind:`schema`,type:`string`,reference:string,expects:`string`,async:!1,message:e,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){return typeof e.value==`string`?e.typed=!0:_addIssue(this,`type`,e,t),e}}}function _subIssues(e){let t;if(e)for(let n of e)t?t.push(...n.issues):t=n.issues;return t}function union(e,t){return{kind:`schema`,type:`union`,reference:union,expects:_joinExpects(e.map(e=>e.expects),`|`),async:!1,options:e,message:t,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){let n,r,i;for(let a of this.options){let o=a[`~run`]({value:e.value},t);if(o.typed)if(o.issues)r?r.push(o):r=[o];else{n=o;break}else i?i.push(o):i=[o]}if(n)return n;if(r){if(r.length===1)return r[0];_addIssue(this,`type`,e,t,{issues:_subIssues(r)}),e.typed=!0}else if(i?.length===1)return i[0];else _addIssue(this,`type`,e,t,{issues:_subIssues(i)});return e}}}function variant(e,t,n){return{kind:`schema`,type:`variant`,reference:variant,expects:`Object`,async:!1,key:e,options:t,message:n,get"~standard"(){return _getStandardProps(this)},"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){let r,i=0,a=this.key,o=[],s=(e,c)=>{for(let l of e.options){if(l.type===`variant`)s(l,new Set(c).add(l.key));else{let e=!0,s=0;for(let t of c){let r=l.entries[t];if(t in n?r[`~run`]({typed:!1,value:n[t]},{abortEarly:!0}).issues:r.type!==`exact_optional`&&r.type!==`optional`&&r.type!==`nullish`){e=!1,a!==t&&(i<s||i===s&&t in n&&!(a in n))&&(i=s,a=t,o=[]),a===t&&o.push(l.entries[t].expects);break}s++}if(e){let e=l[`~run`]({value:n},t);(!r||!r.typed&&e.typed)&&(r=e)}}if(r&&!r.issues)break}};if(s(this,new Set([this.key])),r)return r;_addIssue(this,`type`,e,t,{input:n[a],expected:_joinExpects(o,`|`),path:[{type:`object`,origin:`value`,input:n,key:a,value:n[a]}]})}else _addIssue(this,`type`,e,t);return e}}}function pipe(...e){return _objectSpread2(_objectSpread2({},e[0]),{},{pipe:e,get"~standard"(){return _getStandardProps(this)},"~run"(t,n){for(let r of e)if(r.kind!==`metadata`){if(t.issues&&(r.kind===`schema`||r.kind===`transformation`)){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r[`~run`](t,n))}return t}})}function safeParse(e,t,n){let r=e[`~run`]({value:t},getGlobalConfig(n));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}function summarize(e){let t=``;for(let n of e){t&&(t+=`
`),t+=`× ${n.message}`;let e=getDotPath(n);e&&(t+=`\n → at ${e}`)}return t}function checkChannelsValidity(e,t){let n=new Set;e.forEach(e=>{if(e.start>=e.end)throw t?Error(`Invalid channel range in codec ${t}: ${e.start} >= ${e.end} in channel ${e.name}`):Error(`Invalid channel range: ${e.start} >= ${e.end} in channel ${e.name}`);if(n.has(e.name))throw t?Error(`Duplicate channel name found in codec ${t}: ${e.name}`):Error(`Duplicate channel name found: ${e.name}`);n.add(e.name)})}function checkCodecsValidity(e){if(e.length===0)throw Error(`At least one codec must be provided`);e.forEach(e=>{checkChannelsValidity(e.getChannels(),e.name)}),e.forEach((t,n)=>{if(e.filter((e,t)=>t!==n).some(e=>e.name===t.name))throw Error(`Codec names must be unique. Duplicate found: ${t.name}`)});let t=e[0].getChannels().map(e=>e.name);e.forEach((e,n)=>{if(n===0)return;let r=e.getChannels().map(e=>e.name),i={missing:[],extra:[]};if(r.forEach(e=>{t.includes(e)||i.extra.push(e)}),t.forEach(e=>{r.includes(e)||i.missing.push(e)}),i.extra.length>0)throw Error(`Codec ${e.name} has extra channels not present in other codecs: ${i.extra.join(`, `)}`);if(i.missing.length>0)throw Error(`Codec ${e.name} is missing channels present in other codecs: ${i.missing.join(`, `)}`)});let n=new Map,r={};return e.forEach(e=>{e.getChannels().forEach(e=>{let t=[e.start,e.end],i=e.adjustMeasurementRangeDisallowed??!1;if(n.has(e.name)){let a=n.get(e.name);if(a[0]!==t[0]||a[1]!==t[1])throw Error(`Channel ${e.name} has inconsistent ranges across codecs: ${JSON.stringify(a)} vs ${JSON.stringify(t)}`);let o=r[e.name];if(o!==i)throw Error(`Channel ${e.name} has inconsistent adjustMeasurementRangeDisallowed settings across codecs: ${o} vs ${i}`)}else n.set(e.name,t),r[e.name]=i})}),r}function createFPortSchema(){return pipe(number(),minValue(1),maxValue(255),integer())}function createRecvTimeSchema(){return optional(string())}function createUplinkInputSchema(){return object({bytes:array(pipe(number(),minValue(0),maxValue(255),integer())),fPort:optional(pipe(number(),minValue(1),maxValue(224),integer())),recvTime:optional(string())},"Uplink input should be an object with `bytes` and optional `fPort` and `recvTime` properties.")}function createHexUplinkInputSchema(){return pipe(union([object({bytes:pipe(string()),fPort:optional(createFPortSchema()),recvTime:createRecvTimeSchema()}),string()]),transform(e=>typeof e==`string`?{bytes:e}:e))}function nstr(e,t={}){let{threshold:n=4,maxDecimals:r=10}=t;if(Number.isNaN(e))return`NaN`;if(!isFinite(e)||Number.isInteger(e))return e.toString();let i=e.toFixed(r),a=-1,o=``,s=i.indexOf(`.`),c=s>=0?s+1:i.length;for(let e=c;e<i.length;e++){let t=i[e];if(t===`0`||t===`9`){let r=1,s=e+1;for(;s<i.length&&i[s]===t;)r++,s++;if(r>=n){a=e,o=t;break}e=s-1}}if(a!==-1){let e=i.substring(0,a);if(o===`9`){let t=e,n=Number.parseFloat(t),r=t.indexOf(`.`),i=r>=0?t.length-r-1:0,a=10**-i,o=n<0?n-a:n+a;e=i>0?o.toFixed(i):o.toString()}let t=e.replace(/\.?0+$/,``);return t.endsWith(`.`)&&(t=t.slice(0,-1)),(t===`-0.`||t===`0.`||t===`-0`||t===`0`)&&(t=`0`),t}let l=i.replace(/\.?0+$/,``);return l.endsWith(`.`)&&(l=l.slice(0,-1)),(l===`-0.`||l===`0.`||l===`-0`||l===`0`)&&(l=`0`),l}function getRoundingDecimals(e,t){let n=t??4;return e===void 0||Number.isNaN(e)||e===-1/0?n:e===1/0?1/0:Math.floor(e)>=0?Math.floor(e):n}function hexStringToIntArray(e){let t=e.replaceAll(` `,``);t=t.startsWith(`0x`)?t.slice(2):t;let n=safeParse(pipe(string(),hexadecimal()),t);if(!n.success)return null;let r=[];for(let e=0;e<n.output.length;e+=2){let t=Number.parseInt(n.output.slice(e,e+2),16);r.push(t)}return r}function percentageToValue(e,t){if(t.start>=t.end)throw RangeError(`Range start must be less than range end`);return(t.end-t.start)*(e/100)+t.start}function TULIPValueToValue(e,t){return percentageToValue((e-2500)*100/1e4+0,t)}function slopeValueToValue(e,t){if(e<0||e>1e4)throw RangeError(`Slope value must be between 0 and 10_000, is ${e}`);let n=e/100,r=t.end-t.start;return n/100*r}function roundValue(e,t){if(t=typeof t==`number`?Math.min(Math.max(0,Math.floor(t)),100):void 0,Number.isInteger(e))return e;let n=nstr(e+5*2**-52,{maxDecimals:t});return n===``?0:Number.parseFloat(n)}function intTuple4ToFloat32(e){let t=new ArrayBuffer(4),n=new DataView(t);return n.setUint8(0,e[0]&255),n.setUint8(1,e[1]&255),n.setUint8(2,e[2]&255),n.setUint8(3,e[3]&255),n.getFloat32(0)}function intTuple4ToFloat32WithThreshold(e,t=3){t=Math.max(0,Math.floor(t));let n=intTuple4ToFloat32(e);return Number.parseFloat(nstr(n,{threshold:t}))}function defineParser(e){let{codecs:t,throwOnMultipleDecode:n=!0,parserName:r}=e,i=getRoundingDecimals(e.roundingDecimals),a=checkCodecsValidity(e.codecs);function o(e){return{errors:[s(e)]}}function s(e){return`${r} (JS): ${e}`}function c(e){let r;if(t.forEach(t=>{if(t.canTryDecode(e)){if(!r)r=t;else if(n)throw Error(`Message could not be uniquely decoded. Multiple codecs matched the input.`)}}),!r)throw Error(`Message could not be decoded. No codec matched the input.`);return r.decode(e)}function l(e){try{let t=safeParse(createUplinkInputSchema(),e);if(!t.success)throw Error(`Input is not a valid for decoding. Check your input data.`);let n=c(t.output);return n.warnings&&=n.warnings.map(s),n}catch(t){return t instanceof Error?o(t.message):o(`Unknown error occurred during decoding in parser ${r} with input ${JSON.stringify(e)}`)}}function u(e){let t=safeParse(createHexUplinkInputSchema(),e);if(!t.success)return o(`Input is not a valid for decoding. Check your input data.`);let n=hexStringToIntArray(t.output.bytes);return n?l({bytes:n,fPort:t.output.fPort,recvTime:t.output.recvTime}):o(`Input bytes is not a valid hexadecimal string.`)}function d(e){try{let n=t.find(t=>t.protocol===e.protocol);if(!n)throw Error(`Codec with protocol ${e.protocol} not found in parser. Available protocols: ${t.map(e=>e.protocol).join(`, `)}`);if(!(`encode`in n))throw Error(`Codec with protocol ${e.protocol} does not support encoding. Input could not be encoded.`);return n.encode(e.input)}catch(t){return t instanceof Error?o(t.message):o(`Unknown error occurred during encoding in parser ${r} with input ${JSON.stringify(e)}`)}}function f(e){try{let n=t.find(t=>t.protocol===e.protocol);if(!n)throw Error(`Codec with protocol ${e.protocol} not found in parser. Available protocols: ${t.map(e=>e.protocol).join(`, `)}`);if(!(`encodeMultiple`in n))throw Error(`Codec with protocol ${e.protocol} does not support multiple encoding. Input could not be encoded.`);return n.encodeMultiple(e.input)}catch(t){return t instanceof Error?o(t.message):o(`Unknown error occurred during multiple encoding in parser ${r} with input ${JSON.stringify(e)}`)}}return{decodeUplink:l,decodeHexUplink:u,encodeDownlink:d,encodeMultipleDownlinks:f,adjustMeasuringRange:(e,n)=>{if(!(e in a))throw Error(`Channel ${e} does not exist in parser ${r}. Cannot adjust measuring range.`);if(a[e])throw Error(`Channel ${e} does not allow adjusting the measuring range in parser ${r}.`);t.forEach(t=>{t.adjustMeasuringRange(e,n)})},adjustRoundingDecimals:e=>{let n=getRoundingDecimals(e,i);t.forEach(e=>{e.adjustRoundingDecimals(n)})}}}function defineTULIP2Codec(e){let t=`${e.deviceName}TULIP2`,n=getRoundingDecimals(e.roundingDecimals);checkChannelsValidity(e.channels),e.channels.forEach((e,n,r)=>{let i=r.find((t,r)=>t.channelId===e.channelId&&r!==n);if(i)throw Error(`Duplicate channel ID found: ${e.channelId} for channels ${e.name} and ${i.name} in ${t} Codec`)});function r(t){let n=t.bytes[0];return typeof n==`number`&&n in e.handlers}function i(r){let i=r.bytes[0];if(typeof i!=`number`)throw TypeError(`Input must have at least one byte for ${t} Codec`);let a=e.handlers[i];if(a)return a(r,{roundingDecimals:n,channels:e.channels});throw TypeError(`No handler registered for byte ${i} in ${t} Codec`)}function a(){return e.channels.map(e=>_objectSpread2({end:e.end,name:e.name,start:e.start},e.adjustMeasurementRangeDisallowed?{adjustMeasurementRangeDisallowed:!0}:{}))}let s={name:t,protocol:`TULIP2`,getChannels:a,canTryDecode:r,decode:i,adjustMeasuringRange:(t,n)=>{let r=e.channels.find(e=>e.name===t);if(!r)throw Error(`Channel ${t} not found in ${e.deviceName}TULIP2 Codec`);r.start=n.start,r.end=n.end},adjustRoundingDecimals:e=>{n=getRoundingDecimals(e,n)}};return e.encoderFactory&&(s.encode=e.encoderFactory({getChannels:()=>e.channels})),e.multipleEncodeFactory&&(s.encodeMultiple=e.multipleEncodeFactory({getChannels:()=>e.channels})),s}function createConfigurationIdSchema(e){return optional(pipe(number(`configurationId needs to be a number`),minValue(1,`configurationId needs to be at least 1`),maxValue(e,`configurationId needs to be at most ${e}`),integer(`configurationId needs to be an integer`)))}function createByteLimitSchema(){return optional(pipe(number(),minValue(0),integer()))}function createGenericTULIP2DownlinkActionSchema(e){let t=e.meta?.configurationId??!0,n=e.meta?.byteLimit??!0,r=e.extension??{};return object(_objectSpread2(t&&n?{deviceAction:literal(e.action),configurationId:createConfigurationIdSchema(e.maxConfigId),byteLimit:createByteLimitSchema()}:t?{deviceAction:literal(e.action),configurationId:createConfigurationIdSchema(e.maxConfigId)}:n?{deviceAction:literal(e.action),byteLimit:createByteLimitSchema()}:{deviceAction:literal(e.action)},r))}function createTULIP2DownlinkActionSchemaFactory(e){return t=>createGenericTULIP2DownlinkActionSchema({action:t.action,maxConfigId:e,extension:t.extension,meta:t.meta})}function createTulip2DownlinkMainConfigurationSchema(e){let t={publicationFactorWhenAlarm:pipe(number(),minValue(1),maxValue(2880),integer()),publicationFactorWhenNoAlarm:pipe(number(),minValue(1),maxValue(2880),integer())};return e.mainConfigBLE&&Object.assign(t,{isBLEEnabled:boolean()}),e.mainConfigSingleMeasuringRate?Object.assign(t,{measuringRate:pipe(number(),minValue(60),maxValue(86400),integer())}):Object.assign(t,{measuringRateWhenNoAlarm:pipe(number(),minValue(60),maxValue(86400),integer()),measuringRateWhenAlarm:pipe(number(),minValue(60),maxValue(86400),integer())}),object(t)}function createTulip2DownlinkChannelSchema(e,t,n){let r=e.end-e.start,i=n?.deadBandMaxSpanFactor??1,a=n?.slopeMaxSpanFactor??1,o=n?.measureOffsetMinSpanFactor??1,s=n?.measureOffsetMaxSpanFactor??1,c={alarms:optional(object({deadBand:pipe(number(),minValue(0),maxValue(r*i),transform(e=>Math.round(e/r*100*100))),lowThreshold:optional(pipe(number(),minValue(e.start),maxValue(e.end),transform(t=>Math.round((t-e.start)/r*100*100+2500)))),highThreshold:optional(pipe(number(),minValue(e.start),maxValue(e.end),transform(t=>Math.round((t-e.start)/r*100*100+2500)))),lowThresholdWithDelay:optional(object({value:pipe(number(),minValue(e.start),maxValue(e.end),transform(t=>Math.round((t-e.start)/r*100*100+2500))),delay:pipe(number(),minValue(0),maxValue(65535),integer())})),highThresholdWithDelay:optional(object({value:pipe(number(),minValue(e.start),maxValue(e.end),transform(t=>Math.round((t-e.start)/r*100*100+2500))),delay:pipe(number(),minValue(0),maxValue(65535),integer())})),risingSlope:optional(pipe(number(),minValue(0),maxValue(r*a),transform(e=>Math.round(e/r*100*100)))),fallingSlope:optional(pipe(number(),minValue(0),maxValue(r*a),transform(e=>Math.round(e/r*100*100))))}))};return t.channelsStartupTime&&Object.assign(c,{startUpTime:optional(pipe(number(),minValue(.1),maxValue(15),transform(e=>Math.round(e*10))))}),t.channelsMeasureOffset&&Object.assign(c,{measureOffset:optional(pipe(number(),minValue(-o*r),maxValue(s*r),transform(e=>Math.round(e/r*100*100))))}),object(c)}function createTULIP2DownlinkConfigurationActionSchema(e,t,n){let r=createTULIP2DownlinkActionSchemaFactory(t.maxConfigId),i=new Set(t.channelsBooleanOnly??[]),a=e.reduce((e,r)=>{let a=`channel${r.channelId}`;return i.has(a)?(e[a]=optional(union([literal(!1),literal(!0)])),e):(e[a]=optional(union([literal(!1),literal(!0),createTulip2DownlinkChannelSchema(r,t,n)])),e)},{});return r({action:`configuration`,extension:_objectSpread2({mainConfiguration:optional(createTulip2DownlinkMainConfigurationSchema(t))},a)})}function createDownlinkResetToFactorySchema(){return object({deviceAction:literal(`resetToFactory`)})}function createDownlinkResetBatteryIndicatorSchema(e){return createTULIP2DownlinkActionSchemaFactory(e.maxConfigId)({action:`resetBatteryIndicator`,meta:{byteLimit:!1}})}function createTULIP2DownlinkSchema(e,t,n,r){return variant(`deviceAction`,[createDownlinkResetToFactorySchema(),createTULIP2DownlinkConfigurationActionSchema(e,t,r),...n??[]])}function validateTULIP2DownlinkInput(e,t,n,r,i){let a=safeParse(createTULIP2DownlinkSchema(t,n,r,i),e);if(!a.success)throw Error(summarize(a.issues));return a.output}const NETRISF_MEASUREMENT_CHANNEL={name:`measurement`,channelId:0,start:-312.5,end:312.5},NETRISF_DEVICE_TEMPERATURE_CHANNEL={name:`device temperature`,channelId:1,start:-45,end:110},NETRISF_BATTERY_VOLTAGE_CHANNEL={name:`battery voltage`,channelId:2};function createNetrisFTULIP2Channels(){return[{channelId:NETRISF_MEASUREMENT_CHANNEL.channelId,name:NETRISF_MEASUREMENT_CHANNEL.name,start:NETRISF_MEASUREMENT_CHANNEL.start,end:NETRISF_MEASUREMENT_CHANNEL.end},{channelId:NETRISF_DEVICE_TEMPERATURE_CHANNEL.channelId,name:NETRISF_DEVICE_TEMPERATURE_CHANNEL.name,start:NETRISF_DEVICE_TEMPERATURE_CHANNEL.start,end:NETRISF_DEVICE_TEMPERATURE_CHANNEL.end,adjustMeasurementRangeDisallowed:!0}]}const ALARM_EVENTS={triggered:0,disappeared:1},PROCESS_ALARM_TYPES={"low threshold":1,"high threshold":2,"falling slope":4,"rising slope":8,"low threshold with delay":16,"high threshold with delay":32},PROCESS_ALARM_CHANNEL_NAMES_BY_ID={0:`measurement`,1:`device temperature`},DEVICE_ALARM_CAUSE_OF_FAILURE_NAMES_BY_VALUE={0:`generic`,1:`device dependent`},DEVICE_ALARM_TYPES={"low battery alarm":0,"duty cycle alarm":4},TECHNICAL_ALARM_TYPES={"Punctual sensor error":1,"Permanent sensor error":4,"strain value out of limit":32,"temperature value out of limit":64},PRODUCT_SUB_ID_NAMES={LoRaWAN:0,MIOTY:1},MEASUREMENT_TYPES_BY_ID={1:`absolute`,2:`relative`},PHYSICAL_UNIT_NAMES_MEASUREMENT={45:`N`,47:`kN`,55:`kg`,56:`g`,185:`µeps`},PHYSICAL_UNIT_NAMES_TEMPERATURE={32:`°C`,33:`°F`},CONFIG_STATUS_NAMES_BY_VALUE={2:`configuration applied`,3:`configuration rejected`,5:`configuration discarded`,6:`command success`,7:`command failed`},CONFIG_STATUS_COMMAND_TYPES={"get main configuration":4,"reset battery indicator":64,"get process alarm configuration strain":80,"get process alarm configuration temperature":81,"get channel property configuration strain":96,"get channel property configuration temperature":97},PHYSICAL_UNIT_NAMES_BY_ID=_objectSpread2(_objectSpread2({},PHYSICAL_UNIT_NAMES_MEASUREMENT),PHYSICAL_UNIT_NAMES_TEMPERATURE);Object.keys(PHYSICAL_UNIT_NAMES_MEASUREMENT).map(Number),Object.values(PHYSICAL_UNIT_NAMES_MEASUREMENT),Object.keys(PHYSICAL_UNIT_NAMES_TEMPERATURE).map(Number),Object.values(PHYSICAL_UNIT_NAMES_TEMPERATURE);function getConfigurationChannelSchema(){return optional(union([literal(!0),object({alarms:optional(literal(!0)),measureOffset:optional(literal(!0))})]))}function createNetrisFTULIP2GetConfigurationSchema(){return createTULIP2DownlinkActionSchemaFactory(31)({action:`getConfiguration`,extension:{mainConfiguration:optional(literal(!0)),channel0:getConfigurationChannelSchema(),channel1:getConfigurationChannelSchema()}})}const NETRISF_DOWNLINK_FEATURE_FLAGS={maxConfigId:31,channelsStartupTime:!1,channelsMeasureOffset:!0,mainConfigBLE:!0,mainConfigSingleMeasuringRate:!1},NETRISF_COMMANDS={RESET_FACTORY:1,SET_MAIN_CONFIG:2,GET_MAIN_CONFIG:4,SET_STRAIN_ALARM:32,SET_TEMPERATURE_ALARM:33,SET_STRAIN_PROPERTY:48,SET_TEMPERATURE_PROPERTY:49,RESET_BATTERY:64,GET_STRAIN_ALARM:80,GET_TEMPERATURE_ALARM:81,GET_STRAIN_PROPERTY:96,GET_TEMPERATURE_PROPERTY:97};function getChannelKeys(e){return Object.keys(e).filter(e=>/^channel\d+$/.test(e))}function formatMainConfigurationInput(e){return e.mainConfiguration}function formatProcessAlarmInput(e){let t={},n=!1,r=getChannelKeys(e);for(let i of r){let r=e[i];r&&(r===!0?(t[i]=!0,n=!0):typeof r==`object`&&`alarms`in r&&typeof r.alarms==`object`&&(t[i]=r.alarms,n=!0))}return n?t:void 0}function formatMeasureOffsetInput(e,t){if(t?.channelsMeasureOffset===!1)return;let n={},r=!1,i=getChannelKeys(e);for(let t of i){let i=e[t];i&&typeof i==`object`&&`measureOffset`in i&&i.measureOffset!==void 0&&(n[t]={offset:i.measureOffset},r=!0)}return r?n:void 0}function formatDownlinkOutput(e){return{bytes:e,fPort:1}}function formatMultipleDownlinkOutput(e){return{frames:e,fPort:1}}function pushUint32(e,t){e.push(t>>24&255,t>>16&255,t>>8&255,t&255)}function pushUint16(e,t){e.push(t>>8&255,t&255)}function pushSignedInt16(e,t){let n=t;t<0&&(n=65536+t),e.push(n>>8&255,n&255)}function buildResetFactoryCommand(){return[NETRISF_COMMANDS.RESET_FACTORY]}function buildResetBatteryCommand(){return[NETRISF_COMMANDS.RESET_BATTERY]}function buildGetMainConfigCommand(){return[NETRISF_COMMANDS.GET_MAIN_CONFIG]}function buildGetAlarmConfigCommand(e){return[e===0?NETRISF_COMMANDS.GET_STRAIN_ALARM:NETRISF_COMMANDS.GET_TEMPERATURE_ALARM]}function buildGetPropertyCommand(e){return[e===0?NETRISF_COMMANDS.GET_STRAIN_PROPERTY:NETRISF_COMMANDS.GET_TEMPERATURE_PROPERTY]}const MAX_MEASURING_RATE_SECONDS=604800;function buildNetrisFMainConfigCommand(e){if(!e)return[];if(e.measuringRateWhenNoAlarm<1||e.measuringRateWhenNoAlarm>MAX_MEASURING_RATE_SECONDS)throw Error(`measuringRateWhenNoAlarm must be between 1 and ${MAX_MEASURING_RATE_SECONDS} seconds.`);if(e.measuringRateWhenAlarm<1||e.measuringRateWhenAlarm>MAX_MEASURING_RATE_SECONDS)throw Error(`measuringRateWhenAlarm must be between 1 and ${MAX_MEASURING_RATE_SECONDS} seconds.`);let t=[NETRISF_COMMANDS.SET_MAIN_CONFIG];pushUint32(t,e.measuringRateWhenNoAlarm),pushUint16(t,e.publicationFactorWhenNoAlarm),pushUint32(t,e.measuringRateWhenAlarm),pushUint16(t,e.publicationFactorWhenAlarm),t.push(0);let n=e.isBLEEnabled===!1?1:0;return t.push(n),[t]}function buildNetrisFProcessAlarmCommands(e){if(!e)return[];let t=[];return e.channel0!==void 0&&t.push(buildNetrisFProcessAlarmBytes(NETRISF_COMMANDS.SET_STRAIN_ALARM,e.channel0)),e.channel1!==void 0&&t.push(buildNetrisFProcessAlarmBytes(NETRISF_COMMANDS.SET_TEMPERATURE_ALARM,e.channel1)),t}function buildNetrisFProcessAlarmBytes(e,t){let n=[e];if(t===!0)return n.push(0,0),n.push(0),n;pushUint16(n,t.deadBand);let r=0;return t.lowThreshold!==void 0&&(r|=128),t.highThreshold!==void 0&&(r|=64),t.fallingSlope!==void 0&&(r|=32),t.risingSlope!==void 0&&(r|=16),t.lowThresholdWithDelay!==void 0&&(r|=8),t.highThresholdWithDelay!==void 0&&(r|=4),n.push(r),t.lowThreshold!==void 0&&pushUint16(n,t.lowThreshold),t.highThreshold!==void 0&&pushUint16(n,t.highThreshold),t.fallingSlope!==void 0&&pushUint16(n,t.fallingSlope),t.risingSlope!==void 0&&pushUint16(n,t.risingSlope),t.lowThresholdWithDelay!==void 0&&(pushUint16(n,t.lowThresholdWithDelay.value),pushUint16(n,t.lowThresholdWithDelay.delay)),t.highThresholdWithDelay!==void 0&&(pushUint16(n,t.highThresholdWithDelay.value),pushUint16(n,t.highThresholdWithDelay.delay)),n}function buildNetrisFMeasureOffsetCommands(e){if(!e)return[];let t=[];if(e.channel0?.offset!==void 0){let n=[NETRISF_COMMANDS.SET_STRAIN_PROPERTY];pushSignedInt16(n,e.channel0.offset),t.push(n)}if(e.channel1?.offset!==void 0){let n=[NETRISF_COMMANDS.SET_TEMPERATURE_PROPERTY];pushSignedInt16(n,e.channel1.offset),t.push(n)}return t}function ffd(e,t){if(t=Math.floor(t),t<=0)throw Error(`Limit must be greater than 0`);let n=[];return e.sort((e,t)=>t.length-e.length).forEach(e=>{let r=e.length;if(r>t)throw Error(`Packet is too big to fit in any bin`);let i=!1;for(let a of n)if(t-a.length>=r){a.push(...e),i=!0;break}i||n.push(e)}),n}function buildNetrisFDownlinkFrame(e,t){if(e.length===0)throw Error(`No Downlink commands were provided to build the downlink frame.`);let n=[t.configId,0];for(let t of e)n.push(...t);if(n.length>t.byteLimit)throw Error(`Downlink frame exceeds byte limit of ${t.byteLimit} bytes (got ${n.length} bytes).`);return n}function buildNetrisFDownlinkFrames(e,t){if(e.length===0)throw Error(`No Downlink commands were provided for encoding.`);let n=ffd(e,t.byteLimit-2),r=n.length-1,i=[];for(let e=0;e<n.length;e++){let a=e<<4|r;i.push([t.configId,a,...n[e]])}return i}function NETRISFTULIP2EncodeHandler(e,t=!1){switch(e.deviceAction){case`resetToFactory`:{let e=encodeResetToFactory();return t?formatMultipleDownlinkOutput([e]):formatDownlinkOutput(e)}case`resetBatteryIndicator`:{let n=encodeResetBatteryIndicator(e);return t?formatMultipleDownlinkOutput([n]):formatDownlinkOutput(n)}case`getConfiguration`:return encodeGetConfiguration(e,t);case`configuration`:return encodeDownlinkConfiguration(e,t);default:throw Error(`Unknown device action: ${e.deviceAction}`)}}function encodeResetToFactory(){return buildNetrisFDownlinkFrame([buildResetFactoryCommand()],{configId:1,maxConfigId:NETRISF_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:1/0})}function encodeResetBatteryIndicator(e){let t=e.configurationId??1;return buildNetrisFDownlinkFrame([buildResetBatteryCommand()],{configId:t,maxConfigId:NETRISF_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:1/0})}function encodeDownlinkConfiguration(e,t){let n=e.configurationId??1,r=e.byteLimit??51,i=[...buildNetrisFMainConfigCommand(formatMainConfigurationInput(e)),...buildNetrisFProcessAlarmCommands(formatProcessAlarmInput(e)),...buildNetrisFMeasureOffsetCommands(formatMeasureOffsetInput(e,NETRISF_DOWNLINK_FEATURE_FLAGS))];if(i.length===0)throw Error(`No configuration commands were provided for the downlink frame.`);return t?formatMultipleDownlinkOutput(buildNetrisFDownlinkFrames(i,{configId:n,maxConfigId:NETRISF_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:r})):formatDownlinkOutput(buildNetrisFDownlinkFrame(i,{configId:n,byteLimit:r,maxConfigId:NETRISF_DOWNLINK_FEATURE_FLAGS.maxConfigId}))}function encodeGetConfiguration(e,t){let n=[];if(e.mainConfiguration&&n.push(buildGetMainConfigCommand()),e.channel0===!0?(n.push(buildGetAlarmConfigCommand(0)),n.push(buildGetPropertyCommand(0))):e.channel0&&typeof e.channel0==`object`&&(e.channel0.alarms&&n.push(buildGetAlarmConfigCommand(0)),e.channel0.measureOffset&&n.push(buildGetPropertyCommand(0))),e.channel1===!0?(n.push(buildGetAlarmConfigCommand(1)),n.push(buildGetPropertyCommand(1))):e.channel1&&typeof e.channel1==`object`&&(e.channel1.alarms&&n.push(buildGetAlarmConfigCommand(1)),e.channel1.measureOffset&&n.push(buildGetPropertyCommand(1))),n.length===0)throw Error(`No get configuration commands were provided.`);let r=e.configurationId??1,i=e.byteLimit??1/0,a=buildNetrisFDownlinkFrame(n,{configId:r,maxConfigId:NETRISF_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:i});return t?formatMultipleDownlinkOutput([a]):formatDownlinkOutput(a)}const ERROR_VALUE=65535,handleDataMessage=(e,t)=>{if(e.bytes.length!==7)throw Error(`Data message (0x01/0x02) requires 7 bytes, but received ${e.bytes.length} bytes`);let n=e.bytes[0],r=e.bytes[1],i=e.bytes[2]/10,a=e.bytes[3]<<8|e.bytes[4],o=e.bytes[5]<<8|e.bytes[6],s=t.channels.find(e=>e.channelId===NETRISF_MEASUREMENT_CHANNEL.channelId),c=t.channels.find(e=>e.channelId===NETRISF_DEVICE_TEMPERATURE_CHANNEL.channelId);if(!s||!c)throw Error(`Channel configuration missing for measurement or temperature channel`);let l=roundValue(TULIPValueToValue(a,s),t.roundingDecimals),u=roundValue(TULIPValueToValue(o,c),t.roundingDecimals);return{data:{messageType:n,configurationId:r,measurement:{channels:[{channelId:s.channelId,channelName:s.name,value:l},{channelId:c.channelId,channelName:c.name,value:u},{channelId:NETRISF_BATTERY_VOLTAGE_CHANNEL.channelId,channelName:NETRISF_BATTERY_VOLTAGE_CHANNEL.name,value:roundValue(i,t.roundingDecimals)}]}}}},handleProcessAlarmMessage=(e,t)=>{if(e.bytes.length<5||(e.bytes.length-2)%3!=0)throw Error(`Process alarm message (0x03) requires at least 5 bytes (and target byte count 3n+2), but received ${e.bytes.length} bytes`);let n=e.bytes[1],r=[],i=[];for(let n=2,a=0;n<e.bytes.length;n+=3,a+=1){let o=e.bytes[n],s=(o&128)>>7,c=(o&64)>>6,l=o&63,u=e.bytes[n+1]<<8|e.bytes[n+2],d={lowThreshold:!!(l&PROCESS_ALARM_TYPES[`low threshold`]),highThreshold:!!(l&PROCESS_ALARM_TYPES[`high threshold`]),fallingSlope:!!(l&PROCESS_ALARM_TYPES[`falling slope`]),risingSlope:!!(l&PROCESS_ALARM_TYPES[`rising slope`]),lowThresholdDelay:!!(l&PROCESS_ALARM_TYPES[`low threshold with delay`]),highThresholdDelay:!!(l&PROCESS_ALARM_TYPES[`high threshold with delay`])},f=Object.entries(ALARM_EVENTS).find(([,e])=>e===s)?.[0],p=PROCESS_ALARM_CHANNEL_NAMES_BY_ID[c];if(!f)throw Error(`Unknown event ${s} in process alarm message`);if(!p)throw Error(`Unknown channelId ${c} in process alarm message`);let m=t.channels.find(e=>e.channelId===c);if(!m)throw Error(`Channel configuration missing for channelId ${c} in process alarm message`);let h;h=u===ERROR_VALUE?ERROR_VALUE:l===PROCESS_ALARM_TYPES[`falling slope`]||l===PROCESS_ALARM_TYPES[`rising slope`]?roundValue(slopeValueToValue(u,m),t.roundingDecimals):roundValue(TULIPValueToValue(u,m),t.roundingDecimals),r[a]={channelId:c,channelName:p,event:s,eventName:f,alarmFlags:d,value:h},h===ERROR_VALUE&&i.push(`Invalid data for ${p} channel`)}let a={data:{messageType:3,configurationId:n,processAlarms:r}};return i.length>0&&(a.warnings=i),a},handleTechnicalAlarmMessage=e=>{if(e.bytes.length!==3)throw Error(`Technical alarm message (0x04) requires 3 bytes, but received ${e.bytes.length} bytes`);let t=e.bytes[1],n=e.bytes[2],r=(n&128)>>7,i=n&127,a=Object.entries(ALARM_EVENTS).find(([,e])=>e===r)?.[0];if(!a)throw Error(`Unknown event ${r} in technical alarm message`);let o=Object.entries(TECHNICAL_ALARM_TYPES).find(([,e])=>(i&e)!==0);if(!o)throw Error(`Unknown technical alarm type ${i} in technical alarm message`);let[s,c]=o;return{data:{messageType:4,configurationId:t,technicalAlarms:[{alarmType:c,alarmTypeName:s,event:r,eventName:a}]}}},handleDeviceAlarmMessage=e=>{if(e.bytes.length<3||e.bytes.length>4)throw Error(`Device alarm message (0x05) requires 3 or 4 bytes, but received ${e.bytes.length} bytes`);let t=e.bytes[1],n=e.bytes[2],r=(n&128)>>7,i=Object.entries(ALARM_EVENTS).find(([,e])=>e===r)?.[0];if(!i)throw Error(`Unknown event ${r} in device alarm message`);let a=(n&96)>>6,o=DEVICE_ALARM_CAUSE_OF_FAILURE_NAMES_BY_VALUE[a]??DEVICE_ALARM_CAUSE_OF_FAILURE_NAMES_BY_VALUE[1],s=n&31,c=Object.entries(DEVICE_ALARM_TYPES).find(([,e])=>e===s);if(!c)throw Error(`Unknown alarmType ${s} in device alarm message`);let[l,u]=c,d={event:r,eventName:i,causeOfFailure:a,causeOfFailureName:o,alarmType:u,alarmTypeName:l};if(u===DEVICE_ALARM_TYPES[`low battery alarm`]){if(e.bytes.length<4)throw Error(`Device alarm 05 payload missing battery value byte`);d.batteryValue=e.bytes[3]/10}return{data:{messageType:5,configurationId:t,deviceAlarm:d}}},handleConfigurationStatusMessage=(e,t)=>{if(e.bytes.length<3)throw Error(`Configuration status message (0x06) requires at least 3 bytes, but received ${e.bytes.length} bytes`);let n=e.bytes[1],r=e.bytes[2]>>4&15,i=CONFIG_STATUS_NAMES_BY_VALUE[r];if(!i)throw Error(`Unknown configuration status value ${r} in configuration status message`);let a=r,o;if(e.bytes.length>3){let n=e.bytes[3];if(n===CONFIG_STATUS_COMMAND_TYPES[`get main configuration`]){if(e.bytes.length<19)throw Error(`Get main configuration response requires 19 bytes total, but received ${e.bytes.length}`);let t=e.bytes[4],n=e.bytes[5]*16777216+(e.bytes[6]<<16)+(e.bytes[7]<<8)+e.bytes[8]>>>0,r=e.bytes[9]<<8|e.bytes[10],i=e.bytes[11]*16777216+(e.bytes[12]<<16)+(e.bytes[13]<<8)+e.bytes[14]>>>0,a=e.bytes[15]<<8|e.bytes[16],s=e.bytes[18]===0;o={commandType:CONFIG_STATUS_COMMAND_TYPES[`get main configuration`],commandTypeName:`get main configuration`,commandStatus:t,measurementPeriodNoAlarm:n,transmissionMultiplierNoAlarm:r,measurementPeriodWithAlarm:i,transmissionMultiplierWithAlarm:a,bleAdvertisingEnabled:s}}else if(n===CONFIG_STATUS_COMMAND_TYPES[`reset battery indicator`]){if(e.bytes.length<5)throw Error(`Reset battery indicator response requires 5 bytes total, but received ${e.bytes.length}`);let t=e.bytes[4],n=t===0;o={commandType:CONFIG_STATUS_COMMAND_TYPES[`reset battery indicator`],commandTypeName:`reset battery indicator`,commandStatus:t,resetSuccess:n}}else if(n===CONFIG_STATUS_COMMAND_TYPES[`get process alarm configuration strain`]||n===CONFIG_STATUS_COMMAND_TYPES[`get process alarm configuration temperature`]){if(e.bytes.length<9)throw Error(`Process alarm configuration response requires at least 9 bytes total, but received ${e.bytes.length}`);let r=n===80?`get process alarm configuration strain`:`get process alarm configuration temperature`,i=e.bytes[4],a=e.bytes[5],s=PROCESS_ALARM_CHANNEL_NAMES_BY_ID[a];if(!s)throw Error(`Unknown channel ${a} in process alarm configuration response`);let c=e.bytes[6]<<8|e.bytes[7],l=t.channels.find(e=>e.channelId===a);if(!l)throw Error(`Channel configuration missing for channelId ${a} in process alarm configuration response`);let u=roundValue(slopeValueToValue(c,l),t.roundingDecimals),d=e.bytes[8],f=(d&128)!=0,p=(d&64)!=0,m=(d&32)!=0,h=(d&16)!=0,g=(d&8)!=0,_=(d&4)!=0,v=9,y,b,x,S,C,w,T,E;f&&(y=roundValue(TULIPValueToValue(e.bytes[v]<<8|e.bytes[v+1],l),t.roundingDecimals),v+=2),p&&(b=roundValue(TULIPValueToValue(e.bytes[v]<<8|e.bytes[v+1],l),t.roundingDecimals),v+=2),m&&(x=roundValue(slopeValueToValue(e.bytes[v]<<8|e.bytes[v+1],l),t.roundingDecimals),v+=2),h&&(S=roundValue(slopeValueToValue(e.bytes[v]<<8|e.bytes[v+1],l),t.roundingDecimals),v+=2),g&&(C=roundValue(TULIPValueToValue(e.bytes[v]<<8|e.bytes[v+1],l),t.roundingDecimals),v+=2,w=e.bytes[v]<<8|e.bytes[v+1],v+=2),_&&(T=roundValue(TULIPValueToValue(e.bytes[v]<<8|e.bytes[v+1],l),t.roundingDecimals),v+=2,E=e.bytes[v]<<8|e.bytes[v+1],v+=2),o={commandType:n,commandTypeName:r,commandStatus:i,channel:a,channelName:s,deadBand:u,lowThreshold:f,lowThresholdValue:y,highThreshold:p,highThresholdValue:b,fallingSlope:m,fallingSlopeValue:x,risingSlope:h,risingSlopeValue:S,lowThresholdWithDelay:g,lowThresholdWithDelayValue:C,lowThresholdWithDelayDelay:w,highThresholdWithDelay:_,highThresholdWithDelayValue:T,highThresholdWithDelayDelay:E}}else if(n===CONFIG_STATUS_COMMAND_TYPES[`get channel property configuration strain`]||n===CONFIG_STATUS_COMMAND_TYPES[`get channel property configuration temperature`]){if(e.bytes.length<9)throw Error(`Channel property configuration response requires 9 bytes total, but received ${e.bytes.length}`);let t=n===96?`get channel property configuration strain`:`get channel property configuration temperature`,r=e.bytes[4],i=e.bytes[5],a=PROCESS_ALARM_CHANNEL_NAMES_BY_ID[i];if(!a)throw Error(`Unknown channel ${i} in channel property configuration response`);let s=e.bytes[6]<<8|e.bytes[7];o={commandType:n,commandTypeName:t,commandStatus:r,channel:i,channelName:a,measurementOffset:s>32767?s-65536:s}}else throw Error(`Unknown command type 0x${n.toString(16).padStart(2,`0`)} in configuration status message`)}return{data:{messageType:6,configurationId:n,configStatus:a,configStatusName:i,commandResponse:o}}},handleDeviceIdentificationMessage=e=>{if(e.bytes.length<8||e.bytes.length>38)throw Error(`Device identification message (0x07) requires at least 8 and at most 38 bytes, but received ${e.bytes.length} bytes`);if(e.bytes.length<38)throw Error(`Device identification frame 07 has not all bytes included, received ${e.bytes.length}/38 bytes`);let t=e.bytes[1],n=e.bytes[2];if(n!==11)throw Error(`Invalid productId ${n} in device identification message. Expected 11 (NETRIS_F).`);let r=e.bytes[3],i=Object.entries(PRODUCT_SUB_ID_NAMES).find(([,e])=>e===r)?.[0];if(!i)throw Error(`Unknown productSubId ${r} in device identification message. Only LoRaWAN (0) is supported.`);let a=`${e.bytes[4]>>4&15}.${e.bytes[4]&15}.${e.bytes[5]}`,o=`${e.bytes[6]>>4&15}.${e.bytes[6]&15}.${e.bytes[7]}`,s=``;for(let t=8;t<19;t+=1){let n=e.bytes[t];if(n===0)break;s+=String.fromCharCode(n)}let c=MEASUREMENT_TYPES_BY_ID[e.bytes[19]]??`unknown`,l=intTuple4ToFloat32WithThreshold([e.bytes[20],e.bytes[21],e.bytes[22],e.bytes[23]]),u=intTuple4ToFloat32WithThreshold([e.bytes[24],e.bytes[25],e.bytes[26],e.bytes[27]]),d=intTuple4ToFloat32WithThreshold([e.bytes[28],e.bytes[29],e.bytes[30],e.bytes[31]]),f=intTuple4ToFloat32WithThreshold([e.bytes[32],e.bytes[33],e.bytes[34],e.bytes[35]]),p=e.bytes[36],m=PHYSICAL_UNIT_NAMES_BY_ID[p]??`Unknown`,h=e.bytes[37],g=PHYSICAL_UNIT_NAMES_BY_ID[h]??`Unknown`;return{data:{messageType:7,configurationId:t,deviceInformation:{productId:n,productIdName:`NETRIS_F`,productSubId:r,productSubIdName:i,wirelessModuleFirmwareVersion:a,wirelessModuleHardwareVersion:o,serialNumber:s,measurementType:c,measurementRangeStart:l,measurementRangeEnd:u,measurementRangeStartDeviceTemperature:d,measurementRangeEndDeviceTemperature:f,measurementUnit:p,unitName:m,deviceTemperatureUnit:h,deviceTemperatureUnitName:g}}}},handleKeepAliveMessage=e=>{if(e.bytes.length!==3)throw Error(`Keep alive message (0x08) requires 3 bytes, but received ${e.bytes.length} bytes`);let t=e.bytes[1],n=e.bytes[2];return{data:{messageType:8,configurationId:t,deviceStatistic:{batteryLevelNewEvent:(n&128)>>7!=0,batteryLevelPercent:n&127}}}},netrisFEncoderFactory=e=>{let t=NETRISF_DOWNLINK_FEATURE_FLAGS;return n=>NETRISFTULIP2EncodeHandler(validateTULIP2DownlinkInput(n,e.getChannels(),t,[createDownlinkResetBatteryIndicatorSchema(t),createNetrisFTULIP2GetConfigurationSchema()]))},netrisFMultipleEncodeFactory=e=>{let t=NETRISF_DOWNLINK_FEATURE_FLAGS;return n=>NETRISFTULIP2EncodeHandler(validateTULIP2DownlinkInput(n,e.getChannels(),t,[createDownlinkResetBatteryIndicatorSchema(t),createNetrisFTULIP2GetConfigurationSchema()]),!0)};function createNetrisFTULIP2Codec(){return defineTULIP2Codec({deviceName:NETRISF_NAME,roundingDecimals:4,channels:createNetrisFTULIP2Channels(),handlers:{1:handleDataMessage,2:handleDataMessage,3:handleProcessAlarmMessage,4:handleTechnicalAlarmMessage,5:handleDeviceAlarmMessage,6:handleConfigurationStatusMessage,7:handleDeviceIdentificationMessage,8:handleKeepAliveMessage},encoderFactory:netrisFEncoderFactory,multipleEncodeFactory:netrisFMultipleEncodeFactory})}function createTargetsSchema(e){return object(Object.entries(e).reduce((e,[t,n])=>{if(!t.startsWith(`sensor`))return e;let r=n;return e[t]=optional(object(Object.entries(r).reduce((e,[t])=>(t.startsWith(`channel`)&&(e[t]=optional(boolean())),e),{}))),e},{}))}function createGetAlarmStatusSchema(e){return object({processAlarmRequested:optional(boolean()),cmAlarmRequested:optional(boolean()),sensorAlarmRequested:optional(boolean()),channelAlarmRequested:optional(boolean()),targets:optional(createTargetsSchema(e))})}function createChannelIdentificationReadSchema(e){let t=e.registerConfig.tulip3IdentificationRegisters,n={};t.measurand&&(n.measurand=optional(boolean())),t.unit&&(n.unit=optional(boolean())),t.minMeasureRange&&(n.minMeasureRange=optional(boolean())),t.maxMeasureRange&&(n.maxMeasureRange=optional(boolean())),t.minPhysicalLimit&&(n.minPhysicalLimit=optional(boolean())),t.maxPhysicalLimit&&(n.maxPhysicalLimit=optional(boolean())),t.accuracy&&(n.accuracy=optional(boolean())),t.offset&&(n.offset=optional(boolean())),t.gain&&(n.gain=optional(boolean())),t.calibrationDate&&(n.calibrationDate=optional(boolean()));let r=e.registerConfig.channelSpecificIdentificationRegisters;for(let e of Object.keys(r))n[e]=optional(boolean());return object(n)}function createChannelConfigurationReadSchema(e){let t=e.registerConfig.tulip3ConfigurationRegisters,n={};t.protocolDataType&&(n.protocolDataType=optional(boolean())),t.processAlarmEnabled&&(n.processAlarmEnabled=optional(boolean())),t.processAlarmDeadBand&&(n.processAlarmDeadBand=optional(boolean())),t.lowThresholdAlarmValue&&(n.lowThresholdAlarmValue=optional(boolean())),t.highThresholdAlarmValue&&(n.highThresholdAlarmValue=optional(boolean())),t.fallingSlopeAlarmValue&&(n.fallingSlopeAlarmValue=optional(boolean())),t.risingSlopeAlarmValue&&(n.risingSlopeAlarmValue=optional(boolean())),t.lowThresholdWithDelayAlarmValue&&(n.lowThresholdWithDelayAlarmValue=optional(boolean())),t.lowThresholdWithDelayAlarmDelay&&(n.lowThresholdWithDelayAlarmDelay=optional(boolean())),t.highThresholdWithDelayAlarmValue&&(n.highThresholdWithDelayAlarmValue=optional(boolean())),t.highThresholdWithDelayAlarmDelay&&(n.highThresholdWithDelayAlarmDelay=optional(boolean()));let r=e.registerConfig.channelSpecificConfigurationRegisters;for(let e of Object.keys(r))n[e]=optional(boolean());return object(n)}function createChannelReadMultipleSchema(e){return object({identification:optional(createChannelIdentificationReadSchema(e)),configuration:optional(createChannelConfigurationReadSchema(e))})}function createSensorIdentificationReadSchema(e){let t=e.registerConfig.tulip3IdentificationRegisters,n={};t.sensorType&&(n.sensorType=optional(boolean())),t.existingChannels&&(n.existingChannels=optional(boolean())),t.firmwareVersion&&(n.firmwareVersion=optional(boolean())),t.hardwareVersion&&(n.hardwareVersion=optional(boolean())),t.productionDate&&(n.productionDate=optional(boolean())),t.serialNumberPart1&&(n.serialNumberPart1=optional(boolean())),t.serialNumberPart2&&(n.serialNumberPart2=optional(boolean()));let r=e.registerConfig.sensorSpecificIdentificationRegisters;for(let e of Object.keys(r))n[e]=optional(boolean());return object(n)}function createSensorConfigurationReadSchema(e){let t=e.registerConfig.tulip3ConfigurationRegisters,n={};t.samplingChannels&&(n.samplingChannels=optional(boolean())),t.bootTime&&(n.bootTime=optional(boolean())),t.communicationTimeout&&(n.communicationTimeout=optional(boolean())),t.communicationRetryCount&&(n.communicationRetryCount=optional(boolean()));let r=e.registerConfig.sensorSpecificConfigurationRegisters;for(let e of Object.keys(r))n[e]=optional(boolean());return object(n)}function createCommunicationModuleIdentificationReadSchema(e){let t=e.registerConfig.tulip3IdentificationRegisters,n={};return t.productId&&(n.productId=optional(boolean())),t.productSubId&&(n.productSubId=optional(boolean())),t.channelPlan&&(n.channelPlan=optional(boolean())),t.connectedSensors&&(n.connectedSensors=optional(boolean())),t.firmwareVersion&&(n.firmwareVersion=optional(boolean())),t.hardwareVersion&&(n.hardwareVersion=optional(boolean())),t.productionDate&&(n.productionDate=optional(boolean())),t.serialNumberPart1&&(n.serialNumberPart1=optional(boolean())),t.serialNumberPart2&&(n.serialNumberPart2=optional(boolean())),object(n)}function createCommunicationModuleConfigurationReadSchema(e){let t=e.registerConfig.tulip3ConfigurationRegisters,n={};return t.measuringPeriodAlarmOff&&(n.measuringPeriodAlarmOff=optional(boolean())),t.measuringPeriodAlarmOn&&(n.measuringPeriodAlarmOn=optional(boolean())),t.transmissionRateAlarmOff&&(n.transmissionRateAlarmOff=optional(boolean())),t.transmissionRateAlarmOn&&(n.transmissionRateAlarmOn=optional(boolean())),t.overVoltageThreshold&&(n.overVoltageThreshold=optional(boolean())),t.underVoltageThreshold&&(n.underVoltageThreshold=optional(boolean())),t.overTemperatureCmChip&&(n.overTemperatureCmChip=optional(boolean())),t.underTemperatureCmChip&&(n.underTemperatureCmChip=optional(boolean())),t.downlinkAnswerTimeout&&(n.downlinkAnswerTimeout=optional(boolean())),t.fetchAdditionalDownlinkTimeInterval&&(n.fetchAdditionalDownlinkTimeInterval=optional(boolean())),t.enableBleAdvertising&&(n.enableBleAdvertising=optional(boolean())),object(n)}function createSensorReadMultipleSchema(e){let t=Object.entries(e).reduce((e,[t,n])=>(t.startsWith(`channel`)&&(e[t]=optional(createChannelReadMultipleSchema(n))),e),{});return object(_objectSpread2({identification:optional(createSensorIdentificationReadSchema(e)),configuration:optional(createSensorConfigurationReadSchema(e))},t))}function createReadInputDataMultipleSchema(e){let t=Object.entries(e).reduce((e,[t,n])=>(t.startsWith(`sensor`)&&(e[t]=optional(createSensorReadMultipleSchema(n))),e),{});return object(_objectSpread2({communicationModule:optional(object({identification:optional(createCommunicationModuleIdentificationReadSchema(e)),configuration:optional(createCommunicationModuleConfigurationReadSchema(e))}))},t))}functi