@sebbo2002/vestaboard2mqtt 6.0.4-develop.3 → 6.0.4-develop.5
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/bin/start.cjs +1 -1
- package/dist/bin/start.cjs.map +1 -1
- package/dist/bin/start.js +1 -1
- package/dist/{chunk-Z36WS5HL.js → chunk-KRLCDDZM.js} +2 -2
- package/dist/{chunk-Z36WS5HL.js.map → chunk-KRLCDDZM.js.map} +1 -1
- package/dist/lib/index.cjs +1 -1
- package/dist/lib/index.cjs.map +1 -1
- package/dist/lib/index.js +1 -1
- package/package.json +3 -3
package/dist/bin/start.cjs
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
`+r)),t.removeListener("error",Kn),t.destroy()}function Cg(t){return t.trim()}});var Zl=g((Bm,Jl)=>{"use strict";var nr=Wn();nr.createWebSocketStream=zl();nr.Server=Xl();nr.Receiver=In();nr.Sender=An();Jl.exports=nr});var $n=g((km,zn)=>{"use strict";var{Buffer:sr}=require("buffer"),eu=Zl(),or=_e()("mqttjs:ws"),Pg=ti(),Og=Ne().Transform,Ig=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],tu=typeof process<"u"&&process.title==="browser"||typeof __webpack_require__=="function";function ru(t,e){let r=t.protocol+"://"+t.hostname+":"+t.port+t.path;return typeof t.transformWsUrl=="function"&&(r=t.transformWsUrl(r,t,e)),r}function iu(t){let e=t;return t.hostname||(e.hostname="localhost"),t.port||(t.protocol==="wss"?e.port=443:e.port=80),t.path||(e.path="/"),t.wsOptions||(e.wsOptions={}),!tu&&t.protocol==="wss"&&Ig.forEach(function(r){Object.prototype.hasOwnProperty.call(t,r)&&!Object.prototype.hasOwnProperty.call(t.wsOptions,r)&&(e.wsOptions[r]=t[r])}),e}function Rg(t){let e=iu(t);if(e.hostname||(e.hostname=e.host),!e.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let r=new URL(document.URL);e.hostname=r.hostname,e.port||(e.port=r.port)}return e.objectMode===void 0&&(e.objectMode=!(e.binary===!0||e.binary===void 0)),e}function Ag(t,e,r){or("createWebSocket"),or("protocol: "+r.protocolId+" "+r.protocolVersion);let i=r.protocolId==="MQIsdp"&&r.protocolVersion===3?"mqttv3.1":"mqtt";return or("creating new Websocket for url: "+e+" and protocol: "+i),new eu(e,[i],r.wsOptions)}function Bg(t,e){let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt",i=ru(e,t),n=new WebSocket(i,[r]);return n.binaryType="arraybuffer",n}function kg(t,e){or("streamBuilder");let r=iu(e),i=ru(r,t),n=Ag(t,i,r),s=eu.createWebSocketStream(n,r.wsOptions);return s.url=i,n.on("close",()=>{s.destroy()}),s}function Lg(t,e){or("browserStreamBuilder");let r,n=Rg(e).browserBufferSize||1024*512,s=e.browserBufferTimeout||1e3,o=!e.objectMode,a=Bg(t,e),u=f(e,v,b);e.objectMode||(u._writev=y),u.on("close",()=>{a.close()});let l=typeof a.addEventListener<"u";a.readyState===a.OPEN?r=u:(r=r=Pg(void 0,void 0,e),e.objectMode||(r._writev=y),l?a.addEventListener("open",h):a.onopen=h),r.socket=a,l?(a.addEventListener("close",c),a.addEventListener("error",d),a.addEventListener("message",m)):(a.onclose=c,a.onerror=d,a.onmessage=m);function f(C,D,K){let F=new Og({objectModeMode:C.objectMode});return F._write=D,F._flush=K,F}function h(){r.setReadable(u),r.setWritable(u),r.emit("connect")}function c(){r.end(),r.destroy()}function d(C){r.destroy(C)}function m(C){let D=C.data;D instanceof ArrayBuffer?D=sr.from(D):D=sr.from(D,"utf8"),u.push(D)}function y(C,D){let K=new Array(C.length);for(let F=0;F<C.length;F++)typeof C[F].chunk=="string"?K[F]=sr.from(C[F],"utf8"):K[F]=C[F].chunk;this._write(sr.concat(K),"binary",D)}function v(C,D,K){a.bufferedAmount>n&&setTimeout(v,s,C,D,K),o&&typeof C=="string"&&(C=sr.from(C,"utf8"));try{a.send(C)}catch(F){return K(F)}K()}function b(C){a.close(),C()}return r}tu?zn.exports=Lg:zn.exports=kg});var au=g((Lm,ar)=>{"use strict";var su=dn(),Mg=Rr(),qg=require("url"),Ng=pr(),nu=_e()("mqttjs"),ee={};typeof process<"u"&&process.title!=="browser"||typeof __webpack_require__!="function"?(ee.mqtt=pn(),ee.tcp=pn(),ee.ssl=Jr(),ee.tls=Jr(),ee.mqtts=Jr()):(ee.wx=_n(),ee.wxs=_n(),ee.ali=vn(),ee.alis=vn());ee.ws=$n();ee.wss=$n();function Dg(t){let e;t.auth&&(e=t.auth.match(/^(.+):(.+)$/),e?(t.username=e[1],t.password=e[2]):t.username=t.auth)}function ou(t,e){if(nu("connecting to an MQTT broker..."),typeof t=="object"&&!e&&(e=t,t=null),e=e||{},t){let n=qg.parse(t,!0);if(n.port!=null&&(n.port=Number(n.port)),e=Ng(n,e),e.protocol===null)throw new Error("Missing protocol");e.protocol=e.protocol.replace(/:$/,"")}if(Dg(e),e.query&&typeof e.query.clientId=="string"&&(e.clientId=e.query.clientId),e.cert&&e.key)if(e.protocol){if(["mqtts","wss","wxs","alis"].indexOf(e.protocol)===-1)switch(e.protocol){case"mqtt":e.protocol="mqtts";break;case"ws":e.protocol="wss";break;case"wx":e.protocol="wxs";break;case"ali":e.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+e.protocol+'"!')}}else throw new Error("Missing secure protocol key");if(!ee[e.protocol]){let n=["mqtts","wss"].indexOf(e.protocol)!==-1;e.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter(function(s,o){return n&&o%2===0?!1:typeof ee[s]=="function"})[0]}if(e.clean===!1&&!e.clientId)throw new Error("Missing clientId for unclean clients");e.protocol&&(e.defaultProtocol=e.protocol);function r(n){return e.servers&&((!n._reconnectCount||n._reconnectCount===e.servers.length)&&(n._reconnectCount=0),e.host=e.servers[n._reconnectCount].host,e.port=e.servers[n._reconnectCount].port,e.protocol=e.servers[n._reconnectCount].protocol?e.servers[n._reconnectCount].protocol:e.defaultProtocol,e.hostname=e.host,n._reconnectCount++),nu("calling streambuilder for",e.protocol),ee[e.protocol](n,e)}let i=new su(r,e);return i.on("error",function(){}),i}ar.exports=ou;ar.exports.connect=ou;ar.exports.MqttClient=su;ar.exports.Store=Mg});var uu=g((Mm,lu)=>{"use strict";var Ug=Zi().NumberAllocator;function Ye(){if(!(this instanceof Ye))return new Ye;this.numberAllocator=new Ug(1,65535)}Ye.prototype.allocate=function(){return this.lastId=this.numberAllocator.alloc(),this.lastId};Ye.prototype.getLastAllocated=function(){return this.lastId};Ye.prototype.register=function(t){return this.numberAllocator.use(t)};Ye.prototype.deallocate=function(t){this.numberAllocator.free(t)};Ye.prototype.clear=function(){this.numberAllocator.clear()};lu.exports=Ye});var cu=g((qm,pt)=>{"use strict";var fu=dn(),jg=au(),Fg=Rr(),Wg=fn(),Vg=uu();pt.exports.connect=jg;pt.exports.MqttClient=fu;pt.exports.Client=fu;pt.exports.Store=Fg;pt.exports.DefaultMessageIdProvider=Wg;pt.exports.UniqueMessageIdProvider=Vg});var _u=ui(require("async-mqtt"),1),dv=ui(cu(),1),mu=require("vestaboard-api");var hu=require("fs"),du=require("fs"),pu=require("path"),{readFile:Hg,writeFile:Kg}=du.promises,te=class t{static currentData={};static currentFetch;static file=(0,pu.join)(process.env.HOME||"~",".vestaboard2mqtt");namespace;constructor(e){this.namespace=e}static async fetch(){if(this.currentFetch)return this.currentFetch;let e=this.fetchFromFile();return this.currentFetch=e,e}static async fetchFromFile(){if((0,hu.existsSync)(this.file))try{let e=await Hg(this.file,{encoding:"utf8"});this.currentData=JSON.parse(e)}catch(e){console.warn(`Unable to parse cache file: ${e}`)}}static isCacheItemObject(e){return e!==null&&typeof e=="object"&&"updated"in e&&typeof e.updated=="number"&&"value"in e&&typeof e.value<"u"}static async save(){await Kg(this.file,JSON.stringify(this.currentData,null," "))}async delete(e){!t.currentData||!t.currentData[this.namespace]||(delete t.currentData[this.namespace][e],Object.keys(t.currentData[this.namespace]).length===0&&delete t.currentData[this.namespace],await t.save().catch(r=>{console.warn(`Unable to update cache: ${r}`)}))}async get(e,r=0){if(await t.fetch(),!t.currentData||!t.currentData[this.namespace]||!t.currentData[this.namespace][e])return null;let i=t.currentData[this.namespace][e];return!t.isCacheItemObject(i)&&r>0?null:t.isCacheItemObject(i)?r>0&&new Date().getTime()-i.updated>r?null:i.value:i}async set(e,r){if(await t.fetch(),!t.currentData)throw new Error("Unable to set value: currentData is empty!");t.currentData[this.namespace]=t.currentData[this.namespace]||{},t.currentData[this.namespace][e]={updated:new Date().getTime(),value:r},await t.save().catch(i=>{console.warn(`Unable to update cache: ${i}`)})}};var k=class{static get board(){if(this.loaded&&this.data?.board)return this.data.board;throw new Error("Unable to access board config, is config loaded?")}static get calendar(){if(this.loaded&&this.data?.calendar)return this.data.calendar;throw new Error("Unable to access calendar config, is config loaded?")}static get loaded(){return!!this.data&&!!this.cache}static get mqtt(){if(this.loaded&&this.data?.mqtt)return this.data.mqtt;throw new Error("Unable to access mqtt config, is config loaded?")}static cache=new te("config");static data;static async load(){let e=await this.cache.get("default");if(!e)throw new Error("Unable to load configuration, try to run the setup script\u2026");this.data=e}static async save(e){this.data=e,await this.cache.set("default",e)}static async updateDisabled(e){e===this.data?.board.disabled||!this.loaded||!this.data?.mqtt||(this.data.board.disabled=e,await this.save(this.data))}};var Ae=require("vestaboard-api/lib/cjs/values.js");var zg=[["\xE4",[1,5]],["\xC4",[1,5]],["\xF6",[15,5]],["\xD6",[15,5]],["\xFC",[21,5]],["\xDC",[21,5]],["\xDF",[19,19]],["\u{1F7E5}",[63]],["\u{1F7E7}",[64]],["\u{1F7E8}",[65]],["\u{1F7E9}",[66]],["\u{1F7E6}",[67]],["\u{1F7EA}",[68]],["\u2B1C\uFE0F",[69]],["\u2B1C",[69]],["\u2B1B\uFE0F",[0]],["\u2B1B",[0]],["\uFE6B",[38]],["\uFF20",[38]],["0\uFE0F\u20E3",[36]],["1\uFE0F\u20E3",[27]],["2\uFE0F\u20E3",[28]],["3\uFE0F\u20E3",[29]],["4\uFE0F\u20E3",[30]],["5\uFE0F\u20E3",[31]],["6\uFE0F\u20E3",[32]],["7\uFE0F\u20E3",[33]],["8\uFE0F\u20E3",[34]],["9\uFE0F\u20E3",[35]],["\u2755",[37]],["\u203C\uFE0F",[37,37]],["\u2757\uFE0F",[37]],["\u2049\uFE0F",[37,60]],["\u26A0\uFE0F",[65]],["#\uFE0F\u20E3",[39]],["\u{1F4B8}",[40]],["\u{1F4B2}",[40]],["\u{1F4B5}",[40]],["\u{1F4B0}",[40]],["$",[40]],["\uFE69",[40]],["\uFF04",[40]],["\u2190",[44]],["\u2192",[44]],["\u27A1",[44]],["\u2B05",[44]],["\u2794",[44]],["\u2194",[44]],["\u2013",[44]],["\u2795",[46]],["+",[46]],["\uFE6A",[54]],["\uFF05",[54]],["\u2753",[60]],["\u2754",[60]],["\u2103",[62,3]],["\u2109",[62,6]]],pe=class t{board;currentLine=null;isFilled=!1;constructor(e=t.newBoardCharArray()){this.board=e}static char2char(e){let r=Object.entries(Ae.characterCode).find(([n])=>e===n);if(r)return[r[1]];let i=zg.find(([n])=>e===n);return i&&Array.isArray(i[1])?i[1]:[60]}static charToString(e){let r=Object.entries(Ae.characterCode).filter(([i])=>i.length<=2).find(([,i])=>i===e);if(r)return r[0].toUpperCase()+" ";switch(e){case 63:return"\u{1F7E5}";case 64:return"\u{1F7E7}";case 65:return"\u{1F7E8}";case 66:return"\u{1F7E9}";case 67:return"\u{1F7E6}";case 68:return"\u{1F7EA}";case 69:return"\u2B1C\uFE0F";default:return" "}}static newBoardCharArray(){return JSON.parse(JSON.stringify(Ae.emptyBoard))}static word2chars(e){let r=[];for(let i of e)r.push(...this.char2char(i));return r}center(){let e=[this.board.findIndex(i=>i.find(n=>n!==0)),Math.min(...this.board.map(i=>i.find(n=>n!==0)?i.slice().reverse().findIndex(n=>n!==0):i.length)),this.board.slice().reverse().findIndex(i=>i.find(n=>n!==0)),Math.min(...this.board.map(i=>i.find(n=>n!==0)?i.findIndex(n=>n!==0):i.length))],r=[Math.floor((e[0]+e[2])/2),Math.floor((e[1]+e[3])/2)];if(e[0]!==r[0]){let i=r[0]-e[0];this.board.splice(e[0]<r[0]?0:this.board.length-i,0,...this.board.splice(this.board.length-i,i))}if(e[3]!==r[1]){let i=r[1]-e[3];this.board.forEach(n=>{n.splice(e[3]<r[1]?0:n.length-i,0,...n.splice(n.length-i,i))})}}centerLines(){this.board.forEach(e=>{let r=[e.findIndex(s=>s!==0),e.slice().reverse().findIndex(s=>s!==0)];if(r[0]===-1||r[1]===-1)return;let i=e.slice(r[0],e.length-r[1]),n=Math.floor((r[0]+r[1])/2);e.fill(0,0,n),e.splice(n,i.length,...i),e.fill(0,n+i.length)})}export(){return this.board}isEmpty(){return!this.board.find(e=>e.find(r=>r!==0))}repeat(e,r={}){this.board[r.line||0].fill(t.char2char(e)[0])}toString(){return"#="+"=".repeat(Ae.LINE_LENGTH*2)+`=#
|
|
13
13
|
`+this.board.map(e=>"# "+e.map(r=>t.charToString(r)).join("")+` #
|
|
14
14
|
`).join("")+"#="+"=".repeat(Ae.LINE_LENGTH*2)+`=#
|
|
15
|
-
`}write(e,r={}){let i=0;if(this.isFilled)return;if(r.line==="CURRENT")i=this.currentLine||0;else if(r.line==="NEXT"&&this.currentLine===null)this.currentLine=0,i=this.currentLine;else if(r.line==="NEXT"&&typeof this.currentLine=="number"&&this.currentLine<this.board.length-1)this.currentLine++,i=this.currentLine;else if(r.line==="NEXT"){this.isFilled=!0;return}else r.line!==void 0&&(i=r.line);let n={firstLine:i,firstRow:r.row||0,lastLine:this.board.length-1,lastRow:Ae.LINE_LENGTH-1},s=[n.firstRow,n.firstLine];e.split(/\s+/).forEach((a,u)=>{u!==0&&s[0]!==n.firstRow&&(this.board[s[1]][s[0]]=0,s[0]++);let l=n.lastRow-s[0]+1,f=t.word2chars(a);f.filter(h=>h===60).length===f.length&&f.length>0||(f.length>l&&f.length<=n.lastRow-n.firstRow+1&&s[1]<n.lastLine&&(s[0]=n.firstRow,s[1]++,l=n.lastRow-s[0]),f.length<=l?(this.board[s[1]].splice(s[0],f.length,...f),s[0]+=f.length):f.length>l&&l>5&&(this.board[s[1]].splice(s[0],l,...f.slice(0,l)),s[0]+=l))}),this.currentLine=s[1]}};var yu=ui(require("node-ical"),1);var gt=class{static cache=new te("calendar");parseConfig(e,r,i){let n={};return console.log("parseConfig",i),e==="min-temp"&&Array.isArray(i.temp)?n.temp=[parseInt(r||""),Math.max(...i.temp)]:e==="min-temp"?n.temp=[parseInt(r||""),parseInt(r||"")]:e==="max-temp"&&Array.isArray(i.temp)?n.temp=[Math.min(...i.temp),parseInt(r||"")]:e==="max-temp"?n.temp=[parseInt(r||""),parseInt(r||"")]:e==="precip"?n.precip=parseInt(r||"",10):e==="locale"&&(n.locale=String(r)),n}parsePayload(e){try{return JSON.parse(e||"")}catch{return{}}}async render(e,r){let i=new pe,n=new Date,s=Object.assign({locale:"en",precip:void 0,temp:void 0},r,e);i.write(n.toLocaleString(s.locale,{weekday:"long"})),i.write(n.toLocaleString(s.locale,{day:"numeric",month:"long"}),{line:"NEXT"}),i.write("",{line:"NEXT"});let o=[];Array.isArray(s.temp)&&o.push(`${Math.min(...s.temp)}-${Math.max(...s.temp)}\xB0C`),typeof s.precip=="number"&&s.precip>0&&o.push(`${s.precip}%`),o.length&&i.write(o.join(", "),{line:"NEXT"}),i.center();let a=new Date;return a.setHours(24,0,0,0),{message:i,validTill:a}}};var lr=class t{static cache=new te("calendar");static getTimeStr(e,r=!1){return this.isMidnight(e.start)&&this.isMidnight(e.end)&&this.isSameDay(new Date,e.start)?"Heute":this.isMidnight(e.start)&&this.isMidnight(e.end)&&this.isSameDay(new Date(new Date().getTime()+1e3*60*60*24),e.start)?r?"Morgen":"Morgn":e.start.getHours().toString().padStart(2,"\u2B1B\uFE0F")+":"+e.start.getMinutes().toString().padStart(2,"0")}static isMidnight(e){return!e.getHours()&&!e.getMinutes()&&!e.getSeconds()&&!e.getMilliseconds()}static isSameDay(e,r){return e.getFullYear()===r.getFullYear()&&e.getMonth()===r.getMonth()&&e.getDate()===r.getDate()}async fetchURL(e){let r=await t.cache.get(e,6e5);if(!r){let i=await yu.default.async.fromURL(e);r=Object.values(i).filter(s=>s.type==="VEVENT"&&s.start&&s.end&&s.summary).map(s=>({end:new Date(String(s.end)),start:new Date(String(s.start)),summary:String(s.summary).trim()})).filter(s=>s.end>new Date).sort((s,o)=>s.end.getTime()-o.end.getTime()).slice(0,6),await t.cache.set(e,r)}return r.map(i=>({end:new Date(String(i.end)),start:new Date(String(i.start)),summary:String(i.summary)})).filter(i=>i.end>new Date)}async fetchURLs(e){let r=await Promise.all(e.map(i=>this.fetchURL(i)));return[].concat(...r).filter(i=>i.end>new Date).sort((i,n)=>i.end.getTime()-n.end.getTime())}parseConfig(){return{}}parsePayload(e){return{calendars:(e||"").split(",")}}async render(e){let r=new pe,i=e.calendars.map(o=>k.calendar.urls[o]).filter(Boolean),n=await this.fetchURLs(i).then(o=>o.filter(a=>t.isMidnight(a.start)&&t.isMidnight(a.end)?t.isSameDay(new Date,a.start)||new Date().getHours()>=20&&t.isSameDay(new Date(new Date().getTime()+1e3*60*60*24),a.start):a.start<new Date(new Date().getTime()+1e3*60*60*12)));if(!n.length){let o=new gt,u=await new te("page-config").get("today");return o.render({},u||{})}let s=new Date(new Date().getTime()+1e3*60*10);return n.forEach(o=>{r.write(t.getTimeStr(o,n.length===1),{line:"NEXT"}),r.write(o.summary,{line:"CURRENT",row:6}),r.write("",{line:"NEXT"}),o.end<s&&(s=o.end)}),r.center(),{message:r,validTill:s}}};var ur=class{static cache=new te("calendar");parseConfig(){return{}}parsePayload(e){return e||""}async render(e){let r=new pe;return e.split(`
|
|
15
|
+
`}write(e,r={}){let i=0;if(this.isFilled)return;if(r.line==="CURRENT")i=this.currentLine||0;else if(r.line==="NEXT"&&this.currentLine===null)this.currentLine=0,i=this.currentLine;else if(r.line==="NEXT"&&typeof this.currentLine=="number"&&this.currentLine<this.board.length-1)this.currentLine++,i=this.currentLine;else if(r.line==="NEXT"){this.isFilled=!0;return}else r.line!==void 0&&(i=r.line);let n={firstLine:i,firstRow:r.row||0,lastLine:this.board.length-1,lastRow:Ae.LINE_LENGTH-1},s=[n.firstRow,n.firstLine];e.split(/\s+/).forEach((a,u)=>{u!==0&&s[0]!==n.firstRow&&(this.board[s[1]][s[0]]=0,s[0]++);let l=n.lastRow-s[0]+1,f=t.word2chars(a);f.filter(h=>h===60).length===f.length&&f.length>0||(f.length>l&&f.length<=n.lastRow-n.firstRow+1&&s[1]<n.lastLine&&(s[0]=n.firstRow,s[1]++,l=n.lastRow-s[0]),f.length<=l?(this.board[s[1]].splice(s[0],f.length,...f),s[0]+=f.length):f.length>l&&l>5&&(this.board[s[1]].splice(s[0],l,...f.slice(0,l)),s[0]+=l))}),this.currentLine=s[1]}};var yu=ui(require("node-ical"),1);var gt=class{static cache=new te("calendar");parseConfig(e,r,i){let n={};return console.log("parseConfig",i),e==="min-temp"&&Array.isArray(i.temp)?n.temp=[parseInt(r||""),Math.max(...i.temp)]:e==="min-temp"?n.temp=[parseInt(r||""),parseInt(r||"")]:e==="max-temp"&&Array.isArray(i.temp)?n.temp=[Math.min(...i.temp),parseInt(r||"")]:e==="max-temp"?n.temp=[parseInt(r||""),parseInt(r||"")]:e==="precip"?n.precip=parseInt(r||"",10):e==="locale"&&(n.locale=String(r)),n}parsePayload(e){try{return JSON.parse(e||"")}catch{return{}}}async render(e,r){let i=new pe,n=new Date,s=Object.assign({locale:"en",precip:void 0,temp:void 0},r,e);i.write(n.toLocaleString(s.locale,{weekday:"long"})),i.write(n.toLocaleString(s.locale,{day:"numeric",month:"long"}),{line:"NEXT"}),i.write("",{line:"NEXT"});let o=[];Array.isArray(s.temp)&&o.push(`${Math.min(...s.temp)}-${Math.max(...s.temp)}\xB0C`),typeof s.precip=="number"&&s.precip>0&&o.push(`${s.precip}%`),o.length&&i.write(o.join(", "),{line:"NEXT"}),i.center();let a=new Date;return a.setHours(24,0,0,0),{message:i,validTill:a}}};var lr=class t{static cache=new te("calendar");static getTimeStr(e,r=!1){return this.isMidnight(e.start)&&this.isMidnight(e.end)&&this.isSameDay(new Date,e.start)?"Heute":this.isMidnight(e.start)&&this.isMidnight(e.end)&&this.isSameDay(new Date(new Date().getTime()+1e3*60*60*24),e.start)?r?"Morgen":"Morgn":e.start.getHours().toString().padStart(2,"\u2B1B\uFE0F")+":"+e.start.getMinutes().toString().padStart(2,"0")}static isMidnight(e){return!e.getHours()&&!e.getMinutes()&&!e.getSeconds()&&!e.getMilliseconds()}static isSameDay(e,r){return e.getFullYear()===r.getFullYear()&&e.getMonth()===r.getMonth()&&e.getDate()===r.getDate()}async fetchURL(e){let r=await t.cache.get(e,6e5);if(!r){let i=await yu.default.async.fromURL(e);r=Object.values(i).filter(s=>s&&s.type==="VEVENT"&&s.start&&s.end&&s.summary).map(s=>({end:new Date(String(s.end)),start:new Date(String(s.start)),summary:String(s.summary).trim()})).filter(s=>s.end>new Date).sort((s,o)=>s.end.getTime()-o.end.getTime()).slice(0,6),await t.cache.set(e,r)}return r.map(i=>({end:new Date(String(i.end)),start:new Date(String(i.start)),summary:String(i.summary)})).filter(i=>i.end>new Date)}async fetchURLs(e){let r=await Promise.all(e.map(i=>this.fetchURL(i)));return[].concat(...r).filter(i=>i.end>new Date).sort((i,n)=>i.end.getTime()-n.end.getTime())}parseConfig(){return{}}parsePayload(e){return{calendars:(e||"").split(",")}}async render(e){let r=new pe,i=e.calendars.map(o=>k.calendar.urls[o]).filter(Boolean),n=await this.fetchURLs(i).then(o=>o.filter(a=>t.isMidnight(a.start)&&t.isMidnight(a.end)?t.isSameDay(new Date,a.start)||new Date().getHours()>=20&&t.isSameDay(new Date(new Date().getTime()+1e3*60*60*24),a.start):a.start<new Date(new Date().getTime()+1e3*60*60*12)));if(!n.length){let o=new gt,u=await new te("page-config").get("today");return o.render({},u||{})}let s=new Date(new Date().getTime()+1e3*60*10);return n.forEach(o=>{r.write(t.getTimeStr(o,n.length===1),{line:"NEXT"}),r.write(o.summary,{line:"CURRENT",row:6}),r.write("",{line:"NEXT"}),o.end<s&&(s=o.end)}),r.center(),{message:r,validTill:s}}};var ur=class{static cache=new te("calendar");parseConfig(){return{}}parsePayload(e){return e||""}async render(e){let r=new pe;return e.split(`
|
|
16
16
|
`).forEach(i=>{r.write(i,{line:"NEXT"})}),r.centerLines(),r.center(),{message:r}}};var $g={calendar:new lr,message:new ur,today:new gt},fr=$g;var cr=class t{board;currentMessage;currentTimer;mqtt;pageConfig=new te("page-config");subscriptionIds;constructor(){this.board=new mu.Vesta({apiKey:k.board.key,apiSecret:k.board.secret}),this.mqtt=_u.default.connect(k.mqtt.url,{will:{payload:"offline",qos:0,retain:!0,topic:k.mqtt.prefix+"/status"}}),this.mqtt.on("connect",()=>{this.mqtt.publish(k.mqtt.prefix+"/status","online",{retain:!0}),this.setupBrokerSubscriptions().catch(e=>{console.error(new Error(`Unable to setup mqtt subscriptions: ${e.stack}`)),process.exit(1)})}),this.mqtt.on("message",(e,r)=>{this.handleMessage(e,r.toString()).catch(i=>{this.debug(`Unable to handle message: ${i.stack}`)})})}static async run(){return await k.load(),new t}debug(e){let r=String(e);this.mqtt.publish(k.mqtt.prefix+"/debug",r),console.log(r)}async handleMessage(e,r){if(![k.mqtt.prefix+"/debug",k.mqtt.prefix+"/status"].includes(e))if(e===k.mqtt.prefix+"/disabled"){let i=["1","true","TRUE"].includes(r);await k.updateDisabled(i),i||(this.debug("Board not disabled anymore, update with latest message"),await this.updateCurrentMessage())}else if(Object.keys(fr).map(i=>k.mqtt.prefix+"/"+i).includes(e)){let i=fr[e.substr(k.mqtt.prefix.length+1)];await this.renderMessage(i,r)}else{let i=Object.entries(fr).find(([u])=>e.startsWith(k.mqtt.prefix+"/"+u+"/"));if(!i){this.debug(`Unknown topic ${e}, I'm sorry`);return}let n=e.substr((k.mqtt.prefix+"/"+i[0]+"/").length),s=await this.pageConfig.get(i[0]),o=i[1].parseConfig(n,r,s||{}),a=Object.assign(s||{},o);await this.pageConfig.set(i[0],a),await this.updateCurrentMessage(),this.debug(`Update config for page module ${i[0]}: ${JSON.stringify(a,null," ")}`)}}async renderMessage(e,r){this.currentMessage={page:e,payload:r};let i=Object.entries(fr).find(([,a])=>a===e);if(k.board.disabled||!i)return;let n=await e.parsePayload(r),s=await this.pageConfig.get(i[0]),o=await e.render(n,s||{});o.message&&await this.sendMessage(o.message),this.currentTimer&&(clearTimeout(this.currentTimer),delete this.currentTimer),o.validTill&&(this.debug(`Set timer for ${o.validTill.toString()} to update message`),this.currentTimer=setTimeout(()=>{this.debug("Here I am again, updating the message now\u2026"),this.renderMessage(e,r).catch(a=>{this.debug(`Unable to update page: ${a}`)})},o.validTill.getTime()-new Date().getTime()))}async sendMessage(e=new pe){let r=e.export();if(!this.subscriptionIds){let i=await this.board.getSubscriptions();this.subscriptionIds=i.map(n=>n._id)}this.debug(`Sending Message:
|
|
17
17
|
|
|
18
18
|
`+e.toString()),await Promise.all(this.subscriptionIds.map(i=>this.board.postMessage(i,r)))}async setupBrokerSubscriptions(){if(!this.mqtt)throw new Error("Unable to setup subscriptions: client not set.");await this.mqtt.subscribe(k.mqtt.prefix+"/#")}async updateCurrentMessage(){this.currentMessage&&await this.renderMessage(this.currentMessage.page,this.currentMessage.payload)}};cr.run().catch(t=>{console.log(t),process.exit(1)});
|