@danidoble/webserial 4.5.0-alpha.1 → 4.5.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/jsd.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("./webserial-core-3UL91lxi.cjs"),N=require("./devices-BndwHuvP.cjs");class _{static USE_BIG_ENDIAN=!0;static USE_REFLECTED=!1;static calculate(e){let t;if(this.USE_REFLECTED){t=0;for(const s of e){t^=s&255;for(let n=0;n<8;n++)t&1?t=t>>1^40961:t>>=1}}else{t=0;for(const s of e){t^=s<<8;for(let n=0;n<8;n++)t&32768?t=(t<<1^32773)&65535:t=t<<1&65535}}return this.USE_BIG_ENDIAN?[t>>8&255,t&255]:[t&255,t>>8&255]}static getConfig(){return{bigEndian:this.USE_BIG_ENDIAN,reflected:this.USE_REFLECTED}}}class b{_name="tcpip";get name(){return this._name}get packetId(){return 0}_overridePacketId(e){console.warn(`TCP/IP transport does not use packet IDs. Ignoring override to ${e}.`)}toLittleEndian(e){return[e&255,e>>8&255]}buildPacket(e,t,s){const n=t?t.split("").map(h=>h.charCodeAt(0)):[],a=6+n.length,i=this.toLittleEndian(a),c=this.toLittleEndian(s),o=this.toLittleEndian(e);return{bytes:[...i,...c,...o,...n],packetId:0}}escapeBytes(e){const t=[];for(const s of e)s===192?t.push(219,220):s===219?t.push(219,221):t.push(s);return t}buildAckPacket(e){const n=[192,2,e],[a,i]=_.calculate(n),c=[2,e,a,i];return[192,...this.escapeBytes(c),192]}}class k extends b{packetIdCounter=1;_name="rs232";get packetId(){return this.packetIdCounter}_overridePacketId(e){this.packetIdCounter=e&255}getNextPacketId(){const e=this.packetIdCounter;return this.packetIdCounter=this.packetIdCounter+1&255,this.packetIdCounter===0&&(this.packetIdCounter=1),e}buildPacket(e,t,s){const i=this.getNextPacketId(),{bytes:c}=super.buildPacket(e,t,s),o=[192,1,i,...c],[h,d]=_.calculate(o),l=[1,i,...c,h,d];return{bytes:[192,...this.escapeBytes(l),192],packetId:i}}}const r={requestMachineStatus:100,requestStatusChannel:101,requestStatusSelection:102,configureSelectionDispense:103,addChannelToSelection:104,requestMachineIdentification:105,programWorkingTemperature:106,programWaitingTimings:107,resetSoldOutChannels:108,programTimeWaitingAfterPickup:109,requestJSDVersion:110,requestFaultMachine:111,manageJSDDispensingQueue:112,defineSpecialCharacteristicsSelection:113,configurePerishableProducts:114,requestActiveFaults:115,configureExtendedDispenseStatusData:116,requestStatusTrayPositioningPhototransistors:117,dispenseFromChannel:150,dispenseFromSelection:151,controlLights:152,resetFaultsAndSelfTest:153,performCollectCycle:154,dispenseFromChannelExtended:155,restartingTheJSDKnowingThatItIsDangerous:156,responseFormatCmdWrong:200,responseMachineStatus:201,responseStatusChannel:202,responseStatusSelection:203,responseDispenseStatus:204,responseConfigurationSelectionDispense:205,responseConfigurationChannelsLinkedToSelection:206,responseMachineIdentification:207,responseCurrentTemperature:208,responseReportEventsAlarmsAndFaults:209,responseNewTimingWaitingForProductCollection:210,responsePerformingProductCollectionCycle:211,responseResetMachineSoldOutChannels:212,responseNewTimingWaitingAfterProductCollection:213,responseJSDVersion:214,responseActiveFaults:215,responseJSDDispensingQueue:216,responseSpecialCharacteristicsSelection:217,responsePerishableProducts:218,responseActiveFaultsList:219,responseJSDResetStatus:220,responseExtendedDispenseStatusData:221,responseTraysPositioningPhototransistorsStatus:222,jsdErrorLicenseTemporarilyBlocked:300,jsdErrorLicenseNotActive:301,jsdErrorCommandNotExecutable:302},C=p=>Object.keys(r).find(t=>r[t]===p)||"Unknown",f={VISION:402,LICENSING:600,MANIFESTS_AND_LOGS:601,SIMULATOR_VISION:1e4},L=p=>[f.VISION,f.SIMULATOR_VISION].includes(p),F=p=>[f.LICENSING].includes(p),w=p=>[f.MANIFESTS_AND_LOGS].includes(p);class u{transport;static APP_ID=f.VISION;constructor(e){this.transport=e}static connection({transport:e,packetId:t}){return e._overridePacketId(t||255),new u(e).requestJSDVersion()}requestMachineStatus({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.requestMachineStatus,t,u.APP_ID)}requestStatusChannel({machine:e,tray:t,channel:s}){const n=`${e},${t},${s}`;return this.transport.buildPacket(r.requestStatusChannel,n,u.APP_ID)}requestStatusSelection({selection:e}){const t=`${e}`;return this.transport.buildPacket(r.requestStatusSelection,t,u.APP_ID)}configureSelectionDispense({selection:e,speed:t,timePostRun:s}){const n=`${e},${t},${s}`;return this.transport.buildPacket(r.configureSelectionDispense,n,u.APP_ID)}getSelectionDispenseConfig({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.configureSelectionDispense,t,u.APP_ID)}addChannelToSelection({selection:e,machine:t,tray:s,channel:n}){const a=`${e},${t},${s},${n}`;return this.transport.buildPacket(r.addChannelToSelection,a,u.APP_ID)}getChannelsLinkedToSelection({selection:e}){const t=`${e}`;return this.transport.buildPacket(r.addChannelToSelection,t,u.APP_ID)}requestMachineIdentification({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.requestMachineIdentification,t,u.APP_ID)}formatTemperature(e){const t=e>=0?"+":"-",s=Math.abs(e).toFixed(1).padStart(4,"0");return`${t}${s}`}programWorkingTemperature({machine:e,temperature:t,enable:s}){const n=this.formatTemperature(t),i=`${e},${n},${s?1:0}`;return this.transport.buildPacket(r.programWorkingTemperature,i,u.APP_ID)}getWorkingTemperature({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.programWorkingTemperature,t,u.APP_ID)}programWaitingTimings({collectPosition:e,dispenseManoeuvres:t,afterPickup:s}){const n=`${e},${t},${s}`;return this.transport.buildPacket(r.programWaitingTimings,n,u.APP_ID)}getWaitingTimings(){return this.transport.buildPacket(r.programWaitingTimings,"",u.APP_ID)}resetSoldOutChannels({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.resetSoldOutChannels,t,u.APP_ID)}programTimeWaitingAfterPickup({time:e}){const t=`${e}`;return this.transport.buildPacket(r.programTimeWaitingAfterPickup,t,u.APP_ID)}getTimeWaitingAfterPickup(){return this.transport.buildPacket(r.programTimeWaitingAfterPickup,"",u.APP_ID)}requestJSDVersion(){return this.transport.buildPacket(r.requestJSDVersion,"",u.APP_ID)}requestFaultMachine({machine:e,type:t}){const n=`${e},${{"report-active":0,"report-inactive":1,"clear-inactive":2}[t]}`;return this.transport.buildPacket(r.requestFaultMachine,n,u.APP_ID)}requestReportActiveFaults(e){return this.requestFaultMachine({machine:e,type:"report-active"})}requestReportInactiveFaults(e){return this.requestFaultMachine({machine:e,type:"report-inactive"})}requestClearInactiveFaults(e){return this.requestFaultMachine({machine:e,type:"clear-inactive"})}manageJSDDispensingQueue({type:e}){const t=`${e}`;return this.transport.buildPacket(r.manageJSDDispensingQueue,t,u.APP_ID)}requestJSDDispensingQueueStatus(){return this.manageJSDDispensingQueue({type:0})}clearJSDDispensingQueue(){return this.manageJSDDispensingQueue({type:1})}defineSpecialCharacteristicsSelection({selection:e,perishable:t,fragileOrHeavy:s,typeAdjustElevator:n,timeAdjustElevator:a}){const d=`${e},${t?1:0},${s?1:0},${n==="lower"?0:1},${a}`;return this.transport.buildPacket(r.defineSpecialCharacteristicsSelection,d,u.APP_ID)}getSpecialCharacteristicsSelection({selection:e}){const t=`${e}`;return this.transport.buildPacket(r.defineSpecialCharacteristicsSelection,t,u.APP_ID)}configurePerishableProducts({machine:e,enable:t,temperatureLimit:s,minutesToExpiry:n}){const a=t?1:0,i=this.formatTemperature(s),c=`${e},${a},${i},${n}`;return this.transport.buildPacket(r.configurePerishableProducts,c,u.APP_ID)}requestActiveFaults({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.requestActiveFaults,t,u.APP_ID)}configureExtendedDispenseStatusData({enable:e}){const s=`${e?1:0}`;return this.transport.buildPacket(r.configureExtendedDispenseStatusData,s,u.APP_ID)}getExtendedDispenseStatusDataConfig(){return this.transport.buildPacket(r.configureExtendedDispenseStatusData,"",u.APP_ID)}requestStatusTrayPositioningPhototransistors({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.requestStatusTrayPositioningPhototransistors,t,u.APP_ID)}dispenseFromChannel({token:e,machine:t,tray:s,channel:n,speed:a,timePostRun:i}){const c=`${e},${t},${s},${n},${a},${i}`;return this.transport.buildPacket(r.dispenseFromChannel,c,u.APP_ID)}getDispenseStatusFromChannel({token:e}){const t=`${e}`;return this.transport.buildPacket(r.dispenseFromChannel,t,u.APP_ID)}dispenseFromSelection({token:e,selection:t}){const s=`${e},${t}`;return this.transport.buildPacket(r.dispenseFromSelection,s,u.APP_ID)}getDispenseStatusFromSelection({token:e}){const t=`${e}`;return this.transport.buildPacket(r.dispenseFromSelection,t,u.APP_ID)}controlLights({machine:e,turnOn:t}){const n=`${e},${t?1:0}`;return this.transport.buildPacket(r.controlLights,n,u.APP_ID)}resetFaultsAndSelfTest({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.resetFaultsAndSelfTest,t,u.APP_ID)}performCollectCycle({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.performCollectCycle,t,u.APP_ID)}dispenseFromChannelExtended({token:e,machine:t,tray:s,channel:n,speed:a,timePostRun:i,fragileOrHeavy:c,typeAdjustElevator:o,timeAdjustElevator:h}){const I=`${e},${t},${s},${n},${a},${i},${c?1:0},${o==="lower"?0:1},${h}`;return this.transport.buildPacket(r.dispenseFromChannelExtended,I,u.APP_ID)}getDispenseStatusFromChannelExtended({token:e}){const t=`${e}`;return this.transport.buildPacket(r.dispenseFromChannelExtended,t,u.APP_ID)}restartingTheJSDKnowingThatItIsDangerous(){return this.transport.buildPacket(r.restartingTheJSDKnowingThatItIsDangerous,"",u.APP_ID)}}function q(p){if(p.length>5)throw new Error(`Token must be max 5 characters, got ${p.length}`);return p}function T(){let p;do{const e=new Uint8Array(2);p=parseInt(crypto.getRandomValues(e).toString().replaceAll(",","")).toString(36)}while(p.length>5);return q(p)}const E={status:"NO-CONNECTED",machineInService:!1,doorOpen:!1,availabilityToDispense:"NOT-AVAILABLE-TO-DISPENSE",hasLightsOn:!1,temperature:""};class M{_commands;jsd;APP_ID=f.VISION;_machineStatus=[{...E},{...E},{...E},{...E}];constructor(e,t){this._commands=new u(t),this.jsd=e}_performingChannelAssignment={enabled:!1,selections:[],currentSelection:1};_dispensingTokens={};async send(e,t){return this.jsd._lastApplicationCode=this.APP_ID,this.jsd._toQueue(e,{alias:t.alias,waitResponse:t.waitResponse||!1,timeout:t.timeout||500})}get cmd(){return this._commands}_getMachineIndex(e){return e-1}isAvailableToDispense({machine:e=1}={}){const t=this._getMachineIndex(e);return["ELEVATOR-COLLECTION-POSITION","AVAILABLE-TO-DISPENSE"].includes(this._machineStatus[t]?.availabilityToDispense||"")&&this._machineStatus[t]?.machineInService===!0&&this._machineStatus[t]?.doorOpen===!1&&this._machineStatus[t]?.status==="CONNECTED"}async requestMachineStatus({machine:e=1}={}){const t=this._getMachineIndex(e),s=this.cmd.requestMachineStatus({machine:t});return await this.send(s,{alias:"requestMachineStatus"})}_getTrayChannelFromSelection(e){const t=Math.floor((e-1)/10)+11,s=(e-1)%10;return{tray:t,channel:s}}_getSelectionFromTrayChannel(e,t){return(e-11)*10+t+1}async requestStatusChannel({machine:e,selection:t}){const s=this._getMachineIndex(e),{tray:n,channel:a}=this._getTrayChannelFromSelection(t),i=this.cmd.requestStatusChannel({machine:s,tray:n,channel:a});return await this.send(i,{alias:"requestStatusChannel"})}async assignChannels({machine:e}){if(this._performingChannelAssignment.enabled)throw new Error("Channel assignment already in progress");this._performingChannelAssignment.enabled=!0;for(let t=1;t<=80;t++)await this.requestStatusChannel({machine:e,selection:t});return new Promise(t=>{const s=setInterval(()=>{if(this._performingChannelAssignment.enabled)return;clearInterval(s);const n=this._performingChannelAssignment.selections;this._performingChannelAssignment.selections=[],t(n)},200)})}async requestStatusSelection({selection:e}){const t=this.cmd.requestStatusSelection({selection:e});return await this.send(t,{alias:"requestStatusSelection"})}async configureSelectionDispense({selection:e,speed:t,timePostRun:s}){const n=this.cmd.configureSelectionDispense({selection:e,speed:t,timePostRun:s});return await this.send(n,{alias:"configureSelectionDispense"})}async requestSelectionDispenseConfig({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.getSelectionDispenseConfig({machine:t});return await this.send(s,{alias:"getSelectionDispenseConfig"})}async configureAddChannelToSelection({selection:e,machine:t,tray:s,channel:n}){const a=this._getMachineIndex(t),i=this.cmd.addChannelToSelection({selection:e,machine:a,tray:s,channel:n});return await this.send(i,{alias:"addChannelToSelection"})}async requestChannelsLinkedToSelection({selection:e}){const t=this.cmd.getChannelsLinkedToSelection({selection:e});return await this.send(t,{alias:"getChannelsLinkedToSelection"})}async requestMachineIdentification({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestMachineIdentification({machine:t});return await this.send(s,{alias:"requestMachineIdentification"})}async configureWorkingTemperature({machine:e,temperature:t,enable:s}){const n=this._getMachineIndex(e),a=this.cmd.programWorkingTemperature({machine:n,temperature:t,enable:s});return await this.send(a,{alias:"programWorkingTemperature"})}async requestWorkingTemperature({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.getWorkingTemperature({machine:t});return await this.send(s,{alias:"getWorkingTemperature"})}async configureWaitingTimings({collectPosition:e,dispenseManoeuvres:t,afterPickup:s}){const n=this.cmd.programWaitingTimings({collectPosition:e,dispenseManoeuvres:t,afterPickup:s});return await this.send(n,{alias:"programWaitingTimings"})}async requestWaitingTimings(){const e=this.cmd.getWaitingTimings();return await this.send(e,{alias:"getWaitingTimings"})}async resetSoldOutChannels({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.resetSoldOutChannels({machine:t});return await this.send(s,{alias:"resetSoldOutChannels"})}async resetAllErrors({machine:e}){return await Promise.all([this.clearInactiveFaults({machine:e}),this.resetSoldOutChannels({machine:e}),this.resetFaultsAndSelfTest({machine:e})])}async configureTimeWaitingAfterPickup({time:e}){const t=this.cmd.programTimeWaitingAfterPickup({time:e});return await this.send(t,{alias:"programTimeWaitingAfterPickup"})}async requestTimeWaitingAfterPickup(){const e=this.cmd.getTimeWaitingAfterPickup();return await this.send(e,{alias:"getTimeWaitingAfterPickup"})}async requestJSDVersion(){const e=this.cmd.requestJSDVersion();return await this.send(e,{alias:"requestJSDVersion"})}async requestReportActiveFaults({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestReportActiveFaults(t);return await this.send(s,{alias:"requestReportActiveFaults"})}async requestReportInactiveFaults({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestReportInactiveFaults(t);return await this.send(s,{alias:"requestReportInactiveFaults"})}async clearInactiveFaults({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestClearInactiveFaults(t);return await this.send(s,{alias:"requestClearInactiveFaults"})}async requestJSDDispensingQueueStatus(){const e=this.cmd.requestJSDDispensingQueueStatus();return await this.send(e,{alias:"requestJSDDispensingQueueStatus"})}async clearJSDDispensingQueue(){const e=this.cmd.clearJSDDispensingQueue();return await this.send(e,{alias:"clearJSDDispensingQueue"})}async configureSpecialCharacteristicsSelection({selection:e,perishable:t,fragileOrHeavy:s,typeAdjustElevator:n,timeAdjustElevator:a}){const i=this.cmd.defineSpecialCharacteristicsSelection({selection:e,perishable:t,fragileOrHeavy:s,typeAdjustElevator:n,timeAdjustElevator:a});return await this.send(i,{alias:"defineSpecialCharacteristicsSelection"})}requestSpecialCharacteristicsSelection({selection:e}){const t=this.cmd.getSpecialCharacteristicsSelection({selection:e});return this.send(t,{alias:"getSpecialCharacteristicsSelection"})}configurePerishableProducts({machine:e,enable:t,temperatureLimit:s,minutesToExpiry:n}){const a=this._getMachineIndex(e),i=this.cmd.configurePerishableProducts({machine:a,enable:t,temperatureLimit:s,minutesToExpiry:n});return this.send(i,{alias:"configurePerishableProducts"})}async requestActiveFaults({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestActiveFaults({machine:t});return await this.send(s,{alias:"requestActiveFaults"})}async configureExtendedDispenseStatusData({enable:e}){const t=this.cmd.configureExtendedDispenseStatusData({enable:e});return await this.send(t,{alias:"configureExtendedDispenseStatusData"})}async requestExtendedDispenseStatusDataConfig(){const e=this.cmd.getExtendedDispenseStatusDataConfig();return await this.send(e,{alias:"getExtendedDispenseStatusDataConfig"})}async requestStatusTrayPositioningPhototransistors({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestStatusTrayPositioningPhototransistors({machine:t});return await this.send(s,{alias:"requestStatusTrayPositioningPhototransistors"})}async dispenseFromChannel({machine:e,tray:t,channel:s,speed:n,timePostRun:a,cart:i=!1}){if(!this.isAvailableToDispense({machine:e}))throw new Error(`Machine ${e} is not available to dispense`);const c=this._getMachineIndex(e),o=T(),h=this.cmd.dispenseFromChannel({token:o,machine:c,tray:t,channel:s,speed:n,timePostRun:a});return await this.send(h,{alias:"dispenseFromChannel"}),this._dispensingTokens[o]={cart:!!i,resolve:()=>{delete this._dispensingTokens[o]},reject:()=>{}},new Promise((d,l)=>{this._dispensingTokens[o].resolve=d,this._dispensingTokens[o].reject=l})}async dispense({machine:e,selection:t,speed:s,timePostRun:n,cart:a=!1}){const{tray:i,channel:c}=this._getTrayChannelFromSelection(t);return this.dispenseFromChannel({machine:e,tray:i,channel:c,speed:s||5,timePostRun:n||0,cart:!!a})}async dispenseCart(e=[]){const t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));let s=[];for(const n of t)try{const a=await Promise.all(n.map(o=>this.dispense({machine:o.machine,selection:o.selection,cart:!0}))),i=[...new Set(n.map(o=>o.machine))];await new Promise(o=>{const h=setInterval(()=>{i.every(l=>this.getMachineStatus(l)?.availabilityToDispense==="AVAILABLE-TO-DISPENSE")&&(clearInterval(h),o(!0))},300)});for(const o of i)this._machineStatus[this._getMachineIndex(o)]?.availabilityToDispense==="WAITING-COLLECTION"&&this.emit("waiting-collection",{machine:o!==null?o+1:null});const c=n.map((o,h)=>({machine:o.machine,selection:o.selection,dispensed:a[h]}));s=s.concat(c)}catch(a){console.error("Error sending dispense command:",a)}return s}async requestDispenseStatusFromChannel({token:e}){const t=this.cmd.getDispenseStatusFromChannel({token:e});return await this.send(t,{alias:"getDispenseStatusFromChannel"})}async dispenseFromSelection({selection:e,cart:t=!1}){const s=T(),n=this.cmd.dispenseFromSelection({token:s,selection:e});return await this.send(n,{alias:"dispenseFromSelection"}),this._dispensingTokens[s]={cart:!!t,resolve:()=>{},reject:()=>{}},new Promise((a,i)=>{this._dispensingTokens[s].resolve=a,this._dispensingTokens[s].reject=i})}async requestDispenseStatusFromSelection({token:e}){const t=this.cmd.getDispenseStatusFromSelection({token:e});return await this.send(t,{alias:"getDispenseStatusFromSelection"})}async _configureLights({machine:e,turnOn:t,alias:s}){const n=this._getMachineIndex(e),a=this.cmd.controlLights({machine:n,turnOn:t});return await this.send(a,{alias:s})}async lightsOn({machine:e}){return this._configureLights({machine:e,turnOn:!0,alias:"lightsOn"})}async lightsOff({machine:e}){return this._configureLights({machine:e,turnOn:!1,alias:"lightsOff"})}async resetFaultsAndSelfTest({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.resetFaultsAndSelfTest({machine:t});return await this.send(s,{alias:"resetFaultsAndSelfTest"})}async collect({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.performCollectCycle({machine:t});return await this.send(s,{alias:"performCollectCycle"})}async dispenseFromChannelExtended({machine:e,tray:t,channel:s,speed:n,timePostRun:a,fragileOrHeavy:i,typeAdjustElevator:c,timeAdjustElevator:o,cart:h=!1}){if(!this.isAvailableToDispense({machine:e}))throw new Error(`Machine ${e} is not available to dispense`);const d=this._getMachineIndex(e),l=T(),m=this.cmd.dispenseFromChannelExtended({token:l,machine:d,tray:t,channel:s,speed:n,timePostRun:a,fragileOrHeavy:i,typeAdjustElevator:c,timeAdjustElevator:o});return await this.send(m,{alias:"dispenseFromChannelExtended"}),this._dispensingTokens[l]={cart:!!h,resolve:()=>{},reject:()=>{}},new Promise((I,D)=>{this._dispensingTokens[l].resolve=I,this._dispensingTokens[l].reject=D})}async requestDispenseStatusFromChannelExtended({token:e}){const t=this.cmd.getDispenseStatusFromChannelExtended({token:e});return await this.send(t,{alias:"getDispenseStatusFromChannelExtended"})}async restartJSD(){const e=this.cmd.restartingTheJSDKnowingThatItIsDangerous();return await this.send(e,{alias:"restartingTheJSDKnowingThatItIsDangerous"})}serialMessage(e){switch(e.opcode){case r.responseFormatCmdWrong:this._responseFormatCmdWrong(e);break;case r.responseMachineStatus:this._responseMachineStatus(e);break;case r.responseStatusChannel:this._responseStatusChannel(e);break;case r.responseStatusSelection:this._responseStatusSelection(e);break;case r.responseDispenseStatus:this._responseDispenseStatus(e);break;case r.responseConfigurationSelectionDispense:this._responseConfigurationSelectionDispense(e);break;case r.responseConfigurationChannelsLinkedToSelection:this._responseConfigurationChannelsLinkedToSelection(e);break;case r.responseMachineIdentification:this._responseMachineIdentification(e);break;case r.responseCurrentTemperature:this._responseCurrentTemperature(e);break;case r.responseReportEventsAlarmsAndFaults:this._responseReportEventsAlarmsAndFaults(e);break;case r.responseNewTimingWaitingForProductCollection:this._responseNewTimingWaitingForProductCollection(e);break;case r.responsePerformingProductCollectionCycle:this._responsePerformingProductCollectionCycle(e);break;case r.responseResetMachineSoldOutChannels:this._responseResetMachineSoldOutChannels(e);break;case r.responseNewTimingWaitingAfterProductCollection:this._responseNewTimingWaitingAfterProductCollection(e);break;case r.responseJSDVersion:this._responseJSDVersion(e);break;case r.responseActiveFaults:this._responseActiveFaults(e);break;case r.responseJSDDispensingQueue:this._responseJSDDispensingQueue(e);break;case r.responseSpecialCharacteristicsSelection:this._responseSpecialCharacteristicsSelection(e);break;case r.responsePerishableProducts:this._responsePerishableProducts(e);break;case r.responseActiveFaultsList:this._responseActiveFaultsList(e);break;case r.responseJSDResetStatus:this._responseJSDResetStatus(e);break;case r.responseExtendedDispenseStatusData:this._responseExtendedDispenseStatusData(e);break;case r.responseTraysPositioningPhototransistorsStatus:this._responseTraysPositioningPhototransistorsStatus(e);break;case r.jsdErrorLicenseTemporarilyBlocked:this._responseJsdErrorLicenseTemporarilyBlocked(e);break;case r.jsdErrorLicenseNotActive:this._responseJsdErrorLicenseNotActive(e);break;case r.jsdErrorCommandNotExecutable:this._responseJsdErrorCommandNotExecutable(e);break}}emit(e,...t){this.jsd.dispatch(`vision:${e}`,...t)}_responseFormatCmdWrong(e){const t=parseInt(e.params[0],10),s=e.params.slice(1),n=C(t);this.emit("wrong-cmd",{opcodeName:n,opcode:t,params:s})}setMachineStatus(e,t){this._machineStatus[e]=t}getMachineStatus(e){const t=this._getMachineIndex(e);return this._machineStatus[t]||null}_getMachineStatusName(e){switch(e){case 0:return"NO-CONNECTED";case 1:return"CONNECTED";case 2:return"LOST"}}_responseMachineStatus(e){const[t,s,n,a,i,c,o]=e.params,h={0:"AVAILABLE-TO-DISPENSE",1:"NOT-AVAILABLE-TO-DISPENSE",2:"ALREADY-DISPENSING",3:"WAITING-COLLECTION",4:"ELEVATOR-COLLECTION-POSITION",5:"UNCOLLECTED"},d={status:this._getMachineStatusName(parseInt(s,10)),machineInService:parseInt(n,10)===1,doorOpen:parseInt(a,10)===0,availabilityToDispense:h[i]||"NOT-AVAILABLE-TO-DISPENSE",hasLightsOn:isNaN(parseInt(c,10))?!1:parseInt(c,10)===1,temperature:o||""};this.setMachineStatus(parseInt(t,10),d),this.emit("machine-status",{machine:parseInt(t,10)+1,...d}),this.emit("door",{open:d.doorOpen,machine:parseInt(t,10)+1}),this.emit("connection",{connected:d.status==="CONNECTED",machine:parseInt(t,10)+1})}_statusChannelName(e){switch(e){case 0:return"NO-CONNECTED";case 1:return"AVAILABLE";case 2:return"SOLD-OUT";case 3:return"FAULT";default:return"NO-CONNECTED"}}_responseStatusChannel(e){const[t,s,n,a]=e.params,i=this._statusChannelName(parseInt(a,10)),c=this._getSelectionFromTrayChannel(Number(s),Number(n)),o=["AVAILABLE","SOLD-OUT"].includes(i);if(this._performingChannelAssignment.enabled){this._performingChannelAssignment.selections.push({selection:c,active:o,machine:Number(t)+1}),this._performingChannelAssignment.currentSelection=this._performingChannelAssignment.selections.length;const h=this._performingChannelAssignment.currentSelection/80*100;this.emit("channels-progress",{progress:Math.min(100,Math.round(h*100)/100),current:this._performingChannelAssignment.currentSelection,verified:this._performingChannelAssignment.selections.length}),this._performingChannelAssignment.selections.length>=80&&(this.emit("channels",this._performingChannelAssignment.selections),this._performingChannelAssignment.enabled=!1)}else this.emit("channel-status",{machine:Number(t)+1,selection:c,active:o})}_statusSelectionName(e){switch(e){case 0:return"NO-CONFIGURED";case 1:return"ASSOCIATED";case 2:return"NO-ASSOCIATED";case 3:return"NO-VISION-OWNED";case 4:return"EXPIRED";default:return"NO-CONFIGURED"}}_responseStatusSelection(e){const[t,s]=e.params,n=this._statusSelectionName(parseInt(s,10));this.emit("status-selection",{selection:Number(t),status:n})}_responseDispenseStatus(e){const[t,s,n,a]=e.params,i={0:"RECEIVED",1:"IN-PROGRESS",2:"WAITING-COLLECTION",3:"COLLECTED",4:"NO-PERFORMED",5:"TOKEN-NOT-FOUND",6:"QUEUE-FULL",7:"CHANNEL-NO-CONNECTED",8:"SELECTION-UNAVAILABLE",9:"FAILED-DISPENSE",10:"UNCOLLECTED",11:"DISPENSED-CAN-MULTIPLE",12:"DISPENSE-CANCELLED",13:"PRODUCT-EXPIRED"},c=Object.values(i).filter(D=>["NO-PERFORMED","TOKEN-NOT-FOUND","QUEUE-FULL","CHANNEL-NO-CONNECTED","SELECTION-UNAVAILABLE","FAILED-DISPENSE","DISPENSE-CANCELLED","PRODUCT-EXPIRED","UNCOLLECTED"].includes(D)),o={0:"NONE",1:"DOOR-OPEN",2:"MACHINE-NOT-AVAILABLE",3:"ERROR-PHOTOSENSORS",4:"ERROR-MOTOR-POWER-CONSUMPSION-DETECTOR",5:"ALREADY-SOLD-OUT",6:"ERROR-TEST-PRODUCT-DETECTOR",7:"SOLD-OUT",8:"ELEVATOR-CANT-REACH-TRAY",9:"UNCOLLECTED",10:"MACHINE-RESET-DURING-DISPENSE",11:"MACHINE-COMMUNICATION-ERROR",12:"MACHINE-COMMUNICATION-LOST",13:"NO-VISION",14:"PRODUCT-PERISHABLE-EXPIRED",20:"DECIDE"},h=i[parseInt(s,10)]||"UNKNOWN",[d,l,m]=n&&n.trim()!==""?n.split(".").map(D=>parseInt(D,10)):[null,null,null],I=a?o[parseInt(a,10)]||"UNKNOWN":null;this._dispensingTokens[t]&&(this._dispensingTokens[t].cart===!1&&h==="WAITING-COLLECTION"?(this._dispensingTokens[t].resolve(!0),delete this._dispensingTokens[t],this.emit("waiting-collection",{machine:d!==null?d+1:null})):this._dispensingTokens[t].cart===!0&&h==="DISPENSED-CAN-MULTIPLE"?(this._dispensingTokens[t].resolve(!0),delete this._dispensingTokens[t]):c.includes(h)&&(this._dispensingTokens[t].resolve(!1),delete this._dispensingTokens[t])),h==="IN-PROGRESS"&&this.emit("dispensing",{token:t,machine:d!==null?d+1:null,tray:l!==null?l:null,channel:m!==null?m:null,selection:m!==null&&l!==null?this._getSelectionFromTrayChannel(l,m):null}),this.emit("dispense-status",{token:t,status:h,machine:d!==null?d+1:null,tray:l!==null?l:null,channel:m!==null?m:null,extendedStatus:I})}_responseConfigurationSelectionDispense(e){const[t,s,n]=e.params;this.emit("selection-dispense-config",{selection:Number(t),speed:Number(s),timePostRun:Number(n)})}_responseConfigurationChannelsLinkedToSelection(e){const[t,...s]=e.params,a=s[s.length-1].includes(":")?s.pop():null,i={0:"OK",1:"ALREADY-DEFINED",2:"OUT-OF-RANGE"},c=s.map(o=>{const[h,d,l]=o.split(":");return{machine:parseInt(h,10)+1,tray:parseInt(d,10),channel:parseInt(l,10)}});this.emit("channels-linked-to-selection",{selection:Number(t),linkedChannels:c,status:a?i[parseInt(a,10)]||"UNKNOWN":null})}_responseMachineIdentification(e){const[t,s,n,a]=e.params;this.emit("machine-id",{machine:parseInt(t,10)+1,model:s,serialNumber:n,firmwareVersion:a})}_responseCurrentTemperature(e){const[t,s,n,a,i]=e.params,c=parseInt(t,10)+1,o=parseInt(i,10)===1?"ON":"OFF";this.emit("current-temperature",{machine:c,workingTemperature:s,currentTemperatureInsideMachine:n,currentTemperatureAir:a,coolUnitStatus:o})}_responseReportEventsAlarmsAndFaults(e){const[t,s,n]=e.params,a=parseInt(t,10)+1,i={1:"Product detector",2:"None of the motors are connected. Possible control board faulty",3:"Channels jamp detector error",4:"Temperature control error",5:"Elevator faulty",6:"Photosensor, which determine the position of the elevator in relation with the cabinet, faulty",7:"Elevator tester (flap), ES-Plus, faulty",8:"Product expired (perishable)"};this.emit("alarm-faults-events",{machine:a,event:i[parseInt(s,10)]||"UNKNOWN",status:parseInt(n,10)===1?"ACTIVE":"CLEARED"})}_responseNewTimingWaitingForProductCollection(e){const[t,s,n]=e.params;this.emit("time-waiting-for-product-collection",{minutesProductCollection:Number(t),secondsTimeBetweenDispenseManoeuvres:Number(s),secondsBetweenCollectAndStartNextDispense:Number(n)})}_responsePerformingProductCollectionCycle(e){const[t,s]=e.params,n={0:"Manoeuvre has started",1:"Wron machine number",2:"Machine no connected",3:"Wron machine model",4:"Machine cannot perform collection now",5:"Communication error with machine"};this.emit("collect",{machine:parseInt(t,10)+1,status:n[parseInt(s,10)]||"UNKNOWN"})}_responseResetMachineSoldOutChannels(e){const[t,s]=e.params,n={0:"Reset performed",1:"Wrong machine number",2:"Machine not connected",3:"Communication error with machine"};this.emit("reset-sold-out-channels",{machine:parseInt(t,10)+1,status:n[parseInt(s,10)]||"UNKNOWN"})}_responseNewTimingWaitingAfterProductCollection(e){const[t]=e.params;this.emit("time-waiting-after-product-collection",{secondsBetweenCollectAndStartNextDispense:Number(t)})}_responseJSDVersion(e){const[t,s,n,a]=e.params;this.emit("jsd-version",{name:t,compileNumber:s,compileDate:n,description:a})}_responseActiveFaults(e){const[t,s,n,a,i,c,o]=e.params;this.emit("active-faults",{machine:parseInt(t,10)+1,status:parseInt(s,10)===1?"ACTIVE":"CLEARED",fault:parseInt(n,10),appearancesNumber:parseInt(a,10),partialNumberActivated:parseInt(i,10),minutesActive:parseInt(c,10),date:o})}_responseJSDDispensingQueue(e){const[t,s,n]=e.params;this.emit("jsd-dispensing-queue",{free:parseInt(t,10),processed:parseInt(s,10),notProcessed:parseInt(n,10)})}_responseSpecialCharacteristicsSelection(e){const[t,s,n,a,i]=e.params;this.emit("special-characteristics-selection",{selection:Number(t),perishable:parseInt(s,10)===1,fragileOrHeavy:parseInt(n,10)===1,typeAdjustElevator:a==="0"?"lower":"upper",timeAdjustElevator:Number(i)})}_responsePerishableProducts(e){const[t,s,n,a,i]=e.params;this.emit("perishable-products-config",{machine:parseInt(t,10)+1,perishableActive:parseInt(s,10)===1,alarmPerisableTriggered:parseInt(n,10)===1,maxTemperature:a,minutesBeforeExpire:Number(i)})}_responseActiveFaultsList(e){const[t,...s]=e.params,n={1:"Product detector",2:"None of the motors are connected. Possible control board faulty",3:"Channels jamp detector error",4:"Temperature control error",5:"Elevator faulty",6:"Photosensor, which determine the position of the elevator in relation with the cabinet, faulty",7:"Elevator tester (flap), ES-Plus, faulty",8:"Product expired (perishable)"},a=s.map(i=>({code:parseInt(i,10),description:n[parseInt(i,10)]||"UNKNOWN"}));this.emit("active-faults-list",{machine:parseInt(t,10)+1,faults:a,ok:s.length===0})}_responseJSDResetStatus(e){const[t]=e.params,s={0:"RESETED",1:"RECEIVED"};this.emit("jsd-status-reset",{type:s[parseInt(t,10)]||"UNKNOWN"})}_responseExtendedDispenseStatusData(e){const[t]=e.params;this.emit("extended-dispense-status-data",{enabled:parseInt(t,10)===1})}_responseTraysPositioningPhototransistorsStatus(e){const[t,s,n,a,i,c,o,h,d]=e.params,l={0:"OK",C:"SHORT-CIRCUIT",N:"TRAY-NOT-DETECTED"},m={machine:parseInt(t,10)+1,trays:{11:l[s]||null,12:l[n]||null,13:l[a]||null,14:l[i]||null,15:l[c]||null,16:l[o]||null,17:l[h]||null,18:l[d]||null}};this.emit("trays-positioning-phototransistors-status",m)}_responseJsdErrorLicenseTemporarilyBlocked(e){const[t,...s]=e.params;this.emit("jsd-license-error",{type:"exprired-license",opcode:parseInt(t,10),actionName:C(parseInt(t,10)),params:s})}_responseJsdErrorLicenseNotActive(e){const[t,...s]=e.params;this.emit("jsd-license-error",{type:"app-number-not-licensed",opcode:parseInt(t,10),actionName:C(parseInt(t,10)),params:s})}_responseJsdErrorCommandNotExecutable(e){const[t,...s]=e.params;this.emit("jsd-license-error",{type:"price-control-active-direct-dispense-not-allowed",opcode:parseInt(t),actionName:C(parseInt(t,10)),params:s})}}const g={requestLogsEvents:101,requestLogsByDate:102,requestForSendingManifest:110,sendManifestDataBlock:111,responseCmdWrong:200,responseLineLogEvent:201,responseManifestDataBlock:210,responseManifestCompleted:211},x=p=>Object.keys(g).find(t=>g[t]===p)||"Unknown";class P{transport;static APP_ID=f.MANIFESTS_AND_LOGS;constructor(e){this.transport=e}requestLogsEvents(e=!1){const s=`${e?"+":"0"}`;return this.transport.buildPacket(g.requestLogsEvents,s,P.APP_ID)}requestLogsByDate(e,t){const s=`${e},${t}`;return this.transport.buildPacket(g.requestLogsByDate,s,P.APP_ID)}requestForSendingManifest(e,t){const s=`${e},${t}`;return this.transport.buildPacket(g.requestForSendingManifest,s,P.APP_ID)}sendManifestDataBlock(e,t){const s=Array.from(t).map(a=>a.toString(2).padStart(8,"0")).join(" "),n=`${e},${s}`;return this.transport.buildPacket(g.sendManifestDataBlock,n,P.APP_ID)}}class R{_commands;jsd;APP_ID=f.MANIFESTS_AND_LOGS;_logs={status:"idle",data:[]};constructor(e,t){this._commands=new P(t),this.jsd=e}async send(e,t){return this.jsd._lastApplicationCode=this.APP_ID,this.jsd._toQueue(e,{alias:t.alias,waitResponse:t.waitResponse||!1,timeout:t.timeout||500})}get cmd(){return this._commands}async requestLogsEvent({previous:e}){const t=this.cmd.requestLogsEvents(e);return await this.send(t,{alias:"requestLogsEvents"})}async requestLogs(){if(["fetching","more"].includes(this._logs.status))throw new Error("Already fetching logs");return this._logs.status="fetching",this.requestLogsEvent({previous:!1}),new Promise(e=>{const t=setInterval(()=>{if(this._logs.status==="completed"){clearInterval(t);const s=this._logs.data;e(s)}else this._logs.status==="more"&&(this._logs.status="fetching",this.requestLogsEvent({previous:!0}))},100)})}async requestLogsByDate({since:e,until:t}){const s=c=>{const o=String(c.getMonth()+1).padStart(2,"0"),h=String(c.getDate()).padStart(2,"0"),d=String(c.getHours()).padStart(2,"0"),l=String(c.getMinutes()).padStart(2,"0"),m=String(c.getSeconds()).padStart(2,"0");return`${o}/${h}/${d}/${l}/${m}`},n=s(e),a=s(t),i=this.cmd.requestLogsByDate(n,a);return await this.send(i,{alias:"requestLogsByDate"})}async requestForSendingManifest({fileSizeBytes:e,crc:t}){const s=this.cmd.requestForSendingManifest(e,t);return await this.send(s,{alias:"requestForSendingManifest"})}async sendManifestDataBlock({prevBlockId:e,dataBlock:t}){const s=this.cmd.sendManifestDataBlock(e,t);return await this.send(s,{alias:"sendManifestDataBlock"})}serialMessage(e){switch(e.opcode){case g.responseCmdWrong:this._responseCmdWrong(e);break;case g.responseLineLogEvent:this._responseLineLogEvent(e);break;case g.responseManifestDataBlock:this._responseManifestDataBlock(e);break;case g.responseManifestCompleted:this._responseManifestCompleted(e);break}}emit(e,...t){this.jsd.dispatch(`manifest:${e}`,...t)}_responseCmdWrong(e){const t=parseInt(e.params[0],10),s=e.params.slice(1),n=x(t);this.emit("wrong-cmd",{opcodeName:n,opcode:t,params:s})}_responseLineLogEvent(e){const[...t]=e.params,s=t[0]==="END_LOG";if(s)this._logs.status="completed";else{const a=t.join(",");this._logs.data.push(a),this._logs.status==="fetching"&&(this._logs.status="more")}const n=s?"end":"log";this.emit("log",{type:n,log:t})}_responseManifestDataBlock(e){const[t,s,n]=e.params;this.emit("block",{blockId:parseInt(t,10),indexFile:parseInt(s,10),quantity:parseInt(n,10)})}_responseManifestCompleted(e){const[t]=e.params,s={0:"Success",1:"CRC Error",2:"Transference interrupted",3:"Reset JSD and try again"};this.emit("completed",{result:s[t]||"Unknown Result",resultKey:parseInt(t,10)})}}const S={requestFeatureStatus:100,requestTemporaryLicenseStatus:101,requestSeedData:102,requestLicenseActivation:110,responseCmdWrong:200,responseFeatureStatus:201,responseSeedData:202,responseTemporaryLicenseStatus:203},B=p=>Object.keys(S).find(t=>S[t]===p)||"Unknown";class y{transport;static APP_ID=f.LICENSING;constructor(e){this.transport=e}requestFeatureStatus(e){const t=`${e}`;return this.transport.buildPacket(S.requestFeatureStatus,t,y.APP_ID)}requestTemporaryLicenseStatus(){return this.transport.buildPacket(S.requestTemporaryLicenseStatus,"",y.APP_ID)}requestSeedData(){return this.transport.buildPacket(S.requestSeedData,"",y.APP_ID)}requestLicenseActivation(e){const t=`${e}`;return this.transport.buildPacket(S.requestLicenseActivation,t,y.APP_ID)}}class ${_commands;jsd;APP_ID=f.LICENSING;constructor(e,t){this._commands=new y(t),this.jsd=e}async send(e,t){return this.jsd._lastApplicationCode=this.APP_ID,this.jsd._toQueue(e,{alias:t.alias,waitResponse:t.waitResponse||!1,timeout:t.timeout||500})}get cmd(){return this._commands}async requestFeatureStatus({feature:e}){const t=this.cmd.requestFeatureStatus(e);return this.send(t,{alias:"requestFeatureStatus"})}async requestTemporaryLicenseStatus(){const e=this.cmd.requestTemporaryLicenseStatus();return this.send(e,{alias:"requestTemporaryLicenseStatus"})}async requestSeedData(){const e=this.cmd.requestSeedData();return this.send(e,{alias:"requestSeedData"})}async requestLicenseActivation({license:e}){const t=this.cmd.requestLicenseActivation(e);return this.send(t,{alias:"requestLicenseActivation"})}serialMessage(e){switch(e.opcode){case S.responseCmdWrong:this._responseCmdWrong(e);break;case S.responseFeatureStatus:this._responseFeatureStatus(e);break;case S.responseSeedData:this._responseSeedData(e);break;case S.responseTemporaryLicenseStatus:this._responseTemporaryLicenseStatus(e);break}}emit(e,...t){this.jsd.dispatch(`licensing:${e}`,...t)}_responseCmdWrong(e){const t=parseInt(e.params[0],10),s=e.params.slice(1),n=B(t);this.emit("wrong-cmd",{opcodeName:n,opcode:t,params:s})}_responseFeatureStatus(e){const[t,s]=e.params;this.emit("feature-status",{feature:t,active:s==="1"})}_responseSeedData(e){const[...t]=e.params,s=t.join(","),n=t.map(a=>parseInt(a,10).toString(16).padStart(2,"0")).join(" ");this.emit("seed",{seed:s,hex:n})}_responseTemporaryLicenseStatus(e){const[t,s,n]=e.params,a={0:"Inactive, permanent license",1:"Active",2:"Expired",3:"Blocked up"};this.emit("temporary-license-status",{status:a[t]||"Unknown",remainingDays:parseInt(s,10),daysSinceExpiration:parseInt(n,10)})}}class j{static unescapeBytes(e){const t=[];for(let s=0;s<e.length;s++){const n=e[s];if(n===219){const a=e[s+1];a===220?(t.push(192),s++):a===221?(t.push(219),s++):t.push(n)}else t.push(n)}return t}static parseFrame(e){let t=e;t.length>0&&t[0]===192&&(t=t.slice(1)),t.length>0&&t[t.length-1]===192&&(t=t.slice(0,-1));const s=this.unescapeBytes(t);if(s.length<1)return console.error("Frame too short"),"Frame too short";const n=s[0],a=s[1],i=s.slice(2,-2),c=s[s.length-2],o=s[s.length-1],h=[192,n,a,...i],[d,l]=_.calculate(h);if(d!==c||l!==o)return console.error("CRC mismatch"),"CRC mismatch";if(n===2)return{type:"ACK",id:a};if(n===3)return{type:"NACK",id:a};if(n!==1)return console.warn("Unknown code"),"Unknown code";if(i.length<6)return console.error("JConnect header too short"),"JConnect header too short";const m=i[0]|i[1]<<8,I=i[2]|i[3]<<8,D=i[4]|i[5]<<8,v=i.slice(6),A=String.fromCharCode(...v);return{type:"DATA",opcode:D,appId:I,noBytes:m,params:A?A.split(","):[],id:a,rawAscii:A}}}class W{delimiter;buffer;constructor(e){this.delimiter=e,this.buffer=new Uint8Array(0)}transform(e,t){const s=new Uint8Array(this.buffer.length+e.length);s.set(this.buffer),s.set(e,this.buffer.length),this.buffer=s;let n;for(;(n=this.findDelimiterIndex())!==-1;){const a=this.buffer.slice(0,n);this.buffer=this.buffer.slice(n+this.delimiter.length),t.enqueue(a)}}findDelimiterIndex(){for(let e=0;e<=this.buffer.length-this.delimiter.length;e++){let t=!0;for(let s=0;s<this.delimiter.length;s++)if(this.buffer[e+s]!==this.delimiter[s]){t=!1;break}if(t)return e}return-1}flush(e){this.buffer.length>0&&(e.enqueue(this.buffer),this.buffer=new Uint8Array(0))}}class U extends O.T{_transport;vision;manifest;licensing;_queue=[];_timeoutPacketId=0;_runningQueue=!1;_lastApplicationCode=0;constructor({filters:e=null,config_port:t,no_device:s=1,socket:n=!1,transport:a="rs232"}={}){const i=new Uint8Array([192]),c=new TransformStream(new W(i));if(super({filters:e,config_port:t,no_device:s,socket:n,transformStream:c}),this.__internal__.device.type="jsd",this.__internal__.time.response_general=500,this.__internal__.time.response_engines=500,N.Devices.getCustom(this.typeDevice,s))throw new Error(`Device ${this.typeDevice} ${s} already exists`);N.Devices.add(this),this.#e(),this.getResponseAsUint8Array(),this._transport=a==="rs232"?new k:new b,this.vision=new M(this,this._transport),this.manifest=new R(this,this._transport),this.licensing=new $(this,this._transport),this.afterConnectionSetup()}async afterConnectionSetup(){await new Promise(e=>setTimeout(e,100)),this.vision.requestMachineStatus({machine:1}),this.vision.requestMachineStatus({machine:2}),this.vision.requestMachineStatus({machine:3}),this.vision.requestMachineStatus({machine:4})}#e(){const e=["licensing:wrong-cmd","licensing:feature-status","licensing:seed","licensing:temporary-license-status","manifest:wrong-cmd","manifest:log","manifest:block","manifest:completed","vision:wrong-cmd","vision:machine-status","vision:channels-progress","vision:channels","vision:channel-status","vision:status-selection","vision:dispense-status","vision:selection-dispense-config","vision:channels-linked-to-selection","vision:machine-id","vision:current-temperature","vision:alarm-faults-events","vision:time-waiting-for-product-collection","vision:collect","vision:reset-sold-out-channels","vision:time-waiting-after-product-collection","vision:jsd-version","vision:active-faults","vision:jsd-dispensing-queue","vision:special-characteristics-selection","vision:perishable-products-config","vision:active-faults-list","vision:jsd-status-reset","vision:extended-dispense-status-data","vision:trays-positioning-phototransistors-status","vision:jsd-license-error","serial:jsd-error","serial:jsd-ack","serial:jsd-nack","serial:jsd-data"];for(const t of e)this.serialRegisterAvailableListener(t)}serialSetConnectionConstant(){const e=this._transport?this._transport:new k;let t=255;this._transport&&(t=e.packetId,this._transport._overridePacketId(t+1));const{bytes:s}=u.connection({transport:e,packetId:t});return s}send(e,t){return this.appendToQueue(e,t.alias||"unknown")}onEvent(e,t){super.on(e,t)}offEvent(e,t){super.off(e,t)}onceEvent(e,t){const s=((...n)=>{t(...n),this.offEvent(e,s)});this.onEvent(e,s)}get transport(){return this._transport.name}acknowledge(e){return this._transport.buildAckPacket(e)}ack(e){this.isConnected&&this.send(new Uint8Array(this.acknowledge(e)),{alias:"ACK Response"})}_toQueue(e,t){this._queue.push({packetId:e.packetId,data:e.bytes,alias:t?.alias||"unknown",timeout:t?.timeout||500,resendCount:0}),this._runQueue()}_runQueue(){if(this._queue.length===0||this._runningQueue)return;const e=this._queue[0];this.isConnected&&(this.appendToQueue(new Uint8Array(e.data),e.alias||"unknown"),this._runningQueue=!0,this._timeoutPacketId=setTimeout(()=>{const t=this._queue.findIndex(s=>s.packetId===e.packetId);t!==-1&&(e.resendCount<3?(this._queue[t].resendCount+=1,this._runningQueue=!1,this._runQueue()):(this.dispatch("serial:jsd-error",`No response for packet ID ${e.packetId} after 3 attempts.`),this._queue.splice(t,1),this._runningQueue=!1,this._queue.length>0&&this._runQueue()))},e.timeout))}_dequeue(e){const t=this._queue.findIndex(s=>s.packetId===e);t!==-1&&(this._queue.splice(t,1),this._timeoutPacketId&&(clearTimeout(this._timeoutPacketId),this._timeoutPacketId=0),this._runningQueue=!1,this._queue.length>0&&this._runQueue())}serialMessage(e){const t=Array.from(structuredClone(e));if(t.length===0)return;const s=j.parseFrame(t);if(typeof s=="string")this.dispatch("serial:jsd-error",s);else if(s.type==="ACK")this._queue.findIndex(a=>a.packetId===s.id)!==-1&&this._dequeue(s.id),this.dispatch("serial:jsd-ack",s);else if(s.type==="NACK")this.dispatch("serial:jsd-nack",s);else if(s.type==="DATA"){this.ack(s.id),typeof s.appId>"u"&&(s.appId=this._lastApplicationCode);const n=s.appId;L(n)&&this.vision.serialMessage(s),w(n)&&this.manifest.serialMessage(s),F(n)&&this.licensing.serialMessage(s),this.dispatch("serial:jsd-data",s)}this.dispatch("serial:message",{raw:e,parsed:s})}}exports.JSD=U;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("./webserial-core-3UL91lxi.cjs"),N=require("./devices-BndwHuvP.cjs");class _{static USE_BIG_ENDIAN=!0;static USE_REFLECTED=!1;static calculate(e){let t;if(this.USE_REFLECTED){t=0;for(const s of e){t^=s&255;for(let n=0;n<8;n++)t&1?t=t>>1^40961:t>>=1}}else{t=0;for(const s of e){t^=s<<8;for(let n=0;n<8;n++)t&32768?t=(t<<1^32773)&65535:t=t<<1&65535}}return this.USE_BIG_ENDIAN?[t>>8&255,t&255]:[t&255,t>>8&255]}static getConfig(){return{bigEndian:this.USE_BIG_ENDIAN,reflected:this.USE_REFLECTED}}}class b{_name="tcpip";get name(){return this._name}get packetId(){return 0}_overridePacketId(e){console.warn(`TCP/IP transport does not use packet IDs. Ignoring override to ${e}.`)}toLittleEndian(e){return[e&255,e>>8&255]}buildPacket(e,t,s){const n=t?t.split("").map(h=>h.charCodeAt(0)):[],a=6+n.length,i=this.toLittleEndian(a),c=this.toLittleEndian(s),o=this.toLittleEndian(e);return{bytes:[...i,...c,...o,...n],packetId:0}}escapeBytes(e){const t=[];for(const s of e)s===192?t.push(219,220):s===219?t.push(219,221):t.push(s);return t}buildAckPacket(e){const n=[192,2,e],[a,i]=_.calculate(n),c=[2,e,a,i];return[192,...this.escapeBytes(c),192]}}class k extends b{packetIdCounter=1;_name="rs232";get packetId(){return this.packetIdCounter}_overridePacketId(e){this.packetIdCounter=e&255}getNextPacketId(){const e=this.packetIdCounter;return this.packetIdCounter=this.packetIdCounter+1&255,this.packetIdCounter===0&&(this.packetIdCounter=1),e}buildPacket(e,t,s){const i=this.getNextPacketId(),{bytes:c}=super.buildPacket(e,t,s),o=[192,1,i,...c],[h,d]=_.calculate(o),l=[1,i,...c,h,d];return{bytes:[192,...this.escapeBytes(l),192],packetId:i}}}const r={requestMachineStatus:100,requestStatusChannel:101,requestStatusSelection:102,configureSelectionDispense:103,addChannelToSelection:104,requestMachineIdentification:105,programWorkingTemperature:106,programWaitingTimings:107,resetSoldOutChannels:108,programTimeWaitingAfterPickup:109,requestJSDVersion:110,requestFaultMachine:111,manageJSDDispensingQueue:112,defineSpecialCharacteristicsSelection:113,configurePerishableProducts:114,requestActiveFaults:115,configureExtendedDispenseStatusData:116,requestStatusTrayPositioningPhototransistors:117,dispenseFromChannel:150,dispenseFromSelection:151,controlLights:152,resetFaultsAndSelfTest:153,performCollectCycle:154,dispenseFromChannelExtended:155,restartingTheJSDKnowingThatItIsDangerous:156,responseFormatCmdWrong:200,responseMachineStatus:201,responseStatusChannel:202,responseStatusSelection:203,responseDispenseStatus:204,responseConfigurationSelectionDispense:205,responseConfigurationChannelsLinkedToSelection:206,responseMachineIdentification:207,responseCurrentTemperature:208,responseReportEventsAlarmsAndFaults:209,responseNewTimingWaitingForProductCollection:210,responsePerformingProductCollectionCycle:211,responseResetMachineSoldOutChannels:212,responseNewTimingWaitingAfterProductCollection:213,responseJSDVersion:214,responseActiveFaults:215,responseJSDDispensingQueue:216,responseSpecialCharacteristicsSelection:217,responsePerishableProducts:218,responseActiveFaultsList:219,responseJSDResetStatus:220,responseExtendedDispenseStatusData:221,responseTraysPositioningPhototransistorsStatus:222,jsdErrorLicenseTemporarilyBlocked:300,jsdErrorLicenseNotActive:301,jsdErrorCommandNotExecutable:302},C=p=>Object.keys(r).find(t=>r[t]===p)||"Unknown",f={VISION:402,LICENSING:600,MANIFESTS_AND_LOGS:601,SIMULATOR_VISION:1e4},L=p=>[f.VISION,f.SIMULATOR_VISION].includes(p),F=p=>[f.LICENSING].includes(p),w=p=>[f.MANIFESTS_AND_LOGS].includes(p);class u{transport;static APP_ID=f.VISION;constructor(e){this.transport=e}static connection({transport:e,packetId:t}){return e._overridePacketId(t||255),new u(e).requestJSDVersion()}requestMachineStatus({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.requestMachineStatus,t,u.APP_ID)}requestStatusChannel({machine:e,tray:t,channel:s}){const n=`${e},${t},${s}`;return this.transport.buildPacket(r.requestStatusChannel,n,u.APP_ID)}requestStatusSelection({selection:e}){const t=`${e}`;return this.transport.buildPacket(r.requestStatusSelection,t,u.APP_ID)}configureSelectionDispense({selection:e,speed:t,timePostRun:s}){const n=`${e},${t},${s}`;return this.transport.buildPacket(r.configureSelectionDispense,n,u.APP_ID)}getSelectionDispenseConfig({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.configureSelectionDispense,t,u.APP_ID)}addChannelToSelection({selection:e,machine:t,tray:s,channel:n}){const a=`${e},${t},${s},${n}`;return this.transport.buildPacket(r.addChannelToSelection,a,u.APP_ID)}getChannelsLinkedToSelection({selection:e}){const t=`${e}`;return this.transport.buildPacket(r.addChannelToSelection,t,u.APP_ID)}requestMachineIdentification({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.requestMachineIdentification,t,u.APP_ID)}formatTemperature(e){const t=e>=0?"+":"-",s=Math.abs(e).toFixed(1).padStart(4,"0");return`${t}${s}`}programWorkingTemperature({machine:e,temperature:t,enable:s}){const n=this.formatTemperature(t),i=`${e},${n},${s?1:0}`;return this.transport.buildPacket(r.programWorkingTemperature,i,u.APP_ID)}getWorkingTemperature({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.programWorkingTemperature,t,u.APP_ID)}programWaitingTimings({collectPosition:e,dispenseManoeuvres:t,afterPickup:s}){const n=`${e},${t},${s}`;return this.transport.buildPacket(r.programWaitingTimings,n,u.APP_ID)}getWaitingTimings(){return this.transport.buildPacket(r.programWaitingTimings,"",u.APP_ID)}resetSoldOutChannels({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.resetSoldOutChannels,t,u.APP_ID)}programTimeWaitingAfterPickup({time:e}){const t=`${e}`;return this.transport.buildPacket(r.programTimeWaitingAfterPickup,t,u.APP_ID)}getTimeWaitingAfterPickup(){return this.transport.buildPacket(r.programTimeWaitingAfterPickup,"",u.APP_ID)}requestJSDVersion(){return this.transport.buildPacket(r.requestJSDVersion,"",u.APP_ID)}requestFaultMachine({machine:e,type:t}){const n=`${e},${{"report-active":0,"report-inactive":1,"clear-inactive":2}[t]}`;return this.transport.buildPacket(r.requestFaultMachine,n,u.APP_ID)}requestReportActiveFaults(e){return this.requestFaultMachine({machine:e,type:"report-active"})}requestReportInactiveFaults(e){return this.requestFaultMachine({machine:e,type:"report-inactive"})}requestClearInactiveFaults(e){return this.requestFaultMachine({machine:e,type:"clear-inactive"})}manageJSDDispensingQueue({type:e}){const t=`${e}`;return this.transport.buildPacket(r.manageJSDDispensingQueue,t,u.APP_ID)}requestJSDDispensingQueueStatus(){return this.manageJSDDispensingQueue({type:0})}clearJSDDispensingQueue(){return this.manageJSDDispensingQueue({type:1})}defineSpecialCharacteristicsSelection({selection:e,perishable:t,fragileOrHeavy:s,typeAdjustElevator:n,timeAdjustElevator:a}){const d=`${e},${t?1:0},${s?1:0},${n==="lower"?0:1},${a}`;return this.transport.buildPacket(r.defineSpecialCharacteristicsSelection,d,u.APP_ID)}getSpecialCharacteristicsSelection({selection:e}){const t=`${e}`;return this.transport.buildPacket(r.defineSpecialCharacteristicsSelection,t,u.APP_ID)}configurePerishableProducts({machine:e,enable:t,temperatureLimit:s,minutesToExpiry:n}){const a=t?1:0,i=this.formatTemperature(s),c=`${e},${a},${i},${n}`;return this.transport.buildPacket(r.configurePerishableProducts,c,u.APP_ID)}requestActiveFaults({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.requestActiveFaults,t,u.APP_ID)}configureExtendedDispenseStatusData({enable:e}){const s=`${e?1:0}`;return this.transport.buildPacket(r.configureExtendedDispenseStatusData,s,u.APP_ID)}getExtendedDispenseStatusDataConfig(){return this.transport.buildPacket(r.configureExtendedDispenseStatusData,"",u.APP_ID)}requestStatusTrayPositioningPhototransistors({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.requestStatusTrayPositioningPhototransistors,t,u.APP_ID)}dispenseFromChannel({token:e,machine:t,tray:s,channel:n,speed:a,timePostRun:i}){const c=`${e},${t},${s},${n},${a},${i}`;return this.transport.buildPacket(r.dispenseFromChannel,c,u.APP_ID)}getDispenseStatusFromChannel({token:e}){const t=`${e}`;return this.transport.buildPacket(r.dispenseFromChannel,t,u.APP_ID)}dispenseFromSelection({token:e,selection:t}){const s=`${e},${t}`;return this.transport.buildPacket(r.dispenseFromSelection,s,u.APP_ID)}getDispenseStatusFromSelection({token:e}){const t=`${e}`;return this.transport.buildPacket(r.dispenseFromSelection,t,u.APP_ID)}controlLights({machine:e,turnOn:t}){const n=`${e},${t?1:0}`;return this.transport.buildPacket(r.controlLights,n,u.APP_ID)}resetFaultsAndSelfTest({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.resetFaultsAndSelfTest,t,u.APP_ID)}performCollectCycle({machine:e}){const t=`${e}`;return this.transport.buildPacket(r.performCollectCycle,t,u.APP_ID)}dispenseFromChannelExtended({token:e,machine:t,tray:s,channel:n,speed:a,timePostRun:i,fragileOrHeavy:c,typeAdjustElevator:o,timeAdjustElevator:h}){const I=`${e},${t},${s},${n},${a},${i},${c?1:0},${o==="lower"?0:1},${h}`;return this.transport.buildPacket(r.dispenseFromChannelExtended,I,u.APP_ID)}getDispenseStatusFromChannelExtended({token:e}){const t=`${e}`;return this.transport.buildPacket(r.dispenseFromChannelExtended,t,u.APP_ID)}restartingTheJSDKnowingThatItIsDangerous(){return this.transport.buildPacket(r.restartingTheJSDKnowingThatItIsDangerous,"",u.APP_ID)}}function q(p){if(p.length>5)throw new Error(`Token must be max 5 characters, got ${p.length}`);return p}function T(){let p;do{const e=new Uint8Array(2);p=parseInt(crypto.getRandomValues(e).toString().replaceAll(",","")).toString(36)}while(p.length>5);return q(p)}const E={status:"NO-CONNECTED",machineInService:!1,doorOpen:!1,availabilityToDispense:"NOT-AVAILABLE-TO-DISPENSE",hasLightsOn:!1,temperature:""};class M{_commands;jsd;APP_ID=f.VISION;_machineStatus=[{...E},{...E},{...E},{...E}];constructor(e,t){this._commands=new u(t),this.jsd=e}_performingChannelAssignment={enabled:!1,selections:[],currentSelection:1};_dispensingTokens={};async send(e,t){return this.jsd._lastApplicationCode=this.APP_ID,this.jsd._toQueue(e,{alias:t.alias,waitResponse:t.waitResponse||!1,timeout:t.timeout||500})}get cmd(){return this._commands}_getMachineIndex(e){return e-1}isAvailableToDispense({machine:e=1}={}){const t=this._getMachineIndex(e);return["ELEVATOR-COLLECTION-POSITION","AVAILABLE-TO-DISPENSE"].includes(this._machineStatus[t]?.availabilityToDispense||"")&&this._machineStatus[t]?.machineInService===!0&&this._machineStatus[t]?.doorOpen===!1&&this._machineStatus[t]?.status==="CONNECTED"}async requestMachineStatus({machine:e=1}={}){const t=this._getMachineIndex(e),s=this.cmd.requestMachineStatus({machine:t});return await this.send(s,{alias:"requestMachineStatus"})}_getTrayChannelFromSelection(e){const t=Math.floor((e-1)/10)+11,s=(e-1)%10;return{tray:t,channel:s}}_getSelectionFromTrayChannel(e,t){return(e-11)*10+t+1}async requestStatusChannel({machine:e,selection:t}){const s=this._getMachineIndex(e),{tray:n,channel:a}=this._getTrayChannelFromSelection(t),i=this.cmd.requestStatusChannel({machine:s,tray:n,channel:a});return await this.send(i,{alias:"requestStatusChannel"})}async assignChannels({machine:e}){if(this._performingChannelAssignment.enabled)throw new Error("Channel assignment already in progress");this._performingChannelAssignment.enabled=!0;for(let t=1;t<=80;t++)await this.requestStatusChannel({machine:e,selection:t});return new Promise(t=>{const s=setInterval(()=>{if(this._performingChannelAssignment.enabled)return;clearInterval(s);const n=this._performingChannelAssignment.selections;this._performingChannelAssignment.selections=[],t(n)},200)})}async requestStatusSelection({selection:e}){const t=this.cmd.requestStatusSelection({selection:e});return await this.send(t,{alias:"requestStatusSelection"})}async configureSelectionDispense({selection:e,speed:t,timePostRun:s}){const n=this.cmd.configureSelectionDispense({selection:e,speed:t,timePostRun:s});return await this.send(n,{alias:"configureSelectionDispense"})}async requestSelectionDispenseConfig({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.getSelectionDispenseConfig({machine:t});return await this.send(s,{alias:"getSelectionDispenseConfig"})}async configureAddChannelToSelection({selection:e,machine:t,tray:s,channel:n}){const a=this._getMachineIndex(t),i=this.cmd.addChannelToSelection({selection:e,machine:a,tray:s,channel:n});return await this.send(i,{alias:"addChannelToSelection"})}async requestChannelsLinkedToSelection({selection:e}){const t=this.cmd.getChannelsLinkedToSelection({selection:e});return await this.send(t,{alias:"getChannelsLinkedToSelection"})}async requestMachineIdentification({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestMachineIdentification({machine:t});return await this.send(s,{alias:"requestMachineIdentification"})}async configureWorkingTemperature({machine:e,temperature:t,enable:s}){const n=this._getMachineIndex(e),a=this.cmd.programWorkingTemperature({machine:n,temperature:t,enable:s});return await this.send(a,{alias:"programWorkingTemperature"})}async requestWorkingTemperature({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.getWorkingTemperature({machine:t});return await this.send(s,{alias:"getWorkingTemperature"})}async configureWaitingTimings({collectPosition:e,dispenseManoeuvres:t,afterPickup:s}){const n=this.cmd.programWaitingTimings({collectPosition:e,dispenseManoeuvres:t,afterPickup:s});return await this.send(n,{alias:"programWaitingTimings"})}async requestWaitingTimings(){const e=this.cmd.getWaitingTimings();return await this.send(e,{alias:"getWaitingTimings"})}async resetSoldOutChannels({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.resetSoldOutChannels({machine:t});return await this.send(s,{alias:"resetSoldOutChannels"})}async resetAllErrors({machine:e}){return await Promise.all([this.clearInactiveFaults({machine:e}),this.resetSoldOutChannels({machine:e}),this.resetFaultsAndSelfTest({machine:e})])}async configureTimeWaitingAfterPickup({time:e}){const t=this.cmd.programTimeWaitingAfterPickup({time:e});return await this.send(t,{alias:"programTimeWaitingAfterPickup"})}async requestTimeWaitingAfterPickup(){const e=this.cmd.getTimeWaitingAfterPickup();return await this.send(e,{alias:"getTimeWaitingAfterPickup"})}async requestJSDVersion(){const e=this.cmd.requestJSDVersion();return await this.send(e,{alias:"requestJSDVersion"})}async requestReportActiveFaults({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestReportActiveFaults(t);return await this.send(s,{alias:"requestReportActiveFaults"})}async requestReportInactiveFaults({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestReportInactiveFaults(t);return await this.send(s,{alias:"requestReportInactiveFaults"})}async clearInactiveFaults({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestClearInactiveFaults(t);return await this.send(s,{alias:"requestClearInactiveFaults"})}async requestJSDDispensingQueueStatus(){const e=this.cmd.requestJSDDispensingQueueStatus();return await this.send(e,{alias:"requestJSDDispensingQueueStatus"})}async clearJSDDispensingQueue(){const e=this.cmd.clearJSDDispensingQueue();return await this.send(e,{alias:"clearJSDDispensingQueue"})}async configureSpecialCharacteristicsSelection({selection:e,perishable:t,fragileOrHeavy:s,typeAdjustElevator:n,timeAdjustElevator:a}){const i=this.cmd.defineSpecialCharacteristicsSelection({selection:e,perishable:t,fragileOrHeavy:s,typeAdjustElevator:n,timeAdjustElevator:a});return await this.send(i,{alias:"defineSpecialCharacteristicsSelection"})}requestSpecialCharacteristicsSelection({selection:e}){const t=this.cmd.getSpecialCharacteristicsSelection({selection:e});return this.send(t,{alias:"getSpecialCharacteristicsSelection"})}configurePerishableProducts({machine:e,enable:t,temperatureLimit:s,minutesToExpiry:n}){const a=this._getMachineIndex(e),i=this.cmd.configurePerishableProducts({machine:a,enable:t,temperatureLimit:s,minutesToExpiry:n});return this.send(i,{alias:"configurePerishableProducts"})}async requestActiveFaults({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestActiveFaults({machine:t});return await this.send(s,{alias:"requestActiveFaults"})}async configureExtendedDispenseStatusData({enable:e}){const t=this.cmd.configureExtendedDispenseStatusData({enable:e});return await this.send(t,{alias:"configureExtendedDispenseStatusData"})}async requestExtendedDispenseStatusDataConfig(){const e=this.cmd.getExtendedDispenseStatusDataConfig();return await this.send(e,{alias:"getExtendedDispenseStatusDataConfig"})}async requestStatusTrayPositioningPhototransistors({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.requestStatusTrayPositioningPhototransistors({machine:t});return await this.send(s,{alias:"requestStatusTrayPositioningPhototransistors"})}async dispenseFromChannel({machine:e,tray:t,channel:s,speed:n,timePostRun:a,cart:i=!1}){if(!this.isAvailableToDispense({machine:e}))throw new Error(`Machine ${e} is not available to dispense`);const c=this._getMachineIndex(e),o=T(),h=this.cmd.dispenseFromChannel({token:o,machine:c,tray:t,channel:s,speed:n,timePostRun:a});return await this.send(h,{alias:"dispenseFromChannel"}),this._dispensingTokens[o]={cart:!!i,resolve:()=>{delete this._dispensingTokens[o]},reject:()=>{}},new Promise((d,l)=>{this._dispensingTokens[o].resolve=d,this._dispensingTokens[o].reject=l})}async dispense({machine:e,selection:t,speed:s,timePostRun:n,cart:a=!1}){const{tray:i,channel:c}=this._getTrayChannelFromSelection(t);return this.dispenseFromChannel({machine:e,tray:i,channel:c,speed:s||5,timePostRun:n||0,cart:!!a})}async dispenseCart(e=[]){const t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));let s=[];for(const n of t)try{const a=await Promise.all(n.map(o=>this.dispense({machine:o.machine,selection:o.selection,cart:!0}))),i=[...new Set(n.map(o=>o.machine))];await new Promise(o=>{const h=setInterval(()=>{i.every(l=>this.getMachineStatus(l)?.availabilityToDispense==="AVAILABLE-TO-DISPENSE")&&(clearInterval(h),o(!0))},300)});for(const o of i)this._machineStatus[this._getMachineIndex(o)]?.availabilityToDispense==="WAITING-COLLECTION"&&this.emit("waiting-collection",{machine:o!==null?o+1:null});const c=n.map((o,h)=>({machine:o.machine,selection:o.selection,dispensed:a[h]}));s=s.concat(c)}catch(a){console.error("Error sending dispense command:",a)}return s}async requestDispenseStatusFromChannel({token:e}){const t=this.cmd.getDispenseStatusFromChannel({token:e});return await this.send(t,{alias:"getDispenseStatusFromChannel"})}async dispenseFromSelection({selection:e,cart:t=!1}){const s=T(),n=this.cmd.dispenseFromSelection({token:s,selection:e});return await this.send(n,{alias:"dispenseFromSelection"}),this._dispensingTokens[s]={cart:!!t,resolve:()=>{},reject:()=>{}},new Promise((a,i)=>{this._dispensingTokens[s].resolve=a,this._dispensingTokens[s].reject=i})}async requestDispenseStatusFromSelection({token:e}){const t=this.cmd.getDispenseStatusFromSelection({token:e});return await this.send(t,{alias:"getDispenseStatusFromSelection"})}async _configureLights({machine:e,turnOn:t,alias:s}){const n=this._getMachineIndex(e),a=this.cmd.controlLights({machine:n,turnOn:t});return await this.send(a,{alias:s})}async lightsOn({machine:e}){return this._configureLights({machine:e,turnOn:!0,alias:"lightsOn"})}async lightsOff({machine:e}){return this._configureLights({machine:e,turnOn:!1,alias:"lightsOff"})}async resetFaultsAndSelfTest({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.resetFaultsAndSelfTest({machine:t});return await this.send(s,{alias:"resetFaultsAndSelfTest"})}async collect({machine:e}){const t=this._getMachineIndex(e),s=this.cmd.performCollectCycle({machine:t});return await this.send(s,{alias:"performCollectCycle"})}async dispenseFromChannelExtended({machine:e,tray:t,channel:s,speed:n,timePostRun:a,fragileOrHeavy:i,typeAdjustElevator:c,timeAdjustElevator:o,cart:h=!1}){if(!this.isAvailableToDispense({machine:e}))throw new Error(`Machine ${e} is not available to dispense`);const d=this._getMachineIndex(e),l=T(),m=this.cmd.dispenseFromChannelExtended({token:l,machine:d,tray:t,channel:s,speed:n,timePostRun:a,fragileOrHeavy:i,typeAdjustElevator:c,timeAdjustElevator:o});return await this.send(m,{alias:"dispenseFromChannelExtended"}),this._dispensingTokens[l]={cart:!!h,resolve:()=>{},reject:()=>{}},new Promise((I,D)=>{this._dispensingTokens[l].resolve=I,this._dispensingTokens[l].reject=D})}async requestDispenseStatusFromChannelExtended({token:e}){const t=this.cmd.getDispenseStatusFromChannelExtended({token:e});return await this.send(t,{alias:"getDispenseStatusFromChannelExtended"})}async restartJSD(){const e=this.cmd.restartingTheJSDKnowingThatItIsDangerous();return await this.send(e,{alias:"restartingTheJSDKnowingThatItIsDangerous"})}serialMessage(e){switch(e.opcode){case r.responseFormatCmdWrong:this._responseFormatCmdWrong(e);break;case r.responseMachineStatus:this._responseMachineStatus(e);break;case r.responseStatusChannel:this._responseStatusChannel(e);break;case r.responseStatusSelection:this._responseStatusSelection(e);break;case r.responseDispenseStatus:this._responseDispenseStatus(e);break;case r.responseConfigurationSelectionDispense:this._responseConfigurationSelectionDispense(e);break;case r.responseConfigurationChannelsLinkedToSelection:this._responseConfigurationChannelsLinkedToSelection(e);break;case r.responseMachineIdentification:this._responseMachineIdentification(e);break;case r.responseCurrentTemperature:this._responseCurrentTemperature(e);break;case r.responseReportEventsAlarmsAndFaults:this._responseReportEventsAlarmsAndFaults(e);break;case r.responseNewTimingWaitingForProductCollection:this._responseNewTimingWaitingForProductCollection(e);break;case r.responsePerformingProductCollectionCycle:this._responsePerformingProductCollectionCycle(e);break;case r.responseResetMachineSoldOutChannels:this._responseResetMachineSoldOutChannels(e);break;case r.responseNewTimingWaitingAfterProductCollection:this._responseNewTimingWaitingAfterProductCollection(e);break;case r.responseJSDVersion:this._responseJSDVersion(e);break;case r.responseActiveFaults:this._responseActiveFaults(e);break;case r.responseJSDDispensingQueue:this._responseJSDDispensingQueue(e);break;case r.responseSpecialCharacteristicsSelection:this._responseSpecialCharacteristicsSelection(e);break;case r.responsePerishableProducts:this._responsePerishableProducts(e);break;case r.responseActiveFaultsList:this._responseActiveFaultsList(e);break;case r.responseJSDResetStatus:this._responseJSDResetStatus(e);break;case r.responseExtendedDispenseStatusData:this._responseExtendedDispenseStatusData(e);break;case r.responseTraysPositioningPhototransistorsStatus:this._responseTraysPositioningPhototransistorsStatus(e);break;case r.jsdErrorLicenseTemporarilyBlocked:this._responseJsdErrorLicenseTemporarilyBlocked(e);break;case r.jsdErrorLicenseNotActive:this._responseJsdErrorLicenseNotActive(e);break;case r.jsdErrorCommandNotExecutable:this._responseJsdErrorCommandNotExecutable(e);break}}emit(e,...t){this.jsd.dispatch(`vision:${e}`,...t)}_responseFormatCmdWrong(e){const t=parseInt(e.params[0],10),s=e.params.slice(1),n=C(t);this.emit("wrong-cmd",{opcodeName:n,opcode:t,params:s})}setMachineStatus(e,t){this._machineStatus[e]=t}getMachineStatus(e){const t=this._getMachineIndex(e);return this._machineStatus[t]||null}_getMachineStatusName(e){switch(e){case 0:return"NO-CONNECTED";case 1:return"CONNECTED";case 2:return"LOST"}}_responseMachineStatus(e){const[t,s,n,a,i,c,o]=e.params,h={0:"AVAILABLE-TO-DISPENSE",1:"NOT-AVAILABLE-TO-DISPENSE",2:"ALREADY-DISPENSING",3:"WAITING-COLLECTION",4:"ELEVATOR-COLLECTION-POSITION",5:"UNCOLLECTED"},d={status:this._getMachineStatusName(parseInt(s,10)),machineInService:parseInt(n,10)===1,doorOpen:parseInt(a,10)===0,availabilityToDispense:h[i]||"NOT-AVAILABLE-TO-DISPENSE",hasLightsOn:isNaN(parseInt(c,10))?!1:parseInt(c,10)===1,temperature:o||""};this.setMachineStatus(parseInt(t,10),d),this.emit("machine-status",{machine:parseInt(t,10)+1,...d}),this.emit("door",{open:d.doorOpen,machine:parseInt(t,10)+1}),this.emit("connection",{connected:d.status==="CONNECTED",machine:parseInt(t,10)+1})}_statusChannelName(e){switch(e){case 0:return"NO-CONNECTED";case 1:return"AVAILABLE";case 2:return"SOLD-OUT";case 3:return"FAULT";default:return"NO-CONNECTED"}}_responseStatusChannel(e){const[t,s,n,a]=e.params,i=this._statusChannelName(parseInt(a,10)),c=this._getSelectionFromTrayChannel(Number(s),Number(n)),o=["AVAILABLE","SOLD-OUT"].includes(i);if(this._performingChannelAssignment.enabled){this._performingChannelAssignment.selections.push({selection:c,active:o,machine:Number(t)+1}),this._performingChannelAssignment.currentSelection=this._performingChannelAssignment.selections.length;const h=this._performingChannelAssignment.currentSelection/80*100;this.emit("channels-progress",{progress:Math.min(100,Math.round(h*100)/100),current:this._performingChannelAssignment.currentSelection,verified:this._performingChannelAssignment.selections.length}),this._performingChannelAssignment.selections.length>=80&&(this.emit("channels",this._performingChannelAssignment.selections),this._performingChannelAssignment.enabled=!1)}else this.emit("channel-status",{machine:Number(t)+1,selection:c,active:o})}_statusSelectionName(e){switch(e){case 0:return"NO-CONFIGURED";case 1:return"ASSOCIATED";case 2:return"NO-ASSOCIATED";case 3:return"NO-VISION-OWNED";case 4:return"EXPIRED";default:return"NO-CONFIGURED"}}_responseStatusSelection(e){const[t,s]=e.params,n=this._statusSelectionName(parseInt(s,10));this.emit("status-selection",{selection:Number(t),status:n})}_responseDispenseStatus(e){const[t,s,n,a]=e.params,i={0:"RECEIVED",1:"IN-PROGRESS",2:"WAITING-COLLECTION",3:"COLLECTED",4:"NO-PERFORMED",5:"TOKEN-NOT-FOUND",6:"QUEUE-FULL",7:"CHANNEL-NO-CONNECTED",8:"SELECTION-UNAVAILABLE",9:"FAILED-DISPENSE",10:"UNCOLLECTED",11:"DISPENSED-CAN-MULTIPLE",12:"DISPENSE-CANCELLED",13:"PRODUCT-EXPIRED"},c=Object.values(i).filter(D=>["NO-PERFORMED","TOKEN-NOT-FOUND","QUEUE-FULL","CHANNEL-NO-CONNECTED","SELECTION-UNAVAILABLE","FAILED-DISPENSE","DISPENSE-CANCELLED","PRODUCT-EXPIRED","UNCOLLECTED"].includes(D)),o={0:"NONE",1:"DOOR-OPEN",2:"MACHINE-NOT-AVAILABLE",3:"ERROR-PHOTOSENSORS",4:"ERROR-MOTOR-POWER-CONSUMPSION-DETECTOR",5:"ALREADY-SOLD-OUT",6:"ERROR-TEST-PRODUCT-DETECTOR",7:"SOLD-OUT",8:"ELEVATOR-CANT-REACH-TRAY",9:"UNCOLLECTED",10:"MACHINE-RESET-DURING-DISPENSE",11:"MACHINE-COMMUNICATION-ERROR",12:"MACHINE-COMMUNICATION-LOST",13:"NO-VISION",14:"PRODUCT-PERISHABLE-EXPIRED",20:"DECIDE"},h=i[parseInt(s,10)]||"UNKNOWN",[d,l,m]=n&&n.trim()!==""?n.split(".").map(D=>parseInt(D,10)):[null,null,null],I=a?o[parseInt(a,10)]||"UNKNOWN":null;this._dispensingTokens[t]&&(this._dispensingTokens[t].cart===!1&&h==="WAITING-COLLECTION"?(this._dispensingTokens[t].resolve(!0),delete this._dispensingTokens[t],this.emit("waiting-collection",{machine:d!==null?d+1:null})):this._dispensingTokens[t].cart===!0&&h==="DISPENSED-CAN-MULTIPLE"?(this._dispensingTokens[t].resolve(!0),delete this._dispensingTokens[t]):c.includes(h)&&(this._dispensingTokens[t].resolve(!1),delete this._dispensingTokens[t])),h==="IN-PROGRESS"&&this.emit("dispensing",{token:t,machine:d!==null?d+1:null,tray:l!==null?l:null,channel:m!==null?m:null,selection:m!==null&&l!==null?this._getSelectionFromTrayChannel(l,m):null}),this.emit("dispense-status",{token:t,status:h,machine:d!==null?d+1:null,tray:l!==null?l:null,channel:m!==null?m:null,extendedStatus:I})}_responseConfigurationSelectionDispense(e){const[t,s,n]=e.params;this.emit("selection-dispense-config",{selection:Number(t),speed:Number(s),timePostRun:Number(n)})}_responseConfigurationChannelsLinkedToSelection(e){const[t,...s]=e.params,a=s[s.length-1].includes(":")?s.pop():null,i={0:"OK",1:"ALREADY-DEFINED",2:"OUT-OF-RANGE"},c=s.map(o=>{const[h,d,l]=o.split(":");return{machine:parseInt(h,10)+1,tray:parseInt(d,10),channel:parseInt(l,10)}});this.emit("channels-linked-to-selection",{selection:Number(t),linkedChannels:c,status:a?i[parseInt(a,10)]||"UNKNOWN":null})}_responseMachineIdentification(e){const[t,s,n,a]=e.params;this.emit("machine-id",{machine:parseInt(t,10)+1,model:s,serialNumber:n,firmwareVersion:a})}_responseCurrentTemperature(e){const[t,s,n,a,i]=e.params,c=parseInt(t,10)+1,o=parseInt(i,10)===1?"ON":"OFF";this.emit("current-temperature",{machine:c,workingTemperature:s,currentTemperatureInsideMachine:n,currentTemperatureAir:a,coolUnitStatus:o})}_responseReportEventsAlarmsAndFaults(e){const[t,s,n]=e.params,a=parseInt(t,10)+1,i={1:"Product detector",2:"None of the motors are connected. Possible control board faulty",3:"Channels jamp detector error",4:"Temperature control error",5:"Elevator faulty",6:"Photosensor, which determine the position of the elevator in relation with the cabinet, faulty",7:"Elevator tester (flap), ES-Plus, faulty",8:"Product expired (perishable)"};this.emit("alarm-faults-events",{machine:a,event:i[parseInt(s,10)]||"UNKNOWN",status:parseInt(n,10)===1?"ACTIVE":"CLEARED"})}_responseNewTimingWaitingForProductCollection(e){const[t,s,n]=e.params;this.emit("time-waiting-for-product-collection",{minutesProductCollection:Number(t),secondsTimeBetweenDispenseManoeuvres:Number(s),secondsBetweenCollectAndStartNextDispense:Number(n)})}_responsePerformingProductCollectionCycle(e){const[t,s]=e.params,n={0:"Manoeuvre has started",1:"Wron machine number",2:"Machine no connected",3:"Wron machine model",4:"Machine cannot perform collection now",5:"Communication error with machine"};this.emit("collect",{machine:parseInt(t,10)+1,status:n[parseInt(s,10)]||"UNKNOWN"})}_responseResetMachineSoldOutChannels(e){const[t,s]=e.params,n={0:"Reset performed",1:"Wrong machine number",2:"Machine not connected",3:"Communication error with machine"};this.emit("reset-sold-out-channels",{machine:parseInt(t,10)+1,status:n[parseInt(s,10)]||"UNKNOWN"})}_responseNewTimingWaitingAfterProductCollection(e){const[t]=e.params;this.emit("time-waiting-after-product-collection",{secondsBetweenCollectAndStartNextDispense:Number(t)})}_responseJSDVersion(e){const[t,s,n,a]=e.params;this.emit("jsd-version",{name:t,compileNumber:s,compileDate:n,description:a})}_responseActiveFaults(e){const[t,s,n,a,i,c,o]=e.params;this.emit("active-faults",{machine:parseInt(t,10)+1,status:parseInt(s,10)===1?"ACTIVE":"CLEARED",fault:parseInt(n,10),appearancesNumber:parseInt(a,10),partialNumberActivated:parseInt(i,10),minutesActive:parseInt(c,10),date:o})}_responseJSDDispensingQueue(e){const[t,s,n]=e.params;this.emit("jsd-dispensing-queue",{free:parseInt(t,10),processed:parseInt(s,10),notProcessed:parseInt(n,10)})}_responseSpecialCharacteristicsSelection(e){const[t,s,n,a,i]=e.params;this.emit("special-characteristics-selection",{selection:Number(t),perishable:parseInt(s,10)===1,fragileOrHeavy:parseInt(n,10)===1,typeAdjustElevator:a==="0"?"lower":"upper",timeAdjustElevator:Number(i)})}_responsePerishableProducts(e){const[t,s,n,a,i]=e.params;this.emit("perishable-products-config",{machine:parseInt(t,10)+1,perishableActive:parseInt(s,10)===1,alarmPerisableTriggered:parseInt(n,10)===1,maxTemperature:a,minutesBeforeExpire:Number(i)})}_responseActiveFaultsList(e){const[t,...s]=e.params,n={1:"Product detector",2:"None of the motors are connected. Possible control board faulty",3:"Channels jamp detector error",4:"Temperature control error",5:"Elevator faulty",6:"Photosensor, which determine the position of the elevator in relation with the cabinet, faulty",7:"Elevator tester (flap), ES-Plus, faulty",8:"Product expired (perishable)"},a=s.map(i=>({code:parseInt(i,10),description:n[parseInt(i,10)]||"UNKNOWN"}));this.emit("active-faults-list",{machine:parseInt(t,10)+1,faults:a,ok:s.length===0})}_responseJSDResetStatus(e){const[t]=e.params,s={0:"RESETED",1:"RECEIVED"};this.emit("jsd-status-reset",{type:s[parseInt(t,10)]||"UNKNOWN"})}_responseExtendedDispenseStatusData(e){const[t]=e.params;this.emit("extended-dispense-status-data",{enabled:parseInt(t,10)===1})}_responseTraysPositioningPhototransistorsStatus(e){const[t,s,n,a,i,c,o,h,d]=e.params,l={0:"OK",C:"SHORT-CIRCUIT",N:"TRAY-NOT-DETECTED"},m={machine:parseInt(t,10)+1,trays:{11:l[s]||null,12:l[n]||null,13:l[a]||null,14:l[i]||null,15:l[c]||null,16:l[o]||null,17:l[h]||null,18:l[d]||null}};this.emit("trays-positioning-phototransistors-status",m)}_responseJsdErrorLicenseTemporarilyBlocked(e){const[t,...s]=e.params;this.emit("jsd-license-error",{type:"exprired-license",opcode:parseInt(t,10),actionName:C(parseInt(t,10)),params:s})}_responseJsdErrorLicenseNotActive(e){const[t,...s]=e.params;this.emit("jsd-license-error",{type:"app-number-not-licensed",opcode:parseInt(t,10),actionName:C(parseInt(t,10)),params:s})}_responseJsdErrorCommandNotExecutable(e){const[t,...s]=e.params;this.emit("jsd-license-error",{type:"price-control-active-direct-dispense-not-allowed",opcode:parseInt(t),actionName:C(parseInt(t,10)),params:s})}}const g={requestLogsEvents:101,requestLogsByDate:102,requestForSendingManifest:110,sendManifestDataBlock:111,responseCmdWrong:200,responseLineLogEvent:201,responseManifestDataBlock:210,responseManifestCompleted:211},x=p=>Object.keys(g).find(t=>g[t]===p)||"Unknown";class P{transport;static APP_ID=f.MANIFESTS_AND_LOGS;constructor(e){this.transport=e}requestLogsEvents(e=!1){const s=`${e?"+":"0"}`;return this.transport.buildPacket(g.requestLogsEvents,s,P.APP_ID)}requestLogsByDate(e,t){const s=`${e},${t}`;return this.transport.buildPacket(g.requestLogsByDate,s,P.APP_ID)}requestForSendingManifest(e,t){const s=`${e},${t}`;return this.transport.buildPacket(g.requestForSendingManifest,s,P.APP_ID)}sendManifestDataBlock(e,t){const s=Array.from(t).map(a=>a.toString(2).padStart(8,"0")).join(" "),n=`${e},${s}`;return this.transport.buildPacket(g.sendManifestDataBlock,n,P.APP_ID)}}class R{_commands;jsd;APP_ID=f.MANIFESTS_AND_LOGS;_logs={status:"idle",data:[]};constructor(e,t){this._commands=new P(t),this.jsd=e}async send(e,t){return this.jsd._lastApplicationCode=this.APP_ID,this.jsd._toQueue(e,{alias:t.alias,waitResponse:t.waitResponse||!1,timeout:t.timeout||500})}get cmd(){return this._commands}async requestLogsEvent({previous:e}){const t=this.cmd.requestLogsEvents(e);return await this.send(t,{alias:"requestLogsEvents"})}async requestLogs(){if(["fetching","more"].includes(this._logs.status))throw new Error("Already fetching logs");return this._logs.status="fetching",this.requestLogsEvent({previous:!1}),new Promise(e=>{const t=setInterval(()=>{if(this._logs.status==="completed"){clearInterval(t);const s=this._logs.data;e(s)}else this._logs.status==="more"&&(this._logs.status="fetching",this.requestLogsEvent({previous:!0}))},100)})}async requestLogsByDate({since:e,until:t}){const s=c=>{const o=String(c.getMonth()+1).padStart(2,"0"),h=String(c.getDate()).padStart(2,"0"),d=String(c.getHours()).padStart(2,"0"),l=String(c.getMinutes()).padStart(2,"0"),m=String(c.getSeconds()).padStart(2,"0");return`${o}/${h}/${d}/${l}/${m}`},n=s(e),a=s(t),i=this.cmd.requestLogsByDate(n,a);return await this.send(i,{alias:"requestLogsByDate"})}async requestForSendingManifest({fileSizeBytes:e,crc:t}){const s=this.cmd.requestForSendingManifest(e,t);return await this.send(s,{alias:"requestForSendingManifest"})}async sendManifestDataBlock({prevBlockId:e,dataBlock:t}){const s=this.cmd.sendManifestDataBlock(e,t);return await this.send(s,{alias:"sendManifestDataBlock"})}serialMessage(e){switch(e.opcode){case g.responseCmdWrong:this._responseCmdWrong(e);break;case g.responseLineLogEvent:this._responseLineLogEvent(e);break;case g.responseManifestDataBlock:this._responseManifestDataBlock(e);break;case g.responseManifestCompleted:this._responseManifestCompleted(e);break}}emit(e,...t){this.jsd.dispatch(`manifest:${e}`,...t)}_responseCmdWrong(e){const t=parseInt(e.params[0],10),s=e.params.slice(1),n=x(t);this.emit("wrong-cmd",{opcodeName:n,opcode:t,params:s})}_responseLineLogEvent(e){const[...t]=e.params,s=t[0]==="END_LOG";if(s)this._logs.status="completed";else{const a=t.join(",");this._logs.data.push(a),this._logs.status==="fetching"&&(this._logs.status="more")}const n=s?"end":"log";this.emit("log",{type:n,log:t})}_responseManifestDataBlock(e){const[t,s,n]=e.params;this.emit("block",{blockId:parseInt(t,10),indexFile:parseInt(s,10),quantity:parseInt(n,10)})}_responseManifestCompleted(e){const[t]=e.params,s={0:"Success",1:"CRC Error",2:"Transference interrupted",3:"Reset JSD and try again"};this.emit("completed",{result:s[t]||"Unknown Result",resultKey:parseInt(t,10)})}}const S={requestFeatureStatus:100,requestTemporaryLicenseStatus:101,requestSeedData:102,requestLicenseActivation:110,responseCmdWrong:200,responseFeatureStatus:201,responseSeedData:202,responseTemporaryLicenseStatus:203},B=p=>Object.keys(S).find(t=>S[t]===p)||"Unknown";class y{transport;static APP_ID=f.LICENSING;constructor(e){this.transport=e}requestFeatureStatus(e){const t=`${e}`;return this.transport.buildPacket(S.requestFeatureStatus,t,y.APP_ID)}requestTemporaryLicenseStatus(){return this.transport.buildPacket(S.requestTemporaryLicenseStatus,"",y.APP_ID)}requestSeedData(){return this.transport.buildPacket(S.requestSeedData,"",y.APP_ID)}requestLicenseActivation(e){const t=`${e}`;return this.transport.buildPacket(S.requestLicenseActivation,t,y.APP_ID)}}class ${_commands;jsd;APP_ID=f.LICENSING;constructor(e,t){this._commands=new y(t),this.jsd=e}async send(e,t){return this.jsd._lastApplicationCode=this.APP_ID,this.jsd._toQueue(e,{alias:t.alias,waitResponse:t.waitResponse||!1,timeout:t.timeout||500})}get cmd(){return this._commands}async requestFeatureStatus({feature:e}){const t=this.cmd.requestFeatureStatus(e);return this.send(t,{alias:"requestFeatureStatus"})}async requestTemporaryLicenseStatus(){const e=this.cmd.requestTemporaryLicenseStatus();return this.send(e,{alias:"requestTemporaryLicenseStatus"})}async requestSeedData(){const e=this.cmd.requestSeedData();return this.send(e,{alias:"requestSeedData"})}async requestLicenseActivation({license:e}){const t=this.cmd.requestLicenseActivation(e);return this.send(t,{alias:"requestLicenseActivation"})}serialMessage(e){switch(e.opcode){case S.responseCmdWrong:this._responseCmdWrong(e);break;case S.responseFeatureStatus:this._responseFeatureStatus(e);break;case S.responseSeedData:this._responseSeedData(e);break;case S.responseTemporaryLicenseStatus:this._responseTemporaryLicenseStatus(e);break}}emit(e,...t){this.jsd.dispatch(`licensing:${e}`,...t)}_responseCmdWrong(e){const t=parseInt(e.params[0],10),s=e.params.slice(1),n=B(t);this.emit("wrong-cmd",{opcodeName:n,opcode:t,params:s})}_responseFeatureStatus(e){const[t,s]=e.params;this.emit("feature-status",{feature:t,active:s==="1"})}_responseSeedData(e){const[...t]=e.params,s=t.join(","),n=t.map(a=>parseInt(a,10).toString(16).padStart(2,"0")).join(" ");this.emit("seed",{seed:s,hex:n})}_responseTemporaryLicenseStatus(e){const[t,s,n]=e.params,a={0:"Inactive, permanent license",1:"Active",2:"Expired",3:"Blocked up"};this.emit("temporary-license-status",{status:a[t]||"Unknown",remainingDays:parseInt(s,10),daysSinceExpiration:parseInt(n,10)})}}class j{static unescapeBytes(e){const t=[];for(let s=0;s<e.length;s++){const n=e[s];if(n===219){const a=e[s+1];a===220?(t.push(192),s++):a===221?(t.push(219),s++):t.push(n)}else t.push(n)}return t}static parseFrame(e){let t=e;t.length>0&&t[0]===192&&(t=t.slice(1)),t.length>0&&t[t.length-1]===192&&(t=t.slice(0,-1));const s=this.unescapeBytes(t);if(s.length<1)return console.error("Frame too short"),"Frame too short";const n=s[0],a=s[1],i=s.slice(2,-2),c=s[s.length-2],o=s[s.length-1],h=[192,n,a,...i],[d,l]=_.calculate(h);if(d!==c||l!==o)return console.error("CRC mismatch"),"CRC mismatch";if(n===2)return{type:"ACK",id:a};if(n===3)return{type:"NACK",id:a};if(n!==1)return console.warn("Unknown code"),"Unknown code";if(i.length<6)return console.error("JConnect header too short"),"JConnect header too short";const m=i[0]|i[1]<<8,I=i[2]|i[3]<<8,D=i[4]|i[5]<<8,v=i.slice(6),A=String.fromCharCode(...v);return{type:"DATA",opcode:D,appId:I,noBytes:m,params:A?A.split(","):[],id:a,rawAscii:A}}}class W{delimiter;buffer;constructor(e){this.delimiter=e,this.buffer=new Uint8Array(0)}transform(e,t){const s=new Uint8Array(this.buffer.length+e.length);s.set(this.buffer),s.set(e,this.buffer.length),this.buffer=s;let n;for(;(n=this.findDelimiterIndex())!==-1;){const a=this.buffer.slice(0,n);this.buffer=this.buffer.slice(n+this.delimiter.length),t.enqueue(a)}}findDelimiterIndex(){for(let e=0;e<=this.buffer.length-this.delimiter.length;e++){let t=!0;for(let s=0;s<this.delimiter.length;s++)if(this.buffer[e+s]!==this.delimiter[s]){t=!1;break}if(t)return e}return-1}flush(e){this.buffer.length>0&&(e.enqueue(this.buffer),this.buffer=new Uint8Array(0))}}class U extends O.T{_transport;vision;manifest;licensing;_queue=[];_timeoutPacketId=0;_runningQueue=!1;_lastApplicationCode=0;constructor({filters:e=null,config_port:t,no_device:s=1,socket:n=!1,transport:a="rs232"}={}){const i=new Uint8Array([192]),c=new TransformStream(new W(i));if(super({filters:e,config_port:t,no_device:s,socket:n,transformStream:c}),this.__internal__.device.type="jsd",this.__internal__.time.response_general=500,this.__internal__.time.response_engines=500,N.Devices.getCustom(this.typeDevice,s))throw new Error(`Device ${this.typeDevice} ${s} already exists`);N.Devices.add(this),this.#t(),this.getResponseAsUint8Array(),this._transport=a==="rs232"?new k:new b,this.vision=new M(this,this._transport),this.manifest=new R(this,this._transport),this.licensing=new $(this,this._transport),this.#e()}#e(){this.on("serial:connected",async()=>{await this.afterConnectionSetup()})}async afterConnectionSetup(){await new Promise(e=>setTimeout(e,100)),this.vision.requestMachineStatus({machine:1}),this.vision.requestMachineStatus({machine:2}),this.vision.requestMachineStatus({machine:3}),this.vision.requestMachineStatus({machine:4})}#t(){const e=["licensing:wrong-cmd","licensing:feature-status","licensing:seed","licensing:temporary-license-status","manifest:wrong-cmd","manifest:log","manifest:block","manifest:completed","vision:wrong-cmd","vision:machine-status","vision:channels-progress","vision:channels","vision:channel-status","vision:status-selection","vision:dispense-status","vision:selection-dispense-config","vision:channels-linked-to-selection","vision:machine-id","vision:current-temperature","vision:alarm-faults-events","vision:time-waiting-for-product-collection","vision:collect","vision:reset-sold-out-channels","vision:time-waiting-after-product-collection","vision:jsd-version","vision:active-faults","vision:jsd-dispensing-queue","vision:special-characteristics-selection","vision:perishable-products-config","vision:active-faults-list","vision:jsd-status-reset","vision:extended-dispense-status-data","vision:trays-positioning-phototransistors-status","vision:jsd-license-error","serial:jsd-error","serial:jsd-ack","serial:jsd-nack","serial:jsd-data"];for(const t of e)this.serialRegisterAvailableListener(t)}serialSetConnectionConstant(){const e=this._transport?this._transport:new k;let t=255;this._transport&&(t=e.packetId,this._transport._overridePacketId(t+1));const{bytes:s}=u.connection({transport:e,packetId:t});return s}send(e,t){return this.appendToQueue(e,t.alias||"unknown")}onEvent(e,t){super.on(e,t)}offEvent(e,t){super.off(e,t)}onceEvent(e,t){const s=((...n)=>{t(...n),this.offEvent(e,s)});this.onEvent(e,s)}get transport(){return this._transport.name}acknowledge(e){return this._transport.buildAckPacket(e)}ack(e){this.isConnected&&this.send(new Uint8Array(this.acknowledge(e)),{alias:"ACK Response"})}_toQueue(e,t){this._queue.push({packetId:e.packetId,data:e.bytes,alias:t?.alias||"unknown",timeout:t?.timeout||500,resendCount:0}),this._runQueue()}_runQueue(){if(this._queue.length===0||this._runningQueue)return;const e=this._queue[0];this.isConnected&&(this.appendToQueue(new Uint8Array(e.data),e.alias||"unknown"),this._runningQueue=!0,this._timeoutPacketId=setTimeout(()=>{const t=this._queue.findIndex(s=>s.packetId===e.packetId);t!==-1&&(e.resendCount<3?(this._queue[t].resendCount+=1,this._runningQueue=!1,this._runQueue()):(this.dispatch("serial:jsd-error",`No response for packet ID ${e.packetId} after 3 attempts.`),this._queue.splice(t,1),this._runningQueue=!1,this._queue.length>0&&this._runQueue()))},e.timeout))}_dequeue(e){const t=this._queue.findIndex(s=>s.packetId===e);t!==-1&&(this._queue.splice(t,1),this._timeoutPacketId&&(clearTimeout(this._timeoutPacketId),this._timeoutPacketId=0),this._runningQueue=!1,this._queue.length>0&&this._runQueue())}serialMessage(e){const t=Array.from(structuredClone(e));if(t.length===0)return;const s=j.parseFrame(t);if(typeof s=="string")this.dispatch("serial:jsd-error",s);else if(s.type==="ACK")this._queue.findIndex(a=>a.packetId===s.id)!==-1&&this._dequeue(s.id),this.dispatch("serial:jsd-ack",s);else if(s.type==="NACK")this.dispatch("serial:jsd-nack",s);else if(s.type==="DATA"){this.ack(s.id),typeof s.appId>"u"&&(s.appId=this._lastApplicationCode);const n=s.appId;L(n)&&this.vision.serialMessage(s),w(n)&&this.manifest.serialMessage(s),F(n)&&this.licensing.serialMessage(s),this.dispatch("serial:jsd-data",s)}this.dispatch("serial:message",{raw:e,parsed:s})}}exports.JSD=U;
package/dist/jsd.js CHANGED
@@ -2374,12 +2374,17 @@ class K extends O {
2374
2374
  const i = new Uint8Array([192]), c = new TransformStream(new W(i));
2375
2375
  if (super({ filters: e, config_port: t, no_device: s, socket: n, transformStream: c }), this.__internal__.device.type = "jsd", this.__internal__.time.response_general = 500, this.__internal__.time.response_engines = 500, N.getCustom(this.typeDevice, s))
2376
2376
  throw new Error(`Device ${this.typeDevice} ${s} already exists`);
2377
- N.add(this), this.#e(), this.getResponseAsUint8Array(), this._transport = a === "rs232" ? new k() : new b(), this.vision = new M(this, this._transport), this.manifest = new R(this, this._transport), this.licensing = new $(this, this._transport), this.afterConnectionSetup();
2377
+ N.add(this), this.#t(), this.getResponseAsUint8Array(), this._transport = a === "rs232" ? new k() : new b(), this.vision = new M(this, this._transport), this.manifest = new R(this, this._transport), this.licensing = new $(this, this._transport), this.#e();
2378
+ }
2379
+ #e() {
2380
+ this.on("serial:connected", async () => {
2381
+ await this.afterConnectionSetup();
2382
+ });
2378
2383
  }
2379
2384
  async afterConnectionSetup() {
2380
2385
  await new Promise((e) => setTimeout(e, 100)), this.vision.requestMachineStatus({ machine: 1 }), this.vision.requestMachineStatus({ machine: 2 }), this.vision.requestMachineStatus({ machine: 3 }), this.vision.requestMachineStatus({ machine: 4 });
2381
2386
  }
2382
- #e() {
2387
+ #t() {
2383
2388
  const e = [
2384
2389
  "licensing:wrong-cmd",
2385
2390
  "licensing:feature-status",
@@ -1 +1 @@
1
- {"version":3,"file":"jsd.d.ts","sourceRoot":"","sources":["../../../../lib/serial/jsd.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAItC,OAAO,EAAE,MAAM,EAAE,MAAM,qCAAqC,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,uCAAuC,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAGnE,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAIrG,KAAK,aAAa,CAAC,CAAC,SAAS,GAAG,EAAE,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,IAAI,CAAC;AAE3D,qBAAa,GAAI,SAAQ,IAAI;;IAC3B,OAAO,CAAC,UAAU,CAAgC;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,QAAQ,CAAC;IACnB,SAAS,EAAE,SAAS,CAAC;IAE5B,OAAO,CAAC,MAAM,CAML;IACT,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,aAAa,CAAS;IAEvB,oBAAoB,EAAE,MAAM,CAAK;gBAE5B,EACV,OAAc,EACd,WAAW,EACX,SAAa,EACb,MAAc,EACd,SAAmB,GACpB,GAAE,oBAAyB;YAsBd,oBAAoB;IAyDlC,2BAA2B;IAWpB,IAAI,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE;IAI7F,OAAO,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAIzF,QAAQ,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAI3F,SAAS,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IASlG,IAAW,SAAS,WAEnB;IAED,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,GAAG;IASJ,QAAQ,CACb,IAAI,EAAE,iBAAiB,EACvB,OAAO,CAAC,EAAE;QACR,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,YAAY,CAAC,EAAE,OAAO,CAAC;KACxB,GACA,IAAI;IAgBP,OAAO,CAAC,SAAS;IAkCjB,OAAO,CAAC,QAAQ;IAiBT,aAAa,CAAC,GAAG,EAAE,UAAU;CA4CrC"}
1
+ {"version":3,"file":"jsd.d.ts","sourceRoot":"","sources":["../../../../lib/serial/jsd.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAItC,OAAO,EAAE,MAAM,EAAE,MAAM,qCAAqC,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,uCAAuC,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAGnE,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAIrG,KAAK,aAAa,CAAC,CAAC,SAAS,GAAG,EAAE,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,IAAI,CAAC;AAE3D,qBAAa,GAAI,SAAQ,IAAI;;IAC3B,OAAO,CAAC,UAAU,CAAgC;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,QAAQ,CAAC;IACnB,SAAS,EAAE,SAAS,CAAC;IAE5B,OAAO,CAAC,MAAM,CAML;IACT,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,aAAa,CAAS;IAEvB,oBAAoB,EAAE,MAAM,CAAK;gBAE5B,EACV,OAAc,EACd,WAAW,EACX,SAAa,EACb,MAAc,EACd,SAAmB,GACpB,GAAE,oBAAyB;YA4Bd,oBAAoB;IAyDlC,2BAA2B;IAWpB,IAAI,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE;IAI7F,OAAO,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAIzF,QAAQ,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAI3F,SAAS,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IASlG,IAAW,SAAS,WAEnB;IAED,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,GAAG;IASJ,QAAQ,CACb,IAAI,EAAE,iBAAiB,EACvB,OAAO,CAAC,EAAE;QACR,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,YAAY,CAAC,EAAE,OAAO,CAAC;KACxB,GACA,IAAI;IAgBP,OAAO,CAAC,SAAS;IAkCjB,OAAO,CAAC,QAAQ;IAiBT,aAAa,CAAC,GAAG,EAAE,UAAU;CA4CrC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danidoble/webserial",
3
- "version": "4.5.0-alpha.1",
3
+ "version": "4.5.0-alpha.2",
4
4
  "author": "danidoble",
5
5
  "repository": {
6
6
  "type": "git",