UNPKG

@w2a-iiot/raw-javascript-parsers

Version:

This packages contain the raw built javascript parsers for WIKA's IIoT devices.

2 lines 147 kB
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 isUnsafeProperty(e){return e===`__proto__`}function isDeepKey(e){switch(typeof e){case`number`:case`symbol`:return!1;case`string`:return e.includes(`.`)||e.includes(`[`)||e.includes(`]`)}}function toKey(e){var t;return typeof e==`string`||typeof e==`symbol`?e:Object.is(e==null||(t=e.valueOf)==null?void 0:t.call(e),-0)?`-0`:String(e)}function toString(e){if(e==null)return``;if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(toString).join(`,`);let t=String(e);return t===`0`&&Object.is(Number(e),-0)?`-0`:t}function toPath(e){if(Array.isArray(e))return e.map(toKey);if(typeof e==`symbol`)return[e];e=toString(e);let t=[],n=e.length;if(n===0)return t;let r=0,i=``,a=``,o=!1;for(e.charCodeAt(0)===46&&(t.push(``),r++);r<n;){let s=e[r];a?s===`\\`&&r+1<n?(r++,i+=e[r]):s===a?a=``:i+=s:o?s===`"`||s===`'`?a=s:s===`]`?(o=!1,t.push(i),i=``):i+=s:s===`[`?(o=!0,i&&=(t.push(i),``)):s===`.`?i&&=(t.push(i),``):i+=s,r++}return i&&t.push(i),t}function get(e,t,n){if(e==null)return n;switch(typeof t){case`string`:{if(isUnsafeProperty(t))return n;let r=e[t];return r===void 0?isDeepKey(t)?get(e,toPath(t),n):n:r}case`number`:case`symbol`:{typeof t==`number`&&(t=toKey(t));let r=e[t];return r===void 0?n:r}default:{if(Array.isArray(t))return getWithPath(e,t,n);if(t=Object.is(t?.valueOf(),-0)?`-0`:String(t),isUnsafeProperty(t))return n;let r=e[t];return r===void 0?n:r}}}function getWithPath(e,t,n){if(t.length===0)return n;let r=e;for(let e=0;e<t.length;e++){if(r==null||isUnsafeProperty(t[e]))return n;r=r[t[e]]}return r===void 0?n:r}function isObject(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function isEqualsSameValueZero(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}const IS_UNSIGNED_INTEGER=/^(?:0|[1-9]\d*)$/;function isIndex(e,t=2**53-1){switch(typeof e){case`number`:return Number.isInteger(e)&&e>=0&&e<t;case`symbol`:return!1;case`string`:return IS_UNSIGNED_INTEGER.test(e)}}function isSymbol(e){return typeof e==`symbol`||e instanceof Symbol}const regexIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,regexIsPlainProp=/^\w*$/;function isKey(e,t){return Array.isArray(e)?!1:typeof e==`number`||typeof e==`boolean`||e==null||isSymbol(e)?!0:typeof e==`string`&&(regexIsPlainProp.test(e)||!regexIsDeepProp.test(e))||t!=null&&Object.hasOwn(t,e)}const assignValue=(e,t,n)=>{let r=e[t];(!(Object.hasOwn(e,t)&&isEqualsSameValueZero(r,n))||n===void 0&&!(t in e))&&(e[t]=n)};function updateWith(e,t,n,r){if(e==null&&!isObject(e))return e;let i;i=isKey(t,e)?[t]:Array.isArray(t)?t:toPath(t);let a=n(get(e,i)),o=e;for(let t=0;t<i.length&&o!=null;t++){let n=toKey(i[t]);if(isUnsafeProperty(n))continue;let s;if(t===i.length-1)s=a;else{let a=o[n],c=r?.(a,n,e);s=c===void 0?isObject(a)?a:isIndex(i[t+1])?[]:{}:c}assignValue(o,n,s),o=o[n]}return e}function set(e,t,n){return updateWith(e,t,()=>n,()=>void 0)}const MAX_ADDRESS=2047;function encodeAddressingField(e,t){if(e<0||e>MAX_ADDRESS)throw RangeError(`Address ${e} is out of range. Must be between 0 and ${MAX_ADDRESS} (11 bits).`);if(t<0||t>31)throw RangeError(`Size ${t} is out of range. Must be between 0 and 31 (5 bits).`);let n=e<<5|t&31;return[n>>8,n&255]}function decodeAddressingField(e,t){return{address:(e<<8|t)>>5,size:t&31}}const spontaneousStatusLookup={0:`Success`,1:`Unsupported command`,2:`Logical error`,3:`Memory error`,4:`Device error`,5:`Wrong frame format`,6:`Communication session lock`},productSubIdLookup={0:`LoRaWAN class A`,1:`BLE only`,2:`LoRaWAN class A`,3:`LoRaWAN class B`,4:`LoRaWAN class C`,5:`Mioty class Z`,6:`Mioty class A`,7:`Mioty class B`},configurationStatusLookup={0:`Configuration received but not applied`,1:`Configuration received and applied with success`,2:`Configuration rejected - Tried to write a read only register`,3:`Configuration rejected - At least one register has an invalid value`,4:`Configuration rejected - The combination register start address/number of bytes is wrong`,5:`Entire configuration discarded because of invalid parameter combination`,6:`Entire configuration discarded because no answer from the cloud`,7:`Missing frame`,8:`Frame rejected - frame number already received`},protocolDataTypeLookup={0:`float - IEEE754`,1:`int 24 - Fixed-point s16.7 (Q16.7)`,2:`int 16 - Fixed-point s10.5 (Q10.5)`,3:`uint16 - TULIP scale 2500 - 12500`},protocolDataTypeLengthLookup={"float - IEEE754":4,"int 24 - Fixed-point s16.7 (Q16.7)":3,"int 16 - Fixed-point s10.5 (Q10.5)":2,"uint16 - TULIP scale 2500 - 12500":2},measurandLookup={1:`Temperature`,2:`Temperature difference`,3:`Pressure (gauge)`,4:`Pressure (absolute)`,5:`Pressure (differential)`,6:`Flow (vol.)`,7:`Flow (mass)`,8:`Force`,9:`Mass`,10:`Level`,11:`Length`,12:`Volume`,13:`Current`,14:`Voltage`,15:`Resistance`,16:`Capacitance`,17:`Inductance`,18:`Relative`,19:`Time`,20:`Frequency`,21:`Speed`,22:`Acceleration`,23:`Density`,24:`Density (gauge pressure at 20 °C)`,25:`Density (absolute pressure at 20 °C)`,26:`Humidity (relative)`,27:`Humidity (absolute)`,28:`Angle of rotation / inclination`,29:`Strain`},unitsLookup={1:`°C`,2:`°F`,3:`K`,4:`°R`,7:`bar`,8:`mbar`,9:`μbar`,10:`Pa`,11:`hPa`,12:`kPa`,13:`MPa`,14:`psi`,15:`lbf/ft²`,16:`kN/m²`,17:`N/cm²`,18:`atm`,19:`kg/cm²`,20:`kg/mm²`,21:`μmHg`,22:`mmHg`,23:`cmHg`,24:`inHg`,25:`mmH2O`,26:`mH2O`,27:`inH2O`,28:`ftH2O`,45:`N`,46:`daN`,47:`kN`,48:`MN`,49:`kp`,50:`lbf`,51:`ozf`,52:`dyn`,55:`kg`,56:`g`,57:`mg`,58:`lb`,60:`mm`,61:`cm`,62:`m`,63:`μm`,64:`ft`,65:`in`,70:`l`,71:`ml`,72:`m³`,73:`gal (UK)`,74:`gal (US)`,75:`ft³`,76:`in³`,82:`mΩ`,83:`Ω`,84:`kΩ`,86:`μV`,87:`mV`,88:`V`,90:`mA`,91:`μA`,93:`μF`,94:`nF`,95:`pF`,97:`mH`,98:`μH`,100:`%`,101:`‰`,102:`ppm`,105:`°`,106:`rad`,108:`counts`,110:`kg/m³`,111:`g/m³`,112:`mg/m³`,113:`μg/m³`,114:`kg/l`,115:`g/l`,116:`lb/ft³`,120:`l/min`,121:`l/s`,122:`m³/h`,123:`m³/s`,124:`cfm`,140:`kg/s`,141:`kg/h`,160:`s`,161:`min`,162:`h`,163:`d`,167:`Hz`,168:`kHz`,170:`m/s`,171:`cm/s`,172:`ft/min`,173:`ft/s`,180:`m/s²`,181:`ft/s²`,185:`µeps`};function intArrayToASCII(e){return String.fromCharCode(...e)}function intTuple1ToUInt8(e){return e[0]&255}function intTuple2ToUInt16(e){return(e[0]&255)<<8|e[1]&255}function intTuple3ToSemVer(e){return`${e[0]}.${e[1]}.${e[2]}`}function intTuple3ToDate(e){return`${e[0]+2e3}-${e[1].toString().padStart(2,`0`)}-${e[2].toString().padStart(2,`0`)}`}function intTuple1ToBoolean(e){return!!(e[0]&255)}function intTuple4ToUInt32(e){return(e[0]&255)<<24|(e[1]&255)<<16|(e[2]&255)<<8|e[3]&255}function intTuple1ToInt8(e){let t=e[0]&255;return t>127?t-256:t}function intTuple1ToConnectedSensors(e){let t={};for(let n=1;n<=4;n++)t[`sensor${n}`]=!!(e[0]&1<<n-1);return t}function intTuple1ToExistingChannels(e){let t={};for(let n=1;n<=8;n++)t[`channel${n}`]=!!(e[0]&1<<n-1);return t}function intTuple1ToProductSubId(e){let t=intTuple1ToUInt8(e),n=productSubIdLookup[t];if(n===void 0)throw Error(`Unknown product sub-ID value: ${t} (0x${t.toString(16).padStart(2,`0`)})`);return n}function intTuple1ToChannelPlan(e){return intTuple1ToUInt8(e)}function intTuple1ToMeasurand(e){let t=intTuple1ToUInt8(e),n=measurandLookup[t];if(n===void 0)throw Error(`Unknown measurand value: ${t} (0x${t.toString(16).padStart(2,`0`)})`);return n}function intTuple1ToUnit(e){let t=intTuple1ToUInt8(e),n=unitsLookup[t];if(n===void 0)throw Error(`Unknown unit value: ${t} (0x${t.toString(16).padStart(2,`0`)})`);return n}function intTuple2ToAccuracyPercent(e){return intTuple2ToUInt16(e)/1e3}function intTuple1ToSampleChannels(e){let t={};for(let n=1;n<=8;n++)t[`channel${n}`]=!!(e[0]&1<<n-1);return t}function intTuple1ToProtocolDataType(e){let t=intTuple1ToUInt8(e);return protocolDataTypeLookup[t]||`Unknown type: ${t}`}function intTuple1ToProcessAlarmEnabled(e){let t=e[0]&255;return{lowThreshold:!!(t&128),highThreshold:!!(t&64),fallingSlope:!!(t&32),risingSlope:!!(t&16),lowThresholdWithDelay:!!(t&8),highThresholdWithDelay:!!(t&4)}}function createRegisterEntry(e,t,n){return{path:e,size:t,parsing:n}}function parseRegisterBlocks(e,t={}){let{startPosition:n=2}=t,r=[],i=n;for(;i<e.length;){if(i+1>=e.length){let t=e.length-i;throw RangeError(`Incomplete register block at position ${i}: Found ${t} byte(s) but need 2 bytes for addressing field. Data length: ${e.length}, Expected: addressing field (2 bytes) + register data. This suggests the data stream is truncated or malformed.`)}let{address:t,size:n}=decodeAddressingField(e[i],e[i+1]);if(i+2+n>e.length){let r=e.length-i-2;throw RangeError(`Incomplete register data for address 0x${t.toString(16)} at position ${i}: Need ${n} bytes but only ${r} bytes available in data stream. Total data length: ${e.length}, Current position: ${i}, Required: 2 bytes (addressing) + ${n} bytes (data) = ${2+n} bytes total. This suggests the data stream was cut off or the register size field is incorrect.`)}let a=e.slice(i+2,i+2+n);r.push({startRegisterAddress:t,value:a}),i+=2+n}return r}function evaluateRegisterBlocks(e,t){let n={};for(let r of t){let{startRegisterAddress:t,value:i}=r,a=t;for(;i.length>0;){let o=e[a];if(!o)throw ReferenceError(`Unknown register address 0x${a.toString(16)} in lookup table. This indicates an invalid message sent from the device. This register was expected during parsing of block starting at 0x${t.toString(16)}. This ${a===t?`is the first register in the block`:`is not the first register in the block`}. Starting address: 0x${t.toString(16)}. Available addresses in lookup: [${Object.keys(e).map(e=>`0x${Number(e).toString(16)}`).join(`, `)}]. `);if(`type`in o&&o.type===`guard`)throw RangeError(o.message);let s=o;if(i.length<s.size)throw RangeError(`Insufficient data for register 0x${a.toString(16)} (${s.path}): Expected ${s.size} bytes but only ${i.length} bytes remaining in block. Block started at address 0x${t.toString(16)} with ${r.value.length} total bytes. Current parsing position within block: ${r.value.length-i.length} bytes processed. This suggests a mismatch between register definitions and actual data structure.`);let c=i.slice(0,s.size);i.splice(0,s.size),a+=s.size;try{set(n,s.path,s.parsing(c))}catch(e){let n=e instanceof Error?e.message:String(e);throw Error(`Failed to parse register 0x${(a-s.size).toString(16)} (${s.path}): ${n}. Register data: [${c.map(e=>`0x${e.toString(16).padStart(2,`0`)}`).join(`, `)}] (${c.length} bytes, expected ${s.size} bytes). Block started at address 0x${t.toString(16)}. This may indicate invalid data values or a parsing function error.`,{cause:e})}}}return n}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 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},TECHNICAL_ALARM_TYPES={"ALU saturation error":1,"sensor memory integrity error":2,"sensor busy error":4,reserved:8,"sensor communication error":16,"pressure out of limit":32,"temperature out of limit":64},DEVICE_ALARM_TYPES={"battery low":0,"acknowledged message not emitted":4},ALARM_EVENTS={triggered:0,disappeared:1},DEVICE_ALARM_CAUSE_OF_FAILURE={generic:0,"device dependent":1},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 pressure":80,"get process alarm configuration temperature":81,"get channel property configuration pressure":96,"get channel property configuration temperature":97},PRESSURE_TYPES={absolute:1,"gauge / relative":2},PRESSURE_UNITS={bar:7,MPa:237,psi:6};function createPEWTULIP2DropConfigurationSchema(){return createTULIP2DownlinkActionSchemaFactory(127)({action:`dropConfiguration`,meta:{byteLimit:!1}})}function getConfigurationChannelSchema(){return optional(union([literal(!0),object({alarms:optional(literal(!0)),measureOffset:optional(literal(!0))})]))}function createPEWTULIP2GetConfigurationSchema(){return createTULIP2DownlinkActionSchemaFactory(127)({action:`getConfiguration`,extension:{mainConfiguration:optional(literal(!0)),channel0:getConfigurationChannelSchema(),channel1:getConfigurationChannelSchema()}})}const PEWTULIP2_CHANNEL_0={name:`pressure`,channelId:0,defaultRange:{start:0,end:10}},PEWTULIP2_CHANNEL_1={name:`device temperature`,channelId:1,defaultRange:{start:-45,end:110}};function createTULIP2PEWChannels(){return[{channelId:PEWTULIP2_CHANNEL_0.channelId,name:PEWTULIP2_CHANNEL_0.name,start:PEWTULIP2_CHANNEL_0.defaultRange.start,end:PEWTULIP2_CHANNEL_0.defaultRange.end},{channelId:PEWTULIP2_CHANNEL_1.channelId,name:PEWTULIP2_CHANNEL_1.name,start:PEWTULIP2_CHANNEL_1.defaultRange.start,end:PEWTULIP2_CHANNEL_1.defaultRange.end,adjustMeasurementRangeDisallowed:!0}]}const PEW_DOWNLINK_FEATURE_FLAGS={maxConfigId:127,channelsStartupTime:!1,channelsMeasureOffset:!0,mainConfigBLE:!0,mainConfigSingleMeasuringRate:!1},PEW_COMMANDS={RESET_FACTORY:1,SET_MAIN_CONFIG:2,DROP_ON_AIR:3,GET_MAIN_CONFIG:4,DISABLE_PRESSURE:16,DISABLE_TEMPERATURE:17,SET_PRESSURE_ALARM:32,SET_TEMPERATURE_ALARM:33,SET_PRESSURE_PROPERTY:48,SET_TEMPERATURE_PROPERTY:49,RESET_BATTERY:64,GET_PRESSURE_ALARM:80,GET_TEMPERATURE_ALARM:81,GET_PRESSURE_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 formatDisableChannelInput(e){let t={},n=!1,r=getChannelKeys(e);for(let i of r)e[i]===!1&&(t[i]=!0,n=!0);return n?t:void 0}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[PEW_COMMANDS.RESET_FACTORY]}function buildResetBatteryCommand(){return[PEW_COMMANDS.RESET_BATTERY]}function buildDropOnAirCommand(){return[PEW_COMMANDS.DROP_ON_AIR]}function buildGetMainConfigCommand(){return[PEW_COMMANDS.GET_MAIN_CONFIG]}function buildGetAlarmConfigCommand(e){return[e===0?PEW_COMMANDS.GET_PRESSURE_ALARM:PEW_COMMANDS.GET_TEMPERATURE_ALARM]}function buildGetPropertyCommand(e){return[e===0?PEW_COMMANDS.GET_PRESSURE_PROPERTY:PEW_COMMANDS.GET_TEMPERATURE_PROPERTY]}function buildPEWDisableChannelCommands(e){if(!e)return[];let t=[];return e.channel0===!0&&t.push([PEW_COMMANDS.DISABLE_PRESSURE]),e.channel1===!0&&t.push([PEW_COMMANDS.DISABLE_TEMPERATURE]),t}const MAX_TOTAL_INTERVAL_SECONDS=172800;function buildPEWMainConfigCommand(e,t){if(!e)return[];let n=e.measuringRateWhenNoAlarm*e.publicationFactorWhenNoAlarm,r=e.measuringRateWhenAlarm*e.publicationFactorWhenAlarm;if(n>MAX_TOTAL_INTERVAL_SECONDS)throw Error(`The product of measuringRateWhenNoAlarm and publicationFactorWhenNoAlarm must not exceed 172_800 seconds (48 hours).`);if(r>MAX_TOTAL_INTERVAL_SECONDS)throw Error(`The product of measuringRateWhenAlarm and publicationFactorWhenAlarm must not exceed 172_800 seconds (48 hours).`);let i=[PEW_COMMANDS.SET_MAIN_CONFIG];pushUint32(i,e.measuringRateWhenNoAlarm),pushUint16(i,e.publicationFactorWhenNoAlarm),pushUint32(i,e.measuringRateWhenAlarm),pushUint16(i,e.publicationFactorWhenAlarm),i.push(0);let a=e.isBLEEnabled===!1?1:0;if(i.push(a),i.length>t)throw Error(`Main configuration command exceeds byte limit of ${t} bytes.`);return[i]}function buildPEWProcessAlarmCommands(e){if(!e)return[];let t=[];if(e.channel0!==void 0){let n=buildPEWProcessAlarmBytes(PEW_COMMANDS.SET_PRESSURE_ALARM,e.channel0);t.push(n)}if(e.channel1!==void 0){let n=buildPEWProcessAlarmBytes(PEW_COMMANDS.SET_TEMPERATURE_ALARM,e.channel1);t.push(n)}return t}function buildPEWProcessAlarmBytes(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 buildPEWMeasureOffsetCommands(e){if(!e)return[];let t=[];if(e.channel0?.offset!==void 0){let n=[PEW_COMMANDS.SET_PRESSURE_PROPERTY];pushSignedInt16(n,e.channel0.offset),t.push(n)}if(e.channel1?.offset!==void 0){let n=[PEW_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 buildPEWDownlinkFrame(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===0)throw Error(`No bytes were generated for the downlink frame.`);if(n.length>t.byteLimit)throw Error(`Downlink frame exceeds byte limit of ${t.byteLimit} bytes (got ${n.length} bytes).`);return n}function buildPEWDownlinkFrames(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 PEWTULIP2EncodeHandler(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`dropConfiguration`:{let n=encodeDropConfiguration(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 buildPEWDownlinkFrame([buildResetFactoryCommand()],{configId:1,maxConfigId:PEW_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:1/0})}function encodeResetBatteryIndicator(e){let t=e.configurationId??1;return buildPEWDownlinkFrame([buildResetBatteryCommand()],{configId:t,maxConfigId:PEW_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:1/0})}function encodeDropConfiguration(e){let t=e.configurationId??1;return buildPEWDownlinkFrame([buildDropOnAirCommand()],{configId:t,maxConfigId:PEW_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:1/0})}function encodeDownlinkConfiguration(e,t){let n=e.configurationId??1,r=e.byteLimit??51,i=r-2,a=[...buildPEWMainConfigCommand(formatMainConfigurationInput(e),i),...buildPEWDisableChannelCommands(formatDisableChannelInput(e)),...buildPEWProcessAlarmCommands(formatProcessAlarmInput(e)),...buildPEWMeasureOffsetCommands(formatMeasureOffsetInput(e,PEW_DOWNLINK_FEATURE_FLAGS))];if(a.length===0)throw Error(`No configuration commands were provided for the downlink frame.`);return t?formatMultipleDownlinkOutput(buildPEWDownlinkFrames(a,{configId:n,maxConfigId:PEW_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:r})):formatDownlinkOutput(buildPEWDownlinkFrame(a,{configId:n,byteLimit:r,maxConfigId:PEW_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=buildPEWDownlinkFrame(n,{configId:r,maxConfigId:PEW_DOWNLINK_FEATURE_FLAGS.maxConfigId,byteLimit:i});return t?formatMultipleDownlinkOutput([a]):formatDownlinkOutput(a)}const 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=roundValue(TULIPValueToValue(e.bytes[3]<<8|e.bytes[4],t.channels[0]),t.roundingDecimals),a=roundValue(TULIPValueToValue(e.bytes[5]<<8|e.bytes[6],t.channels[1]),t.roundingDecimals),o=e.bytes[2]/10;return{data:{configurationId:r,messageType:n,measurement:{channels:[{channelId:0,channelName:`pressure`,value:i},{channelId:1,channelName:`device temperature`,value:a},{channelId:2,channelName:`battery voltage`,value:o}]}}}},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=[];for(let n=2;n<e.bytes.length;n+=3){let i=(e.bytes[n]&64)>>6,a=t.channels.find(e=>e.channelId===i);if(!a)throw TypeError(`Unknown channel ID: ${i} in process alarm message`);let o=(e.bytes[n]&128)>>7,s=e.bytes[n]&63,c={lowThreshold:!!(s&PROCESS_ALARM_TYPES[`low threshold`]),highThreshold:!!(s&PROCESS_ALARM_TYPES[`high threshold`]),fallingSlope:!!(s&PROCESS_ALARM_TYPES[`falling slope`]),risingSlope:!!(s&PROCESS_ALARM_TYPES[`rising slope`]),lowThresholdDelay:!!(s&PROCESS_ALARM_TYPES[`low threshold with delay`]),highThresholdDelay:!!(s&PROCESS_ALARM_TYPES[`high threshold with delay`])},l=e.bytes[n+1]<<8|e.bytes[n+2],u=c.fallingSlope||c.risingSlope?slopeValueToValue(l,a):TULIPValueToValue(l,a);r.push({channelId:i,channelName:a.name,value:roundValue(u,t.roundingDecimals),event:o,alarmFlags:c,eventName:Object.keys(ALARM_EVENTS).find(e=>ALARM_EVENTS[e]===o)})}let i=[],a={data:{messageType:3,configurationId:n,processAlarms:r}};for(let e of r)e.value===65535&&i.push(`Invalid data for ${e.channelName} channel`);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=[];return Object.entries(TECHNICAL_ALARM_TYPES).forEach(([e,t])=>{(i&t)!==0&&a.push(e)}),{data:{messageType:4,configurationId:t,technicalAlarms:[{event:r,eventName:Object.keys(ALARM_EVENTS).find(e=>ALARM_EVENTS[e]===r),alarmType:i,alarmTypeNames: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.keys(ALARM_EVENTS).find(e=>ALARM_EVENTS[e]===r),a=(n&96)>>6,o=Object.keys(DEVICE_ALARM_CAUSE_OF_FAILURE).find(e=>DEVICE_ALARM_CAUSE_OF_FAILURE[e]===a),s=n&31,c=Object.keys(DEVICE_ALARM_TYPES).find(e=>DEVICE_ALARM_TYPES[e]===s),l;s===0&&e.bytes.length===4&&(l=e.bytes[3]/10);let u={event:r,eventName:i,alarmType:s,alarmTypeName:c,causeOfFailure:a,causeOfFailureName:o};return s===0&&(u.value=l),{data:{messageType:5,configurationId:t,deviceAlarm:u}}};function parseMainConfigurationData(e){if(e.length!==14)throw Error(`Main configuration payload requires 14 bytes, but received ${e.length} bytes`);return{measurementPeriodNoAlarm:e[0]*16777216+(e[1]<<16)+(e[2]<<8)+e[3]>>>0,transmissionMultiplierNoAlarm:intTuple2ToUInt16([e[4],e[5]]),measurementPeriodWithAlarm:e[6]*16777216+(e[7]<<16)+(e[8]<<8)+e[9]>>>0,transmissionMultiplierWithAlarm:intTuple2ToUInt16([e[10],e[11]]),bleAdvertisingEnabled:e[13]===0}}function parseProcessAlarmConfigurationData(e,t){if(e.length<4)throw Error(`Process alarm configuration payload requires at least 4 bytes, but received ${e.length} bytes`);let n=e[0],r=t.channels.find(e=>e.channelId===n);if(!r)throw Error(`Unknown channel ${n} in process alarm configuration message`);let i=roundValue(slopeValueToValue(intTuple2ToUInt16([e[1],e[2]]),r),t.roundingDecimals),a=e[3],o=(a&128)!=0,s=(a&64)!=0,c=(a&32)!=0,l=(a&16)!=0,u=(a&8)!=0,d=(a&4)!=0,f=4+(o?2:0)+(s?2:0)+(c?2:0)+(l?2:0)+(u?4:0)+(d?4:0);if(e.length!==f)throw Error(`Process alarm configuration payload contains an invalid length: ${e.length}`);let p=4,m,h,g,_,v,y,b,x;return o&&(m=roundValue(TULIPValueToValue(intTuple2ToUInt16([e[p],e[p+1]]),r),t.roundingDecimals),p+=2),s&&(h=roundValue(TULIPValueToValue(intTuple2ToUInt16([e[p],e[p+1]]),r),t.roundingDecimals),p+=2),c&&(g=roundValue(slopeValueToValue(intTuple2ToUInt16([e[p],e[p+1]]),r),t.roundingDecimals),p+=2),l&&(_=roundValue(slopeValueToValue(intTuple2ToUInt16([e[p],e[p+1]]),r),t.roundingDecimals),p+=2),u&&(v=roundValue(TULIPValueToValue(intTuple2ToUInt16([e[p],e[p+1]]),r),t.roundingDecimals),p+=2,y=intTuple2ToUInt16([e[p],e[p+1]]),p+=2),d&&(b=roundValue(TULIPValueToValue(intTuple2ToUInt16([e[p],e[p+1]]),r),t.roundingDecimals),p+=2,x=intTuple2ToUInt16([e[p],e[p+1]]),p+=2),{channel:n,channelName:r.name,deadBand:i,lowThreshold:o,lowThresholdValue:m,highThreshold:s,highThresholdValue:h,fallingSlope:c,fallingSlopeValue:g,risingSlope:l,risingSlopeValue:_,lowThresholdWithDelay:u,lowThresholdWithDelayValue:v,lowThresholdWithDelayDelay:y,highThresholdWithDelay:d,highThresholdWithDelayValue:b,highThresholdWithDelayDelay:x}}function parseChannelPropertyConfigurationData(e,t){if(e.length!==4)throw Error(`Channel property configuration payload requires 4 bytes, but received ${e.length} bytes`);let n=e[0],r=t.channels.find(e=>e.channelId===n);if(!r)throw Error(`Unknown channel ${n} in channel property configuration message`);let i=intTuple2ToUInt16([e[1],e[2]]),a=i>32767?i-65536:i;return{channel:n,channelName:r.name,measurementOffset:a}}const 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,s;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=parseMainConfigurationData(e.bytes.slice(5,19));s=_objectSpread2({commandType:CONFIG_STATUS_COMMAND_TYPES[`get main configuration`],commandTypeName:`get main configuration`,commandStatus:t},n)}else if(n===CONFIG_STATUS_COMMAND_TYPES[`reset battery indicat