diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile deleted file mode 100644 index 20e1b84..0000000 --- a/.devcontainer/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/ubuntu/.devcontainer/base.Dockerfile - -# [Choice] Ubuntu version (use ubuntu-22.04 or ubuntu-18.04 on local arm64/Apple Silicon): ubuntu-22.04, ubuntu-20.04, ubuntu-18.04 -ARG VARIANT="jammy" -FROM mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT} - -# [Optional] Uncomment this section to install additional OS packages. -RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ - && apt-get -y install --no-install-recommends build-essential - - diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 5ba109d..0000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: -// https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/ubuntu -{ - "name": "Ubuntu", - "build": { - "dockerfile": "Dockerfile", - // Update 'VARIANT' to pick an Ubuntu version: jammy / ubuntu-22.04, focal / ubuntu-20.04, bionic /ubuntu-18.04 - // Use ubuntu-22.04 or ubuntu-18.04 on local arm64/Apple Silicon. - "args": { "VARIANT": "ubuntu-22.04" } - }, - - // Use 'postCreateCommand' to run commands after the container is created. - // "postCreateCommand": "uname -a", - - // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. - "remoteUser": "vscode", - "forwardPorts": [8000] -} diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 378eac2..0000000 --- a/.dockerignore +++ /dev/null @@ -1 +0,0 @@ -build diff --git a/.github/workflows/build_docker.yml b/.github/workflows/build_docker.yml deleted file mode 100644 index 5827bab..0000000 --- a/.github/workflows/build_docker.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Docker - -on: - push: - branches: - - main - - pull_request: - -jobs: - - compile-ubuntu-docker: - name: Build Docker image - runs-on: ubuntu-latest - steps: - - name: Check out repository code - uses: actions/checkout@v3 - with: - submodules: recursive - - name: Get Docker - run: | - sudo apt update - sudo apt install docker - - name: Build Docker image - run: docker build -t matthx/microocppsimulator:latest . diff --git a/.github/workflows/build_ubuntu.yml b/.github/workflows/build_ubuntu.yml deleted file mode 100644 index f7fa298..0000000 --- a/.github/workflows/build_ubuntu.yml +++ /dev/null @@ -1,27 +0,0 @@ -name: Ubuntu - -on: - push: - branches: - - main - - pull_request: - -jobs: - - compile-ubuntu-native: - name: Compile for Ubuntu - runs-on: ubuntu-latest - steps: - - name: Check out repository code - uses: actions/checkout@v3 - with: - submodules: recursive - - name: Get compiler toolchain - run: | - sudo apt update - sudo apt install cmake libssl-dev build-essential - - name: Generate CMake files - run: cmake -S . -B ./build - - name: Compile - run: cmake --build ./build -j 16 --target mo_simulator diff --git a/.github/workflows/build_wasm.yml b/.github/workflows/build_wasm.yml deleted file mode 100644 index b66fa97..0000000 --- a/.github/workflows/build_wasm.yml +++ /dev/null @@ -1,27 +0,0 @@ -name: WebAssembly - -on: - push: - branches: - - main - - pull_request: - -jobs: - - compile-esmscripten: - name: Compile for WebAssembly - runs-on: ubuntu-latest - steps: - - name: Check out repository code - uses: actions/checkout@v3 - with: - submodules: recursive - - name: Set up emscripten - uses: mymindstorm/setup-emsdk@v11 - - name: Verify - run: emcc -v - - name: Generate CMake files - run: emcmake cmake -S . -B ./build - - name: Compile - run: cmake --build ./build -j 16 --target mo_simulator_wasm diff --git a/.gitignore b/.gitignore deleted file mode 100644 index cffd789..0000000 --- a/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -.vs -*.exe -*.obj -build_and_run.sh -mo_store/* -!mo_store/README.md -build diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index ceb826b..0000000 --- a/.gitmodules +++ /dev/null @@ -1,18 +0,0 @@ -[submodule "lib/ArduinoJson"] - path = lib/ArduinoJson - url = https://github.com/bblanchon/ArduinoJson.git -[submodule "lib/MicroOcpp"] - path = lib/MicroOcpp - url = https://github.com/matth-x/MicroOcpp -[submodule "lib/MicroOcppMongoose"] - path = lib/MicroOcppMongoose - url = https://github.com/matth-x/MicroOcppMongoose -[submodule "lib/mongoose"] - path = lib/mongoose - url = https://github.com/cesanta/mongoose -[submodule "webapp-src"] - path = webapp-src - url = https://github.com/agruenb/arduino-ocpp-dashboard.git -[submodule "lib/mbedtls"] - path = lib/mbedtls - url = https://github.com/Mbed-TLS/mbedtls diff --git a/196.js b/196.js new file mode 100644 index 0000000..1294bd9 --- /dev/null +++ b/196.js @@ -0,0 +1,2 @@ +/*! For license information please see 196.js.LICENSE.txt */ +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[196],{9196:(e,t,n)=>{function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}var o;n.r(t),n.d(t,{WasmApi:()=>f});const i=(o="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=n;i.ready=new Promise((function(n,r){e=n,t=r}));var a,s,u,c=Object.assign({},i),f=function(e,t){throw t},l=!1,d="";l?d=self.location.href:"undefined"!=typeof document&&document.currentScript&&(d=document.currentScript.src),o&&(d=o),d=0!==d.indexOf("blob:")?d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):"",a=function(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},l&&(u=function(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),s=function(e,t,n){var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=function(){200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)};var m,p=i.print||console.log.bind(console),h=i.printErr||console.error.bind(console);Object.assign(i,c),c=null,i.arguments&&i.arguments,i.thisProgram&&i.thisProgram,i.quit&&(f=i.quit),i.wasmBinary&&(m=i.wasmBinary);var v,w=i.noExitRuntime||!0;"object"!=("undefined"==typeof WebAssembly?"undefined":r(WebAssembly))&&O("no native wasm support detected");var g,y,E,k,b,_,L,S=!1;function F(e,t){e||O(t)}var M=[],P=[],D=[],x=[];function A(){return w||!1}var R=0,C=null,z=null;function j(e){R++,i.monitorRunDependencies&&i.monitorRunDependencies(R)}function N(e){if(R--,i.monitorRunDependencies&&i.monitorRunDependencies(R),0==R&&(null!==C&&(clearInterval(C),C=null),z)){var t=z;z=null,t()}}function O(e){i.onAbort&&i.onAbort(e),h(e="Aborted("+e+")"),S=!0,g=1,e+=". Build with -sASSERTIONS for more info.";var n=new WebAssembly.RuntimeError(e);throw t(n),n}var T,q,I,B;function U(e){return e.startsWith("data:application/octet-stream;base64,")}function X(e){if(e==T&&m)return new Uint8Array(m);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}function H(e,t,n){return function(e){return m||"function"!=typeof fetch?Promise.resolve().then((function(){return X(e)})):fetch(e,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()})).catch((function(){return X(e)}))}(e).then((function(e){return WebAssembly.instantiate(e,t)})).then((function(e){return e})).then(n,(function(e){h("failed to asynchronously prepare wasm: "+e),O(e)}))}function Y(e){this.name="ExitStatus",this.message="Program terminated with exit(".concat(e,")"),this.status=e}U(T="mo_simulator_wasm.wasm")||(q=T,T=i.locateFile?i.locateFile(q,d):d+q);var G=function(e){for(;e.length>0;)e.shift()(i)};function W(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){_[this.ptr+4>>2]=e},this.get_type=function(){return _[this.ptr+4>>2]},this.set_destructor=function(e){_[this.ptr+8>>2]=e},this.get_destructor=function(){return _[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,y[this.ptr+12>>0]=e},this.get_caught=function(){return 0!=y[this.ptr+12>>0]},this.set_rethrown=function(e){e=e?1:0,y[this.ptr+13>>0]=e},this.get_rethrown=function(){return 0!=y[this.ptr+13>>0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){_[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return _[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Te(this.get_type()))return _[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var V={isAbs:function(e){return"/"===e.charAt(0)},splitPath:function(e){return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,t){for(var n=0,r=e.length-1;r>=0;r--){var o=e[r];"."===o?e.splice(r,1):".."===o?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift("..");return e},normalize:function(e){var t=V.isAbs(e),n="/"===e.substr(-1);return(e=V.normalizeArray(e.split("/").filter((function(e){return!!e})),!t).join("/"))||t||(e="."),e&&n&&(e+="/"),(t?"/":"")+e},dirname:function(e){var t=V.splitPath(e),n=t[0],r=t[1];return n||r?(r&&(r=r.substr(0,r.length-1)),n+r):"."},basename:function(e){if("/"===e)return"/";var t=(e=(e=V.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return V.normalize(e.join("/"))},join2:function(e,t){return V.normalize(e+"/"+t)}},K=function(e){return(K=function(){if("object"==("undefined"==typeof crypto?"undefined":r(crypto))&&"function"==typeof crypto.getRandomValues)return function(e){return crypto.getRandomValues(e)};O("initRandomDevice")}())(e)},J={resolve:function(){for(var e="",t=!1,n=arguments.length-1;n>=-1&&!t;n--){var r=n>=0?arguments[n]:ce.cwd();if("string"!=typeof r)throw new TypeError("Arguments to path.resolve must be strings");if(!r)return"";e=r+"/"+e,t=V.isAbs(r)}return(t?"/":"")+(e=V.normalizeArray(e.split("/").filter((function(e){return!!e})),!t).join("/"))||"."},relative:function(e,t){function n(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=J.resolve(e).substr(1),t=J.resolve(t).substr(1);for(var r=n(e.split("/")),o=n(t.split("/")),i=Math.min(r.length,o.length),a=i,s=0;s=r);)++o;if(o-t>16&&e.buffer&&$)return $.decode(e.subarray(t,o));for(var i="";t>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|s)}else i+=String.fromCharCode(a)}return i},Z=[],ee=function(e){for(var t=0,n=0;n=55296&&r<=57343?(t+=4,++n):t+=3}return t},te=function(e,t,n,r){if(!(r>0))return 0;for(var o=n,i=n+r-1,a=0;a=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(n>=i)break;t[n++]=s}else if(s<=2047){if(n+1>=i)break;t[n++]=192|s>>6,t[n++]=128|63&s}else if(s<=65535){if(n+2>=i)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|63&s}else{if(n+3>=i)break;t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}}return t[n]=0,n-o};function ne(e,t,n){var r=n>0?n:ee(e)+1,o=new Array(r),i=te(e,o,0,o.length);return t&&(o.length=i),o}var re={ttys:[],init:function(){},shutdown:function(){},register:function(e,t){re.ttys[e]={input:[],output:[],ops:t},ce.registerDevice(e,re.stream_ops)},stream_ops:{open:function(e){var t=re.ttys[e.node.rdev];if(!t)throw new ce.ErrnoError(43);e.tty=t,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,t,n,r,o){if(!e.tty||!e.tty.ops.get_char)throw new ce.ErrnoError(60);for(var i=0,a=0;a0&&(p(Q(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,t,n){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(h(Q(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(h(Q(e.output,0)),e.output=[])}}},oe=function(e){O()},ie={ops_table:null,mount:function(e){return ie.createNode(null,"/",16895,0)},createNode:function(e,t,n,r){if(ce.isBlkdev(n)||ce.isFIFO(n))throw new ce.ErrnoError(63);ie.ops_table||(ie.ops_table={dir:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,lookup:ie.node_ops.lookup,mknod:ie.node_ops.mknod,rename:ie.node_ops.rename,unlink:ie.node_ops.unlink,rmdir:ie.node_ops.rmdir,readdir:ie.node_ops.readdir,symlink:ie.node_ops.symlink},stream:{llseek:ie.stream_ops.llseek}},file:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:{llseek:ie.stream_ops.llseek,read:ie.stream_ops.read,write:ie.stream_ops.write,allocate:ie.stream_ops.allocate,mmap:ie.stream_ops.mmap,msync:ie.stream_ops.msync}},link:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,readlink:ie.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:ce.chrdev_stream_ops}});var o=ce.createNode(e,t,n,r);return ce.isDir(o.mode)?(o.node_ops=ie.ops_table.dir.node,o.stream_ops=ie.ops_table.dir.stream,o.contents={}):ce.isFile(o.mode)?(o.node_ops=ie.ops_table.file.node,o.stream_ops=ie.ops_table.file.stream,o.usedBytes=0,o.contents=null):ce.isLink(o.mode)?(o.node_ops=ie.ops_table.link.node,o.stream_ops=ie.ops_table.link.stream):ce.isChrdev(o.mode)&&(o.node_ops=ie.ops_table.chrdev.node,o.stream_ops=ie.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,t){var n=e.contents?e.contents.length:0;if(!(n>=t)){t=Math.max(t,n*(n<1048576?2:1.125)>>>0),0!=n&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var n=e.contents;e.contents=new Uint8Array(t),n&&e.contents.set(n.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr:function(e){var t={};return t.dev=ce.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,ce.isDir(e.mode)?t.size=4096:ce.isFile(e.mode)?t.size=e.usedBytes:ce.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&ie.resizeFileStorage(e,t.size)},lookup:function(e,t){throw ce.genericErrors[44]},mknod:function(e,t,n,r){return ie.createNode(e,t,n,r)},rename:function(e,t,n){if(ce.isDir(e.mode)){var r;try{r=ce.lookupNode(t,n)}catch(e){}if(r)for(var o in r.contents)throw new ce.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=n,t.contents[n]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink:function(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir:function(e,t){var n=ce.lookupNode(e,t);for(var r in n.contents)throw new ce.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir:function(e){var t=[".",".."];for(var n in e.contents)e.contents.hasOwnProperty(n)&&t.push(n);return t},symlink:function(e,t,n){var r=ie.createNode(e,t,41471,0);return r.link=n,r},readlink:function(e){if(!ce.isLink(e.mode))throw new ce.ErrnoError(28);return e.link}},stream_ops:{read:function(e,t,n,r,o){var i=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,r);if(a>8&&i.subarray)t.set(i.subarray(o,o+a),n);else for(var s=0;s0||n+t1&&void 0!==arguments[1]?arguments[1]:{};if(!(e=J.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new ce.ErrnoError(32);for(var n=e.split("/").filter((function(e){return!!e})),r=ce.root,o="/",i=0;i40)throw new ce.ErrnoError(32)}}return{path:o,node:r}},getPath:function(e){for(var t;;){if(ce.isRoot(e)){var n=e.mount.mountpoint;return t?"/"!==n[n.length-1]?"".concat(n,"/").concat(t):n+t:n}t=t?"".concat(e.name,"/").concat(t):e.name,e=e.parent}},hashName:function(e,t){for(var n=0,r=0;r>>0)%ce.nameTable.length},hashAddNode:function(e){var t=ce.hashName(e.parent.id,e.name);e.name_next=ce.nameTable[t],ce.nameTable[t]=e},hashRemoveNode:function(e){var t=ce.hashName(e.parent.id,e.name);if(ce.nameTable[t]===e)ce.nameTable[t]=e.name_next;else for(var n=ce.nameTable[t];n;){if(n.name_next===e){n.name_next=e.name_next;break}n=n.name_next}},lookupNode:function(e,t){var n=ce.mayLookup(e);if(n)throw new ce.ErrnoError(n,e);for(var r=ce.hashName(e.id,t),o=ce.nameTable[r];o;o=o.name_next){var i=o.name;if(o.parent.id===e.id&&i===t)return o}return ce.lookup(e,t)},createNode:function(e,t,n,r){var o=new ce.FSNode(e,t,n,r);return ce.hashAddNode(o),o},destroyNode:function(e){ce.hashRemoveNode(e)},isRoot:function(e){return e===e.parent},isMountpoint:function(e){return!!e.mounted},isFile:function(e){return 32768==(61440&e)},isDir:function(e){return 16384==(61440&e)},isLink:function(e){return 40960==(61440&e)},isChrdev:function(e){return 8192==(61440&e)},isBlkdev:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return 49152==(49152&e)},flagsToPermissionString:function(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:function(e,t){return ce.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2},mayLookup:function(e){return ce.nodePermissions(e,"x")||(e.node_ops.lookup?0:2)},mayCreate:function(e,t){try{return ce.lookupNode(e,t),20}catch(e){}return ce.nodePermissions(e,"wx")},mayDelete:function(e,t,n){var r;try{r=ce.lookupNode(e,t)}catch(e){return e.errno}var o=ce.nodePermissions(e,"wx");if(o)return o;if(n){if(!ce.isDir(r.mode))return 54;if(ce.isRoot(r)||ce.getPath(r)===ce.cwd())return 10}else if(ce.isDir(r.mode))return 31;return 0},mayOpen:function(e,t){return e?ce.isLink(e.mode)?32:ce.isDir(e.mode)&&("r"!==ce.flagsToPermissionString(t)||512&t)?31:ce.nodePermissions(e,ce.flagsToPermissionString(t)):44},MAX_OPEN_FDS:4096,nextfd:function(){for(var e=0;e<=ce.MAX_OPEN_FDS;e++)if(!ce.streams[e])return e;throw new ce.ErrnoError(33)},getStreamChecked:function(e){var t=ce.getStream(e);if(!t)throw new ce.ErrnoError(8);return t},getStream:function(e){return ce.streams[e]},createStream:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return ce.FSStream||(ce.FSStream=function(){this.shared={}},ce.FSStream.prototype={},Object.defineProperties(ce.FSStream.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return 0!=(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}},flags:{get:function(){return this.shared.flags},set:function(e){this.shared.flags=e}},position:{get:function(){return this.shared.position},set:function(e){this.shared.position=e}}})),e=Object.assign(new ce.FSStream,e),-1==t&&(t=ce.nextfd()),e.fd=t,ce.streams[t]=e,e},closeStream:function(e){ce.streams[e]=null},chrdev_stream_ops:{open:function(e){var t=ce.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:function(){throw new ce.ErrnoError(70)}},major:function(e){return e>>8},minor:function(e){return 255&e},makedev:function(e,t){return e<<8|t},registerDevice:function(e,t){ce.devices[e]={stream_ops:t}},getDevice:function(e){return ce.devices[e]},getMounts:function(e){for(var t=[],n=[e];n.length;){var r=n.pop();t.push(r),n.push.apply(n,r.mounts)}return t},syncfs:function(e,t){"function"==typeof e&&(t=e,e=!1),ce.syncFSRequests++,ce.syncFSRequests>1&&h("warning: ".concat(ce.syncFSRequests," FS.syncfs operations in flight at once, probably just doing extra work"));var n=ce.getMounts(ce.root.mount),r=0;function o(e){return ce.syncFSRequests--,t(e)}function i(e){if(e)return i.errored?void 0:(i.errored=!0,o(e));++r>=n.length&&o(null)}n.forEach((function(t){if(!t.type.syncfs)return i(null);t.type.syncfs(t,e,i)}))},mount:function(e,t,n){var r,o="/"===n,i=!n;if(o&&ce.root)throw new ce.ErrnoError(10);if(!o&&!i){var a=ce.lookupPath(n,{follow_mount:!1});if(n=a.path,r=a.node,ce.isMountpoint(r))throw new ce.ErrnoError(10);if(!ce.isDir(r.mode))throw new ce.ErrnoError(54)}var s={type:e,opts:t,mountpoint:n,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?ce.root=u:r&&(r.mounted=s,r.mount&&r.mount.mounts.push(s)),u},unmount:function(e){var t=ce.lookupPath(e,{follow_mount:!1});if(!ce.isMountpoint(t.node))throw new ce.ErrnoError(28);var n=t.node,r=n.mounted,o=ce.getMounts(r);Object.keys(ce.nameTable).forEach((function(e){for(var t=ce.nameTable[e];t;){var n=t.name_next;o.includes(t.mount)&&ce.destroyNode(t),t=n}})),n.mounted=null;var i=n.mount.mounts.indexOf(r);n.mount.mounts.splice(i,1)},lookup:function(e,t){return e.node_ops.lookup(e,t)},mknod:function(e,t,n){var r=ce.lookupPath(e,{parent:!0}).node,o=V.basename(e);if(!o||"."===o||".."===o)throw new ce.ErrnoError(28);var i=ce.mayCreate(r,o);if(i)throw new ce.ErrnoError(i);if(!r.node_ops.mknod)throw new ce.ErrnoError(63);return r.node_ops.mknod(r,o,t,n)},create:function(e,t){return t=void 0!==t?t:438,t&=4095,t|=32768,ce.mknod(e,t,0)},mkdir:function(e,t){return t=void 0!==t?t:511,t&=1023,t|=16384,ce.mknod(e,t,0)},mkdirTree:function(e,t){for(var n=e.split("/"),r="",o=0;o1&&void 0!==arguments[1]?arguments[1]:{};if(n.flags=n.flags||0,n.encoding=n.encoding||"binary","utf8"!==n.encoding&&"binary"!==n.encoding)throw new Error('Invalid encoding type "'.concat(n.encoding,'"'));var r=ce.open(e,n.flags),o=ce.stat(e).size,i=new Uint8Array(o);return ce.read(r,i,0,o,0),"utf8"===n.encoding?t=Q(i,0):"binary"===n.encoding&&(t=i),ce.close(r),t},writeFile:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.flags=n.flags||577;var r=ce.open(e,n.flags,n.mode);if("string"==typeof t){var o=new Uint8Array(ee(t)+1),i=te(t,o,0,o.length);ce.write(r,o,0,i,void 0,n.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");ce.write(r,t,0,t.byteLength,void 0,n.canOwn)}ce.close(r)},cwd:function(){return ce.currentPath},chdir:function(e){var t=ce.lookupPath(e,{follow:!0});if(null===t.node)throw new ce.ErrnoError(44);if(!ce.isDir(t.node.mode))throw new ce.ErrnoError(54);var n=ce.nodePermissions(t.node,"x");if(n)throw new ce.ErrnoError(n);ce.currentPath=t.path},createDefaultDirectories:function(){ce.mkdir("/tmp"),ce.mkdir("/home"),ce.mkdir("/home/web_user")},createDefaultDevices:function(){ce.mkdir("/dev"),ce.registerDevice(ce.makedev(1,3),{read:function(){return 0},write:function(e,t,n,r,o){return r}}),ce.mkdev("/dev/null",ce.makedev(1,3)),re.register(ce.makedev(5,0),re.default_tty_ops),re.register(ce.makedev(6,0),re.default_tty1_ops),ce.mkdev("/dev/tty",ce.makedev(5,0)),ce.mkdev("/dev/tty1",ce.makedev(6,0));var e=new Uint8Array(1024),t=0,n=function(){return 0===t&&(t=K(e).byteLength),e[--t]};ce.createDevice("/dev","random",n),ce.createDevice("/dev","urandom",n),ce.mkdir("/dev/shm"),ce.mkdir("/dev/shm/tmp")},createSpecialDirectories:function(){ce.mkdir("/proc");var e=ce.mkdir("/proc/self");ce.mkdir("/proc/self/fd"),ce.mount({mount:function(){var t=ce.createNode(e,"fd",16895,73);return t.node_ops={lookup:function(e,t){var n=+t,r=ce.getStreamChecked(n),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:function(){return r.path}}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams:function(){i.stdin?ce.createDevice("/dev","stdin",i.stdin):ce.symlink("/dev/tty","/dev/stdin"),i.stdout?ce.createDevice("/dev","stdout",null,i.stdout):ce.symlink("/dev/tty","/dev/stdout"),i.stderr?ce.createDevice("/dev","stderr",null,i.stderr):ce.symlink("/dev/tty1","/dev/stderr"),ce.open("/dev/stdin",0),ce.open("/dev/stdout",1),ce.open("/dev/stderr",1)},ensureErrnoError:function(){ce.ErrnoError||(ce.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},ce.ErrnoError.prototype=new Error,ce.ErrnoError.prototype.constructor=ce.ErrnoError,[44].forEach((function(e){ce.genericErrors[e]=new ce.ErrnoError(e),ce.genericErrors[e].stack=""})))},staticInit:function(){ce.ensureErrnoError(),ce.nameTable=new Array(4096),ce.mount(ie,{},"/"),ce.createDefaultDirectories(),ce.createDefaultDevices(),ce.createSpecialDirectories(),ce.filesystems={MEMFS:ie}},init:function(e,t,n){ce.init.initialized=!0,ce.ensureErrnoError(),i.stdin=e||i.stdin,i.stdout=t||i.stdout,i.stderr=n||i.stderr,ce.createStandardStreams()},quit:function(){ce.init.initialized=!1;for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,n=e/this.chunkSize|0;return this.getter(n)[t]}},i.prototype.setDataGetter=function(e){this.getter=e},i.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",n,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+n+". Status: "+e.status);var t,r=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,i=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,a=1048576;o||(a=r);var s=this;s.setDataGetter((function(e){var t=e*a,o=(e+1)*a-1;if(o=Math.min(o,r-1),void 0===s.chunks[e]&&(s.chunks[e]=function(e,t){if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>r-1)throw new Error("only "+r+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",n,!1),r!==a&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+n+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):ne(o.responseText||"",!0)}(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!i&&r||(a=r=1,r=this.getter(0).length,a=r,p("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=r,this._chunkSize=a,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!l)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var a=new i;Object.defineProperties(a,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:a}}else s={isDevice:!1,url:n};var u=ce.createFile(e,t,s,r,o);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function f(e,t,n,r,o){var i=e.node.contents;if(o>=i.length)return 0;var a=Math.min(i.length-o,r);if(i.slice)for(var s=0;s>2]=r.dev,b[n+4>>2]=r.mode,_[n+8>>2]=r.nlink,b[n+12>>2]=r.uid,b[n+16>>2]=r.gid,b[n+20>>2]=r.rdev,B=[r.size>>>0,(I=r.size,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+24>>2]=B[0],b[n+28>>2]=B[1],b[n+32>>2]=4096,b[n+36>>2]=r.blocks;var o=r.atime.getTime(),i=r.mtime.getTime(),a=r.ctime.getTime();return B=[Math.floor(o/1e3)>>>0,(I=Math.floor(o/1e3),+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+40>>2]=B[0],b[n+44>>2]=B[1],_[n+48>>2]=o%1e3*1e3,B=[Math.floor(i/1e3)>>>0,(I=Math.floor(i/1e3),+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+56>>2]=B[0],b[n+60>>2]=B[1],_[n+64>>2]=i%1e3*1e3,B=[Math.floor(a/1e3)>>>0,(I=Math.floor(a/1e3),+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+72>>2]=B[0],b[n+76>>2]=B[1],_[n+80>>2]=a%1e3*1e3,B=[r.ino>>>0,(I=r.ino,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+88>>2]=B[0],b[n+92>>2]=B[1],0},doMsync:function(e,t,n,r,o){if(!ce.isFile(t.node.mode))throw new ce.ErrnoError(43);if(2&r)return 0;var i=E.slice(e,e+n);ce.msync(t,i,o,n,r)},varargs:void 0,get:function(){return le.varargs+=4,b[le.varargs-4>>2]},getStr:function(e){return fe(e)},getStreamFromFD:function(e){return ce.getStreamChecked(e)}},de=function(e,t,n){return te(e,E,t,n)};ue=function(){return performance.now()};var me=function(e){if(e instanceof Y||"unwind"==e)return g;f(1,e)},pe=function(e,t){var n;g=e,g=n=e,A()||(i.onExit&&i.onExit(n),S=!0),f(n,new Y(n))},he=pe,ve=function(e){if(!S)try{e(),function(){if(!A())try{he(g)}catch(e){me(e)}}()}catch(e){me(e)}},we=function(e,t){return setTimeout((function(){ve(e)}),t)},ge={mainLoop:{running:!1,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){ge.mainLoop.scheduler=null,ge.mainLoop.currentlyRunningMainloop++},resume:function(){ge.mainLoop.currentlyRunningMainloop++;var e=ge.mainLoop.timingMode,t=ge.mainLoop.timingValue,n=ge.mainLoop.func;ge.mainLoop.func=null,Ee(n,0,!1,ge.mainLoop.arg,!0),ye(e,t),ge.mainLoop.scheduler()},updateStatus:function(){if(i.setStatus){var e=i.statusMessage||"Please wait...",t=ge.mainLoop.remainingBlockers,n=ge.mainLoop.expectedBlockers;t?t=6;){var a=r>>o-6&63;o-=6,n+=t[a]}return 2==o?(n+=t[(3&r)<<4],n+="=="):4==o&&(n+=t[(15&r)<<2],n+="="),n}(e),i(u))},u.src=s,we((function(){i(u)}),1e4)}};ae.push(t);var n=i.canvas;n&&(n.requestPointerLock=n.requestPointerLock||n.mozRequestPointerLock||n.webkitRequestPointerLock||n.msRequestPointerLock||function(){},n.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},n.exitPointerLock=n.exitPointerLock.bind(document),document.addEventListener("pointerlockchange",r,!1),document.addEventListener("mozpointerlockchange",r,!1),document.addEventListener("webkitpointerlockchange",r,!1),document.addEventListener("mspointerlockchange",r,!1),i.elementPointerLock&&n.addEventListener("click",(function(e){!ge.pointerLock&&i.canvas.requestPointerLock&&(i.canvas.requestPointerLock(),e.preventDefault())}),!1))}function r(){ge.pointerLock=document.pointerLockElement===i.canvas||document.mozPointerLockElement===i.canvas||document.webkitPointerLockElement===i.canvas||document.msPointerLockElement===i.canvas}},createContext:function(e,t,n,r){if(t&&i.ctx&&e==i.canvas)return i.ctx;var o,a;if(t){var s={antialias:!1,alpha:!1,majorVersion:1};if(r)for(var u in r)s[u]=r[u];"undefined"!=typeof GL&&(a=GL.createContext(e,s))&&(o=GL.getContext(a).GLctx)}else o=e.getContext("2d");return o?(n&&(t||F("undefined"==typeof GLctx,"cannot set in module if GLctx is used, but we are a non-GL context that would replace it"),i.ctx=o,t&&GL.makeContextCurrent(a),i.useWebGL=t,ge.moduleContextCreatedCallbacks.forEach((function(e){return e()})),ge.init()),o):null},destroyContext:function(e,t,n){},fullscreenHandlersInstalled:!1,lockPointer:void 0,resizeCanvas:void 0,requestFullscreen:function(e,t){ge.lockPointer=e,ge.resizeCanvas=t,void 0===ge.lockPointer&&(ge.lockPointer=!0),void 0===ge.resizeCanvas&&(ge.resizeCanvas=!1);var n=i.canvas;function r(){ge.isFullscreen=!1;var e=n.parentNode;(document.fullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement)===e?(n.exitFullscreen=ge.exitFullscreen,ge.lockPointer&&n.requestPointerLock(),ge.isFullscreen=!0,ge.resizeCanvas?ge.setFullscreenCanvasSize():ge.updateCanvasDimensions(n)):(e.parentNode.insertBefore(n,e),e.parentNode.removeChild(e),ge.resizeCanvas?ge.setWindowedCanvasSize():ge.updateCanvasDimensions(n)),i.onFullScreen&&i.onFullScreen(ge.isFullscreen),i.onFullscreen&&i.onFullscreen(ge.isFullscreen)}ge.fullscreenHandlersInstalled||(ge.fullscreenHandlersInstalled=!0,document.addEventListener("fullscreenchange",r,!1),document.addEventListener("mozfullscreenchange",r,!1),document.addEventListener("webkitfullscreenchange",r,!1),document.addEventListener("MSFullscreenChange",r,!1));var o=document.createElement("div");n.parentNode.insertBefore(o,n),o.appendChild(n),o.requestFullscreen=o.requestFullscreen||o.mozRequestFullScreen||o.msRequestFullscreen||(o.webkitRequestFullscreen?function(){return o.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)}:null)||(o.webkitRequestFullScreen?function(){return o.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),o.requestFullscreen()},exitFullscreen:function(){return!!ge.isFullscreen&&((document.exitFullscreen||document.cancelFullScreen||document.mozCancelFullScreen||document.msExitFullscreen||document.webkitCancelFullScreen||function(){}).apply(document,[]),!0)},nextRAF:0,fakeRequestAnimationFrame:function(e){var t=Date.now();if(0===ge.nextRAF)ge.nextRAF=t+1e3/60;else for(;t+2>=ge.nextRAF;)ge.nextRAF+=1e3/60;var n=Math.max(ge.nextRAF-t,0);setTimeout(e,n)},requestAnimationFrame:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){"function"!=typeof requestAnimationFrame?(0,ge.fakeRequestAnimationFrame)(e):requestAnimationFrame(e)})),safeSetTimeout:function(e,t){return we(e,t)},safeRequestAnimationFrame:function(e){return ge.requestAnimationFrame((function(){ve(e)}))},getMimetype:function(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[e.substr(e.lastIndexOf(".")+1)]},getUserMedia:function(e){window.getUserMedia||(window.getUserMedia=navigator.getUserMedia||navigator.mozGetUserMedia),window.getUserMedia(e)},getMovementX:function(e){return e.movementX||e.mozMovementX||e.webkitMovementX||0},getMovementY:function(e){return e.movementY||e.mozMovementY||e.webkitMovementY||0},getMouseWheelDelta:function(e){var t=0;switch(e.type){case"DOMMouseScroll":t=e.detail/3;break;case"mousewheel":t=e.wheelDelta/120;break;case"wheel":switch(t=e.deltaY,e.deltaMode){case 0:t/=100;break;case 1:t/=3;break;case 2:t*=80;break;default:throw"unrecognized mouse wheel delta mode: "+e.deltaMode}break;default:throw"unrecognized mouse wheel event: "+e.type}return t},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(e){if(ge.pointerLock)"mousemove"!=e.type&&"mozMovementX"in e?ge.mouseMovementX=ge.mouseMovementY=0:(ge.mouseMovementX=ge.getMovementX(e),ge.mouseMovementY=ge.getMovementY(e)),"undefined"!=typeof SDL?(ge.mouseX=SDL.mouseX+ge.mouseMovementX,ge.mouseY=SDL.mouseY+ge.mouseMovementY):(ge.mouseX+=ge.mouseMovementX,ge.mouseY+=ge.mouseMovementY);else{var t=i.canvas.getBoundingClientRect(),n=i.canvas.width,r=i.canvas.height,o=void 0!==window.scrollX?window.scrollX:window.pageXOffset,a=void 0!==window.scrollY?window.scrollY:window.pageYOffset;if("touchstart"===e.type||"touchend"===e.type||"touchmove"===e.type){var s=e.touch;if(void 0===s)return;var u=s.pageX-(o+t.left),c=s.pageY-(a+t.top),f={x:u*=n/t.width,y:c*=r/t.height};if("touchstart"===e.type)ge.lastTouches[s.identifier]=f,ge.touches[s.identifier]=f;else if("touchend"===e.type||"touchmove"===e.type){var l=ge.touches[s.identifier];l||(l=f),ge.lastTouches[s.identifier]=l,ge.touches[s.identifier]=f}return}var d=e.pageX-(o+t.left),m=e.pageY-(a+t.top);d*=n/t.width,m*=r/t.height,ge.mouseMovementX=d-ge.mouseX,ge.mouseMovementY=m-ge.mouseY,ge.mouseX=d,ge.mouseY=m}},resizeListeners:[],updateResizeListeners:function(){var e=i.canvas;ge.resizeListeners.forEach((function(t){return t(e.width,e.height)}))},setCanvasSize:function(e,t,n){var r=i.canvas;ge.updateCanvasDimensions(r,e,t),n||ge.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if("undefined"!=typeof SDL){var e=_[SDL.screen>>2];e|=8388608,b[SDL.screen>>2]=e}ge.updateCanvasDimensions(i.canvas),ge.updateResizeListeners()},setWindowedCanvasSize:function(){if("undefined"!=typeof SDL){var e=_[SDL.screen>>2];e&=-8388609,b[SDL.screen>>2]=e}ge.updateCanvasDimensions(i.canvas),ge.updateResizeListeners()},updateCanvasDimensions:function(e,t,n){t&&n?(e.widthNative=t,e.heightNative=n):(t=e.widthNative,n=e.heightNative);var r=t,o=n;if(i.forcedAspectRatio&&i.forcedAspectRatio>0&&(r/o0){var t=Date.now(),n=ge.mainLoop.queue.shift();if(n.func(n.arg),ge.mainLoop.remainingBlockers){var o=ge.mainLoop.remainingBlockers,i=o%1==0?o-1:Math.floor(o);n.counted?ge.mainLoop.remainingBlockers=i:(i+=.5,ge.mainLoop.remainingBlockers=(8*o+i)/9)}if(p('main loop blocker "'+n.name+'" took '+(Date.now()-t)+" ms"),ge.mainLoop.updateStatus(),!s())return;setTimeout(ge.mainLoop.runner,0)}else s()&&(ge.mainLoop.currentFrameNumber=ge.mainLoop.currentFrameNumber+1|0,1==ge.mainLoop.timingMode&&ge.mainLoop.timingValue>1&&ge.mainLoop.currentFrameNumber%ge.mainLoop.timingValue!=0?ge.mainLoop.scheduler():(0==ge.mainLoop.timingMode&&(ge.mainLoop.tickStartTime=ue()),ge.mainLoop.runIter(e),s()&&("object"==("undefined"==typeof SDL?"undefined":r(SDL))&&SDL.audio&&SDL.audio.queueNewAudioData&&SDL.audio.queueNewAudioData(),ge.mainLoop.scheduler())))},i||(t&&t>0?ye(0,1e3/t):ye(1,1),ge.mainLoop.scheduler()),n)throw"unwind"}var ke=[],be=function(e){var t=ke[e];return t||(e>=ke.length&&(ke.length=e+1),ke[e]=t=L.get(e)),t},_e={sockets:[null],socketEvent:null};function Le(e){return i["_"+e]}var Se=function(e,t,n,r,o){var i={string:function(e){var t=0;return null!=e&&0!==e&&(t=function(e){var t=ee(e)+1,n=Oe(t);return de(e,n,t),n}(e)),t},array:function(e){var t,n,r=Oe(e.length);return t=e,n=r,y.set(t,n),r}},a=Le(e),s=[],u=0;if(r)for(var c=0;c>1]=2,0;case 16:case 8:default:return-28;case 9:return 28,b[ze()>>2]=28,-1}}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},u:function(e,t,n){try{var r=le.getStreamFromFD(e);r.getdents||(r.getdents=ce.readdir(r.path));for(var o=280,i=0,a=ce.llseek(r,0,1),s=Math.floor(a/o);s>>0,(I=u,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[t+i>>2]=B[0],b[t+i+4>>2]=B[1],B=[(s+1)*o>>>0,(I=(s+1)*o,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[t+i+8>>2]=B[0],b[t+i+12>>2]=B[1],k[t+i+16>>1]=280,y[t+i+18>>0]=c,de(f,t+i+19,256),i+=o,s+=1}return ce.llseek(r,s*o,0),i}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},x:function(e,t,n){le.varargs=n;try{var r=le.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return r.tty?0:-59;case 21505:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcgets){var o=r.tty.ops.ioctl_tcgets(r),i=le.get();b[i>>2]=o.c_iflag||0,b[i+4>>2]=o.c_oflag||0,b[i+8>>2]=o.c_cflag||0,b[i+12>>2]=o.c_lflag||0;for(var a=0;a<32;a++)y[i+a+17>>0]=o.c_cc[a]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcsets){i=le.get();var s=b[i>>2],u=b[i+4>>2],c=b[i+8>>2],f=b[i+12>>2],l=[];for(a=0;a<32;a++)l.push(y[i+a+17>>0]);return r.tty.ops.ioctl_tcsets(r.tty,t,{c_iflag:s,c_oflag:u,c_cflag:c,c_lflag:f,c_cc:l})}return 0;case 21519:return r.tty?(i=le.get(),b[i>>2]=0,0):-59;case 21520:return r.tty?-28:-59;case 21531:return i=le.get(),ce.ioctl(r,t,i);case 21523:if(!r.tty)return-59;if(r.tty.ops.ioctl_tiocgwinsz){var d=r.tty.ops.ioctl_tiocgwinsz(r.tty);i=le.get(),k[i>>1]=d[0],k[i+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},f:function(e,t,n,r){le.varargs=r;try{t=le.getStr(t),t=le.calculateAt(e,t);var o=r?le.get():0;return ce.open(t,n,o).fd}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},r:function(e){try{return e=le.getStr(e),ce.rmdir(e),0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},q:function(e,t){try{return e=le.getStr(e),le.doStat(ce.stat,e,t)}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},s:function(e,t,n){try{return t=le.getStr(t),t=le.calculateAt(e,t),0===n?ce.unlink(t):512===n?ce.rmdir(t):O("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},o:function(){return!0},c:function(){O("")},v:ue,y:function(e,t,n){return E.copyWithin(e,t,t+n)},p:function(e){E.length,O("OOM")},t:function(e,t,n){Ee(be(e),t,n)},z:function(e,t,n){var r=_e.sockets[e];return r?(n&&fe(n),n?r.close(t||void 0,fe(n)):t?r.close(t):r.close(),0):-3},h:function(e){var t=_e.sockets[e];return t?(t.onopen=t.onerror=t.onclose=t.onmessage=null,delete _e.sockets[e],0):-3},m:function(e){if("undefined"==typeof WebSocket)return-1;if(!e)return-5;var t=e>>2,n=fe(b[t]),r=b[t+1],o=r?new WebSocket(n,fe(r).split(",")):new WebSocket(n);o.binaryType="arraybuffer";var i=_e.sockets.length;return _e.sockets[i]=o,i},g:function(e,t){var n=_e.sockets[e];if(!n)return-3;var r=fe(t);return n.send(r),0},i:function(e,t,n,r){_e.socketEvent||(_e.socketEvent=Re(1024));var o=_e.sockets[e];return o?(o.onclose=function(r){_[_e.socketEvent>>2]=e,_[_e.socketEvent+4>>2]=r.wasClean,_[_e.socketEvent+8>>2]=r.code,de(r.reason,_e.socketEvent+10,512),be(n)(0,_e.socketEvent,t)},0):-3},j:function(e,t,n,r){_e.socketEvent||(_e.socketEvent=Re(1024));var o=_e.sockets[e];return o?(o.onerror=function(r){_[_e.socketEvent>>2]=e,be(n)(0,_e.socketEvent,t)},0):-3},k:function(e,t,n,r){_e.socketEvent||(_e.socketEvent=Re(1024));var o=_e.sockets[e];return o?(o.onmessage=function(r){if(_[_e.socketEvent>>2]=e,"string"==typeof r.data){var o=(a=r.data,s=ee(a)+1,(u=Re(s))&&de(a,u,s),u),i=ee(r.data)+1;_[_e.socketEvent+12>>2]=1}else i=r.data.byteLength,o=Re(i),y.set(new Uint8Array(r.data),o),_[_e.socketEvent+12>>2]=0;var a,s,u;_[_e.socketEvent+4>>2]=o,_[_e.socketEvent+8>>2]=i,be(n)(0,_e.socketEvent,t),Ce(o)},0):-3},l:function(e,t,n,r){_e.socketEvent||(_e.socketEvent=Re(1024));var o=_e.sockets[e];return o?(o.onopen=function(r){_[_e.socketEvent>>2]=e,be(n)(0,_e.socketEvent,t)},0):-3},A:he,a:function(e){try{var t=le.getStreamFromFD(e);return ce.close(t),0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return e.errno}},w:function(e,t,n,r){try{var o=function(e,t,n,r){for(var o=0,i=0;i>2],s=_[t+4>>2];t+=8;var u=ce.read(e,y,a,s,r);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return e.errno}},n:function(e,t,n,r,o){var i,a,s=(a=n)+2097152>>>0<4194305-!!(i=t)?(i>>>0)+4294967296*a:NaN;try{if(isNaN(s))return 61;var u=le.getStreamFromFD(e);return ce.llseek(u,s,r),B=[u.position>>>0,(I=u.position,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[o>>2]=B[0],b[o+4>>2]=B[1],u.getdents&&0===s&&0===r&&(u.getdents=null),0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return e.errno}},d:function(e,t,n,r){try{var o=function(e,t,n,r){for(var o=0,i=0;i>2],s=_[t+4>>2];t+=8;var u=ce.write(e,y,a,s,r);if(u<0)return-1;o+=u,void 0!==r&&(r+=u)}return o}(le.getStreamFromFD(e),t,n);return _[r>>2]=o,0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return e.errno}}},Ae=(function(){var e,n,r,o,a={a:xe};function s(e,t){var n,r,o=e.exports;return n=(v=o).B.buffer,i.HEAP8=y=new Int8Array(n),i.HEAP16=k=new Int16Array(n),i.HEAP32=b=new Int32Array(n),i.HEAPU8=E=new Uint8Array(n),i.HEAPU16=new Uint16Array(n),i.HEAPU32=_=new Uint32Array(n),i.HEAPF32=new Float32Array(n),i.HEAPF64=new Float64Array(n),L=v.D,r=v.C,P.unshift(r),N(),o}if(j(),i.instantiateWasm)try{return i.instantiateWasm(a,s)}catch(e){h("Module.instantiateWasm callback failed with error: "+e),t(e)}(e=m,n=T,r=a,o=function(e){s(e.instance)},e||"function"!=typeof WebAssembly.instantiateStreaming||U(n)||"function"!=typeof fetch?H(n,r,o):fetch(n,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,r).then(o,(function(e){return h("wasm streaming compile failed: "+e),h("falling back to ArrayBuffer instantiation"),H(n,r,o)}))}))).catch(t)}(),i._main=function(e,t){return(Ae=i._main=v.E)(e,t)}),Re=(i._mocpp_wasm_api_call=function(e,t,n){return(i._mocpp_wasm_api_call=v.F)(e,t,n)},function(e){return(Re=v.G)(e)}),Ce=function(e){return(Ce=v.H)(e)},ze=function(){return(ze=v.I)()},je=function(){return(je=v.J)()},Ne=function(e){return(Ne=v.K)(e)},Oe=function(e){return(Oe=v.L)(e)},Te=function(e){return(Te=v.M)(e)};function qe(){function t(){Me||(Me=!0,i.calledRun=!0,S||(i.noFSInit||ce.init.initialized||ce.init(),ce.ignorePermissions=!1,re.init(),G(P),G(D),e(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),Ie&&function(){var e=Ae;try{var t=e(0,0);return pe(t),t}catch(e){return me(e)}}(),function(){if(i.postRun)for("function"==typeof i.postRun&&(i.postRun=[i.postRun]);i.postRun.length;)e=i.postRun.shift(),x.unshift(e);var e;G(x)}()))}R>0||(function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)e=i.preRun.shift(),M.unshift(e);var e;G(M)}(),R>0||(i.setStatus?(i.setStatus("Running..."),setTimeout((function(){setTimeout((function(){i.setStatus("")}),1),t()}),1)):t()))}if(i.ccall=Se,i.cwrap=function(e,t,n,r){var o=!n||n.every((function(e){return"number"===e||"boolean"===e}));return"string"!==t&&o&&!r?Le(e):function(){return Se(e,t,n,arguments)}},z=function e(){Me||qe(),Me||(z=e)},i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();var Ie=!0;return i.noInitialRun&&(Ie=!1),qe(),n.ready});function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(){s=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(e,t,n){e[t]=n.value},i="function"==typeof Symbol?Symbol:{},u=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",f=i.toStringTag||"@@toStringTag";function l(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{l({},"")}catch(e){l=function(e,t,n){return e[t]=n}}function d(e,t,n,r){var i=t&&t.prototype instanceof y?t:y,a=Object.create(i.prototype),s=new R(r||[]);return o(a,"_invoke",{value:P(e,n,s)}),a}function m(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}t.wrap=d;var p="suspendedStart",h="suspendedYield",v="executing",w="completed",g={};function y(){}function E(){}function k(){}var b={};l(b,u,(function(){return this}));var _=Object.getPrototypeOf,L=_&&_(_(C([])));L&&L!==n&&r.call(L,u)&&(b=L);var S=k.prototype=y.prototype=Object.create(b);function F(e){["next","throw","return"].forEach((function(t){l(e,t,(function(e){return this._invoke(t,e)}))}))}function M(e,t){function n(o,i,s,u){var c=m(e[o],e,i);if("throw"!==c.type){var f=c.arg,l=f.value;return l&&"object"==a(l)&&r.call(l,"__await")?t.resolve(l.__await).then((function(e){n("next",e,s,u)}),(function(e){n("throw",e,s,u)})):t.resolve(l).then((function(e){f.value=e,s(f)}),(function(e){return n("throw",e,s,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(e,r){function o(){return new t((function(t,o){n(e,r,t,o)}))}return i=i?i.then(o,o):o()}})}function P(t,n,r){var o=p;return function(i,a){if(o===v)throw new Error("Generator is already running");if(o===w){if("throw"===i)throw a;return{value:e,done:!0}}for(r.method=i,r.arg=a;;){var s=r.delegate;if(s){var u=D(s,r);if(u){if(u===g)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=w,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=v;var c=m(t,n,r);if("normal"===c.type){if(o=r.done?w:h,c.arg===g)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(o=w,r.method="throw",r.arg=c.arg)}}}function D(t,n){var r=n.method,o=t.iterator[r];if(o===e)return n.delegate=null,"throw"===r&&t.iterator.return&&(n.method="return",n.arg=e,D(t,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=m(o,t.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[t.resultName]=a.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function x(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function A(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(x,this),this.reset(!0)}function C(t){if(t||""===t){var n=t[u];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function n(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=r.call(a,"catchLoc"),c=r.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),A(n),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;A(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:C(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),g}},t}function u(e,t,n,r,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void n(e)}s.done?t(u):Promise.resolve(u).then(r,o)}function c(e,t){for(var n=0;n{function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}var o;n.r(t),n.d(t,{WasmApi:()=>f});const i=(o="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=n;i.ready=new Promise((function(n,r){e=n,t=r}));var a,s,u,c=Object.assign({},i),f=function(e,t){throw t},l=!1,d="";l?d=self.location.href:"undefined"!=typeof document&&document.currentScript&&(d=document.currentScript.src),o&&(d=o),d=0!==d.indexOf("blob:")?d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):"",a=function(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},l&&(u=function(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),s=function(e,t,n){var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=function(){200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)};var m,p=i.print||console.log.bind(console),h=i.printErr||console.error.bind(console);Object.assign(i,c),c=null,i.arguments&&i.arguments,i.thisProgram&&i.thisProgram,i.quit&&(f=i.quit),i.wasmBinary&&(m=i.wasmBinary);var v,w=i.noExitRuntime||!0;"object"!=("undefined"==typeof WebAssembly?"undefined":r(WebAssembly))&&O("no native wasm support detected");var g,y,E,k,b,_,L,S=!1;function F(e,t){e||O(t)}var M=[],P=[],D=[],x=[];function A(){return w||!1}var R=0,C=null,z=null;function j(e){R++,i.monitorRunDependencies&&i.monitorRunDependencies(R)}function N(e){if(R--,i.monitorRunDependencies&&i.monitorRunDependencies(R),0==R&&(null!==C&&(clearInterval(C),C=null),z)){var t=z;z=null,t()}}function O(e){i.onAbort&&i.onAbort(e),h(e="Aborted("+e+")"),S=!0,g=1,e+=". Build with -sASSERTIONS for more info.";var n=new WebAssembly.RuntimeError(e);throw t(n),n}var T,q,I,B;function U(e){return e.startsWith("data:application/octet-stream;base64,")}function X(e){if(e==T&&m)return new Uint8Array(m);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}function H(e,t,n){return function(e){return m||"function"!=typeof fetch?Promise.resolve().then((function(){return X(e)})):fetch(e,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()})).catch((function(){return X(e)}))}(e).then((function(e){return WebAssembly.instantiate(e,t)})).then((function(e){return e})).then(n,(function(e){h("failed to asynchronously prepare wasm: "+e),O(e)}))}function Y(e){this.name="ExitStatus",this.message="Program terminated with exit(".concat(e,")"),this.status=e}U(T="mo_simulator_for_wasm.wasm")||(q=T,T=i.locateFile?i.locateFile(q,d):d+q);var G=function(e){for(;e.length>0;)e.shift()(i)};function W(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){_[this.ptr+4>>2]=e},this.get_type=function(){return _[this.ptr+4>>2]},this.set_destructor=function(e){_[this.ptr+8>>2]=e},this.get_destructor=function(){return _[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,y[this.ptr+12>>0]=e},this.get_caught=function(){return 0!=y[this.ptr+12>>0]},this.set_rethrown=function(e){e=e?1:0,y[this.ptr+13>>0]=e},this.get_rethrown=function(){return 0!=y[this.ptr+13>>0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){_[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return _[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Te(this.get_type()))return _[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var V={isAbs:function(e){return"/"===e.charAt(0)},splitPath:function(e){return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,t){for(var n=0,r=e.length-1;r>=0;r--){var o=e[r];"."===o?e.splice(r,1):".."===o?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift("..");return e},normalize:function(e){var t=V.isAbs(e),n="/"===e.substr(-1);return(e=V.normalizeArray(e.split("/").filter((function(e){return!!e})),!t).join("/"))||t||(e="."),e&&n&&(e+="/"),(t?"/":"")+e},dirname:function(e){var t=V.splitPath(e),n=t[0],r=t[1];return n||r?(r&&(r=r.substr(0,r.length-1)),n+r):"."},basename:function(e){if("/"===e)return"/";var t=(e=(e=V.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return V.normalize(e.join("/"))},join2:function(e,t){return V.normalize(e+"/"+t)}},K=function(e){return(K=function(){if("object"==("undefined"==typeof crypto?"undefined":r(crypto))&&"function"==typeof crypto.getRandomValues)return function(e){return crypto.getRandomValues(e)};O("initRandomDevice")}())(e)},J={resolve:function(){for(var e="",t=!1,n=arguments.length-1;n>=-1&&!t;n--){var r=n>=0?arguments[n]:ce.cwd();if("string"!=typeof r)throw new TypeError("Arguments to path.resolve must be strings");if(!r)return"";e=r+"/"+e,t=V.isAbs(r)}return(t?"/":"")+(e=V.normalizeArray(e.split("/").filter((function(e){return!!e})),!t).join("/"))||"."},relative:function(e,t){function n(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=J.resolve(e).substr(1),t=J.resolve(t).substr(1);for(var r=n(e.split("/")),o=n(t.split("/")),i=Math.min(r.length,o.length),a=i,s=0;s=r);)++o;if(o-t>16&&e.buffer&&$)return $.decode(e.subarray(t,o));for(var i="";t>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|s)}else i+=String.fromCharCode(a)}return i},Z=[],ee=function(e){for(var t=0,n=0;n=55296&&r<=57343?(t+=4,++n):t+=3}return t},te=function(e,t,n,r){if(!(r>0))return 0;for(var o=n,i=n+r-1,a=0;a=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(n>=i)break;t[n++]=s}else if(s<=2047){if(n+1>=i)break;t[n++]=192|s>>6,t[n++]=128|63&s}else if(s<=65535){if(n+2>=i)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|63&s}else{if(n+3>=i)break;t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}}return t[n]=0,n-o};function ne(e,t,n){var r=n>0?n:ee(e)+1,o=new Array(r),i=te(e,o,0,o.length);return t&&(o.length=i),o}var re={ttys:[],init:function(){},shutdown:function(){},register:function(e,t){re.ttys[e]={input:[],output:[],ops:t},ce.registerDevice(e,re.stream_ops)},stream_ops:{open:function(e){var t=re.ttys[e.node.rdev];if(!t)throw new ce.ErrnoError(43);e.tty=t,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,t,n,r,o){if(!e.tty||!e.tty.ops.get_char)throw new ce.ErrnoError(60);for(var i=0,a=0;a0&&(p(Q(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,t,n){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(h(Q(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(h(Q(e.output,0)),e.output=[])}}},oe=function(e){O()},ie={ops_table:null,mount:function(e){return ie.createNode(null,"/",16895,0)},createNode:function(e,t,n,r){if(ce.isBlkdev(n)||ce.isFIFO(n))throw new ce.ErrnoError(63);ie.ops_table||(ie.ops_table={dir:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,lookup:ie.node_ops.lookup,mknod:ie.node_ops.mknod,rename:ie.node_ops.rename,unlink:ie.node_ops.unlink,rmdir:ie.node_ops.rmdir,readdir:ie.node_ops.readdir,symlink:ie.node_ops.symlink},stream:{llseek:ie.stream_ops.llseek}},file:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:{llseek:ie.stream_ops.llseek,read:ie.stream_ops.read,write:ie.stream_ops.write,allocate:ie.stream_ops.allocate,mmap:ie.stream_ops.mmap,msync:ie.stream_ops.msync}},link:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,readlink:ie.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:ce.chrdev_stream_ops}});var o=ce.createNode(e,t,n,r);return ce.isDir(o.mode)?(o.node_ops=ie.ops_table.dir.node,o.stream_ops=ie.ops_table.dir.stream,o.contents={}):ce.isFile(o.mode)?(o.node_ops=ie.ops_table.file.node,o.stream_ops=ie.ops_table.file.stream,o.usedBytes=0,o.contents=null):ce.isLink(o.mode)?(o.node_ops=ie.ops_table.link.node,o.stream_ops=ie.ops_table.link.stream):ce.isChrdev(o.mode)&&(o.node_ops=ie.ops_table.chrdev.node,o.stream_ops=ie.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,t){var n=e.contents?e.contents.length:0;if(!(n>=t)){t=Math.max(t,n*(n<1048576?2:1.125)>>>0),0!=n&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var n=e.contents;e.contents=new Uint8Array(t),n&&e.contents.set(n.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr:function(e){var t={};return t.dev=ce.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,ce.isDir(e.mode)?t.size=4096:ce.isFile(e.mode)?t.size=e.usedBytes:ce.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&ie.resizeFileStorage(e,t.size)},lookup:function(e,t){throw ce.genericErrors[44]},mknod:function(e,t,n,r){return ie.createNode(e,t,n,r)},rename:function(e,t,n){if(ce.isDir(e.mode)){var r;try{r=ce.lookupNode(t,n)}catch(e){}if(r)for(var o in r.contents)throw new ce.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=n,t.contents[n]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink:function(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir:function(e,t){var n=ce.lookupNode(e,t);for(var r in n.contents)throw new ce.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir:function(e){var t=[".",".."];for(var n in e.contents)e.contents.hasOwnProperty(n)&&t.push(n);return t},symlink:function(e,t,n){var r=ie.createNode(e,t,41471,0);return r.link=n,r},readlink:function(e){if(!ce.isLink(e.mode))throw new ce.ErrnoError(28);return e.link}},stream_ops:{read:function(e,t,n,r,o){var i=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,r);if(a>8&&i.subarray)t.set(i.subarray(o,o+a),n);else for(var s=0;s0||n+t1&&void 0!==arguments[1]?arguments[1]:{};if(!(e=J.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new ce.ErrnoError(32);for(var n=e.split("/").filter((function(e){return!!e})),r=ce.root,o="/",i=0;i40)throw new ce.ErrnoError(32)}}return{path:o,node:r}},getPath:function(e){for(var t;;){if(ce.isRoot(e)){var n=e.mount.mountpoint;return t?"/"!==n[n.length-1]?"".concat(n,"/").concat(t):n+t:n}t=t?"".concat(e.name,"/").concat(t):e.name,e=e.parent}},hashName:function(e,t){for(var n=0,r=0;r>>0)%ce.nameTable.length},hashAddNode:function(e){var t=ce.hashName(e.parent.id,e.name);e.name_next=ce.nameTable[t],ce.nameTable[t]=e},hashRemoveNode:function(e){var t=ce.hashName(e.parent.id,e.name);if(ce.nameTable[t]===e)ce.nameTable[t]=e.name_next;else for(var n=ce.nameTable[t];n;){if(n.name_next===e){n.name_next=e.name_next;break}n=n.name_next}},lookupNode:function(e,t){var n=ce.mayLookup(e);if(n)throw new ce.ErrnoError(n,e);for(var r=ce.hashName(e.id,t),o=ce.nameTable[r];o;o=o.name_next){var i=o.name;if(o.parent.id===e.id&&i===t)return o}return ce.lookup(e,t)},createNode:function(e,t,n,r){var o=new ce.FSNode(e,t,n,r);return ce.hashAddNode(o),o},destroyNode:function(e){ce.hashRemoveNode(e)},isRoot:function(e){return e===e.parent},isMountpoint:function(e){return!!e.mounted},isFile:function(e){return 32768==(61440&e)},isDir:function(e){return 16384==(61440&e)},isLink:function(e){return 40960==(61440&e)},isChrdev:function(e){return 8192==(61440&e)},isBlkdev:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return 49152==(49152&e)},flagsToPermissionString:function(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:function(e,t){return ce.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2},mayLookup:function(e){return ce.nodePermissions(e,"x")||(e.node_ops.lookup?0:2)},mayCreate:function(e,t){try{return ce.lookupNode(e,t),20}catch(e){}return ce.nodePermissions(e,"wx")},mayDelete:function(e,t,n){var r;try{r=ce.lookupNode(e,t)}catch(e){return e.errno}var o=ce.nodePermissions(e,"wx");if(o)return o;if(n){if(!ce.isDir(r.mode))return 54;if(ce.isRoot(r)||ce.getPath(r)===ce.cwd())return 10}else if(ce.isDir(r.mode))return 31;return 0},mayOpen:function(e,t){return e?ce.isLink(e.mode)?32:ce.isDir(e.mode)&&("r"!==ce.flagsToPermissionString(t)||512&t)?31:ce.nodePermissions(e,ce.flagsToPermissionString(t)):44},MAX_OPEN_FDS:4096,nextfd:function(){for(var e=0;e<=ce.MAX_OPEN_FDS;e++)if(!ce.streams[e])return e;throw new ce.ErrnoError(33)},getStreamChecked:function(e){var t=ce.getStream(e);if(!t)throw new ce.ErrnoError(8);return t},getStream:function(e){return ce.streams[e]},createStream:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return ce.FSStream||(ce.FSStream=function(){this.shared={}},ce.FSStream.prototype={},Object.defineProperties(ce.FSStream.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return 0!=(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}},flags:{get:function(){return this.shared.flags},set:function(e){this.shared.flags=e}},position:{get:function(){return this.shared.position},set:function(e){this.shared.position=e}}})),e=Object.assign(new ce.FSStream,e),-1==t&&(t=ce.nextfd()),e.fd=t,ce.streams[t]=e,e},closeStream:function(e){ce.streams[e]=null},chrdev_stream_ops:{open:function(e){var t=ce.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:function(){throw new ce.ErrnoError(70)}},major:function(e){return e>>8},minor:function(e){return 255&e},makedev:function(e,t){return e<<8|t},registerDevice:function(e,t){ce.devices[e]={stream_ops:t}},getDevice:function(e){return ce.devices[e]},getMounts:function(e){for(var t=[],n=[e];n.length;){var r=n.pop();t.push(r),n.push.apply(n,r.mounts)}return t},syncfs:function(e,t){"function"==typeof e&&(t=e,e=!1),ce.syncFSRequests++,ce.syncFSRequests>1&&h("warning: ".concat(ce.syncFSRequests," FS.syncfs operations in flight at once, probably just doing extra work"));var n=ce.getMounts(ce.root.mount),r=0;function o(e){return ce.syncFSRequests--,t(e)}function i(e){if(e)return i.errored?void 0:(i.errored=!0,o(e));++r>=n.length&&o(null)}n.forEach((function(t){if(!t.type.syncfs)return i(null);t.type.syncfs(t,e,i)}))},mount:function(e,t,n){var r,o="/"===n,i=!n;if(o&&ce.root)throw new ce.ErrnoError(10);if(!o&&!i){var a=ce.lookupPath(n,{follow_mount:!1});if(n=a.path,r=a.node,ce.isMountpoint(r))throw new ce.ErrnoError(10);if(!ce.isDir(r.mode))throw new ce.ErrnoError(54)}var s={type:e,opts:t,mountpoint:n,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?ce.root=u:r&&(r.mounted=s,r.mount&&r.mount.mounts.push(s)),u},unmount:function(e){var t=ce.lookupPath(e,{follow_mount:!1});if(!ce.isMountpoint(t.node))throw new ce.ErrnoError(28);var n=t.node,r=n.mounted,o=ce.getMounts(r);Object.keys(ce.nameTable).forEach((function(e){for(var t=ce.nameTable[e];t;){var n=t.name_next;o.includes(t.mount)&&ce.destroyNode(t),t=n}})),n.mounted=null;var i=n.mount.mounts.indexOf(r);n.mount.mounts.splice(i,1)},lookup:function(e,t){return e.node_ops.lookup(e,t)},mknod:function(e,t,n){var r=ce.lookupPath(e,{parent:!0}).node,o=V.basename(e);if(!o||"."===o||".."===o)throw new ce.ErrnoError(28);var i=ce.mayCreate(r,o);if(i)throw new ce.ErrnoError(i);if(!r.node_ops.mknod)throw new ce.ErrnoError(63);return r.node_ops.mknod(r,o,t,n)},create:function(e,t){return t=void 0!==t?t:438,t&=4095,t|=32768,ce.mknod(e,t,0)},mkdir:function(e,t){return t=void 0!==t?t:511,t&=1023,t|=16384,ce.mknod(e,t,0)},mkdirTree:function(e,t){for(var n=e.split("/"),r="",o=0;o1&&void 0!==arguments[1]?arguments[1]:{};if(n.flags=n.flags||0,n.encoding=n.encoding||"binary","utf8"!==n.encoding&&"binary"!==n.encoding)throw new Error('Invalid encoding type "'.concat(n.encoding,'"'));var r=ce.open(e,n.flags),o=ce.stat(e).size,i=new Uint8Array(o);return ce.read(r,i,0,o,0),"utf8"===n.encoding?t=Q(i,0):"binary"===n.encoding&&(t=i),ce.close(r),t},writeFile:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.flags=n.flags||577;var r=ce.open(e,n.flags,n.mode);if("string"==typeof t){var o=new Uint8Array(ee(t)+1),i=te(t,o,0,o.length);ce.write(r,o,0,i,void 0,n.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");ce.write(r,t,0,t.byteLength,void 0,n.canOwn)}ce.close(r)},cwd:function(){return ce.currentPath},chdir:function(e){var t=ce.lookupPath(e,{follow:!0});if(null===t.node)throw new ce.ErrnoError(44);if(!ce.isDir(t.node.mode))throw new ce.ErrnoError(54);var n=ce.nodePermissions(t.node,"x");if(n)throw new ce.ErrnoError(n);ce.currentPath=t.path},createDefaultDirectories:function(){ce.mkdir("/tmp"),ce.mkdir("/home"),ce.mkdir("/home/web_user")},createDefaultDevices:function(){ce.mkdir("/dev"),ce.registerDevice(ce.makedev(1,3),{read:function(){return 0},write:function(e,t,n,r,o){return r}}),ce.mkdev("/dev/null",ce.makedev(1,3)),re.register(ce.makedev(5,0),re.default_tty_ops),re.register(ce.makedev(6,0),re.default_tty1_ops),ce.mkdev("/dev/tty",ce.makedev(5,0)),ce.mkdev("/dev/tty1",ce.makedev(6,0));var e=new Uint8Array(1024),t=0,n=function(){return 0===t&&(t=K(e).byteLength),e[--t]};ce.createDevice("/dev","random",n),ce.createDevice("/dev","urandom",n),ce.mkdir("/dev/shm"),ce.mkdir("/dev/shm/tmp")},createSpecialDirectories:function(){ce.mkdir("/proc");var e=ce.mkdir("/proc/self");ce.mkdir("/proc/self/fd"),ce.mount({mount:function(){var t=ce.createNode(e,"fd",16895,73);return t.node_ops={lookup:function(e,t){var n=+t,r=ce.getStreamChecked(n),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:function(){return r.path}}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams:function(){i.stdin?ce.createDevice("/dev","stdin",i.stdin):ce.symlink("/dev/tty","/dev/stdin"),i.stdout?ce.createDevice("/dev","stdout",null,i.stdout):ce.symlink("/dev/tty","/dev/stdout"),i.stderr?ce.createDevice("/dev","stderr",null,i.stderr):ce.symlink("/dev/tty1","/dev/stderr"),ce.open("/dev/stdin",0),ce.open("/dev/stdout",1),ce.open("/dev/stderr",1)},ensureErrnoError:function(){ce.ErrnoError||(ce.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},ce.ErrnoError.prototype=new Error,ce.ErrnoError.prototype.constructor=ce.ErrnoError,[44].forEach((function(e){ce.genericErrors[e]=new ce.ErrnoError(e),ce.genericErrors[e].stack=""})))},staticInit:function(){ce.ensureErrnoError(),ce.nameTable=new Array(4096),ce.mount(ie,{},"/"),ce.createDefaultDirectories(),ce.createDefaultDevices(),ce.createSpecialDirectories(),ce.filesystems={MEMFS:ie}},init:function(e,t,n){ce.init.initialized=!0,ce.ensureErrnoError(),i.stdin=e||i.stdin,i.stdout=t||i.stdout,i.stderr=n||i.stderr,ce.createStandardStreams()},quit:function(){ce.init.initialized=!1;for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,n=e/this.chunkSize|0;return this.getter(n)[t]}},i.prototype.setDataGetter=function(e){this.getter=e},i.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",n,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+n+". Status: "+e.status);var t,r=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,i=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,a=1048576;o||(a=r);var s=this;s.setDataGetter((function(e){var t=e*a,o=(e+1)*a-1;if(o=Math.min(o,r-1),void 0===s.chunks[e]&&(s.chunks[e]=function(e,t){if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>r-1)throw new Error("only "+r+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",n,!1),r!==a&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+n+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):ne(o.responseText||"",!0)}(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!i&&r||(a=r=1,r=this.getter(0).length,a=r,p("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=r,this._chunkSize=a,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!l)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var a=new i;Object.defineProperties(a,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:a}}else s={isDevice:!1,url:n};var u=ce.createFile(e,t,s,r,o);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function f(e,t,n,r,o){var i=e.node.contents;if(o>=i.length)return 0;var a=Math.min(i.length-o,r);if(i.slice)for(var s=0;s>2]=r.dev,b[n+4>>2]=r.mode,_[n+8>>2]=r.nlink,b[n+12>>2]=r.uid,b[n+16>>2]=r.gid,b[n+20>>2]=r.rdev,B=[r.size>>>0,(I=r.size,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+24>>2]=B[0],b[n+28>>2]=B[1],b[n+32>>2]=4096,b[n+36>>2]=r.blocks;var o=r.atime.getTime(),i=r.mtime.getTime(),a=r.ctime.getTime();return B=[Math.floor(o/1e3)>>>0,(I=Math.floor(o/1e3),+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+40>>2]=B[0],b[n+44>>2]=B[1],_[n+48>>2]=o%1e3*1e3,B=[Math.floor(i/1e3)>>>0,(I=Math.floor(i/1e3),+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+56>>2]=B[0],b[n+60>>2]=B[1],_[n+64>>2]=i%1e3*1e3,B=[Math.floor(a/1e3)>>>0,(I=Math.floor(a/1e3),+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+72>>2]=B[0],b[n+76>>2]=B[1],_[n+80>>2]=a%1e3*1e3,B=[r.ino>>>0,(I=r.ino,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[n+88>>2]=B[0],b[n+92>>2]=B[1],0},doMsync:function(e,t,n,r,o){if(!ce.isFile(t.node.mode))throw new ce.ErrnoError(43);if(2&r)return 0;var i=E.slice(e,e+n);ce.msync(t,i,o,n,r)},varargs:void 0,get:function(){return le.varargs+=4,b[le.varargs-4>>2]},getStr:function(e){return fe(e)},getStreamFromFD:function(e){return ce.getStreamChecked(e)}},de=function(e,t,n){return te(e,E,t,n)};ue=function(){return performance.now()};var me=function(e){if(e instanceof Y||"unwind"==e)return g;f(1,e)},pe=function(e,t){var n;g=e,g=n=e,A()||(i.onExit&&i.onExit(n),S=!0),f(n,new Y(n))},he=pe,ve=function(e){if(!S)try{e(),function(){if(!A())try{he(g)}catch(e){me(e)}}()}catch(e){me(e)}},we=function(e,t){return setTimeout((function(){ve(e)}),t)},ge={mainLoop:{running:!1,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){ge.mainLoop.scheduler=null,ge.mainLoop.currentlyRunningMainloop++},resume:function(){ge.mainLoop.currentlyRunningMainloop++;var e=ge.mainLoop.timingMode,t=ge.mainLoop.timingValue,n=ge.mainLoop.func;ge.mainLoop.func=null,Ee(n,0,!1,ge.mainLoop.arg,!0),ye(e,t),ge.mainLoop.scheduler()},updateStatus:function(){if(i.setStatus){var e=i.statusMessage||"Please wait...",t=ge.mainLoop.remainingBlockers,n=ge.mainLoop.expectedBlockers;t?t=6;){var a=r>>o-6&63;o-=6,n+=t[a]}return 2==o?(n+=t[(3&r)<<4],n+="=="):4==o&&(n+=t[(15&r)<<2],n+="="),n}(e),i(u))},u.src=s,we((function(){i(u)}),1e4)}};ae.push(t);var n=i.canvas;n&&(n.requestPointerLock=n.requestPointerLock||n.mozRequestPointerLock||n.webkitRequestPointerLock||n.msRequestPointerLock||function(){},n.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},n.exitPointerLock=n.exitPointerLock.bind(document),document.addEventListener("pointerlockchange",r,!1),document.addEventListener("mozpointerlockchange",r,!1),document.addEventListener("webkitpointerlockchange",r,!1),document.addEventListener("mspointerlockchange",r,!1),i.elementPointerLock&&n.addEventListener("click",(function(e){!ge.pointerLock&&i.canvas.requestPointerLock&&(i.canvas.requestPointerLock(),e.preventDefault())}),!1))}function r(){ge.pointerLock=document.pointerLockElement===i.canvas||document.mozPointerLockElement===i.canvas||document.webkitPointerLockElement===i.canvas||document.msPointerLockElement===i.canvas}},createContext:function(e,t,n,r){if(t&&i.ctx&&e==i.canvas)return i.ctx;var o,a;if(t){var s={antialias:!1,alpha:!1,majorVersion:1};if(r)for(var u in r)s[u]=r[u];"undefined"!=typeof GL&&(a=GL.createContext(e,s))&&(o=GL.getContext(a).GLctx)}else o=e.getContext("2d");return o?(n&&(t||F("undefined"==typeof GLctx,"cannot set in module if GLctx is used, but we are a non-GL context that would replace it"),i.ctx=o,t&&GL.makeContextCurrent(a),i.useWebGL=t,ge.moduleContextCreatedCallbacks.forEach((function(e){return e()})),ge.init()),o):null},destroyContext:function(e,t,n){},fullscreenHandlersInstalled:!1,lockPointer:void 0,resizeCanvas:void 0,requestFullscreen:function(e,t){ge.lockPointer=e,ge.resizeCanvas=t,void 0===ge.lockPointer&&(ge.lockPointer=!0),void 0===ge.resizeCanvas&&(ge.resizeCanvas=!1);var n=i.canvas;function r(){ge.isFullscreen=!1;var e=n.parentNode;(document.fullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement)===e?(n.exitFullscreen=ge.exitFullscreen,ge.lockPointer&&n.requestPointerLock(),ge.isFullscreen=!0,ge.resizeCanvas?ge.setFullscreenCanvasSize():ge.updateCanvasDimensions(n)):(e.parentNode.insertBefore(n,e),e.parentNode.removeChild(e),ge.resizeCanvas?ge.setWindowedCanvasSize():ge.updateCanvasDimensions(n)),i.onFullScreen&&i.onFullScreen(ge.isFullscreen),i.onFullscreen&&i.onFullscreen(ge.isFullscreen)}ge.fullscreenHandlersInstalled||(ge.fullscreenHandlersInstalled=!0,document.addEventListener("fullscreenchange",r,!1),document.addEventListener("mozfullscreenchange",r,!1),document.addEventListener("webkitfullscreenchange",r,!1),document.addEventListener("MSFullscreenChange",r,!1));var o=document.createElement("div");n.parentNode.insertBefore(o,n),o.appendChild(n),o.requestFullscreen=o.requestFullscreen||o.mozRequestFullScreen||o.msRequestFullscreen||(o.webkitRequestFullscreen?function(){return o.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)}:null)||(o.webkitRequestFullScreen?function(){return o.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),o.requestFullscreen()},exitFullscreen:function(){return!!ge.isFullscreen&&((document.exitFullscreen||document.cancelFullScreen||document.mozCancelFullScreen||document.msExitFullscreen||document.webkitCancelFullScreen||function(){}).apply(document,[]),!0)},nextRAF:0,fakeRequestAnimationFrame:function(e){var t=Date.now();if(0===ge.nextRAF)ge.nextRAF=t+1e3/60;else for(;t+2>=ge.nextRAF;)ge.nextRAF+=1e3/60;var n=Math.max(ge.nextRAF-t,0);setTimeout(e,n)},requestAnimationFrame:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){"function"!=typeof requestAnimationFrame?(0,ge.fakeRequestAnimationFrame)(e):requestAnimationFrame(e)})),safeSetTimeout:function(e,t){return we(e,t)},safeRequestAnimationFrame:function(e){return ge.requestAnimationFrame((function(){ve(e)}))},getMimetype:function(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[e.substr(e.lastIndexOf(".")+1)]},getUserMedia:function(e){window.getUserMedia||(window.getUserMedia=navigator.getUserMedia||navigator.mozGetUserMedia),window.getUserMedia(e)},getMovementX:function(e){return e.movementX||e.mozMovementX||e.webkitMovementX||0},getMovementY:function(e){return e.movementY||e.mozMovementY||e.webkitMovementY||0},getMouseWheelDelta:function(e){var t=0;switch(e.type){case"DOMMouseScroll":t=e.detail/3;break;case"mousewheel":t=e.wheelDelta/120;break;case"wheel":switch(t=e.deltaY,e.deltaMode){case 0:t/=100;break;case 1:t/=3;break;case 2:t*=80;break;default:throw"unrecognized mouse wheel delta mode: "+e.deltaMode}break;default:throw"unrecognized mouse wheel event: "+e.type}return t},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(e){if(ge.pointerLock)"mousemove"!=e.type&&"mozMovementX"in e?ge.mouseMovementX=ge.mouseMovementY=0:(ge.mouseMovementX=ge.getMovementX(e),ge.mouseMovementY=ge.getMovementY(e)),"undefined"!=typeof SDL?(ge.mouseX=SDL.mouseX+ge.mouseMovementX,ge.mouseY=SDL.mouseY+ge.mouseMovementY):(ge.mouseX+=ge.mouseMovementX,ge.mouseY+=ge.mouseMovementY);else{var t=i.canvas.getBoundingClientRect(),n=i.canvas.width,r=i.canvas.height,o=void 0!==window.scrollX?window.scrollX:window.pageXOffset,a=void 0!==window.scrollY?window.scrollY:window.pageYOffset;if("touchstart"===e.type||"touchend"===e.type||"touchmove"===e.type){var s=e.touch;if(void 0===s)return;var u=s.pageX-(o+t.left),c=s.pageY-(a+t.top),f={x:u*=n/t.width,y:c*=r/t.height};if("touchstart"===e.type)ge.lastTouches[s.identifier]=f,ge.touches[s.identifier]=f;else if("touchend"===e.type||"touchmove"===e.type){var l=ge.touches[s.identifier];l||(l=f),ge.lastTouches[s.identifier]=l,ge.touches[s.identifier]=f}return}var d=e.pageX-(o+t.left),m=e.pageY-(a+t.top);d*=n/t.width,m*=r/t.height,ge.mouseMovementX=d-ge.mouseX,ge.mouseMovementY=m-ge.mouseY,ge.mouseX=d,ge.mouseY=m}},resizeListeners:[],updateResizeListeners:function(){var e=i.canvas;ge.resizeListeners.forEach((function(t){return t(e.width,e.height)}))},setCanvasSize:function(e,t,n){var r=i.canvas;ge.updateCanvasDimensions(r,e,t),n||ge.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if("undefined"!=typeof SDL){var e=_[SDL.screen>>2];e|=8388608,b[SDL.screen>>2]=e}ge.updateCanvasDimensions(i.canvas),ge.updateResizeListeners()},setWindowedCanvasSize:function(){if("undefined"!=typeof SDL){var e=_[SDL.screen>>2];e&=-8388609,b[SDL.screen>>2]=e}ge.updateCanvasDimensions(i.canvas),ge.updateResizeListeners()},updateCanvasDimensions:function(e,t,n){t&&n?(e.widthNative=t,e.heightNative=n):(t=e.widthNative,n=e.heightNative);var r=t,o=n;if(i.forcedAspectRatio&&i.forcedAspectRatio>0&&(r/o0){var t=Date.now(),n=ge.mainLoop.queue.shift();if(n.func(n.arg),ge.mainLoop.remainingBlockers){var o=ge.mainLoop.remainingBlockers,i=o%1==0?o-1:Math.floor(o);n.counted?ge.mainLoop.remainingBlockers=i:(i+=.5,ge.mainLoop.remainingBlockers=(8*o+i)/9)}if(p('main loop blocker "'+n.name+'" took '+(Date.now()-t)+" ms"),ge.mainLoop.updateStatus(),!s())return;setTimeout(ge.mainLoop.runner,0)}else s()&&(ge.mainLoop.currentFrameNumber=ge.mainLoop.currentFrameNumber+1|0,1==ge.mainLoop.timingMode&&ge.mainLoop.timingValue>1&&ge.mainLoop.currentFrameNumber%ge.mainLoop.timingValue!=0?ge.mainLoop.scheduler():(0==ge.mainLoop.timingMode&&(ge.mainLoop.tickStartTime=ue()),ge.mainLoop.runIter(e),s()&&("object"==("undefined"==typeof SDL?"undefined":r(SDL))&&SDL.audio&&SDL.audio.queueNewAudioData&&SDL.audio.queueNewAudioData(),ge.mainLoop.scheduler())))},i||(t&&t>0?ye(0,1e3/t):ye(1,1),ge.mainLoop.scheduler()),n)throw"unwind"}var ke=[],be=function(e){var t=ke[e];return t||(e>=ke.length&&(ke.length=e+1),ke[e]=t=L.get(e)),t},_e={sockets:[null],socketEvent:null};function Le(e){return i["_"+e]}var Se=function(e,t,n,r,o){var i={string:function(e){var t=0;return null!=e&&0!==e&&(t=function(e){var t=ee(e)+1,n=Oe(t);return de(e,n,t),n}(e)),t},array:function(e){var t,n,r=Oe(e.length);return t=e,n=r,y.set(t,n),r}},a=Le(e),s=[],u=0;if(r)for(var c=0;c>1]=2,0;case 16:case 8:default:return-28;case 9:return 28,b[ze()>>2]=28,-1}}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},u:function(e,t,n){try{var r=le.getStreamFromFD(e);r.getdents||(r.getdents=ce.readdir(r.path));for(var o=280,i=0,a=ce.llseek(r,0,1),s=Math.floor(a/o);s>>0,(I=u,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[t+i>>2]=B[0],b[t+i+4>>2]=B[1],B=[(s+1)*o>>>0,(I=(s+1)*o,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[t+i+8>>2]=B[0],b[t+i+12>>2]=B[1],k[t+i+16>>1]=280,y[t+i+18>>0]=c,de(f,t+i+19,256),i+=o,s+=1}return ce.llseek(r,s*o,0),i}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},x:function(e,t,n){le.varargs=n;try{var r=le.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return r.tty?0:-59;case 21505:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcgets){var o=r.tty.ops.ioctl_tcgets(r),i=le.get();b[i>>2]=o.c_iflag||0,b[i+4>>2]=o.c_oflag||0,b[i+8>>2]=o.c_cflag||0,b[i+12>>2]=o.c_lflag||0;for(var a=0;a<32;a++)y[i+a+17>>0]=o.c_cc[a]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcsets){i=le.get();var s=b[i>>2],u=b[i+4>>2],c=b[i+8>>2],f=b[i+12>>2],l=[];for(a=0;a<32;a++)l.push(y[i+a+17>>0]);return r.tty.ops.ioctl_tcsets(r.tty,t,{c_iflag:s,c_oflag:u,c_cflag:c,c_lflag:f,c_cc:l})}return 0;case 21519:return r.tty?(i=le.get(),b[i>>2]=0,0):-59;case 21520:return r.tty?-28:-59;case 21531:return i=le.get(),ce.ioctl(r,t,i);case 21523:if(!r.tty)return-59;if(r.tty.ops.ioctl_tiocgwinsz){var d=r.tty.ops.ioctl_tiocgwinsz(r.tty);i=le.get(),k[i>>1]=d[0],k[i+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},f:function(e,t,n,r){le.varargs=r;try{t=le.getStr(t),t=le.calculateAt(e,t);var o=r?le.get():0;return ce.open(t,n,o).fd}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},r:function(e){try{return e=le.getStr(e),ce.rmdir(e),0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},q:function(e,t){try{return e=le.getStr(e),le.doStat(ce.stat,e,t)}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},s:function(e,t,n){try{return t=le.getStr(t),t=le.calculateAt(e,t),0===n?ce.unlink(t):512===n?ce.rmdir(t):O("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return-e.errno}},o:function(){return!0},c:function(){O("")},v:ue,y:function(e,t,n){return E.copyWithin(e,t,t+n)},p:function(e){E.length,O("OOM")},t:function(e,t,n){Ee(be(e),t,n)},z:function(e,t,n){var r=_e.sockets[e];return r?(n&&fe(n),n?r.close(t||void 0,fe(n)):t?r.close(t):r.close(),0):-3},h:function(e){var t=_e.sockets[e];return t?(t.onopen=t.onerror=t.onclose=t.onmessage=null,delete _e.sockets[e],0):-3},m:function(e){if("undefined"==typeof WebSocket)return-1;if(!e)return-5;var t=e>>2,n=fe(b[t]),r=b[t+1],o=r?new WebSocket(n,fe(r).split(",")):new WebSocket(n);o.binaryType="arraybuffer";var i=_e.sockets.length;return _e.sockets[i]=o,i},g:function(e,t){var n=_e.sockets[e];if(!n)return-3;var r=fe(t);return n.send(r),0},i:function(e,t,n,r){_e.socketEvent||(_e.socketEvent=Re(1024));var o=_e.sockets[e];return o?(o.onclose=function(r){_[_e.socketEvent>>2]=e,_[_e.socketEvent+4>>2]=r.wasClean,_[_e.socketEvent+8>>2]=r.code,de(r.reason,_e.socketEvent+10,512),be(n)(0,_e.socketEvent,t)},0):-3},j:function(e,t,n,r){_e.socketEvent||(_e.socketEvent=Re(1024));var o=_e.sockets[e];return o?(o.onerror=function(r){_[_e.socketEvent>>2]=e,be(n)(0,_e.socketEvent,t)},0):-3},k:function(e,t,n,r){_e.socketEvent||(_e.socketEvent=Re(1024));var o=_e.sockets[e];return o?(o.onmessage=function(r){if(_[_e.socketEvent>>2]=e,"string"==typeof r.data){var o=(a=r.data,s=ee(a)+1,(u=Re(s))&&de(a,u,s),u),i=ee(r.data)+1;_[_e.socketEvent+12>>2]=1}else i=r.data.byteLength,o=Re(i),y.set(new Uint8Array(r.data),o),_[_e.socketEvent+12>>2]=0;var a,s,u;_[_e.socketEvent+4>>2]=o,_[_e.socketEvent+8>>2]=i,be(n)(0,_e.socketEvent,t),Ce(o)},0):-3},l:function(e,t,n,r){_e.socketEvent||(_e.socketEvent=Re(1024));var o=_e.sockets[e];return o?(o.onopen=function(r){_[_e.socketEvent>>2]=e,be(n)(0,_e.socketEvent,t)},0):-3},A:he,a:function(e){try{var t=le.getStreamFromFD(e);return ce.close(t),0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return e.errno}},w:function(e,t,n,r){try{var o=function(e,t,n,r){for(var o=0,i=0;i>2],s=_[t+4>>2];t+=8;var u=ce.read(e,y,a,s,r);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return e.errno}},n:function(e,t,n,r,o){var i,a,s=(a=n)+2097152>>>0<4194305-!!(i=t)?(i>>>0)+4294967296*a:NaN;try{if(isNaN(s))return 61;var u=le.getStreamFromFD(e);return ce.llseek(u,s,r),B=[u.position>>>0,(I=u.position,+Math.abs(I)>=1?I>0?+Math.floor(I/4294967296)>>>0:~~+Math.ceil((I-+(~~I>>>0))/4294967296)>>>0:0)],b[o>>2]=B[0],b[o+4>>2]=B[1],u.getdents&&0===s&&0===r&&(u.getdents=null),0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return e.errno}},d:function(e,t,n,r){try{var o=function(e,t,n,r){for(var o=0,i=0;i>2],s=_[t+4>>2];t+=8;var u=ce.write(e,y,a,s,r);if(u<0)return-1;o+=u,void 0!==r&&(r+=u)}return o}(le.getStreamFromFD(e),t,n);return _[r>>2]=o,0}catch(e){if(void 0===ce||"ErrnoError"!==e.name)throw e;return e.errno}}},Ae=(function(){var e,n,r,o,a={a:xe};function s(e,t){var n,r,o=e.exports;return n=(v=o).B.buffer,i.HEAP8=y=new Int8Array(n),i.HEAP16=k=new Int16Array(n),i.HEAP32=b=new Int32Array(n),i.HEAPU8=E=new Uint8Array(n),i.HEAPU16=new Uint16Array(n),i.HEAPU32=_=new Uint32Array(n),i.HEAPF32=new Float32Array(n),i.HEAPF64=new Float64Array(n),L=v.D,r=v.C,P.unshift(r),N(),o}if(j(),i.instantiateWasm)try{return i.instantiateWasm(a,s)}catch(e){h("Module.instantiateWasm callback failed with error: "+e),t(e)}(e=m,n=T,r=a,o=function(e){s(e.instance)},e||"function"!=typeof WebAssembly.instantiateStreaming||U(n)||"function"!=typeof fetch?H(n,r,o):fetch(n,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,r).then(o,(function(e){return h("wasm streaming compile failed: "+e),h("falling back to ArrayBuffer instantiation"),H(n,r,o)}))}))).catch(t)}(),i._main=function(e,t){return(Ae=i._main=v.E)(e,t)}),Re=(i._mocpp_wasm_api_call=function(e,t,n){return(i._mocpp_wasm_api_call=v.F)(e,t,n)},function(e){return(Re=v.G)(e)}),Ce=function(e){return(Ce=v.H)(e)},ze=function(){return(ze=v.I)()},je=function(){return(je=v.J)()},Ne=function(e){return(Ne=v.K)(e)},Oe=function(e){return(Oe=v.L)(e)},Te=function(e){return(Te=v.M)(e)};function qe(){function t(){Me||(Me=!0,i.calledRun=!0,S||(i.noFSInit||ce.init.initialized||ce.init(),ce.ignorePermissions=!1,re.init(),G(P),G(D),e(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),Ie&&function(){var e=Ae;try{var t=e(0,0);return pe(t),t}catch(e){return me(e)}}(),function(){if(i.postRun)for("function"==typeof i.postRun&&(i.postRun=[i.postRun]);i.postRun.length;)e=i.postRun.shift(),x.unshift(e);var e;G(x)}()))}R>0||(function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)e=i.preRun.shift(),M.unshift(e);var e;G(M)}(),R>0||(i.setStatus?(i.setStatus("Running..."),setTimeout((function(){setTimeout((function(){i.setStatus("")}),1),t()}),1)):t()))}if(i.ccall=Se,i.cwrap=function(e,t,n,r){var o=!n||n.every((function(e){return"number"===e||"boolean"===e}));return"string"!==t&&o&&!r?Le(e):function(){return Se(e,t,n,arguments)}},z=function e(){Me||qe(),Me||(z=e)},i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();var Ie=!0;return i.noInitialRun&&(Ie=!1),qe(),n.ready});function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(){s=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,o=Object.defineProperty||function(e,t,n){e[t]=n.value},i="function"==typeof Symbol?Symbol:{},u=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",f=i.toStringTag||"@@toStringTag";function l(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{l({},"")}catch(e){l=function(e,t,n){return e[t]=n}}function d(e,t,n,r){var i=t&&t.prototype instanceof y?t:y,a=Object.create(i.prototype),s=new R(r||[]);return o(a,"_invoke",{value:P(e,n,s)}),a}function m(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}t.wrap=d;var p="suspendedStart",h="suspendedYield",v="executing",w="completed",g={};function y(){}function E(){}function k(){}var b={};l(b,u,(function(){return this}));var _=Object.getPrototypeOf,L=_&&_(_(C([])));L&&L!==n&&r.call(L,u)&&(b=L);var S=k.prototype=y.prototype=Object.create(b);function F(e){["next","throw","return"].forEach((function(t){l(e,t,(function(e){return this._invoke(t,e)}))}))}function M(e,t){function n(o,i,s,u){var c=m(e[o],e,i);if("throw"!==c.type){var f=c.arg,l=f.value;return l&&"object"==a(l)&&r.call(l,"__await")?t.resolve(l.__await).then((function(e){n("next",e,s,u)}),(function(e){n("throw",e,s,u)})):t.resolve(l).then((function(e){f.value=e,s(f)}),(function(e){return n("throw",e,s,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(e,r){function o(){return new t((function(t,o){n(e,r,t,o)}))}return i=i?i.then(o,o):o()}})}function P(t,n,r){var o=p;return function(i,a){if(o===v)throw new Error("Generator is already running");if(o===w){if("throw"===i)throw a;return{value:e,done:!0}}for(r.method=i,r.arg=a;;){var s=r.delegate;if(s){var u=D(s,r);if(u){if(u===g)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===p)throw o=w,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=v;var c=m(t,n,r);if("normal"===c.type){if(o=r.done?w:h,c.arg===g)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(o=w,r.method="throw",r.arg=c.arg)}}}function D(t,n){var r=n.method,o=t.iterator[r];if(o===e)return n.delegate=null,"throw"===r&&t.iterator.return&&(n.method="return",n.arg=e,D(t,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var i=m(o,t.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,g;var a=i.arg;return a?a.done?(n[t.resultName]=a.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,g):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}function x(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function A(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(x,this),this.reset(!0)}function C(t){if(t||""===t){var n=t[u];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function n(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=r.call(a,"catchLoc"),c=r.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),A(n),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;A(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:C(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),g}},t}function u(e,t,n,r,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void n(e)}s.done?t(u):Promise.resolve(u).then(r,o)}function c(e,t){for(var n=0;n - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/README.md b/README.md deleted file mode 100644 index 6ccc07f..0000000 --- a/README.md +++ /dev/null @@ -1,123 +0,0 @@ -# Icon   MicroOcppSimulator - -[![Build (Ubuntu)](https://github.com/matth-x/MicroOcppSimulator/workflows/Ubuntu/badge.svg)]((https://github.com/matth-x/MicroOcppSimulator/actions)) -[![Build (Docker)](https://github.com/matth-x/MicroOcppSimulator/workflows/Docker/badge.svg)]((https://github.com/matth-x/MicroOcppSimulator/actions)) -[![Build (WebAssembly)](https://github.com/matth-x/MicroOcppSimulator/workflows/WebAssembly/badge.svg)]((https://github.com/matth-x/MicroOcppSimulator/actions)) - -Tester / Demo App for the [MicroOCPP](https://github.com/matth-x/MicroOcpp) Client, running on native Ubuntu, WSL, WebAssembly or MSYS2. Online demo: [Try it](https://demo.micro-ocpp.com/) - -[![Screenshot](https://github.com/agruenb/arduino-ocpp-dashboard/blob/master/docs/img/status_page.png)](https://demo.micro-ocpp.com/) - -The Simulator has two purposes: -- As a development tool, it allows to run MicroOCPP directly on the host computer and simplifies the development (no flashing of the microcontroller required) -- As a demonstration tool, it allows backend operators to test and use MicroOCPP without the need to set up an actual microcontroller or to buy an actual charger with MicroOCPP. - -That means that the Simulator runs on your computer and connects to an OCPP server using the same software like a -microcontroller. It provides a Graphical User Interface to show the connection status and to trigger simulated charging -sessions (and further simulated actions). - -## Running on Docker - -The Simulator can be run on Docker. This is the easiest way to get it up and running. The Docker image is based on -Ubuntu 20.04 and contains all necessary dependencies. - -Firstly, build the image: - -```shell -docker build -t matthx/microocppsimulator:latest . -``` - -Then run the image: - -```shell -docker run -p 8000:8000 matthx/microocppsimulator:latest -``` - -The Simulator should be up and running now on [localhost:8000](http://localhost:8000). - -## Installation (Ubuntu or WSL) - -On Windows, get the Windows Subsystem for Linux (WSL): [https://ubuntu.com/wsl](https://ubuntu.com/wsl) or [MSYS2](https://www.msys2.org/). - -Then follow the same steps like for Ubuntu. - -On Ubuntu (other distros probably work as well, tested on Ubuntu 20.04 and 22.04), install cmake, OpenSSL and the C++ -compiler: - -```shell -sudo apt install cmake libssl-dev build-essential -``` - -Navigate to the preferred installation directory or just to the home folder. Clone the Simulator and all submodules: - -```shell -git clone --recurse-submodules https://github.com/matth-x/MicroOcppSimulator -``` - -Navigate to the copy of the Simulator and build: - -```shell -cd MicroOcppSimulator -cmake -S . -B ./build -cmake --build ./build -j 16 --target mo_simulator -``` - -The installation is complete! To run the Simulator, type: - -```shell -./build/mo_simulator -``` - -This will open [localhost:8000](http://localhost:8000). You can access the Graphical User Interface by entering that -address into a browser running on the same computer. Make sure that the firewall settings allow the Simulator to connect -and to be reached. - -The Simulator should be up and running now! - -## Building the Webapp (Developers) - -The webapp is registered as a git submodule in *webapp-src*. - -Before you can build the webapp, you have to create a *.env.production* file in the *webapp-src* folder. If you just -want to try out the build process, you can simply duplicate the *.env.development* file and rename it. - -After that, to build it for deployment, all you have to do is run `./build-webapp/build_webapp.ps1` (Windows) from the -root directory. -For this to work NodeJS, npm and git have to be installed on your machine. The called script automatically performs the -following tasks: - -- pull the newest version of the the [arduino-ocpp-dashboard](https://github.com/agruenb/arduino-ocpp-dashboard) -- check if you have added a *.env.production* file -- install webapp dependencies -- build the webapp -- compress the webapp -- move the g-zipped bundle file into the public folder - -During the process there might be some warnings displayed. Als long as the script exits without an error everything worked fine. An up-to-date version of the webapp should be placed in the *public* folder. - -## Porting to WebAssembly (Developers) - -If you want to run the Simulator in the browser instead of a Linux host, you can port the code for WebAssembly. - -Make sure that emscripten is installed and on the path (see [https://emscripten.org/docs/getting_started/downloads.html#installation-instructions-using-the-emsdk-recommended](https://emscripten.org/docs/getting_started/downloads.html#installation-instructions-using-the-emsdk-recommended)). - -Then, create the CMake build files with the corresponding emscripten tool and change the target: - -```shell -emcmake cmake -S . -B ./build -cmake --build ./build -j 16 --target mo_simulator_wasm -``` - -The compiler toolchain should emit the WebAssembly binary and a JavaScript wrapper into the build folder. They need to be built into the preact webapp. Instead of making XHR requests to the server, the webapp will call the API of the WebAssembly JS wrapper then. The `install_webassembly.sh` script patches the webapp sources with the WASM binary and JS wrapper: - -```shell -./build-webapp/install_webassembly.sh -``` - -Now, the GUI can be developed or built as described in the [webapp repository](https://github.com/agruenb/arduino-ocpp-dashboard). - -After building the GUI, the emited files contain the full Simulator functionality. To run the Simualtor, start an HTTP file server in the dist folder and access it with your browser. - -## License - -This project is licensed under the GPL as it uses the [Mongoose Embedded Networking Library](https://github.com/cesanta/mongoose). If you have a proprietary license of Mongoose, then the [MIT License](https://github.com/matth-x/MicroOcpp/blob/master/LICENSE) applies. diff --git a/build-webapp/build_webapp.ps1 b/build-webapp/build_webapp.ps1 deleted file mode 100644 index c035cca..0000000 --- a/build-webapp/build_webapp.ps1 +++ /dev/null @@ -1,40 +0,0 @@ -#build, compress the web-app and move the bundle file to the public folder - -#exit script on error -$ErrorActionPreference = "Stop" -#check relevant installs -echo "[info] NodeJS and npm need to be installed to build the web-app" - -cd ./webapp-src - -#fetch most recent version -git pull - -echo "Building web-app..." - -#check .env.production file exists -$file = ".env.production" - -#If the file does not exist, create it. -if (Test-Path -Path $file -PathType Leaf) { - echo "production environment found" -}else{ - echo "no .env.production file found" - cd .. - exit 1 -} - - -#install dependencies -npm install -#build the webapp -npm run build -#compress the project -npm run compress - -#move the compressed file into the public folder -Move-Item ./dist/bundle.html.gz ../public/ -Force - -echo "[success] Up-to-date version of the web-app bundle was placed in the /public folder!" - -cd .. \ No newline at end of file diff --git a/build-webapp/build_webapp.sh b/build-webapp/build_webapp.sh deleted file mode 100644 index 230e3dc..0000000 --- a/build-webapp/build_webapp.sh +++ /dev/null @@ -1,31 +0,0 @@ -#build, compress the web-app and move the bundle file to the public folder - -#exit script on error -set -e -#check relevant installs -echo "[info] NodeJS and npm need to be installed to build the web-app" - -cd ./webapp-src - -echo "Building web-app..." - -#check .env.production file exists -if [ -f ".env.production" ] -then -echo "production environment found" -else - echo "no .env.production file found" - exit 1 -fi - -#install dependencies -npm install -#build the webapp -npm run build -#compress the project -npm run compress - -#move the compressed file into the public folder -mv -f ./dist/bundle.html.gz ../public/ - -echo "Up-to-date version of the web-app bundle was placed in the /public folder!" \ No newline at end of file diff --git a/build-webapp/install_webassembly.sh b/build-webapp/install_webassembly.sh deleted file mode 100644 index 4cbcc4d..0000000 --- a/build-webapp/install_webassembly.sh +++ /dev/null @@ -1,14 +0,0 @@ -# execute after building cmake Simulator WebAssembly target: -# move created WebAssembly files into webapp folder and patch webapp - -echo "installing WebAssembly files" - -cp ./build/mo_simulator_wasm.mjs ./webapp-src/src/ -cp ./build/mo_simulator_wasm.wasm ./webapp-src/public/ - -if [ -e ./webapp-src/src/DataService_wasm.js.template ] -then - echo "patch DataService" - mv ./webapp-src/src/DataService.js ./webapp-src/src/DataService_http.js.template - mv ./webapp-src/src/DataService_wasm.js.template ./webapp-src/src/DataService.js -fi diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..42096b5 Binary files /dev/null and b/favicon.ico differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..41514e3 --- /dev/null +++ b/index.html @@ -0,0 +1,18 @@ + + + + + + + EVSE Dashboard + + + + + +
+ + + + \ No newline at end of file diff --git a/lib/ArduinoJson b/lib/ArduinoJson deleted file mode 160000 index b350a96..0000000 --- a/lib/ArduinoJson +++ /dev/null @@ -1 +0,0 @@ -Subproject commit b350a9664370f37654a406d75f99b1e5b3a2d637 diff --git a/lib/MicroOcpp b/lib/MicroOcpp deleted file mode 160000 index 4b89f46..0000000 --- a/lib/MicroOcpp +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4b89f4649d65c83cc559e4cc7c65f430db482217 diff --git a/lib/MicroOcppMongoose b/lib/MicroOcppMongoose deleted file mode 160000 index e228297..0000000 --- a/lib/MicroOcppMongoose +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e2282976eed4b98e200e5987f2dded5313902cab diff --git a/lib/mbedtls b/lib/mbedtls deleted file mode 160000 index dd79db1..0000000 --- a/lib/mbedtls +++ /dev/null @@ -1 +0,0 @@ -Subproject commit dd79db10014d85b26d11fe57218431f2e5ede6f2 diff --git a/lib/mongoose b/lib/mongoose deleted file mode 160000 index 9729693..0000000 --- a/lib/mongoose +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 97296934ab594241ba2489f018a21779882a7936 diff --git a/main.js.LICENSE.txt b/main.js.LICENSE.txt new file mode 100644 index 0000000..ae386fb --- /dev/null +++ b/main.js.LICENSE.txt @@ -0,0 +1 @@ +/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ diff --git a/mo_simulator_wasm.wasm b/mo_simulator_wasm.wasm new file mode 100644 index 0000000..c35dc9d Binary files /dev/null and b/mo_simulator_wasm.wasm differ diff --git a/mo_store/README.md b/mo_store/README.md deleted file mode 100644 index 9af6d10..0000000 --- a/mo_store/README.md +++ /dev/null @@ -1,5 +0,0 @@ -### JSON key-value store - -MicroOcpp has a local storage for the persistency of the OCPP configurations, transactions and more. As MicroOcpp is initialized for the first time, this folder is populated with all stored objects. The storage format is JSON with mostly human-readable keys. Feel free to open the stored objects with your favorite JSON viewer and inspect them to learn more about MicroOcpp. - -To change the local storage folder in a productive environment, see the build flag `MO_FILENAME_PREFIX` in the CMakeLists.txt. The folder must already exist, MicroOcpp won't create a new folder at the specified location. diff --git a/public/bundle.html.gz b/public/bundle.html.gz deleted file mode 100644 index d419b54..0000000 Binary files a/public/bundle.html.gz and /dev/null differ diff --git a/src/api.cpp b/src/api.cpp deleted file mode 100644 index 054f37c..0000000 --- a/src/api.cpp +++ /dev/null @@ -1,349 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#include "api.h" -#include "mongoose.h" - -#include -#include -#include -#include - -#include "evse.h" - -//simple matching function; takes * as a wildcard -bool str_match(const char *query, const char *pattern) { - size_t qi = 0, pi = 0; - - while (pattern[pi]) { - if (query[qi] && query[qi] == pattern[pi]) { - qi++; - pi++; - } else if (pattern[pi] == '*') { - while (pattern[pi] == '*') pi++; - while (query[qi] != pattern[pi]) qi++; - } else { - break; - } - } - - return !query[qi] && !pattern[pi]; -} - -int mocpp_api_call(const char *endpoint, MicroOcpp::Method method, const char *body, char *resp_body, size_t resp_body_size) { - - MO_DBG_VERBOSE("process %s, %s: %s", - endpoint, - method == MicroOcpp::Method::GET ? "GET" : - method == MicroOcpp::Method::POST ? "POST" : "error", - body); - - int status = 500; - StaticJsonDocument<512> response; - if (resp_body_size >= sizeof("{}")) { - sprintf(resp_body, "%s", "{}"); - } - - StaticJsonDocument<512> request; - if (*body) { - auto err = deserializeJson(request, body); - if (err) { - MO_DBG_WARN("malformatted body: %s", err.c_str()); - return 400; - } - } - - unsigned int connectorId = 0; - - if (strlen(endpoint) >= 11) { - if (endpoint[11] == '1') { - connectorId = 1; - } else if (endpoint[11] == '2') { - connectorId = 2; - } - } - - MO_DBG_VERBOSE("connectorId = %u", connectorId); - - Evse *evse = nullptr; - if (connectorId >= 1 && connectorId < MO_NUMCONNECTORS) { - evse = &connectors[connectorId-1]; - } - - //start different api endpoints - if(str_match(endpoint, "/connectors")) { - MO_DBG_VERBOSE("query connectors"); - response.add("1"); - response.add("2"); - status = 200; - } else if(str_match(endpoint, "/connector/*/evse")){ - MO_DBG_VERBOSE("query evse"); - if (!evse) { - return 404; - } - - if (method == MicroOcpp::Method::POST) { - if (request.containsKey("evPlugged")) { - evse->setEvPlugged(request["evPlugged"]); - } - if (request.containsKey("evsePlugged")) { - evse->setEvsePlugged(request["evsePlugged"]); - } - if (request.containsKey("evReady")) { - evse->setEvReady(request["evReady"]); - } - if (request.containsKey("evseReady")) { - evse->setEvseReady(request["evseReady"]); - } - } - - response["evPlugged"] = evse->getEvPlugged(); - response["evsePlugged"] = evse->getEvsePlugged(); - response["evReady"] = evse->getEvReady(); - response["evseReady"] = evse->getEvseReady(); - response["chargePointStatus"] = evse->getOcppStatus(); - status = 200; - } else if(str_match(endpoint, "/connector/*/meter")){ - MO_DBG_VERBOSE("query meter"); - if (!evse) { - return 404; - } - - response["energy"] = evse->getEnergy(); - response["power"] = evse->getPower(); - response["current"] = evse->getCurrent(); - response["voltage"] = evse->getVoltage(); - status = 200; - } else if(str_match(endpoint, "/connector/*/transaction")){ - MO_DBG_VERBOSE("query transaction"); - if (!evse) { - return 404; - } - - if (method == MicroOcpp::Method::POST) { - if (request.containsKey("idTag")) { - evse->presentNfcTag(request["idTag"] | ""); - } - } - response["idTag"] = evse->getSessionIdTag(); - response["transactionId"] = evse->getTransactionId(); - response["authorizationStatus"] = ""; - status = 200; - } else if(str_match(endpoint, "/connector/*/smartcharging")){ - MO_DBG_VERBOSE("query smartcharging"); - if (!evse) { - return 404; - } - - response["maxPower"] = evse->getSmartChargingMaxPower(); - response["maxCurrent"] = evse->getSmartChargingMaxCurrent(); - status = 200; - } else { - return 404; - } - - if (response.overflowed()) { - return 500; - } - - std::string out; - serializeJson(response, out); - if (out.length() >= resp_body_size) { - return 500; - } - - if (!out.empty()) { - sprintf(resp_body, "%s", out.c_str()); - } - - return status; -} - -int mocpp_api2_call(const char *uri_raw, size_t uri_raw_len, MicroOcpp::Method method, const char *query_raw, size_t query_raw_len, char *resp_body, size_t resp_body_size) { - - snprintf(resp_body, resp_body_size, "%s", ""); - - struct mg_str uri = mg_str_n(uri_raw, uri_raw_len); - struct mg_str query = mg_str_n(query_raw, query_raw_len); - - int evse_id = -1; - int connector_id = -1; - - unsigned int num; - struct mg_str evse_id_str = mg_http_var(query, mg_str("evse_id")); - if (evse_id_str.buf) { - if (!mg_str_to_num(evse_id_str, 10, &num, sizeof(num)) || num < 1 || num >= MO_NUM_EVSEID) { - snprintf(resp_body, resp_body_size, "invalid connector_id"); - return 400; - } - evse_id = (int)num; - } - - struct mg_str connector_id_str = mg_http_var(query, mg_str("connector_id")); - if (connector_id_str.buf) { - if (!mg_str_to_num(connector_id_str, 10, &num, sizeof(num)) || num != 1) { - snprintf(resp_body, resp_body_size, "invalid connector_id"); - return 400; - } - connector_id = (int)num; - } - - if (mg_match(uri, mg_str("/plugin"), NULL)) { - if (method != MicroOcpp::Method::POST) { - return 405; - } - if (evse_id < 0) { - snprintf(resp_body, resp_body_size, "no action taken"); - return 200; - } else { - snprintf(resp_body, resp_body_size, "%s", connectors[evse_id-1].getEvPlugged() ? "EV already plugged" : "plugged in EV"); - connectors[evse_id-1].setEvPlugged(true); - connectors[evse_id-1].setEvReady(true); - connectors[evse_id-1].setEvseReady(true); - return 200; - } - } else if (mg_match(uri, mg_str("/plugout"), NULL)) { - if (method != MicroOcpp::Method::POST) { - return 405; - } - if (evse_id < 0) { - snprintf(resp_body, resp_body_size, "no action taken"); - return 200; - } else { - snprintf(resp_body, resp_body_size, "%s", connectors[evse_id-1].getEvPlugged() ? "EV already unplugged" : "unplug EV"); - connectors[evse_id-1].setEvPlugged(false); - connectors[evse_id-1].setEvReady(false); - connectors[evse_id-1].setEvseReady(false); - return 200; - } - } else if (mg_match(uri, mg_str("/end"), NULL)) { - if (method != MicroOcpp::Method::POST) { - return 405; - } - bool trackEvReady = false; - for (size_t i = 0; i < connectors.size(); i++) { - trackEvReady |= connectors[i].getEvReady(); - connectors[i].setEvReady(false); - } - snprintf(resp_body, resp_body_size, "%s", trackEvReady ? "suspended EV" : "EV already suspended"); - return 200; - } else if (mg_match(uri, mg_str("/state"), NULL)) { - if (method != MicroOcpp::Method::POST) { - return 405; - } - struct mg_str ready_str = mg_http_var(query, mg_str("ready")); - bool ready = true; - if (ready_str.buf) { - if (mg_match(ready_str, mg_str("true"), NULL)) { - ready = true; - } else if (mg_match(ready_str, mg_str("false"), NULL)) { - ready = false; - } else { - snprintf(resp_body, resp_body_size, "invalid ready"); - return 400; - } - } - bool trackEvReady = false; - for (size_t i = 0; i < connectors.size(); i++) { - if (connectors[i].getEvPlugged()) { - bool trackEvReady = connectors[i].getEvReady(); - connectors[i].setEvReady(ready); - snprintf(resp_body, resp_body_size, "%s, %s", ready ? "EV suspended" : "EV not suspended", trackEvReady ? "suspended before" : "not suspended before"); - return 200; - } - } - snprintf(resp_body, resp_body_size, "no action taken - EV not plugged"); - return 200; - } else if (mg_match(uri, mg_str("/authorize"), NULL)) { - if (method != MicroOcpp::Method::POST) { - return 405; - } - struct mg_str id = mg_http_var(query, mg_str("id")); - if (!id.buf) { - snprintf(resp_body, resp_body_size, "missing id"); - return 400; - } - struct mg_str type = mg_http_var(query, mg_str("type")); - if (!id.buf) { - snprintf(resp_body, resp_body_size, "missing type"); - return 400; - } - - int ret; - char id_buf [MO_IDTOKEN_LEN_MAX + 1]; - ret = snprintf(id_buf, sizeof(id_buf), "%.*s", (int)id.len, id.buf); - if (ret < 0 || ret >= sizeof(id_buf)) { - snprintf(resp_body, resp_body_size, "invalid id"); - return 400; - } - char type_buf [128]; - ret = snprintf(type_buf, sizeof(type_buf), "%.*s", (int)type.len, type.buf); - if (ret < 0 || ret >= sizeof(type_buf)) { - snprintf(resp_body, resp_body_size, "invalid type"); - return 400; - } - - if (evse_id <= 0) { - snprintf(resp_body, resp_body_size, "invalid evse_id"); - return 400; - } - - bool trackAuthActive = connectors[evse_id-1].getSessionIdTag(); - - if (!connectors[evse_id-1].presentNfcTag(id_buf, type_buf)) { - snprintf(resp_body, resp_body_size, "invalid id and / or type"); - return 400; - } - - bool authActive = connectors[evse_id-1].getSessionIdTag(); - - snprintf(resp_body, resp_body_size, "%s", - !trackAuthActive && authActive ? "authorize in progress" : - trackAuthActive && !authActive ? "unauthorize in progress" : - trackAuthActive && authActive ? "no action taken (EVSE still authorized)" : - "no action taken (EVSE not authorized)"); - - return 200; - } else if (mg_match(uri, mg_str("/memory/info"), NULL)) { - #if MO_OVERRIDE_ALLOCATION && MO_ENABLE_HEAP_PROFILER - { - if (method != MicroOcpp::Method::GET) { - return 405; - } - - int ret = mo_mem_write_stats_json(resp_body, resp_body_size); - if (ret < 0 || ret >= resp_body_size) { - snprintf(resp_body, resp_body_size, "internal error"); - return 500; - } - - return 200; - } - #else - { - snprintf(resp_body, resp_body_size, "memory profiler disabled"); - return 404; - } - #endif - } else if (mg_match(uri, mg_str("/memory/reset"), NULL)) { - #if MO_OVERRIDE_ALLOCATION && MO_ENABLE_HEAP_PROFILER - { - if (method != MicroOcpp::Method::POST) { - return 405; - } - - MO_MEM_RESET(); - return 200; - } - #else - { - snprintf(resp_body, resp_body_size, "memory profiler disabled"); - return 404; - } - #endif - - } - - return 404; -} diff --git a/src/api.h b/src/api.h deleted file mode 100644 index a2de1f8..0000000 --- a/src/api.h +++ /dev/null @@ -1,24 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#ifndef MO_SIM_API_H -#define MO_SIM_API_H - -#include - -namespace MicroOcpp { - -enum class Method { - GET, - POST, - UNDEFINED -}; - -} - -int mocpp_api_call(const char *endpoint, MicroOcpp::Method method, const char *body, char *resp_body, size_t resp_body_size); - -int mocpp_api2_call(const char *endpoint, size_t endpoint_len, MicroOcpp::Method method, const char *query, size_t query_len, char *resp_body, size_t resp_body_size); - -#endif diff --git a/src/evse.cpp b/src/evse.cpp deleted file mode 100644 index a0261d6..0000000 --- a/src/evse.cpp +++ /dev/null @@ -1,262 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#include "evse.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -Evse::Evse(unsigned int connectorId) : connectorId{connectorId} { - -} - -void Evse::setup() { - -#if MO_ENABLE_V201 - if (auto context = getOcppContext()) { - if (context->getVersion().major == 2) { - //load some example variables for testing - - if (auto varService = context->getModel().getVariableService()) { - varService->declareVariable("AuthCtrlr", "LocalAuthorizeOffline", false, MicroOcpp::Variable::Mutability::ReadOnly, false); - } - } - } -#endif - - char key [30] = {'\0'}; - - snprintf(key, 30, "evPlugged_cId_%u", connectorId); - trackEvPluggedKey = key; - trackEvPluggedBool = MicroOcpp::declareConfiguration(trackEvPluggedKey.c_str(), false, SIMULATOR_FN, false, false, false); - snprintf(key, 30, "evsePlugged_cId_%u", connectorId); - trackEvsePluggedKey = key; - trackEvsePluggedBool = MicroOcpp::declareConfiguration(trackEvsePluggedKey.c_str(), false, SIMULATOR_FN, false, false, false); - snprintf(key, 30, "evReady_cId_%u", connectorId); - trackEvReadyKey = key; - trackEvReadyBool = MicroOcpp::declareConfiguration(trackEvReadyKey.c_str(), false, SIMULATOR_FN, false, false, false); - snprintf(key, 30, "evseReady_cId_%u", connectorId); - trackEvseReadyKey = key; - trackEvseReadyBool = MicroOcpp::declareConfiguration(trackEvseReadyKey.c_str(), false, SIMULATOR_FN, false, false, false); - - MicroOcpp::configuration_load(SIMULATOR_FN); - - setConnectorPluggedInput([this] () -> bool { - return trackEvPluggedBool->getBool(); //return if J1772 is in State B or C - }, connectorId); - - setEvReadyInput([this] () -> bool { - return trackEvReadyBool->getBool(); //return if J1772 is in State C - }, connectorId); - - setEvseReadyInput([this] () -> bool { - return trackEvseReadyBool->getBool(); - }, connectorId); - - addErrorCodeInput([this] () -> const char* { - const char *errorCode = nullptr; //if error is present, point to error code; any number of error code samplers can be added in this project - return errorCode; - }, connectorId); - - setEnergyMeterInput([this] () -> float { - return simulate_energy; - }, connectorId); - - setPowerMeterInput([this] () -> float { - return simulate_power; - }, connectorId); - - addMeterValueInput([this] () { - return (int32_t) getCurrent(); - }, - "Current.Import", - "A", - "Outlet", - nullptr, - connectorId); - - addMeterValueInput([this] () { - return (int32_t) getVoltage(); - }, - "Voltage", - "V", - nullptr, - nullptr, - connectorId); - - addMeterValueInput([this] () { - return (int32_t) (simulate_power > 1.f ? 44.f : 0.f); - }, - "SoC", - nullptr, - nullptr, - nullptr, - connectorId); - - setOnResetExecute([] (bool isHard) { - exit(0); - }); - - setSmartChargingPowerOutput([this] (float limit) { - if (limit >= 0.f) { - MO_DBG_DEBUG("set limit: %f", limit); - this->limit_power = limit; - } else { - // negative value means no limit defined - this->limit_power = SIMULATE_POWER_CONST; - } - }, connectorId); -} - -void Evse::loop() { - - auto curStatus = getChargePointStatus(connectorId); - - if (status.compare(MicroOcpp::cstrFromOcppEveState(curStatus))) { - status = MicroOcpp::cstrFromOcppEveState(curStatus); - } - - bool simulate_isCharging = ocppPermitsCharge(connectorId) && trackEvPluggedBool->getBool() && trackEvsePluggedBool->getBool() && trackEvReadyBool->getBool() && trackEvseReadyBool->getBool(); - - simulate_isCharging &= limit_power >= 720.f; //minimum charging current is 6A (720W for 120V grids) according to J1772 - - if (simulate_isCharging) { - if (simulate_power >= 1.f) { - simulate_energy += (float) (mocpp_tick_ms() - simulate_energy_track_time) * simulate_power * (0.001f / 3600.f); - } - - simulate_power = SIMULATE_POWER_CONST; - simulate_power = std::min(simulate_power, limit_power); - simulate_power += (((mocpp_tick_ms() / 5000) * 3483947) % 20000) * 0.001f - 10.f; - simulate_energy_track_time = mocpp_tick_ms(); - } else { - simulate_power = 0.f; - } - -} - -void Evse::presentNfcTag(const char *uid) { - if (!uid) { - MO_DBG_ERR("invalid argument"); - return; - } - -#if MO_ENABLE_V201 - if (auto context = getOcppContext()) { - if (context->getVersion().major == 2) { - presentNfcTag(uid, "ISO14443"); - return; - } - } -#endif - - if (isTransactionActive(connectorId)) { - if (!strcmp(uid, getTransactionIdTag(connectorId))) { - endTransaction(uid, "Local", connectorId); - } else { - MO_DBG_INFO("RFID card denied"); - } - } else { - beginTransaction(uid, connectorId); - } -} - -#if MO_ENABLE_V201 -bool Evse::presentNfcTag(const char *uid, const char *type) { - - MicroOcpp::IdToken idToken {nullptr, MicroOcpp::IdToken::Type::UNDEFINED, "Simulator"}; - if (!idToken.parseCstr(uid, type)) { - return false; - } - - if (auto txService = getOcppContext()->getModel().getTransactionService()) { - if (auto evse = txService->getEvse(connectorId)) { - if (evse->getTransaction() && evse->getTransaction()->isAuthorizationActive) { - evse->endAuthorization(idToken); - } else { - evse->beginAuthorization(idToken); - } - return true; - } - } - return false; -} -#endif - -void Evse::setEvPlugged(bool plugged) { - if (!trackEvPluggedBool) return; - trackEvPluggedBool->setBool(plugged); - MicroOcpp::configuration_save(); -} - -bool Evse::getEvPlugged() { - if (!trackEvPluggedBool) return false; - return trackEvPluggedBool->getBool(); -} - -void Evse::setEvsePlugged(bool plugged) { - if (!trackEvsePluggedBool) return; - trackEvsePluggedBool->setBool(plugged); - MicroOcpp::configuration_save(); -} - -bool Evse::getEvsePlugged() { - if (!trackEvsePluggedBool) return false; - return trackEvsePluggedBool->getBool(); -} - -void Evse::setEvReady(bool ready) { - if (!trackEvReadyBool) return; - trackEvReadyBool->setBool(ready); - MicroOcpp::configuration_save(); -} - -bool Evse::getEvReady() { - if (!trackEvReadyBool) return false; - return trackEvReadyBool->getBool(); -} - -void Evse::setEvseReady(bool ready) { - if (!trackEvseReadyBool) return; - trackEvseReadyBool->setBool(ready); - MicroOcpp::configuration_save(); -} - -bool Evse::getEvseReady() { - if (!trackEvseReadyBool) return false; - return trackEvseReadyBool->getBool(); -} - -const char *Evse::getSessionIdTag() { - return getTransactionIdTag(connectorId) ? getTransactionIdTag(connectorId) : ""; -} - -int Evse::getTransactionId() { - return getTransaction(connectorId) ? getTransaction(connectorId)->getTransactionId() : -1; -} - -bool Evse::chargingPermitted() { - return ocppPermitsCharge(connectorId); -} - -int Evse::getPower() { - return (int) simulate_power; -} - -float Evse::getVoltage() { - if (getPower() > 1.f) { - return 228.f + (((mocpp_tick_ms() / 5000) * 7484311) % 4000) * 0.001f; - } else { - return 0.f; - } -} diff --git a/src/evse.h b/src/evse.h deleted file mode 100644 index eaf37dc..0000000 --- a/src/evse.h +++ /dev/null @@ -1,113 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#ifndef EVSE_H -#define EVSE_H - -#include -#include -#include -#include - -#define SIMULATOR_FN MO_FILENAME_PREFIX "simulator.jsn" - -class Evse { -private: - const unsigned int connectorId; - - std::shared_ptr trackEvPluggedBool; - std::string trackEvPluggedKey; - std::shared_ptr trackEvsePluggedBool; - std::string trackEvsePluggedKey; - std::shared_ptr trackEvReadyBool; - std::string trackEvReadyKey; - std::shared_ptr trackEvseReadyBool; - std::string trackEvseReadyKey; - - const float SIMULATE_POWER_CONST = 11000.f; - float simulate_power = 0; - float limit_power = 11000.f; - const float SIMULATE_ENERGY_DELTA_MS = SIMULATE_POWER_CONST / (3600.f * 1000.f); - unsigned long simulate_energy_track_time = 0; - float simulate_energy = 0; - - std::string status; -public: - Evse(unsigned int connectorId); - - void setup(); - - void loop(); - - void presentNfcTag(const char *uid); - -#if MO_ENABLE_V201 - bool presentNfcTag(const char *uid, const char *type); -#endif //MO_ENABLE_V201 - - void setEvPlugged(bool plugged); - - bool getEvPlugged(); - - void setEvsePlugged(bool plugged); - - bool getEvsePlugged(); - - void setEvReady(bool ready); - - bool getEvReady(); - - void setEvseReady(bool ready); - - bool getEvseReady(); - - const char *getSessionIdTag(); - int getTransactionId(); - bool chargingPermitted(); - - bool isCharging() { - return chargingPermitted() && trackEvReadyBool->getBool(); - } - - const char *getOcppStatus() { - return status.c_str(); - } - - unsigned int getConnectorId() { - return connectorId; - } - - int getEnergy() { - return (int) simulate_energy; - } - - int getPower(); - - float getVoltage(); - - float getCurrent() { - float volts = getVoltage(); - if (volts <= 0.f) { - return 0.f; - } - return 0.333f * (float) getPower() / volts; - } - - int getSmartChargingMaxPower() { - return limit_power; - } - - float getSmartChargingMaxCurrent() { - float volts = getVoltage(); - if (volts <= 0.f) { - return 0.f; - } - return 0.333f * (float) getSmartChargingMaxPower() / volts; - } - -}; - -extern std::array connectors; - -#endif diff --git a/src/main.cpp b/src/main.cpp deleted file mode 100644 index 0e945fd..0000000 --- a/src/main.cpp +++ /dev/null @@ -1,233 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#include -#include - -#include - -#include -#include -#include -#include "evse.h" -#include "api.h" - -#include - -#if MO_NUMCONNECTORS == 3 -std::array connectors {{1,2}}; -#else -std::array connectors {{1}}; -#endif - -bool g_isOcpp201 = false; -bool g_runSimulator = true; - -bool g_isUpAndRunning = false; //if the initial BootNotification and StatusNotifications got through + 1s delay -unsigned int g_bootNotificationTime = 0; - -#define MO_NETLIB_MONGOOSE 1 -#define MO_NETLIB_WASM 2 - - -#if MO_NETLIB == MO_NETLIB_MONGOOSE -#include "mongoose.h" -#include - -#include "net_mongoose.h" - -struct mg_mgr mgr; -MicroOcpp::MOcppMongooseClient *osock; - -#elif MO_NETLIB == MO_NETLIB_WASM -#include - -#include - -#include "net_wasm.h" - -MicroOcpp::Connection *conn = nullptr; - -#else -#error Please ensure that build flag MO_NETLIB is set as MO_NETLIB_MONGOOSE or MO_NETLIB_WASM -#endif - -#if MBEDTLS_PLATFORM_MEMORY //configure MbedTLS with allocation hook functions - -void *mo_mem_mbedtls_calloc( size_t n, size_t count ) { - size_t size = n * count; - auto ptr = MO_MALLOC("MbedTLS", size); - if (ptr) { - memset(ptr, 0, size); - } - return ptr; -} -void mo_mem_mbedtls_free( void *ptr ) { - MO_FREE(ptr); -} - -#endif //MBEDTLS_PLATFORM_MEMORY - -void mo_sim_sig_handler(int s){ - - if (!g_runSimulator) { //already tried to shut down, now force stop - exit(EXIT_FAILURE); - } - - g_runSimulator = false; //shut down simulator gracefully -} - -/* - * Setup MicroOcpp and API - */ -void load_ocpp_version(std::shared_ptr filesystem) { - - MicroOcpp::configuration_init(filesystem); - - #if MO_ENABLE_V201 - { - auto protocolVersion_stored = MicroOcpp::declareConfiguration("OcppVersion", "1.6", SIMULATOR_FN, false, false, false); - MicroOcpp::configuration_load(SIMULATOR_FN); - if (!strcmp(protocolVersion_stored->getString(), "2.0.1")) { - //select OCPP 2.0.1 - g_isOcpp201 = true; - return; - } - } - #endif //MO_ENABLE_V201 - - g_isOcpp201 = false; -} - -void app_setup(MicroOcpp::Connection& connection, std::shared_ptr filesystem) { - mocpp_initialize(connection, - g_isOcpp201 ? - ChargerCredentials::v201("MicroOcpp Simulator", "MicroOcpp") : - ChargerCredentials("MicroOcpp Simulator", "MicroOcpp"), - filesystem, - false, - g_isOcpp201 ? - MicroOcpp::ProtocolVersion{2,0,1} : - MicroOcpp::ProtocolVersion{1,6} - ); - - for (unsigned int i = 0; i < connectors.size(); i++) { - connectors[i].setup(); - } -} - -/* - * Execute one loop iteration - */ -void app_loop() { - mocpp_loop(); - for (unsigned int i = 0; i < connectors.size(); i++) { - connectors[i].loop(); - } -} - -#if MO_NETLIB == MO_NETLIB_MONGOOSE - -#ifndef MO_SIM_ENDPOINT_URL -#define MO_SIM_ENDPOINT_URL "http://0.0.0.0:8000" //URL to forward to mg_http_listen(). Will be ignored if the URL field exists in api.jsn -#endif - -int main() { - -#if MBEDTLS_PLATFORM_MEMORY - mbedtls_platform_set_calloc_free(mo_mem_mbedtls_calloc, mo_mem_mbedtls_free); -#endif //MBEDTLS_PLATFORM_MEMORY - - struct sigaction sigIntHandler; - sigIntHandler.sa_handler = mo_sim_sig_handler; - sigemptyset(&sigIntHandler.sa_mask); - sigIntHandler.sa_flags = 0; - sigaction(SIGINT, &sigIntHandler, NULL); - - mg_log_set(MG_LL_INFO); - mg_mgr_init(&mgr); - - auto filesystem = MicroOcpp::makeDefaultFilesystemAdapter(MicroOcpp::FilesystemOpt::Use_Mount_FormatOnFail); - - load_ocpp_version(filesystem); - - struct mg_str api_cert = mg_file_read(&mg_fs_posix, MO_FILENAME_PREFIX "api_cert.pem"); - struct mg_str api_key = mg_file_read(&mg_fs_posix, MO_FILENAME_PREFIX "api_key.pem"); - - auto api_settings_doc = MicroOcpp::FilesystemUtils::loadJson(filesystem, MO_FILENAME_PREFIX "api.jsn", "Simulator"); - if (!api_settings_doc) { - api_settings_doc = MicroOcpp::makeJsonDoc("Simulator", 0); - } - JsonObject api_settings = api_settings_doc->as(); - - const char *api_url = api_settings["url"] | MO_SIM_ENDPOINT_URL; - - mg_http_listen(&mgr, api_url, http_serve, (void*)api_url); // Create listening connection - - osock = new MicroOcpp::MOcppMongooseClient(&mgr, - "ws://echo.websocket.events", - "charger-01", - "", - "", - filesystem, - g_isOcpp201 ? - MicroOcpp::ProtocolVersion{2,0,1} : - MicroOcpp::ProtocolVersion{1,6} - ); - - server_initialize(osock, api_cert.buf ? api_cert.buf : "", api_key.buf ? api_key.buf : "", api_settings["user"] | "", api_settings["pass"] | ""); - app_setup(*osock, filesystem); - - setOnResetExecute([] (bool isHard) { - g_runSimulator = false; - }); - - while (g_runSimulator) { //Run Simulator until OCPP Reset is executed or user presses Ctrl+C - mg_mgr_poll(&mgr, 100); - app_loop(); - - if (!g_bootNotificationTime && getOcppContext()->getModel().getClock().now() >= MicroOcpp::MIN_TIME) { - //time has been set, BootNotification succeeded - g_bootNotificationTime = mocpp_tick_ms(); - } - - if (!g_isUpAndRunning && g_bootNotificationTime && mocpp_tick_ms() - g_bootNotificationTime >= 1000) { - printf("[Sim] Resetting maximum heap usage after boot success\n"); - g_isUpAndRunning = true; - MO_MEM_RESET(); - } - } - - printf("[Sim] Shutting down Simulator\n"); - - MO_MEM_PRINT_STATS(); - - mocpp_deinitialize(); - - delete osock; - mg_mgr_free(&mgr); - free(api_cert.buf); - free(api_key.buf); - return 0; -} - -#elif MO_NETLIB == MO_NETLIB_WASM - -int main() { - - printf("[WASM] start\n"); - - auto filesystem = MicroOcpp::makeDefaultFilesystemAdapter(MicroOcpp::FilesystemOpt::Deactivate); - - conn = wasm_ocpp_connection_init(nullptr, nullptr, nullptr); - - app_setup(*conn, filesystem); - - const int LOOP_FREQ = 10; //called 10 times per second - const int BLOCK_INFINITELY = 0; //0 for non-blocking execution, 1 for blocking infinitely - emscripten_set_main_loop(app_loop, LOOP_FREQ, BLOCK_INFINITELY); - - printf("[WASM] setup complete\n"); -} -#endif diff --git a/src/net_mongoose.cpp b/src/net_mongoose.cpp deleted file mode 100644 index e203279..0000000 --- a/src/net_mongoose.cpp +++ /dev/null @@ -1,160 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#include "net_mongoose.h" -#include "evse.h" -#include "api.h" -#include -#include -#include -#include -#include - -//cors_headers allow the browser to make requests from any domain, allowing all headers and all methods -#define DEFAULT_HEADER "Content-Type: application/json\r\n" -#define CORS_HEADERS "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Headers:Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers\r\nAccess-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT\r\n" - -MicroOcpp::MOcppMongooseClient *ao_sock = nullptr; -const char *api_cert = ""; -const char *api_key = ""; -const char *api_user = ""; -const char *api_pass = ""; - -void server_initialize(MicroOcpp::MOcppMongooseClient *osock, const char *cert, const char *key, const char *user, const char *pass) { - ao_sock = osock; - api_cert = cert; - api_key = key; - api_user = user; - api_pass = pass; -} - -bool api_check_basic_auth(const char *user, const char *pass) { - if (strcmp(api_user, user)) { - return false; - } - if (strcmp(api_pass, pass)) { - return false; - } - return true; -} - -void http_serve(struct mg_connection *c, int ev, void *ev_data) { - if (ev == MG_EV_ACCEPT) { - if (mg_url_is_ssl((const char*)c->fn_data)) { // TLS listener! - MO_DBG_VERBOSE("API TLS setup"); - struct mg_tls_opts opts = {0}; - opts.cert = mg_str(api_cert); - opts.key = mg_str(api_key); - mg_tls_init(c, &opts); - } - } else if (ev == MG_EV_HTTP_MSG) { - //struct mg_http_message *message_data = (struct mg_http_message *) ev_data; - struct mg_http_message *message_data = reinterpret_cast(ev_data); - const char *final_headers = DEFAULT_HEADER CORS_HEADERS; - - char user[64], pass[64]; - mg_http_creds(message_data, user, sizeof(user), pass, sizeof(pass)); - if (!api_check_basic_auth(user, pass)) { - mg_http_reply(c, 401, final_headers, "Unauthorized. Expect Basic Auth user and / or password\n"); - return; - } - - struct mg_str json = message_data->body; - - MO_DBG_VERBOSE("%.*s", 20, message_data->uri.buf); - - MicroOcpp::Method method = MicroOcpp::Method::UNDEFINED; - - if (!mg_strcasecmp(message_data->method, mg_str("POST"))) { - method = MicroOcpp::Method::POST; - MO_DBG_VERBOSE("POST"); - } else if (!mg_strcasecmp(message_data->method, mg_str("GET"))) { - method = MicroOcpp::Method::GET; - MO_DBG_VERBOSE("GET"); - } - - //start different api endpoints - if(mg_match(message_data->uri, mg_str("/api/websocket"), NULL)){ - MO_DBG_VERBOSE("query websocket"); - auto webSocketPingIntervalInt = MicroOcpp::declareConfiguration("WebSocketPingInterval", 10, MO_WSCONN_FN); - auto reconnectIntervalInt = MicroOcpp::declareConfiguration(MO_CONFIG_EXT_PREFIX "ReconnectInterval", 30, MO_WSCONN_FN); - - if (method == MicroOcpp::Method::POST) { - if (auto val = mg_json_get_str(json, "$.backendUrl")) { - ao_sock->setBackendUrl(val); - } - if (auto val = mg_json_get_str(json, "$.chargeBoxId")) { - ao_sock->setChargeBoxId(val); - } - if (auto val = mg_json_get_str(json, "$.authorizationKey")) { - ao_sock->setAuthKey(val); - } - ao_sock->reloadConfigs(); - { - auto val = mg_json_get_long(json, "$.pingInterval", -1); - if (val > 0) { - webSocketPingIntervalInt->setInt(val); - } - } - { - auto val = mg_json_get_long(json, "$.reconnectInterval", -1); - if (val > 0) { - reconnectIntervalInt->setInt(val); - } - } - if (auto val = mg_json_get_str(json, "$.dnsUrl")) { - MO_DBG_WARN("dnsUrl not implemented"); - (void)val; - } - MicroOcpp::configuration_save(); - } - StaticJsonDocument<256> doc; - doc["backendUrl"] = ao_sock->getBackendUrl(); - doc["chargeBoxId"] = ao_sock->getChargeBoxId(); - doc["authorizationKey"] = ao_sock->getAuthKey(); - doc["pingInterval"] = webSocketPingIntervalInt->getInt(); - doc["reconnectInterval"] = reconnectIntervalInt->getInt(); - std::string serialized; - serializeJson(doc, serialized); - mg_http_reply(c, 200, final_headers, serialized.c_str()); - return; - } else if (strncmp(message_data->uri.buf, "/api", strlen("api")) == 0) { - #define RESP_BUF_SIZE 8192 - char resp_buf [RESP_BUF_SIZE]; - - //replace endpoint-body separator by null - if (char *c = strchr((char*) message_data->uri.buf, ' ')) { - *c = '\0'; - } - - int status = 404; - if (status == 404) { - status = mocpp_api2_call( - message_data->uri.buf + strlen("/api"), - message_data->uri.len - strlen("/api"), - method, - message_data->query.buf, - message_data->query.len, - resp_buf, RESP_BUF_SIZE); - } - if (status == 404) { - status = mocpp_api_call( - message_data->uri.buf + strlen("/api"), - method, - message_data->body.buf, - resp_buf, RESP_BUF_SIZE); - } - - mg_http_reply(c, status, final_headers, resp_buf); - } else if (mg_match(message_data->uri, mg_str("/"), NULL)) { //if no specific path is given serve dashboard application file - struct mg_http_serve_opts opts; - memset(&opts, 0, sizeof(opts)); - opts.root_dir = "./public"; - opts.extra_headers = "Content-Type: text/html\r\nContent-Encoding: gzip\r\n"; - mg_http_serve_file(c, message_data, "public/bundle.html.gz", &opts); - } else { - mg_http_reply(c, 404, final_headers, "API endpoint not found"); - } - } -} diff --git a/src/net_mongoose.h b/src/net_mongoose.h deleted file mode 100644 index aa88717..0000000 --- a/src/net_mongoose.h +++ /dev/null @@ -1,22 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#ifndef MO_NET_MONGOOSE_H -#define MO_NET_MONGOOSE_H - -#if MO_NETLIB == MO_NETLIB_MONGOOSE - -#include "mongoose.h" - -namespace MicroOcpp { -class MOcppMongooseClient; -} - -void server_initialize(MicroOcpp::MOcppMongooseClient *osock, const char *cert = "", const char *key = "", const char *user = "", const char *pass = ""); - -void http_serve(struct mg_connection *c, int ev, void *ev_data); - -#endif //MO_NETLIB == MO_NETLIB_MONGOOSE - -#endif diff --git a/src/net_wasm.cpp b/src/net_wasm.cpp deleted file mode 100644 index 99ac1f2..0000000 --- a/src/net_wasm.cpp +++ /dev/null @@ -1,439 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#include "net_wasm.h" - -#include -#include -#include - -#include -#include -#include - -#include "api.h" - -#define DEBUG_MSG_INTERVAL 5000UL -#define WS_UNRESPONSIVE_THRESHOLD_MS 15000UL - -using namespace MicroOcpp; - -class WasmOcppConnection : public Connection { -private: - EMSCRIPTEN_WEBSOCKET_T websocket; - std::string backend_url; - std::string cb_id; - std::string url; //url = backend_url + '/' + cb_id - std::string auth_key; - std::string basic_auth64; - std::shared_ptr setting_backend_url_str; - std::shared_ptr setting_cb_id_str; - std::shared_ptr setting_auth_key_str; - unsigned long last_status_dbg_msg {0}, last_recv {0}; - std::shared_ptr reconnect_interval_int; //minimum time between two connect trials in s - unsigned long last_reconnection_attempt {-1UL / 2UL}; - std::shared_ptr stale_timeout_int; //inactivity period after which the connection will be closed - std::shared_ptr ws_ping_interval_int; //heartbeat intervall in s. 0 sets hb off - unsigned long last_hb {0}; - bool connection_established {false}; - unsigned long last_connection_established {-1UL / 2UL}; - bool connection_closing {false}; - ReceiveTXTcallback receiveTXTcallback = [] (const char *, size_t) {return false;}; - - void maintainWsConn() { - if (mocpp_tick_ms() - last_status_dbg_msg >= DEBUG_MSG_INTERVAL) { - last_status_dbg_msg = mocpp_tick_ms(); - - //WS successfully connected? - if (!isConnectionOpen()) { - MO_DBG_DEBUG("WS unconnected"); - } else if (mocpp_tick_ms() - last_recv >= (ws_ping_interval_int && ws_ping_interval_int->getInt() > 0 ? (ws_ping_interval_int->getInt() * 1000UL) : 0UL) + WS_UNRESPONSIVE_THRESHOLD_MS) { - //WS connected but unresponsive - MO_DBG_DEBUG("WS unresponsive"); - } - } - - if (websocket && isConnectionOpen() && - stale_timeout_int && stale_timeout_int->getInt() > 0 && mocpp_tick_ms() - last_recv >= (stale_timeout_int->getInt() * 1000UL)) { - MO_DBG_INFO("connection %s -- stale, reconnect", url.c_str()); - reconnect(); - return; - } - - if (websocket && isConnectionOpen() && - ws_ping_interval_int && ws_ping_interval_int->getInt() > 0 && mocpp_tick_ms() - last_hb >= (ws_ping_interval_int->getInt() * 1000UL)) { - last_hb = mocpp_tick_ms(); - MO_DBG_VERBOSE("omit heartbeat"); - } - - if (websocket != NULL) { //connection pointer != NULL means that the socket is still open - return; - } - - if (url.empty()) { - //cannot open OCPP connection: credentials missing - return; - } - - if (reconnect_interval_int && reconnect_interval_int->getInt() > 0 && mocpp_tick_ms() - last_reconnection_attempt < (reconnect_interval_int->getInt() * 1000UL)) { - return; - } - - MO_DBG_DEBUG("(re-)connect to %s", url.c_str()); - - last_reconnection_attempt = mocpp_tick_ms(); - - EmscriptenWebSocketCreateAttributes attr; - emscripten_websocket_init_create_attributes(&attr); - - attr.url = url.c_str(); - attr.protocols = "ocpp1.6"; - attr.createOnMainThread = true; - - websocket = emscripten_websocket_new(&attr); - if (websocket < 0) { - MO_DBG_ERR("emscripten_websocket_new: %i", websocket); - websocket = 0; - } - - if (websocket <= 0) { - return; - } - - auto ret_open = emscripten_websocket_set_onopen_callback( - websocket, - this, - [] (int eventType, const EmscriptenWebSocketOpenEvent *websocketEvent, void *userData) -> EM_BOOL { - WasmOcppConnection *conn = reinterpret_cast(userData); - MO_DBG_DEBUG("on open eventType: %i", eventType); - MO_DBG_INFO("connection %s -- connected!", conn->getUrl()); - conn->setConnectionOpen(true); - conn->updateRcvTimer(); - return true; - }); - if (ret_open < 0) { - MO_DBG_ERR("emscripten_websocket_set_onopen_callback: %i", ret_open); - } - - auto ret_message = emscripten_websocket_set_onmessage_callback( - websocket, - this, - [] (int eventType, const EmscriptenWebSocketMessageEvent *websocketEvent, void *userData) -> EM_BOOL { - WasmOcppConnection *conn = reinterpret_cast(userData); - MO_DBG_DEBUG("evenType: %i", eventType); - MO_DBG_DEBUG("txt: %s", websocketEvent->data ? (const char*) websocketEvent->data : "undefined"); - if (!conn->getReceiveTXTcallback()((const char*) websocketEvent->data, websocketEvent->numBytes)) { - MO_DBG_WARN("processing input message failed"); - } - conn->updateRcvTimer(); - return true; - }); - if (ret_message < 0) { - MO_DBG_ERR("emscripten_websocket_set_onmessage_callback: %i", ret_message); - } - - auto ret_err = emscripten_websocket_set_onerror_callback( - websocket, - this, - [] (int eventType, const EmscriptenWebSocketErrorEvent *websocketEvent, void *userData) -> EM_BOOL { - WasmOcppConnection *conn = reinterpret_cast(userData); - MO_DBG_DEBUG("on error eventType: %i", eventType); - MO_DBG_INFO("connection %s -- %s", conn->getUrl(), "error"); - conn->cleanConnection(); - return true; - }); - if (ret_open < 0) { - MO_DBG_ERR("emscripten_websocket_set_onopen_callback: %i", ret_open); - } - - auto ret_close = emscripten_websocket_set_onclose_callback( - websocket, - this, - [] (int eventType, const EmscriptenWebSocketCloseEvent *websocketEvent, void *userData) -> EM_BOOL { - WasmOcppConnection *conn = reinterpret_cast(userData); - MO_DBG_DEBUG("on close eventType: %i", eventType); - MO_DBG_INFO("connection %s -- %s", conn->getUrl(), "closed"); - conn->cleanConnection(); - return true; - }); - if (ret_open < 0) { - MO_DBG_ERR("emscripten_websocket_set_onopen_callback: %i", ret_open); - } - } - - void reconnect() { - if (!websocket) { - return; - } - auto ret = emscripten_websocket_close(websocket, 1000, "reconnect"); - if (ret < 0) { - MO_DBG_ERR("emscripten_websocket_close: %i", ret); - } - setConnectionOpen(false); - } - -public: - WasmOcppConnection( - const char *backend_url_factory, - const char *charge_box_id_factory, - const char *auth_key_factory) { - - setting_backend_url_str = declareConfiguration( - MO_CONFIG_EXT_PREFIX "BackendUrl", backend_url_factory, CONFIGURATION_VOLATILE, true, true); - setting_cb_id_str = declareConfiguration( - MO_CONFIG_EXT_PREFIX "ChargeBoxId", charge_box_id_factory, CONFIGURATION_VOLATILE, true, true); - setting_auth_key_str = declareConfiguration( - "AuthorizationKey", auth_key_factory, CONFIGURATION_VOLATILE, true, true); - ws_ping_interval_int = declareConfiguration( - "WebSocketPingInterval", 5, CONFIGURATION_VOLATILE); - reconnect_interval_int = declareConfiguration( - MO_CONFIG_EXT_PREFIX "ReconnectInterval", 10, CONFIGURATION_VOLATILE); - stale_timeout_int = declareConfiguration( - MO_CONFIG_EXT_PREFIX "StaleTimeout", 300, CONFIGURATION_VOLATILE); - - reloadConfigs(); //load WS creds with configs values - - MO_DBG_DEBUG("connection initialized"); - - maintainWsConn(); - } - - ~WasmOcppConnection() { - if (websocket) { - emscripten_websocket_delete(websocket); - websocket = NULL; - } - } - - void loop() override { - maintainWsConn(); - } - - bool sendTXT(const char *msg, size_t length) override { - if (!websocket || !isConnectionOpen()) { - return false; - } - - if (auto ret = emscripten_websocket_send_utf8_text(websocket, msg) < 0) { - MO_DBG_ERR("emscripten_websocket_send_utf8_text: %i", ret); - return false; - } - - return true; - } - - void setReceiveTXTcallback(MicroOcpp::ReceiveTXTcallback &receiveTXT) override { - this->receiveTXTcallback = receiveTXT; - } - - MicroOcpp::ReceiveTXTcallback &getReceiveTXTcallback() { - return receiveTXTcallback; - } - - void setBackendUrl(const char *backend_url_cstr) { - if (!backend_url_cstr) { - MO_DBG_ERR("invalid argument"); - return; - } - - if (setting_backend_url_str) { - setting_backend_url_str->setString(backend_url_cstr); - configuration_save(); - } - } - - void setChargeBoxId(const char *cb_id_cstr) { - if (!cb_id_cstr) { - MO_DBG_ERR("invalid argument"); - return; - } - - if (setting_cb_id_str) { - setting_cb_id_str->setString(cb_id_cstr); - configuration_save(); - } - } - - void setAuthKey(const char *auth_key_cstr) { - if (!auth_key_cstr) { - MO_DBG_ERR("invalid argument"); - return; - } - - if (setting_auth_key_str) { - setting_auth_key_str->setString(auth_key_cstr); - configuration_save(); - } - } - - void reloadConfigs() { - - reconnect(); //closes WS connection; will be reopened in next maintainWsConn execution - - /* - * reload WS credentials from configs - */ - if (setting_backend_url_str) { - backend_url = setting_backend_url_str->getString(); - } - - if (setting_cb_id_str) { - cb_id = setting_cb_id_str->getString(); - } - - if (setting_auth_key_str) { - auth_key = setting_auth_key_str->getString(); - } - - /* - * determine new URL and auth token with updated WS credentials - */ - - url.clear(); - basic_auth64.clear(); - - if (backend_url.empty()) { - MO_DBG_DEBUG("empty URL closes connection"); - return; - } else { - url = backend_url; - - if (url.back() != '/' && !cb_id.empty()) { - url.append("/"); - } - - url.append(cb_id); - } - - if (!auth_key.empty()) { - MO_DBG_WARN("WASM app does not support Securiy Profile 2 yet"); - } else { - MO_DBG_DEBUG("no authentication"); - (void) 0; - } - } - - const char *getBackendUrl() {return backend_url.c_str();} - const char *getChargeBoxId() {return cb_id.c_str();} - const char *getAuthKey() {return auth_key.c_str();} - - const char *getUrl() {return url.c_str();} - - void setConnectionOpen(bool open) { - if (open) { - connection_established = true; - last_connection_established = mocpp_tick_ms(); - } else { - connection_closing = true; - } - } - bool isConnectionOpen() {return connection_established && !connection_closing;} - void cleanConnection() { - connection_established = false; - connection_closing = false; - websocket = NULL; - } - - void updateRcvTimer() { - last_recv = mocpp_tick_ms(); - } - unsigned long getLastRecv() override { - return last_recv; - } - unsigned long getLastConnected() override { - return last_connection_established; - } - -}; - -WasmOcppConnection *wasm_ocpp_connection_instance = nullptr; - -MicroOcpp::Connection *wasm_ocpp_connection_init(const char *backend_url_default, const char *charge_box_id_default, const char *auth_key_default) { - if (!wasm_ocpp_connection_instance) { - wasm_ocpp_connection_instance = new WasmOcppConnection(backend_url_default, charge_box_id_default, auth_key_default); - } - - return wasm_ocpp_connection_instance; -} - -#define MO_WASM_RESP_BUF_SIZE 1024 -char wasm_resp_buf [MO_WASM_RESP_BUF_SIZE] = {'\0'}; - -//exported to WebAssembly -extern "C" char* mocpp_wasm_api_call(const char *endpoint, const char *method, const char *body) { - MO_DBG_DEBUG("API call: %s, %s, %s", endpoint, method, body); - - auto method_parsed = Method::UNDEFINED; - if (!strcmp(method, "GET")) { - method_parsed = Method::GET; - } else if (!strcmp(method, "POST")) { - method_parsed = Method::POST; - } - - //handle endpoint /websocket - if (!strcmp(endpoint, "/websocket")) { - sprintf(wasm_resp_buf, "%s", "{}"); - if (!wasm_ocpp_connection_instance) { - MO_DBG_ERR("no websocket instance"); - return nullptr; - } - StaticJsonDocument<512> request; - if (*body) { - auto err = deserializeJson(request, body); - if (err) { - MO_DBG_WARN("malformatted body: %s", err.c_str()); - return nullptr; - } - } - - auto webSocketPingInterval = declareConfiguration("WebSocketPingInterval", 5, CONFIGURATION_VOLATILE); - auto reconnectInterval = declareConfiguration(MO_CONFIG_EXT_PREFIX "ReconnectInterval", 10, CONFIGURATION_VOLATILE); - - if (method_parsed == Method::POST) { - if (request.containsKey("backendUrl")) { - wasm_ocpp_connection_instance->setBackendUrl(request["backendUrl"] | ""); - } - if (request.containsKey("chargeBoxId")) { - wasm_ocpp_connection_instance->setChargeBoxId(request["chargeBoxId"] | ""); - } - if (request.containsKey("authorizationKey")) { - wasm_ocpp_connection_instance->setAuthKey(request["authorizationKey"] | ""); - } - wasm_ocpp_connection_instance->reloadConfigs(); - if (request.containsKey("pingInterval")) { - webSocketPingInterval->setInt(request["pingInterval"] | 0); - } - if (request.containsKey("reconnectInterval")) { - reconnectInterval->setInt(request["reconnectInterval"] | 0); - } - if (request.containsKey("dnsUrl")) { - MO_DBG_WARN("dnsUrl not implemented"); - (void)0; - } - MicroOcpp::configuration_save(); - } - - StaticJsonDocument<512> response; - response["backendUrl"] = wasm_ocpp_connection_instance->getBackendUrl(); - response["chargeBoxId"] = wasm_ocpp_connection_instance->getChargeBoxId(); - response["authorizationKey"] = wasm_ocpp_connection_instance->getAuthKey(); - - response["pingInterval"] = webSocketPingInterval ? webSocketPingInterval->getInt() : 0; - response["reconnectInterval"] = reconnectInterval ? reconnectInterval->getInt() : 0; - serializeJson(response, wasm_resp_buf, MO_WASM_RESP_BUF_SIZE); - return wasm_resp_buf; - } - - //forward all other endpoints to main API - int status = mocpp_api_call(endpoint, method_parsed, body, wasm_resp_buf, MO_WASM_RESP_BUF_SIZE); - - if (status == 200) { - //200: HTTP status code Success - MO_DBG_DEBUG("API resp: %s", wasm_resp_buf); - return wasm_resp_buf; - } else { - MO_DBG_DEBUG("API err: %i", status); - return nullptr; - } -} diff --git a/src/net_wasm.h b/src/net_wasm.h deleted file mode 100644 index bca1b5e..0000000 --- a/src/net_wasm.h +++ /dev/null @@ -1,16 +0,0 @@ -// matth-x/MicroOcppSimulator -// Copyright Matthias Akstaller 2022 - 2024 -// GPL-3.0 License - -#ifndef MO_NET_WASM_H -#define MO_NET_WASM_H - -#if MO_NETLIB == MO_NETLIB_WASM - -#include - -MicroOcpp::Connection *wasm_ocpp_connection_init(const char *backend_url_default, const char *charge_box_id_default, const char *auth_key_default); - -#endif //MO_NETLIB == MO_NETLIB_WASM - -#endif diff --git a/webapp-src b/webapp-src deleted file mode 160000 index 015a0e8..0000000 --- a/webapp-src +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 015a0e816ca4fc617e67acdbe7d067688d6b3939