├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .dockerignore ├── .github └── workflows │ ├── build_docker.yml │ ├── build_ubuntu.yml │ └── build_wasm.yml ├── .gitignore ├── .gitmodules ├── CMakeLists.txt ├── Dockerfile ├── LICENSE ├── README.md ├── build-webapp ├── build_webapp.ps1 ├── build_webapp.sh └── install_webassembly.sh ├── mo_store └── README.md ├── public └── bundle.html.gz └── src ├── api.cpp ├── api.h ├── evse.cpp ├── evse.h ├── main.cpp ├── net_mongoose.cpp ├── net_mongoose.h ├── net_wasm.cpp └── net_wasm.h /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/ubuntu/.devcontainer/base.Dockerfile 2 | 3 | # [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 4 | ARG VARIANT="jammy" 5 | FROM mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT} 6 | 7 | # [Optional] Uncomment this section to install additional OS packages. 8 | RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 9 | && apt-get -y install --no-install-recommends build-essential 10 | 11 | 12 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: 2 | // https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/ubuntu 3 | { 4 | "name": "Ubuntu", 5 | "build": { 6 | "dockerfile": "Dockerfile", 7 | // Update 'VARIANT' to pick an Ubuntu version: jammy / ubuntu-22.04, focal / ubuntu-20.04, bionic /ubuntu-18.04 8 | // Use ubuntu-22.04 or ubuntu-18.04 on local arm64/Apple Silicon. 9 | "args": { "VARIANT": "ubuntu-22.04" } 10 | }, 11 | 12 | // Use 'postCreateCommand' to run commands after the container is created. 13 | // "postCreateCommand": "uname -a", 14 | 15 | // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 16 | "remoteUser": "vscode", 17 | "forwardPorts": [8000] 18 | } 19 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /.github/workflows/build_docker.yml: -------------------------------------------------------------------------------- 1 | name: Docker 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | pull_request: 9 | 10 | jobs: 11 | 12 | compile-ubuntu-docker: 13 | name: Build Docker image 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Check out repository code 17 | uses: actions/checkout@v3 18 | with: 19 | submodules: recursive 20 | - name: Get Docker 21 | run: | 22 | sudo apt update 23 | sudo apt install docker 24 | - name: Build Docker image 25 | run: docker build -t matthx/microocppsimulator:latest . 26 | -------------------------------------------------------------------------------- /.github/workflows/build_ubuntu.yml: -------------------------------------------------------------------------------- 1 | name: Ubuntu 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | pull_request: 9 | 10 | jobs: 11 | 12 | compile-ubuntu-native: 13 | name: Compile for Ubuntu 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Check out repository code 17 | uses: actions/checkout@v3 18 | with: 19 | submodules: recursive 20 | - name: Get compiler toolchain 21 | run: | 22 | sudo apt update 23 | sudo apt install cmake libssl-dev build-essential 24 | - name: Generate CMake files 25 | run: cmake -S . -B ./build 26 | - name: Compile 27 | run: cmake --build ./build -j 16 --target mo_simulator 28 | -------------------------------------------------------------------------------- /.github/workflows/build_wasm.yml: -------------------------------------------------------------------------------- 1 | name: WebAssembly 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | pull_request: 9 | 10 | jobs: 11 | 12 | compile-esmscripten: 13 | name: Compile for WebAssembly 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Check out repository code 17 | uses: actions/checkout@v3 18 | with: 19 | submodules: recursive 20 | - name: Set up emscripten 21 | uses: mymindstorm/setup-emsdk@v11 22 | - name: Verify 23 | run: emcc -v 24 | - name: Generate CMake files 25 | run: emcmake cmake -S . -B ./build 26 | - name: Compile 27 | run: cmake --build ./build -j 16 --target mo_simulator_wasm 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vs 2 | *.exe 3 | *.obj 4 | build_and_run.sh 5 | mo_store/* 6 | !mo_store/README.md 7 | build 8 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/ArduinoJson"] 2 | path = lib/ArduinoJson 3 | url = https://github.com/bblanchon/ArduinoJson.git 4 | [submodule "lib/MicroOcpp"] 5 | path = lib/MicroOcpp 6 | url = https://github.com/matth-x/MicroOcpp 7 | [submodule "lib/MicroOcppMongoose"] 8 | path = lib/MicroOcppMongoose 9 | url = https://github.com/matth-x/MicroOcppMongoose 10 | [submodule "lib/mongoose"] 11 | path = lib/mongoose 12 | url = https://github.com/cesanta/mongoose 13 | [submodule "webapp-src"] 14 | path = webapp-src 15 | url = https://github.com/agruenb/arduino-ocpp-dashboard.git 16 | [submodule "lib/mbedtls"] 17 | path = lib/mbedtls 18 | url = https://github.com/Mbed-TLS/mbedtls 19 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # matth-x/MicroOcppSimulator 2 | # Copyright Matthias Akstaller 2022 - 2024 3 | # GPL-3.0 License 4 | 5 | cmake_minimum_required(VERSION 3.13) 6 | 7 | set(CMAKE_CXX_STANDARD 11) 8 | 9 | set(MO_SIM_SRC 10 | src/evse.cpp 11 | src/main.cpp 12 | src/api.cpp 13 | ) 14 | 15 | set(MO_SIM_MG_SRC 16 | src/net_mongoose.cpp 17 | lib/mongoose/mongoose.c 18 | ) 19 | 20 | set(MO_SIM_WASM_SRC 21 | src/net_wasm.cpp 22 | ) 23 | 24 | project(MicroOcppSimulator 25 | VERSION 0.0.1) 26 | 27 | set(CMAKE_CXX_STANDARD 11) 28 | set(CMAKE_CXX_STANDARD_REQUIRED True) 29 | 30 | add_compile_definitions( 31 | MO_PLATFORM=MO_PLATFORM_UNIX 32 | MO_NUMCONNECTORS=3 33 | MO_TRAFFIC_OUT 34 | MO_DBG_LEVEL=MO_DL_INFO 35 | MO_FILENAME_PREFIX="./mo_store/" 36 | MO_ENABLE_V201=1 37 | MO_ENABLE_MBEDTLS=1 38 | MO_ENABLE_TIMESTAMP_MILLISECONDS=1 39 | MO_MG_USE_VERSION=MO_MG_V715 40 | ) 41 | 42 | add_executable(mo_simulator ${MO_SIM_SRC} ${MO_SIM_MG_SRC}) 43 | 44 | target_include_directories(mo_simulator PUBLIC 45 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/ArduinoJson/src" 46 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/mongoose" 47 | ) 48 | 49 | target_compile_definitions(mo_simulator PUBLIC 50 | MO_NETLIB=MO_NETLIB_MONGOOSE 51 | ) 52 | 53 | add_subdirectory(lib/MicroOcpp) 54 | target_link_libraries(mo_simulator PUBLIC MicroOcpp) 55 | 56 | # disable some warnings for MbedTLS which cause compilation errors on WASM 57 | if (${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") 58 | add_compile_options( 59 | -Wno-unused-but-set-variable 60 | -Wno-documentation 61 | ) 62 | endif() 63 | 64 | # disable MbedTLS unit tests and test suites (not needed for the Simualtor) 65 | option(ENABLE_TESTING "Build mbed TLS tests." OFF) 66 | option(ENABLE_PROGRAMS "Build mbed TLS programs." OFF) 67 | 68 | add_subdirectory(lib/mbedtls) 69 | target_link_libraries(MicroOcpp PUBLIC 70 | mbedtls 71 | mbedcrypto 72 | mbedx509 73 | ) 74 | 75 | if (MO_SIM_BUILD_USE_OPENSSL) 76 | 77 | message("Using OpenSSL for WebSocket") 78 | 79 | # find OpenSSL 80 | find_package(OpenSSL REQUIRED) 81 | target_include_directories(mo_simulator PUBLIC 82 | "${OPENSSL_INCLUDE_DIR}" 83 | ) 84 | target_link_libraries(mo_simulator PUBLIC 85 | ${OPENSSL_LIBRARIES} 86 | ) 87 | target_compile_definitions(mo_simulator PUBLIC 88 | MG_ENABLE_OPENSSL=1 89 | ) 90 | 91 | else() 92 | 93 | message("Using MbedTLS for WebSocket") 94 | 95 | target_link_libraries(mo_simulator PUBLIC 96 | mbedtls 97 | mbedcrypto 98 | mbedx509 99 | ) 100 | target_compile_definitions(mo_simulator PUBLIC 101 | MG_TLS=MG_TLS_MBED 102 | ) 103 | 104 | endif() 105 | 106 | add_subdirectory(lib/MicroOcppMongoose) 107 | target_link_libraries(mo_simulator PUBLIC MicroOcppMongoose) 108 | 109 | # experimental WebAssembly port 110 | add_executable(mo_simulator_wasm ${MO_SIM_SRC} ${MO_SIM_WASM_SRC}) 111 | 112 | target_include_directories(mo_simulator_wasm PUBLIC 113 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/ArduinoJson/src" 114 | "${CMAKE_CURRENT_SOURCE_DIR}/lib/MicroOcppMongoose/src" 115 | ) 116 | 117 | target_compile_definitions(mo_simulator_wasm PUBLIC 118 | MO_NETLIB=MO_NETLIB_WASM 119 | ) 120 | 121 | target_link_options(mo_simulator_wasm PUBLIC 122 | -lwebsocket.js 123 | -sENVIRONMENT=web 124 | -sEXPORT_NAME=createModule 125 | -sUSE_ES6_IMPORT_META=0 126 | -sEXPORTED_FUNCTIONS=_main,_mocpp_wasm_api_call 127 | -sEXPORTED_RUNTIME_METHODS=ccall,cwrap 128 | -Os 129 | ) 130 | 131 | target_link_libraries(mo_simulator_wasm PUBLIC MicroOcpp) 132 | 133 | if (${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") 134 | set(CMAKE_EXECUTABLE_SUFFIX ".mjs") 135 | endif() 136 | 137 | if(WIN32) 138 | target_link_libraries(mo_simulator PUBLIC wsock32 ws2_32) 139 | set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++ -static") 140 | endif() 141 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Use Alpine Linux as the base image 2 | FROM alpine:latest 3 | 4 | # Update package lists and install necessary dependencies 5 | RUN apk update && \ 6 | apk add --no-cache \ 7 | git \ 8 | cmake \ 9 | openssl-dev \ 10 | build-base 11 | 12 | # Set the working directory inside the container 13 | WORKDIR /MicroOcppSimulator 14 | 15 | # Copy your application files to the container's working directory 16 | COPY . . 17 | 18 | RUN git submodule init && git submodule update 19 | RUN cmake -S . -B ./build 20 | RUN cmake --build ./build -j 16 --target mo_simulator -j 16 21 | 22 | # Grant execute permissions to the shell script 23 | RUN chmod +x /MicroOcppSimulator/build/mo_simulator 24 | 25 | # Expose port 8000 26 | EXPOSE 8000 27 | 28 | # Run the shell script inside the container 29 | CMD ["./build/mo_simulator"] 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Icon   MicroOcppSimulator 2 | 3 | [![Build (Ubuntu)](https://github.com/matth-x/MicroOcppSimulator/workflows/Ubuntu/badge.svg)]((https://github.com/matth-x/MicroOcppSimulator/actions)) 4 | [![Build (Docker)](https://github.com/matth-x/MicroOcppSimulator/workflows/Docker/badge.svg)]((https://github.com/matth-x/MicroOcppSimulator/actions)) 5 | [![Build (WebAssembly)](https://github.com/matth-x/MicroOcppSimulator/workflows/WebAssembly/badge.svg)]((https://github.com/matth-x/MicroOcppSimulator/actions)) 6 | 7 | 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/) 8 | 9 | [![Screenshot](https://github.com/agruenb/arduino-ocpp-dashboard/blob/master/docs/img/status_page.png)](https://demo.micro-ocpp.com/) 10 | 11 | The Simulator has two purposes: 12 | - As a development tool, it allows to run MicroOCPP directly on the host computer and simplifies the development (no flashing of the microcontroller required) 13 | - 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. 14 | 15 | That means that the Simulator runs on your computer and connects to an OCPP server using the same software like a 16 | microcontroller. It provides a Graphical User Interface to show the connection status and to trigger simulated charging 17 | sessions (and further simulated actions). 18 | 19 | ## Running on Docker 20 | 21 | The Simulator can be run on Docker. This is the easiest way to get it up and running. The Docker image is based on 22 | Ubuntu 20.04 and contains all necessary dependencies. 23 | 24 | Firstly, build the image: 25 | 26 | ```shell 27 | docker build -t matthx/microocppsimulator:latest . 28 | ``` 29 | 30 | Then run the image: 31 | 32 | ```shell 33 | docker run -p 8000:8000 matthx/microocppsimulator:latest 34 | ``` 35 | 36 | The Simulator should be up and running now on [localhost:8000](http://localhost:8000). 37 | 38 | ## Installation (Ubuntu or WSL) 39 | 40 | On Windows, get the Windows Subsystem for Linux (WSL): [https://ubuntu.com/wsl](https://ubuntu.com/wsl) or [MSYS2](https://www.msys2.org/). 41 | 42 | Then follow the same steps like for Ubuntu. 43 | 44 | On Ubuntu (other distros probably work as well, tested on Ubuntu 20.04 and 22.04), install cmake, OpenSSL and the C++ 45 | compiler: 46 | 47 | ```shell 48 | sudo apt install cmake libssl-dev build-essential 49 | ``` 50 | 51 | Navigate to the preferred installation directory or just to the home folder. Clone the Simulator and all submodules: 52 | 53 | ```shell 54 | git clone --recurse-submodules https://github.com/matth-x/MicroOcppSimulator 55 | ``` 56 | 57 | Navigate to the copy of the Simulator and build: 58 | 59 | ```shell 60 | cd MicroOcppSimulator 61 | cmake -S . -B ./build 62 | cmake --build ./build -j 16 --target mo_simulator 63 | ``` 64 | 65 | The installation is complete! To run the Simulator, type: 66 | 67 | ```shell 68 | ./build/mo_simulator 69 | ``` 70 | 71 | This will open [localhost:8000](http://localhost:8000). You can access the Graphical User Interface by entering that 72 | address into a browser running on the same computer. Make sure that the firewall settings allow the Simulator to connect 73 | and to be reached. 74 | 75 | The Simulator should be up and running now! 76 | 77 | ## Building the Webapp (Developers) 78 | 79 | The webapp is registered as a git submodule in *webapp-src*. 80 | 81 | Before you can build the webapp, you have to create a *.env.production* file in the *webapp-src* folder. If you just 82 | want to try out the build process, you can simply duplicate the *.env.development* file and rename it. 83 | 84 | After that, to build it for deployment, all you have to do is run `./build-webapp/build_webapp.ps1` (Windows) from the 85 | root directory. 86 | For this to work NodeJS, npm and git have to be installed on your machine. The called script automatically performs the 87 | following tasks: 88 | 89 | - pull the newest version of the the [arduino-ocpp-dashboard](https://github.com/agruenb/arduino-ocpp-dashboard) 90 | - check if you have added a *.env.production* file 91 | - install webapp dependencies 92 | - build the webapp 93 | - compress the webapp 94 | - move the g-zipped bundle file into the public folder 95 | 96 | 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. 97 | 98 | ## Porting to WebAssembly (Developers) 99 | 100 | If you want to run the Simulator in the browser instead of a Linux host, you can port the code for WebAssembly. 101 | 102 | 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)). 103 | 104 | Then, create the CMake build files with the corresponding emscripten tool and change the target: 105 | 106 | ```shell 107 | emcmake cmake -S . -B ./build 108 | cmake --build ./build -j 16 --target mo_simulator_wasm 109 | ``` 110 | 111 | 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: 112 | 113 | ```shell 114 | ./build-webapp/install_webassembly.sh 115 | ``` 116 | 117 | Now, the GUI can be developed or built as described in the [webapp repository](https://github.com/agruenb/arduino-ocpp-dashboard). 118 | 119 | 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. 120 | 121 | ## License 122 | 123 | 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. 124 | -------------------------------------------------------------------------------- /build-webapp/build_webapp.ps1: -------------------------------------------------------------------------------- 1 | #build, compress the web-app and move the bundle file to the public folder 2 | 3 | #exit script on error 4 | $ErrorActionPreference = "Stop" 5 | #check relevant installs 6 | echo "[info] NodeJS and npm need to be installed to build the web-app" 7 | 8 | cd ./webapp-src 9 | 10 | #fetch most recent version 11 | git pull 12 | 13 | echo "Building web-app..." 14 | 15 | #check .env.production file exists 16 | $file = ".env.production" 17 | 18 | #If the file does not exist, create it. 19 | if (Test-Path -Path $file -PathType Leaf) { 20 | echo "production environment found" 21 | }else{ 22 | echo "no .env.production file found" 23 | cd .. 24 | exit 1 25 | } 26 | 27 | 28 | #install dependencies 29 | npm install 30 | #build the webapp 31 | npm run build 32 | #compress the project 33 | npm run compress 34 | 35 | #move the compressed file into the public folder 36 | Move-Item ./dist/bundle.html.gz ../public/ -Force 37 | 38 | echo "[success] Up-to-date version of the web-app bundle was placed in the /public folder!" 39 | 40 | cd .. -------------------------------------------------------------------------------- /build-webapp/build_webapp.sh: -------------------------------------------------------------------------------- 1 | #build, compress the web-app and move the bundle file to the public folder 2 | 3 | #exit script on error 4 | set -e 5 | #check relevant installs 6 | echo "[info] NodeJS and npm need to be installed to build the web-app" 7 | 8 | cd ./webapp-src 9 | 10 | echo "Building web-app..." 11 | 12 | #check .env.production file exists 13 | if [ -f ".env.production" ] 14 | then 15 | echo "production environment found" 16 | else 17 | echo "no .env.production file found" 18 | exit 1 19 | fi 20 | 21 | #install dependencies 22 | npm install 23 | #build the webapp 24 | npm run build 25 | #compress the project 26 | npm run compress 27 | 28 | #move the compressed file into the public folder 29 | mv -f ./dist/bundle.html.gz ../public/ 30 | 31 | echo "Up-to-date version of the web-app bundle was placed in the /public folder!" -------------------------------------------------------------------------------- /build-webapp/install_webassembly.sh: -------------------------------------------------------------------------------- 1 | # execute after building cmake Simulator WebAssembly target: 2 | # move created WebAssembly files into webapp folder and patch webapp 3 | 4 | echo "installing WebAssembly files" 5 | 6 | cp ./build/mo_simulator_wasm.mjs ./webapp-src/src/ 7 | cp ./build/mo_simulator_wasm.wasm ./webapp-src/public/ 8 | 9 | if [ -e ./webapp-src/src/DataService_wasm.js.template ] 10 | then 11 | echo "patch DataService" 12 | mv ./webapp-src/src/DataService.js ./webapp-src/src/DataService_http.js.template 13 | mv ./webapp-src/src/DataService_wasm.js.template ./webapp-src/src/DataService.js 14 | fi 15 | -------------------------------------------------------------------------------- /mo_store/README.md: -------------------------------------------------------------------------------- 1 | ### JSON key-value store 2 | 3 | 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. 4 | 5 | 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. 6 | -------------------------------------------------------------------------------- /public/bundle.html.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matth-x/MicroOcppSimulator/2cb07cdbe53954a694a29336ab31eac2d2b48673/public/bundle.html.gz -------------------------------------------------------------------------------- /src/api.cpp: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #include "api.h" 6 | #include "mongoose.h" 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "evse.h" 14 | 15 | //simple matching function; takes * as a wildcard 16 | bool str_match(const char *query, const char *pattern) { 17 | size_t qi = 0, pi = 0; 18 | 19 | while (pattern[pi]) { 20 | if (query[qi] && query[qi] == pattern[pi]) { 21 | qi++; 22 | pi++; 23 | } else if (pattern[pi] == '*') { 24 | while (pattern[pi] == '*') pi++; 25 | while (query[qi] != pattern[pi]) qi++; 26 | } else { 27 | break; 28 | } 29 | } 30 | 31 | return !query[qi] && !pattern[pi]; 32 | } 33 | 34 | int mocpp_api_call(const char *endpoint, MicroOcpp::Method method, const char *body, char *resp_body, size_t resp_body_size) { 35 | 36 | MO_DBG_VERBOSE("process %s, %s: %s", 37 | endpoint, 38 | method == MicroOcpp::Method::GET ? "GET" : 39 | method == MicroOcpp::Method::POST ? "POST" : "error", 40 | body); 41 | 42 | int status = 500; 43 | StaticJsonDocument<512> response; 44 | if (resp_body_size >= sizeof("{}")) { 45 | sprintf(resp_body, "%s", "{}"); 46 | } 47 | 48 | StaticJsonDocument<512> request; 49 | if (*body) { 50 | auto err = deserializeJson(request, body); 51 | if (err) { 52 | MO_DBG_WARN("malformatted body: %s", err.c_str()); 53 | return 400; 54 | } 55 | } 56 | 57 | unsigned int connectorId = 0; 58 | 59 | if (strlen(endpoint) >= 11) { 60 | if (endpoint[11] == '1') { 61 | connectorId = 1; 62 | } else if (endpoint[11] == '2') { 63 | connectorId = 2; 64 | } 65 | } 66 | 67 | MO_DBG_VERBOSE("connectorId = %u", connectorId); 68 | 69 | Evse *evse = nullptr; 70 | if (connectorId >= 1 && connectorId < MO_NUMCONNECTORS) { 71 | evse = &connectors[connectorId-1]; 72 | } 73 | 74 | //start different api endpoints 75 | if(str_match(endpoint, "/connectors")) { 76 | MO_DBG_VERBOSE("query connectors"); 77 | response.add("1"); 78 | response.add("2"); 79 | status = 200; 80 | } else if(str_match(endpoint, "/connector/*/evse")){ 81 | MO_DBG_VERBOSE("query evse"); 82 | if (!evse) { 83 | return 404; 84 | } 85 | 86 | if (method == MicroOcpp::Method::POST) { 87 | if (request.containsKey("evPlugged")) { 88 | evse->setEvPlugged(request["evPlugged"]); 89 | } 90 | if (request.containsKey("evsePlugged")) { 91 | evse->setEvsePlugged(request["evsePlugged"]); 92 | } 93 | if (request.containsKey("evReady")) { 94 | evse->setEvReady(request["evReady"]); 95 | } 96 | if (request.containsKey("evseReady")) { 97 | evse->setEvseReady(request["evseReady"]); 98 | } 99 | } 100 | 101 | response["evPlugged"] = evse->getEvPlugged(); 102 | response["evsePlugged"] = evse->getEvsePlugged(); 103 | response["evReady"] = evse->getEvReady(); 104 | response["evseReady"] = evse->getEvseReady(); 105 | response["chargePointStatus"] = evse->getOcppStatus(); 106 | status = 200; 107 | } else if(str_match(endpoint, "/connector/*/meter")){ 108 | MO_DBG_VERBOSE("query meter"); 109 | if (!evse) { 110 | return 404; 111 | } 112 | 113 | response["energy"] = evse->getEnergy(); 114 | response["power"] = evse->getPower(); 115 | response["current"] = evse->getCurrent(); 116 | response["voltage"] = evse->getVoltage(); 117 | status = 200; 118 | } else if(str_match(endpoint, "/connector/*/transaction")){ 119 | MO_DBG_VERBOSE("query transaction"); 120 | if (!evse) { 121 | return 404; 122 | } 123 | 124 | if (method == MicroOcpp::Method::POST) { 125 | if (request.containsKey("idTag")) { 126 | evse->presentNfcTag(request["idTag"] | ""); 127 | } 128 | } 129 | response["idTag"] = evse->getSessionIdTag(); 130 | response["transactionId"] = evse->getTransactionId(); 131 | response["authorizationStatus"] = ""; 132 | status = 200; 133 | } else if(str_match(endpoint, "/connector/*/smartcharging")){ 134 | MO_DBG_VERBOSE("query smartcharging"); 135 | if (!evse) { 136 | return 404; 137 | } 138 | 139 | response["maxPower"] = evse->getSmartChargingMaxPower(); 140 | response["maxCurrent"] = evse->getSmartChargingMaxCurrent(); 141 | status = 200; 142 | } else { 143 | return 404; 144 | } 145 | 146 | if (response.overflowed()) { 147 | return 500; 148 | } 149 | 150 | std::string out; 151 | serializeJson(response, out); 152 | if (out.length() >= resp_body_size) { 153 | return 500; 154 | } 155 | 156 | if (!out.empty()) { 157 | sprintf(resp_body, "%s", out.c_str()); 158 | } 159 | 160 | return status; 161 | } 162 | 163 | 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) { 164 | 165 | snprintf(resp_body, resp_body_size, "%s", ""); 166 | 167 | struct mg_str uri = mg_str_n(uri_raw, uri_raw_len); 168 | struct mg_str query = mg_str_n(query_raw, query_raw_len); 169 | 170 | int evse_id = -1; 171 | int connector_id = -1; 172 | 173 | unsigned int num; 174 | struct mg_str evse_id_str = mg_http_var(query, mg_str("evse_id")); 175 | if (evse_id_str.buf) { 176 | if (!mg_str_to_num(evse_id_str, 10, &num, sizeof(num)) || num < 1 || num >= MO_NUM_EVSEID) { 177 | snprintf(resp_body, resp_body_size, "invalid connector_id"); 178 | return 400; 179 | } 180 | evse_id = (int)num; 181 | } 182 | 183 | struct mg_str connector_id_str = mg_http_var(query, mg_str("connector_id")); 184 | if (connector_id_str.buf) { 185 | if (!mg_str_to_num(connector_id_str, 10, &num, sizeof(num)) || num != 1) { 186 | snprintf(resp_body, resp_body_size, "invalid connector_id"); 187 | return 400; 188 | } 189 | connector_id = (int)num; 190 | } 191 | 192 | if (mg_match(uri, mg_str("/plugin"), NULL)) { 193 | if (method != MicroOcpp::Method::POST) { 194 | return 405; 195 | } 196 | if (evse_id < 0) { 197 | snprintf(resp_body, resp_body_size, "no action taken"); 198 | return 200; 199 | } else { 200 | snprintf(resp_body, resp_body_size, "%s", connectors[evse_id-1].getEvPlugged() ? "EV already plugged" : "plugged in EV"); 201 | connectors[evse_id-1].setEvPlugged(true); 202 | connectors[evse_id-1].setEvReady(true); 203 | connectors[evse_id-1].setEvseReady(true); 204 | return 200; 205 | } 206 | } else if (mg_match(uri, mg_str("/plugout"), NULL)) { 207 | if (method != MicroOcpp::Method::POST) { 208 | return 405; 209 | } 210 | if (evse_id < 0) { 211 | snprintf(resp_body, resp_body_size, "no action taken"); 212 | return 200; 213 | } else { 214 | snprintf(resp_body, resp_body_size, "%s", connectors[evse_id-1].getEvPlugged() ? "EV already unplugged" : "unplug EV"); 215 | connectors[evse_id-1].setEvPlugged(false); 216 | connectors[evse_id-1].setEvReady(false); 217 | connectors[evse_id-1].setEvseReady(false); 218 | return 200; 219 | } 220 | } else if (mg_match(uri, mg_str("/end"), NULL)) { 221 | if (method != MicroOcpp::Method::POST) { 222 | return 405; 223 | } 224 | bool trackEvReady = false; 225 | for (size_t i = 0; i < connectors.size(); i++) { 226 | trackEvReady |= connectors[i].getEvReady(); 227 | connectors[i].setEvReady(false); 228 | } 229 | snprintf(resp_body, resp_body_size, "%s", trackEvReady ? "suspended EV" : "EV already suspended"); 230 | return 200; 231 | } else if (mg_match(uri, mg_str("/state"), NULL)) { 232 | if (method != MicroOcpp::Method::POST) { 233 | return 405; 234 | } 235 | struct mg_str ready_str = mg_http_var(query, mg_str("ready")); 236 | bool ready = true; 237 | if (ready_str.buf) { 238 | if (mg_match(ready_str, mg_str("true"), NULL)) { 239 | ready = true; 240 | } else if (mg_match(ready_str, mg_str("false"), NULL)) { 241 | ready = false; 242 | } else { 243 | snprintf(resp_body, resp_body_size, "invalid ready"); 244 | return 400; 245 | } 246 | } 247 | bool trackEvReady = false; 248 | for (size_t i = 0; i < connectors.size(); i++) { 249 | if (connectors[i].getEvPlugged()) { 250 | bool trackEvReady = connectors[i].getEvReady(); 251 | connectors[i].setEvReady(ready); 252 | snprintf(resp_body, resp_body_size, "%s, %s", ready ? "EV suspended" : "EV not suspended", trackEvReady ? "suspended before" : "not suspended before"); 253 | return 200; 254 | } 255 | } 256 | snprintf(resp_body, resp_body_size, "no action taken - EV not plugged"); 257 | return 200; 258 | } else if (mg_match(uri, mg_str("/authorize"), NULL)) { 259 | if (method != MicroOcpp::Method::POST) { 260 | return 405; 261 | } 262 | struct mg_str id = mg_http_var(query, mg_str("id")); 263 | if (!id.buf) { 264 | snprintf(resp_body, resp_body_size, "missing id"); 265 | return 400; 266 | } 267 | struct mg_str type = mg_http_var(query, mg_str("type")); 268 | if (!id.buf) { 269 | snprintf(resp_body, resp_body_size, "missing type"); 270 | return 400; 271 | } 272 | 273 | int ret; 274 | char id_buf [MO_IDTOKEN_LEN_MAX + 1]; 275 | ret = snprintf(id_buf, sizeof(id_buf), "%.*s", (int)id.len, id.buf); 276 | if (ret < 0 || ret >= sizeof(id_buf)) { 277 | snprintf(resp_body, resp_body_size, "invalid id"); 278 | return 400; 279 | } 280 | char type_buf [128]; 281 | ret = snprintf(type_buf, sizeof(type_buf), "%.*s", (int)type.len, type.buf); 282 | if (ret < 0 || ret >= sizeof(type_buf)) { 283 | snprintf(resp_body, resp_body_size, "invalid type"); 284 | return 400; 285 | } 286 | 287 | if (evse_id <= 0) { 288 | snprintf(resp_body, resp_body_size, "invalid evse_id"); 289 | return 400; 290 | } 291 | 292 | bool trackAuthActive = connectors[evse_id-1].getSessionIdTag(); 293 | 294 | if (!connectors[evse_id-1].presentNfcTag(id_buf, type_buf)) { 295 | snprintf(resp_body, resp_body_size, "invalid id and / or type"); 296 | return 400; 297 | } 298 | 299 | bool authActive = connectors[evse_id-1].getSessionIdTag(); 300 | 301 | snprintf(resp_body, resp_body_size, "%s", 302 | !trackAuthActive && authActive ? "authorize in progress" : 303 | trackAuthActive && !authActive ? "unauthorize in progress" : 304 | trackAuthActive && authActive ? "no action taken (EVSE still authorized)" : 305 | "no action taken (EVSE not authorized)"); 306 | 307 | return 200; 308 | } else if (mg_match(uri, mg_str("/memory/info"), NULL)) { 309 | #if MO_OVERRIDE_ALLOCATION && MO_ENABLE_HEAP_PROFILER 310 | { 311 | if (method != MicroOcpp::Method::GET) { 312 | return 405; 313 | } 314 | 315 | int ret = mo_mem_write_stats_json(resp_body, resp_body_size); 316 | if (ret < 0 || ret >= resp_body_size) { 317 | snprintf(resp_body, resp_body_size, "internal error"); 318 | return 500; 319 | } 320 | 321 | return 200; 322 | } 323 | #else 324 | { 325 | snprintf(resp_body, resp_body_size, "memory profiler disabled"); 326 | return 404; 327 | } 328 | #endif 329 | } else if (mg_match(uri, mg_str("/memory/reset"), NULL)) { 330 | #if MO_OVERRIDE_ALLOCATION && MO_ENABLE_HEAP_PROFILER 331 | { 332 | if (method != MicroOcpp::Method::POST) { 333 | return 405; 334 | } 335 | 336 | MO_MEM_RESET(); 337 | return 200; 338 | } 339 | #else 340 | { 341 | snprintf(resp_body, resp_body_size, "memory profiler disabled"); 342 | return 404; 343 | } 344 | #endif 345 | 346 | } 347 | 348 | return 404; 349 | } 350 | -------------------------------------------------------------------------------- /src/api.h: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #ifndef MO_SIM_API_H 6 | #define MO_SIM_API_H 7 | 8 | #include 9 | 10 | namespace MicroOcpp { 11 | 12 | enum class Method { 13 | GET, 14 | POST, 15 | UNDEFINED 16 | }; 17 | 18 | } 19 | 20 | int mocpp_api_call(const char *endpoint, MicroOcpp::Method method, const char *body, char *resp_body, size_t resp_body_size); 21 | 22 | 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); 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /src/evse.cpp: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #include "evse.h" 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | Evse::Evse(unsigned int connectorId) : connectorId{connectorId} { 20 | 21 | } 22 | 23 | void Evse::setup() { 24 | 25 | #if MO_ENABLE_V201 26 | if (auto context = getOcppContext()) { 27 | if (context->getVersion().major == 2) { 28 | //load some example variables for testing 29 | 30 | if (auto varService = context->getModel().getVariableService()) { 31 | varService->declareVariable("AuthCtrlr", "LocalAuthorizeOffline", false, MicroOcpp::Variable::Mutability::ReadOnly, false); 32 | } 33 | } 34 | } 35 | #endif 36 | 37 | char key [30] = {'\0'}; 38 | 39 | snprintf(key, 30, "evPlugged_cId_%u", connectorId); 40 | trackEvPluggedKey = key; 41 | trackEvPluggedBool = MicroOcpp::declareConfiguration(trackEvPluggedKey.c_str(), false, SIMULATOR_FN, false, false, false); 42 | snprintf(key, 30, "evsePlugged_cId_%u", connectorId); 43 | trackEvsePluggedKey = key; 44 | trackEvsePluggedBool = MicroOcpp::declareConfiguration(trackEvsePluggedKey.c_str(), false, SIMULATOR_FN, false, false, false); 45 | snprintf(key, 30, "evReady_cId_%u", connectorId); 46 | trackEvReadyKey = key; 47 | trackEvReadyBool = MicroOcpp::declareConfiguration(trackEvReadyKey.c_str(), false, SIMULATOR_FN, false, false, false); 48 | snprintf(key, 30, "evseReady_cId_%u", connectorId); 49 | trackEvseReadyKey = key; 50 | trackEvseReadyBool = MicroOcpp::declareConfiguration(trackEvseReadyKey.c_str(), false, SIMULATOR_FN, false, false, false); 51 | 52 | MicroOcpp::configuration_load(SIMULATOR_FN); 53 | 54 | setConnectorPluggedInput([this] () -> bool { 55 | return trackEvPluggedBool->getBool(); //return if J1772 is in State B or C 56 | }, connectorId); 57 | 58 | setEvReadyInput([this] () -> bool { 59 | return trackEvReadyBool->getBool(); //return if J1772 is in State C 60 | }, connectorId); 61 | 62 | setEvseReadyInput([this] () -> bool { 63 | return trackEvseReadyBool->getBool(); 64 | }, connectorId); 65 | 66 | addErrorCodeInput([this] () -> const char* { 67 | const char *errorCode = nullptr; //if error is present, point to error code; any number of error code samplers can be added in this project 68 | return errorCode; 69 | }, connectorId); 70 | 71 | setEnergyMeterInput([this] () -> float { 72 | return simulate_energy; 73 | }, connectorId); 74 | 75 | setPowerMeterInput([this] () -> float { 76 | return simulate_power; 77 | }, connectorId); 78 | 79 | addMeterValueInput([this] () { 80 | return (int32_t) getCurrent(); 81 | }, 82 | "Current.Import", 83 | "A", 84 | "Outlet", 85 | nullptr, 86 | connectorId); 87 | 88 | addMeterValueInput([this] () { 89 | return (int32_t) getVoltage(); 90 | }, 91 | "Voltage", 92 | "V", 93 | nullptr, 94 | nullptr, 95 | connectorId); 96 | 97 | addMeterValueInput([this] () { 98 | return (int32_t) (simulate_power > 1.f ? 44.f : 0.f); 99 | }, 100 | "SoC", 101 | nullptr, 102 | nullptr, 103 | nullptr, 104 | connectorId); 105 | 106 | setOnResetExecute([] (bool isHard) { 107 | exit(0); 108 | }); 109 | 110 | setSmartChargingPowerOutput([this] (float limit) { 111 | if (limit >= 0.f) { 112 | MO_DBG_DEBUG("set limit: %f", limit); 113 | this->limit_power = limit; 114 | } else { 115 | // negative value means no limit defined 116 | this->limit_power = SIMULATE_POWER_CONST; 117 | } 118 | }, connectorId); 119 | } 120 | 121 | void Evse::loop() { 122 | 123 | auto curStatus = getChargePointStatus(connectorId); 124 | 125 | if (status.compare(MicroOcpp::cstrFromOcppEveState(curStatus))) { 126 | status = MicroOcpp::cstrFromOcppEveState(curStatus); 127 | } 128 | 129 | bool simulate_isCharging = ocppPermitsCharge(connectorId) && trackEvPluggedBool->getBool() && trackEvsePluggedBool->getBool() && trackEvReadyBool->getBool() && trackEvseReadyBool->getBool(); 130 | 131 | simulate_isCharging &= limit_power >= 720.f; //minimum charging current is 6A (720W for 120V grids) according to J1772 132 | 133 | if (simulate_isCharging) { 134 | if (simulate_power >= 1.f) { 135 | simulate_energy += (float) (mocpp_tick_ms() - simulate_energy_track_time) * simulate_power * (0.001f / 3600.f); 136 | } 137 | 138 | simulate_power = SIMULATE_POWER_CONST; 139 | simulate_power = std::min(simulate_power, limit_power); 140 | simulate_power += (((mocpp_tick_ms() / 5000) * 3483947) % 20000) * 0.001f - 10.f; 141 | simulate_energy_track_time = mocpp_tick_ms(); 142 | } else { 143 | simulate_power = 0.f; 144 | } 145 | 146 | } 147 | 148 | void Evse::presentNfcTag(const char *uid) { 149 | if (!uid) { 150 | MO_DBG_ERR("invalid argument"); 151 | return; 152 | } 153 | 154 | #if MO_ENABLE_V201 155 | if (auto context = getOcppContext()) { 156 | if (context->getVersion().major == 2) { 157 | presentNfcTag(uid, "ISO14443"); 158 | return; 159 | } 160 | } 161 | #endif 162 | 163 | if (isTransactionActive(connectorId)) { 164 | if (!strcmp(uid, getTransactionIdTag(connectorId))) { 165 | endTransaction(uid, "Local", connectorId); 166 | } else { 167 | MO_DBG_INFO("RFID card denied"); 168 | } 169 | } else { 170 | beginTransaction(uid, connectorId); 171 | } 172 | } 173 | 174 | #if MO_ENABLE_V201 175 | bool Evse::presentNfcTag(const char *uid, const char *type) { 176 | 177 | MicroOcpp::IdToken idToken {nullptr, MicroOcpp::IdToken::Type::UNDEFINED, "Simulator"}; 178 | if (!idToken.parseCstr(uid, type)) { 179 | return false; 180 | } 181 | 182 | if (auto txService = getOcppContext()->getModel().getTransactionService()) { 183 | if (auto evse = txService->getEvse(connectorId)) { 184 | if (evse->getTransaction() && evse->getTransaction()->isAuthorizationActive) { 185 | evse->endAuthorization(idToken); 186 | } else { 187 | evse->beginAuthorization(idToken); 188 | } 189 | return true; 190 | } 191 | } 192 | return false; 193 | } 194 | #endif 195 | 196 | void Evse::setEvPlugged(bool plugged) { 197 | if (!trackEvPluggedBool) return; 198 | trackEvPluggedBool->setBool(plugged); 199 | MicroOcpp::configuration_save(); 200 | } 201 | 202 | bool Evse::getEvPlugged() { 203 | if (!trackEvPluggedBool) return false; 204 | return trackEvPluggedBool->getBool(); 205 | } 206 | 207 | void Evse::setEvsePlugged(bool plugged) { 208 | if (!trackEvsePluggedBool) return; 209 | trackEvsePluggedBool->setBool(plugged); 210 | MicroOcpp::configuration_save(); 211 | } 212 | 213 | bool Evse::getEvsePlugged() { 214 | if (!trackEvsePluggedBool) return false; 215 | return trackEvsePluggedBool->getBool(); 216 | } 217 | 218 | void Evse::setEvReady(bool ready) { 219 | if (!trackEvReadyBool) return; 220 | trackEvReadyBool->setBool(ready); 221 | MicroOcpp::configuration_save(); 222 | } 223 | 224 | bool Evse::getEvReady() { 225 | if (!trackEvReadyBool) return false; 226 | return trackEvReadyBool->getBool(); 227 | } 228 | 229 | void Evse::setEvseReady(bool ready) { 230 | if (!trackEvseReadyBool) return; 231 | trackEvseReadyBool->setBool(ready); 232 | MicroOcpp::configuration_save(); 233 | } 234 | 235 | bool Evse::getEvseReady() { 236 | if (!trackEvseReadyBool) return false; 237 | return trackEvseReadyBool->getBool(); 238 | } 239 | 240 | const char *Evse::getSessionIdTag() { 241 | return getTransactionIdTag(connectorId) ? getTransactionIdTag(connectorId) : ""; 242 | } 243 | 244 | int Evse::getTransactionId() { 245 | return getTransaction(connectorId) ? getTransaction(connectorId)->getTransactionId() : -1; 246 | } 247 | 248 | bool Evse::chargingPermitted() { 249 | return ocppPermitsCharge(connectorId); 250 | } 251 | 252 | int Evse::getPower() { 253 | return (int) simulate_power; 254 | } 255 | 256 | float Evse::getVoltage() { 257 | if (getPower() > 1.f) { 258 | return 228.f + (((mocpp_tick_ms() / 5000) * 7484311) % 4000) * 0.001f; 259 | } else { 260 | return 0.f; 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /src/evse.h: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #ifndef EVSE_H 6 | #define EVSE_H 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define SIMULATOR_FN MO_FILENAME_PREFIX "simulator.jsn" 14 | 15 | class Evse { 16 | private: 17 | const unsigned int connectorId; 18 | 19 | std::shared_ptr trackEvPluggedBool; 20 | std::string trackEvPluggedKey; 21 | std::shared_ptr trackEvsePluggedBool; 22 | std::string trackEvsePluggedKey; 23 | std::shared_ptr trackEvReadyBool; 24 | std::string trackEvReadyKey; 25 | std::shared_ptr trackEvseReadyBool; 26 | std::string trackEvseReadyKey; 27 | 28 | const float SIMULATE_POWER_CONST = 11000.f; 29 | float simulate_power = 0; 30 | float limit_power = 11000.f; 31 | const float SIMULATE_ENERGY_DELTA_MS = SIMULATE_POWER_CONST / (3600.f * 1000.f); 32 | unsigned long simulate_energy_track_time = 0; 33 | float simulate_energy = 0; 34 | 35 | std::string status; 36 | public: 37 | Evse(unsigned int connectorId); 38 | 39 | void setup(); 40 | 41 | void loop(); 42 | 43 | void presentNfcTag(const char *uid); 44 | 45 | #if MO_ENABLE_V201 46 | bool presentNfcTag(const char *uid, const char *type); 47 | #endif //MO_ENABLE_V201 48 | 49 | void setEvPlugged(bool plugged); 50 | 51 | bool getEvPlugged(); 52 | 53 | void setEvsePlugged(bool plugged); 54 | 55 | bool getEvsePlugged(); 56 | 57 | void setEvReady(bool ready); 58 | 59 | bool getEvReady(); 60 | 61 | void setEvseReady(bool ready); 62 | 63 | bool getEvseReady(); 64 | 65 | const char *getSessionIdTag(); 66 | int getTransactionId(); 67 | bool chargingPermitted(); 68 | 69 | bool isCharging() { 70 | return chargingPermitted() && trackEvReadyBool->getBool(); 71 | } 72 | 73 | const char *getOcppStatus() { 74 | return status.c_str(); 75 | } 76 | 77 | unsigned int getConnectorId() { 78 | return connectorId; 79 | } 80 | 81 | int getEnergy() { 82 | return (int) simulate_energy; 83 | } 84 | 85 | int getPower(); 86 | 87 | float getVoltage(); 88 | 89 | float getCurrent() { 90 | float volts = getVoltage(); 91 | if (volts <= 0.f) { 92 | return 0.f; 93 | } 94 | return 0.333f * (float) getPower() / volts; 95 | } 96 | 97 | int getSmartChargingMaxPower() { 98 | return limit_power; 99 | } 100 | 101 | float getSmartChargingMaxCurrent() { 102 | float volts = getVoltage(); 103 | if (volts <= 0.f) { 104 | return 0.f; 105 | } 106 | return 0.333f * (float) getSmartChargingMaxPower() / volts; 107 | } 108 | 109 | }; 110 | 111 | extern std::array connectors; 112 | 113 | #endif 114 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include "evse.h" 14 | #include "api.h" 15 | 16 | #include 17 | 18 | #if MO_NUMCONNECTORS == 3 19 | std::array connectors {{1,2}}; 20 | #else 21 | std::array connectors {{1}}; 22 | #endif 23 | 24 | bool g_isOcpp201 = false; 25 | bool g_runSimulator = true; 26 | 27 | bool g_isUpAndRunning = false; //if the initial BootNotification and StatusNotifications got through + 1s delay 28 | unsigned int g_bootNotificationTime = 0; 29 | 30 | #define MO_NETLIB_MONGOOSE 1 31 | #define MO_NETLIB_WASM 2 32 | 33 | 34 | #if MO_NETLIB == MO_NETLIB_MONGOOSE 35 | #include "mongoose.h" 36 | #include 37 | 38 | #include "net_mongoose.h" 39 | 40 | struct mg_mgr mgr; 41 | MicroOcpp::MOcppMongooseClient *osock; 42 | 43 | #elif MO_NETLIB == MO_NETLIB_WASM 44 | #include 45 | 46 | #include 47 | 48 | #include "net_wasm.h" 49 | 50 | MicroOcpp::Connection *conn = nullptr; 51 | 52 | #else 53 | #error Please ensure that build flag MO_NETLIB is set as MO_NETLIB_MONGOOSE or MO_NETLIB_WASM 54 | #endif 55 | 56 | #if MBEDTLS_PLATFORM_MEMORY //configure MbedTLS with allocation hook functions 57 | 58 | void *mo_mem_mbedtls_calloc( size_t n, size_t count ) { 59 | size_t size = n * count; 60 | auto ptr = MO_MALLOC("MbedTLS", size); 61 | if (ptr) { 62 | memset(ptr, 0, size); 63 | } 64 | return ptr; 65 | } 66 | void mo_mem_mbedtls_free( void *ptr ) { 67 | MO_FREE(ptr); 68 | } 69 | 70 | #endif //MBEDTLS_PLATFORM_MEMORY 71 | 72 | void mo_sim_sig_handler(int s){ 73 | 74 | if (!g_runSimulator) { //already tried to shut down, now force stop 75 | exit(EXIT_FAILURE); 76 | } 77 | 78 | g_runSimulator = false; //shut down simulator gracefully 79 | } 80 | 81 | /* 82 | * Setup MicroOcpp and API 83 | */ 84 | void load_ocpp_version(std::shared_ptr filesystem) { 85 | 86 | MicroOcpp::configuration_init(filesystem); 87 | 88 | #if MO_ENABLE_V201 89 | { 90 | auto protocolVersion_stored = MicroOcpp::declareConfiguration("OcppVersion", "1.6", SIMULATOR_FN, false, false, false); 91 | MicroOcpp::configuration_load(SIMULATOR_FN); 92 | if (!strcmp(protocolVersion_stored->getString(), "2.0.1")) { 93 | //select OCPP 2.0.1 94 | g_isOcpp201 = true; 95 | return; 96 | } 97 | } 98 | #endif //MO_ENABLE_V201 99 | 100 | g_isOcpp201 = false; 101 | } 102 | 103 | void app_setup(MicroOcpp::Connection& connection, std::shared_ptr filesystem) { 104 | mocpp_initialize(connection, 105 | g_isOcpp201 ? 106 | ChargerCredentials::v201("MicroOcpp Simulator", "MicroOcpp") : 107 | ChargerCredentials("MicroOcpp Simulator", "MicroOcpp"), 108 | filesystem, 109 | false, 110 | g_isOcpp201 ? 111 | MicroOcpp::ProtocolVersion{2,0,1} : 112 | MicroOcpp::ProtocolVersion{1,6} 113 | ); 114 | 115 | for (unsigned int i = 0; i < connectors.size(); i++) { 116 | connectors[i].setup(); 117 | } 118 | } 119 | 120 | /* 121 | * Execute one loop iteration 122 | */ 123 | void app_loop() { 124 | mocpp_loop(); 125 | for (unsigned int i = 0; i < connectors.size(); i++) { 126 | connectors[i].loop(); 127 | } 128 | } 129 | 130 | #if MO_NETLIB == MO_NETLIB_MONGOOSE 131 | 132 | #ifndef MO_SIM_ENDPOINT_URL 133 | #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 134 | #endif 135 | 136 | int main() { 137 | 138 | #if MBEDTLS_PLATFORM_MEMORY 139 | mbedtls_platform_set_calloc_free(mo_mem_mbedtls_calloc, mo_mem_mbedtls_free); 140 | #endif //MBEDTLS_PLATFORM_MEMORY 141 | 142 | struct sigaction sigIntHandler; 143 | sigIntHandler.sa_handler = mo_sim_sig_handler; 144 | sigemptyset(&sigIntHandler.sa_mask); 145 | sigIntHandler.sa_flags = 0; 146 | sigaction(SIGINT, &sigIntHandler, NULL); 147 | 148 | mg_log_set(MG_LL_INFO); 149 | mg_mgr_init(&mgr); 150 | 151 | auto filesystem = MicroOcpp::makeDefaultFilesystemAdapter(MicroOcpp::FilesystemOpt::Use_Mount_FormatOnFail); 152 | 153 | load_ocpp_version(filesystem); 154 | 155 | struct mg_str api_cert = mg_file_read(&mg_fs_posix, MO_FILENAME_PREFIX "api_cert.pem"); 156 | struct mg_str api_key = mg_file_read(&mg_fs_posix, MO_FILENAME_PREFIX "api_key.pem"); 157 | 158 | auto api_settings_doc = MicroOcpp::FilesystemUtils::loadJson(filesystem, MO_FILENAME_PREFIX "api.jsn", "Simulator"); 159 | if (!api_settings_doc) { 160 | api_settings_doc = MicroOcpp::makeJsonDoc("Simulator", 0); 161 | } 162 | JsonObject api_settings = api_settings_doc->as(); 163 | 164 | const char *api_url = api_settings["url"] | MO_SIM_ENDPOINT_URL; 165 | 166 | mg_http_listen(&mgr, api_url, http_serve, (void*)api_url); // Create listening connection 167 | 168 | osock = new MicroOcpp::MOcppMongooseClient(&mgr, 169 | "ws://echo.websocket.events", 170 | "charger-01", 171 | "", 172 | "", 173 | filesystem, 174 | g_isOcpp201 ? 175 | MicroOcpp::ProtocolVersion{2,0,1} : 176 | MicroOcpp::ProtocolVersion{1,6} 177 | ); 178 | 179 | server_initialize(osock, api_cert.buf ? api_cert.buf : "", api_key.buf ? api_key.buf : "", api_settings["user"] | "", api_settings["pass"] | ""); 180 | app_setup(*osock, filesystem); 181 | 182 | setOnResetExecute([] (bool isHard) { 183 | g_runSimulator = false; 184 | }); 185 | 186 | while (g_runSimulator) { //Run Simulator until OCPP Reset is executed or user presses Ctrl+C 187 | mg_mgr_poll(&mgr, 100); 188 | app_loop(); 189 | 190 | if (!g_bootNotificationTime && getOcppContext()->getModel().getClock().now() >= MicroOcpp::MIN_TIME) { 191 | //time has been set, BootNotification succeeded 192 | g_bootNotificationTime = mocpp_tick_ms(); 193 | } 194 | 195 | if (!g_isUpAndRunning && g_bootNotificationTime && mocpp_tick_ms() - g_bootNotificationTime >= 1000) { 196 | printf("[Sim] Resetting maximum heap usage after boot success\n"); 197 | g_isUpAndRunning = true; 198 | MO_MEM_RESET(); 199 | } 200 | } 201 | 202 | printf("[Sim] Shutting down Simulator\n"); 203 | 204 | MO_MEM_PRINT_STATS(); 205 | 206 | mocpp_deinitialize(); 207 | 208 | delete osock; 209 | mg_mgr_free(&mgr); 210 | free(api_cert.buf); 211 | free(api_key.buf); 212 | return 0; 213 | } 214 | 215 | #elif MO_NETLIB == MO_NETLIB_WASM 216 | 217 | int main() { 218 | 219 | printf("[WASM] start\n"); 220 | 221 | auto filesystem = MicroOcpp::makeDefaultFilesystemAdapter(MicroOcpp::FilesystemOpt::Deactivate); 222 | 223 | conn = wasm_ocpp_connection_init(nullptr, nullptr, nullptr); 224 | 225 | app_setup(*conn, filesystem); 226 | 227 | const int LOOP_FREQ = 10; //called 10 times per second 228 | const int BLOCK_INFINITELY = 0; //0 for non-blocking execution, 1 for blocking infinitely 229 | emscripten_set_main_loop(app_loop, LOOP_FREQ, BLOCK_INFINITELY); 230 | 231 | printf("[WASM] setup complete\n"); 232 | } 233 | #endif 234 | -------------------------------------------------------------------------------- /src/net_mongoose.cpp: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #include "net_mongoose.h" 6 | #include "evse.h" 7 | #include "api.h" 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | //cors_headers allow the browser to make requests from any domain, allowing all headers and all methods 15 | #define DEFAULT_HEADER "Content-Type: application/json\r\n" 16 | #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" 17 | 18 | MicroOcpp::MOcppMongooseClient *ao_sock = nullptr; 19 | const char *api_cert = ""; 20 | const char *api_key = ""; 21 | const char *api_user = ""; 22 | const char *api_pass = ""; 23 | 24 | void server_initialize(MicroOcpp::MOcppMongooseClient *osock, const char *cert, const char *key, const char *user, const char *pass) { 25 | ao_sock = osock; 26 | api_cert = cert; 27 | api_key = key; 28 | api_user = user; 29 | api_pass = pass; 30 | } 31 | 32 | bool api_check_basic_auth(const char *user, const char *pass) { 33 | if (strcmp(api_user, user)) { 34 | return false; 35 | } 36 | if (strcmp(api_pass, pass)) { 37 | return false; 38 | } 39 | return true; 40 | } 41 | 42 | void http_serve(struct mg_connection *c, int ev, void *ev_data) { 43 | if (ev == MG_EV_ACCEPT) { 44 | if (mg_url_is_ssl((const char*)c->fn_data)) { // TLS listener! 45 | MO_DBG_VERBOSE("API TLS setup"); 46 | struct mg_tls_opts opts = {0}; 47 | opts.cert = mg_str(api_cert); 48 | opts.key = mg_str(api_key); 49 | mg_tls_init(c, &opts); 50 | } 51 | } else if (ev == MG_EV_HTTP_MSG) { 52 | //struct mg_http_message *message_data = (struct mg_http_message *) ev_data; 53 | struct mg_http_message *message_data = reinterpret_cast(ev_data); 54 | const char *final_headers = DEFAULT_HEADER CORS_HEADERS; 55 | 56 | char user[64], pass[64]; 57 | mg_http_creds(message_data, user, sizeof(user), pass, sizeof(pass)); 58 | if (!api_check_basic_auth(user, pass)) { 59 | mg_http_reply(c, 401, final_headers, "Unauthorized. Expect Basic Auth user and / or password\n"); 60 | return; 61 | } 62 | 63 | struct mg_str json = message_data->body; 64 | 65 | MO_DBG_VERBOSE("%.*s", 20, message_data->uri.buf); 66 | 67 | MicroOcpp::Method method = MicroOcpp::Method::UNDEFINED; 68 | 69 | if (!mg_strcasecmp(message_data->method, mg_str("POST"))) { 70 | method = MicroOcpp::Method::POST; 71 | MO_DBG_VERBOSE("POST"); 72 | } else if (!mg_strcasecmp(message_data->method, mg_str("GET"))) { 73 | method = MicroOcpp::Method::GET; 74 | MO_DBG_VERBOSE("GET"); 75 | } 76 | 77 | //start different api endpoints 78 | if(mg_match(message_data->uri, mg_str("/api/websocket"), NULL)){ 79 | MO_DBG_VERBOSE("query websocket"); 80 | auto webSocketPingIntervalInt = MicroOcpp::declareConfiguration("WebSocketPingInterval", 10, MO_WSCONN_FN); 81 | auto reconnectIntervalInt = MicroOcpp::declareConfiguration(MO_CONFIG_EXT_PREFIX "ReconnectInterval", 30, MO_WSCONN_FN); 82 | 83 | if (method == MicroOcpp::Method::POST) { 84 | if (auto val = mg_json_get_str(json, "$.backendUrl")) { 85 | ao_sock->setBackendUrl(val); 86 | } 87 | if (auto val = mg_json_get_str(json, "$.chargeBoxId")) { 88 | ao_sock->setChargeBoxId(val); 89 | } 90 | if (auto val = mg_json_get_str(json, "$.authorizationKey")) { 91 | ao_sock->setAuthKey(val); 92 | } 93 | ao_sock->reloadConfigs(); 94 | { 95 | auto val = mg_json_get_long(json, "$.pingInterval", -1); 96 | if (val > 0) { 97 | webSocketPingIntervalInt->setInt(val); 98 | } 99 | } 100 | { 101 | auto val = mg_json_get_long(json, "$.reconnectInterval", -1); 102 | if (val > 0) { 103 | reconnectIntervalInt->setInt(val); 104 | } 105 | } 106 | if (auto val = mg_json_get_str(json, "$.dnsUrl")) { 107 | MO_DBG_WARN("dnsUrl not implemented"); 108 | (void)val; 109 | } 110 | MicroOcpp::configuration_save(); 111 | } 112 | StaticJsonDocument<256> doc; 113 | doc["backendUrl"] = ao_sock->getBackendUrl(); 114 | doc["chargeBoxId"] = ao_sock->getChargeBoxId(); 115 | doc["authorizationKey"] = ao_sock->getAuthKey(); 116 | doc["pingInterval"] = webSocketPingIntervalInt->getInt(); 117 | doc["reconnectInterval"] = reconnectIntervalInt->getInt(); 118 | std::string serialized; 119 | serializeJson(doc, serialized); 120 | mg_http_reply(c, 200, final_headers, serialized.c_str()); 121 | return; 122 | } else if (strncmp(message_data->uri.buf, "/api", strlen("api")) == 0) { 123 | #define RESP_BUF_SIZE 8192 124 | char resp_buf [RESP_BUF_SIZE]; 125 | 126 | //replace endpoint-body separator by null 127 | if (char *c = strchr((char*) message_data->uri.buf, ' ')) { 128 | *c = '\0'; 129 | } 130 | 131 | int status = 404; 132 | if (status == 404) { 133 | status = mocpp_api2_call( 134 | message_data->uri.buf + strlen("/api"), 135 | message_data->uri.len - strlen("/api"), 136 | method, 137 | message_data->query.buf, 138 | message_data->query.len, 139 | resp_buf, RESP_BUF_SIZE); 140 | } 141 | if (status == 404) { 142 | status = mocpp_api_call( 143 | message_data->uri.buf + strlen("/api"), 144 | method, 145 | message_data->body.buf, 146 | resp_buf, RESP_BUF_SIZE); 147 | } 148 | 149 | mg_http_reply(c, status, final_headers, resp_buf); 150 | } else if (mg_match(message_data->uri, mg_str("/"), NULL)) { //if no specific path is given serve dashboard application file 151 | struct mg_http_serve_opts opts; 152 | memset(&opts, 0, sizeof(opts)); 153 | opts.root_dir = "./public"; 154 | opts.extra_headers = "Content-Type: text/html\r\nContent-Encoding: gzip\r\n"; 155 | mg_http_serve_file(c, message_data, "public/bundle.html.gz", &opts); 156 | } else { 157 | mg_http_reply(c, 404, final_headers, "API endpoint not found"); 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/net_mongoose.h: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #ifndef MO_NET_MONGOOSE_H 6 | #define MO_NET_MONGOOSE_H 7 | 8 | #if MO_NETLIB == MO_NETLIB_MONGOOSE 9 | 10 | #include "mongoose.h" 11 | 12 | namespace MicroOcpp { 13 | class MOcppMongooseClient; 14 | } 15 | 16 | void server_initialize(MicroOcpp::MOcppMongooseClient *osock, const char *cert = "", const char *key = "", const char *user = "", const char *pass = ""); 17 | 18 | void http_serve(struct mg_connection *c, int ev, void *ev_data); 19 | 20 | #endif //MO_NETLIB == MO_NETLIB_MONGOOSE 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /src/net_wasm.cpp: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #include "net_wasm.h" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #include "api.h" 16 | 17 | #define DEBUG_MSG_INTERVAL 5000UL 18 | #define WS_UNRESPONSIVE_THRESHOLD_MS 15000UL 19 | 20 | using namespace MicroOcpp; 21 | 22 | class WasmOcppConnection : public Connection { 23 | private: 24 | EMSCRIPTEN_WEBSOCKET_T websocket; 25 | std::string backend_url; 26 | std::string cb_id; 27 | std::string url; //url = backend_url + '/' + cb_id 28 | std::string auth_key; 29 | std::string basic_auth64; 30 | std::shared_ptr setting_backend_url_str; 31 | std::shared_ptr setting_cb_id_str; 32 | std::shared_ptr setting_auth_key_str; 33 | unsigned long last_status_dbg_msg {0}, last_recv {0}; 34 | std::shared_ptr reconnect_interval_int; //minimum time between two connect trials in s 35 | unsigned long last_reconnection_attempt {-1UL / 2UL}; 36 | std::shared_ptr stale_timeout_int; //inactivity period after which the connection will be closed 37 | std::shared_ptr ws_ping_interval_int; //heartbeat intervall in s. 0 sets hb off 38 | unsigned long last_hb {0}; 39 | bool connection_established {false}; 40 | unsigned long last_connection_established {-1UL / 2UL}; 41 | bool connection_closing {false}; 42 | ReceiveTXTcallback receiveTXTcallback = [] (const char *, size_t) {return false;}; 43 | 44 | void maintainWsConn() { 45 | if (mocpp_tick_ms() - last_status_dbg_msg >= DEBUG_MSG_INTERVAL) { 46 | last_status_dbg_msg = mocpp_tick_ms(); 47 | 48 | //WS successfully connected? 49 | if (!isConnectionOpen()) { 50 | MO_DBG_DEBUG("WS unconnected"); 51 | } 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) { 52 | //WS connected but unresponsive 53 | MO_DBG_DEBUG("WS unresponsive"); 54 | } 55 | } 56 | 57 | if (websocket && isConnectionOpen() && 58 | stale_timeout_int && stale_timeout_int->getInt() > 0 && mocpp_tick_ms() - last_recv >= (stale_timeout_int->getInt() * 1000UL)) { 59 | MO_DBG_INFO("connection %s -- stale, reconnect", url.c_str()); 60 | reconnect(); 61 | return; 62 | } 63 | 64 | if (websocket && isConnectionOpen() && 65 | ws_ping_interval_int && ws_ping_interval_int->getInt() > 0 && mocpp_tick_ms() - last_hb >= (ws_ping_interval_int->getInt() * 1000UL)) { 66 | last_hb = mocpp_tick_ms(); 67 | MO_DBG_VERBOSE("omit heartbeat"); 68 | } 69 | 70 | if (websocket != NULL) { //connection pointer != NULL means that the socket is still open 71 | return; 72 | } 73 | 74 | if (url.empty()) { 75 | //cannot open OCPP connection: credentials missing 76 | return; 77 | } 78 | 79 | if (reconnect_interval_int && reconnect_interval_int->getInt() > 0 && mocpp_tick_ms() - last_reconnection_attempt < (reconnect_interval_int->getInt() * 1000UL)) { 80 | return; 81 | } 82 | 83 | MO_DBG_DEBUG("(re-)connect to %s", url.c_str()); 84 | 85 | last_reconnection_attempt = mocpp_tick_ms(); 86 | 87 | EmscriptenWebSocketCreateAttributes attr; 88 | emscripten_websocket_init_create_attributes(&attr); 89 | 90 | attr.url = url.c_str(); 91 | attr.protocols = "ocpp1.6"; 92 | attr.createOnMainThread = true; 93 | 94 | websocket = emscripten_websocket_new(&attr); 95 | if (websocket < 0) { 96 | MO_DBG_ERR("emscripten_websocket_new: %i", websocket); 97 | websocket = 0; 98 | } 99 | 100 | if (websocket <= 0) { 101 | return; 102 | } 103 | 104 | auto ret_open = emscripten_websocket_set_onopen_callback( 105 | websocket, 106 | this, 107 | [] (int eventType, const EmscriptenWebSocketOpenEvent *websocketEvent, void *userData) -> EM_BOOL { 108 | WasmOcppConnection *conn = reinterpret_cast(userData); 109 | MO_DBG_DEBUG("on open eventType: %i", eventType); 110 | MO_DBG_INFO("connection %s -- connected!", conn->getUrl()); 111 | conn->setConnectionOpen(true); 112 | conn->updateRcvTimer(); 113 | return true; 114 | }); 115 | if (ret_open < 0) { 116 | MO_DBG_ERR("emscripten_websocket_set_onopen_callback: %i", ret_open); 117 | } 118 | 119 | auto ret_message = emscripten_websocket_set_onmessage_callback( 120 | websocket, 121 | this, 122 | [] (int eventType, const EmscriptenWebSocketMessageEvent *websocketEvent, void *userData) -> EM_BOOL { 123 | WasmOcppConnection *conn = reinterpret_cast(userData); 124 | MO_DBG_DEBUG("evenType: %i", eventType); 125 | MO_DBG_DEBUG("txt: %s", websocketEvent->data ? (const char*) websocketEvent->data : "undefined"); 126 | if (!conn->getReceiveTXTcallback()((const char*) websocketEvent->data, websocketEvent->numBytes)) { 127 | MO_DBG_WARN("processing input message failed"); 128 | } 129 | conn->updateRcvTimer(); 130 | return true; 131 | }); 132 | if (ret_message < 0) { 133 | MO_DBG_ERR("emscripten_websocket_set_onmessage_callback: %i", ret_message); 134 | } 135 | 136 | auto ret_err = emscripten_websocket_set_onerror_callback( 137 | websocket, 138 | this, 139 | [] (int eventType, const EmscriptenWebSocketErrorEvent *websocketEvent, void *userData) -> EM_BOOL { 140 | WasmOcppConnection *conn = reinterpret_cast(userData); 141 | MO_DBG_DEBUG("on error eventType: %i", eventType); 142 | MO_DBG_INFO("connection %s -- %s", conn->getUrl(), "error"); 143 | conn->cleanConnection(); 144 | return true; 145 | }); 146 | if (ret_open < 0) { 147 | MO_DBG_ERR("emscripten_websocket_set_onopen_callback: %i", ret_open); 148 | } 149 | 150 | auto ret_close = emscripten_websocket_set_onclose_callback( 151 | websocket, 152 | this, 153 | [] (int eventType, const EmscriptenWebSocketCloseEvent *websocketEvent, void *userData) -> EM_BOOL { 154 | WasmOcppConnection *conn = reinterpret_cast(userData); 155 | MO_DBG_DEBUG("on close eventType: %i", eventType); 156 | MO_DBG_INFO("connection %s -- %s", conn->getUrl(), "closed"); 157 | conn->cleanConnection(); 158 | return true; 159 | }); 160 | if (ret_open < 0) { 161 | MO_DBG_ERR("emscripten_websocket_set_onopen_callback: %i", ret_open); 162 | } 163 | } 164 | 165 | void reconnect() { 166 | if (!websocket) { 167 | return; 168 | } 169 | auto ret = emscripten_websocket_close(websocket, 1000, "reconnect"); 170 | if (ret < 0) { 171 | MO_DBG_ERR("emscripten_websocket_close: %i", ret); 172 | } 173 | setConnectionOpen(false); 174 | } 175 | 176 | public: 177 | WasmOcppConnection( 178 | const char *backend_url_factory, 179 | const char *charge_box_id_factory, 180 | const char *auth_key_factory) { 181 | 182 | setting_backend_url_str = declareConfiguration( 183 | MO_CONFIG_EXT_PREFIX "BackendUrl", backend_url_factory, CONFIGURATION_VOLATILE, true, true); 184 | setting_cb_id_str = declareConfiguration( 185 | MO_CONFIG_EXT_PREFIX "ChargeBoxId", charge_box_id_factory, CONFIGURATION_VOLATILE, true, true); 186 | setting_auth_key_str = declareConfiguration( 187 | "AuthorizationKey", auth_key_factory, CONFIGURATION_VOLATILE, true, true); 188 | ws_ping_interval_int = declareConfiguration( 189 | "WebSocketPingInterval", 5, CONFIGURATION_VOLATILE); 190 | reconnect_interval_int = declareConfiguration( 191 | MO_CONFIG_EXT_PREFIX "ReconnectInterval", 10, CONFIGURATION_VOLATILE); 192 | stale_timeout_int = declareConfiguration( 193 | MO_CONFIG_EXT_PREFIX "StaleTimeout", 300, CONFIGURATION_VOLATILE); 194 | 195 | reloadConfigs(); //load WS creds with configs values 196 | 197 | MO_DBG_DEBUG("connection initialized"); 198 | 199 | maintainWsConn(); 200 | } 201 | 202 | ~WasmOcppConnection() { 203 | if (websocket) { 204 | emscripten_websocket_delete(websocket); 205 | websocket = NULL; 206 | } 207 | } 208 | 209 | void loop() override { 210 | maintainWsConn(); 211 | } 212 | 213 | bool sendTXT(const char *msg, size_t length) override { 214 | if (!websocket || !isConnectionOpen()) { 215 | return false; 216 | } 217 | 218 | if (auto ret = emscripten_websocket_send_utf8_text(websocket, msg) < 0) { 219 | MO_DBG_ERR("emscripten_websocket_send_utf8_text: %i", ret); 220 | return false; 221 | } 222 | 223 | return true; 224 | } 225 | 226 | void setReceiveTXTcallback(MicroOcpp::ReceiveTXTcallback &receiveTXT) override { 227 | this->receiveTXTcallback = receiveTXT; 228 | } 229 | 230 | MicroOcpp::ReceiveTXTcallback &getReceiveTXTcallback() { 231 | return receiveTXTcallback; 232 | } 233 | 234 | void setBackendUrl(const char *backend_url_cstr) { 235 | if (!backend_url_cstr) { 236 | MO_DBG_ERR("invalid argument"); 237 | return; 238 | } 239 | 240 | if (setting_backend_url_str) { 241 | setting_backend_url_str->setString(backend_url_cstr); 242 | configuration_save(); 243 | } 244 | } 245 | 246 | void setChargeBoxId(const char *cb_id_cstr) { 247 | if (!cb_id_cstr) { 248 | MO_DBG_ERR("invalid argument"); 249 | return; 250 | } 251 | 252 | if (setting_cb_id_str) { 253 | setting_cb_id_str->setString(cb_id_cstr); 254 | configuration_save(); 255 | } 256 | } 257 | 258 | void setAuthKey(const char *auth_key_cstr) { 259 | if (!auth_key_cstr) { 260 | MO_DBG_ERR("invalid argument"); 261 | return; 262 | } 263 | 264 | if (setting_auth_key_str) { 265 | setting_auth_key_str->setString(auth_key_cstr); 266 | configuration_save(); 267 | } 268 | } 269 | 270 | void reloadConfigs() { 271 | 272 | reconnect(); //closes WS connection; will be reopened in next maintainWsConn execution 273 | 274 | /* 275 | * reload WS credentials from configs 276 | */ 277 | if (setting_backend_url_str) { 278 | backend_url = setting_backend_url_str->getString(); 279 | } 280 | 281 | if (setting_cb_id_str) { 282 | cb_id = setting_cb_id_str->getString(); 283 | } 284 | 285 | if (setting_auth_key_str) { 286 | auth_key = setting_auth_key_str->getString(); 287 | } 288 | 289 | /* 290 | * determine new URL and auth token with updated WS credentials 291 | */ 292 | 293 | url.clear(); 294 | basic_auth64.clear(); 295 | 296 | if (backend_url.empty()) { 297 | MO_DBG_DEBUG("empty URL closes connection"); 298 | return; 299 | } else { 300 | url = backend_url; 301 | 302 | if (url.back() != '/' && !cb_id.empty()) { 303 | url.append("/"); 304 | } 305 | 306 | url.append(cb_id); 307 | } 308 | 309 | if (!auth_key.empty()) { 310 | MO_DBG_WARN("WASM app does not support Securiy Profile 2 yet"); 311 | } else { 312 | MO_DBG_DEBUG("no authentication"); 313 | (void) 0; 314 | } 315 | } 316 | 317 | const char *getBackendUrl() {return backend_url.c_str();} 318 | const char *getChargeBoxId() {return cb_id.c_str();} 319 | const char *getAuthKey() {return auth_key.c_str();} 320 | 321 | const char *getUrl() {return url.c_str();} 322 | 323 | void setConnectionOpen(bool open) { 324 | if (open) { 325 | connection_established = true; 326 | last_connection_established = mocpp_tick_ms(); 327 | } else { 328 | connection_closing = true; 329 | } 330 | } 331 | bool isConnectionOpen() {return connection_established && !connection_closing;} 332 | void cleanConnection() { 333 | connection_established = false; 334 | connection_closing = false; 335 | websocket = NULL; 336 | } 337 | 338 | void updateRcvTimer() { 339 | last_recv = mocpp_tick_ms(); 340 | } 341 | unsigned long getLastRecv() override { 342 | return last_recv; 343 | } 344 | unsigned long getLastConnected() override { 345 | return last_connection_established; 346 | } 347 | 348 | }; 349 | 350 | WasmOcppConnection *wasm_ocpp_connection_instance = nullptr; 351 | 352 | MicroOcpp::Connection *wasm_ocpp_connection_init(const char *backend_url_default, const char *charge_box_id_default, const char *auth_key_default) { 353 | if (!wasm_ocpp_connection_instance) { 354 | wasm_ocpp_connection_instance = new WasmOcppConnection(backend_url_default, charge_box_id_default, auth_key_default); 355 | } 356 | 357 | return wasm_ocpp_connection_instance; 358 | } 359 | 360 | #define MO_WASM_RESP_BUF_SIZE 1024 361 | char wasm_resp_buf [MO_WASM_RESP_BUF_SIZE] = {'\0'}; 362 | 363 | //exported to WebAssembly 364 | extern "C" char* mocpp_wasm_api_call(const char *endpoint, const char *method, const char *body) { 365 | MO_DBG_DEBUG("API call: %s, %s, %s", endpoint, method, body); 366 | 367 | auto method_parsed = Method::UNDEFINED; 368 | if (!strcmp(method, "GET")) { 369 | method_parsed = Method::GET; 370 | } else if (!strcmp(method, "POST")) { 371 | method_parsed = Method::POST; 372 | } 373 | 374 | //handle endpoint /websocket 375 | if (!strcmp(endpoint, "/websocket")) { 376 | sprintf(wasm_resp_buf, "%s", "{}"); 377 | if (!wasm_ocpp_connection_instance) { 378 | MO_DBG_ERR("no websocket instance"); 379 | return nullptr; 380 | } 381 | StaticJsonDocument<512> request; 382 | if (*body) { 383 | auto err = deserializeJson(request, body); 384 | if (err) { 385 | MO_DBG_WARN("malformatted body: %s", err.c_str()); 386 | return nullptr; 387 | } 388 | } 389 | 390 | auto webSocketPingInterval = declareConfiguration("WebSocketPingInterval", 5, CONFIGURATION_VOLATILE); 391 | auto reconnectInterval = declareConfiguration(MO_CONFIG_EXT_PREFIX "ReconnectInterval", 10, CONFIGURATION_VOLATILE); 392 | 393 | if (method_parsed == Method::POST) { 394 | if (request.containsKey("backendUrl")) { 395 | wasm_ocpp_connection_instance->setBackendUrl(request["backendUrl"] | ""); 396 | } 397 | if (request.containsKey("chargeBoxId")) { 398 | wasm_ocpp_connection_instance->setChargeBoxId(request["chargeBoxId"] | ""); 399 | } 400 | if (request.containsKey("authorizationKey")) { 401 | wasm_ocpp_connection_instance->setAuthKey(request["authorizationKey"] | ""); 402 | } 403 | wasm_ocpp_connection_instance->reloadConfigs(); 404 | if (request.containsKey("pingInterval")) { 405 | webSocketPingInterval->setInt(request["pingInterval"] | 0); 406 | } 407 | if (request.containsKey("reconnectInterval")) { 408 | reconnectInterval->setInt(request["reconnectInterval"] | 0); 409 | } 410 | if (request.containsKey("dnsUrl")) { 411 | MO_DBG_WARN("dnsUrl not implemented"); 412 | (void)0; 413 | } 414 | MicroOcpp::configuration_save(); 415 | } 416 | 417 | StaticJsonDocument<512> response; 418 | response["backendUrl"] = wasm_ocpp_connection_instance->getBackendUrl(); 419 | response["chargeBoxId"] = wasm_ocpp_connection_instance->getChargeBoxId(); 420 | response["authorizationKey"] = wasm_ocpp_connection_instance->getAuthKey(); 421 | 422 | response["pingInterval"] = webSocketPingInterval ? webSocketPingInterval->getInt() : 0; 423 | response["reconnectInterval"] = reconnectInterval ? reconnectInterval->getInt() : 0; 424 | serializeJson(response, wasm_resp_buf, MO_WASM_RESP_BUF_SIZE); 425 | return wasm_resp_buf; 426 | } 427 | 428 | //forward all other endpoints to main API 429 | int status = mocpp_api_call(endpoint, method_parsed, body, wasm_resp_buf, MO_WASM_RESP_BUF_SIZE); 430 | 431 | if (status == 200) { 432 | //200: HTTP status code Success 433 | MO_DBG_DEBUG("API resp: %s", wasm_resp_buf); 434 | return wasm_resp_buf; 435 | } else { 436 | MO_DBG_DEBUG("API err: %i", status); 437 | return nullptr; 438 | } 439 | } 440 | -------------------------------------------------------------------------------- /src/net_wasm.h: -------------------------------------------------------------------------------- 1 | // matth-x/MicroOcppSimulator 2 | // Copyright Matthias Akstaller 2022 - 2024 3 | // GPL-3.0 License 4 | 5 | #ifndef MO_NET_WASM_H 6 | #define MO_NET_WASM_H 7 | 8 | #if MO_NETLIB == MO_NETLIB_WASM 9 | 10 | #include 11 | 12 | MicroOcpp::Connection *wasm_ocpp_connection_init(const char *backend_url_default, const char *charge_box_id_default, const char *auth_key_default); 13 | 14 | #endif //MO_NETLIB == MO_NETLIB_WASM 15 | 16 | #endif 17 | --------------------------------------------------------------------------------