From 3babe1e3f53e48e7abb9078f46cb7c1e5a6468d3 Mon Sep 17 00:00:00 2001 From: yan9a Date: Thu, 22 Aug 2024 23:03:58 +1200 Subject: [PATCH 01/10] Update tcp server --- .github/workflows/cmake.yml | 112 +- .gitignore | 94 +- CMakeCPack.txt | 10 +- CMakeLists.txt | 179 +- CMakeM1.txt | 122 +- Dockerfile | 94 +- LICENSE | 42 +- README.md | 262 +-- ceutilw.bat | 26 +- examples/CMakeLists.txt | 34 +- examples/I2C/CMakeLists.txt | 22 +- examples/I2C/I2C.sh | 120 +- examples/I2C/src/I2C.cpp | 50 +- examples/Log/CMakeLists.txt | 24 +- examples/Log/Log.sh | 120 +- examples/Log/Log/Log.sln | 62 +- examples/Log/Log/Log.vcxproj | 268 +-- examples/Log/Log/Log.vcxproj.filters | 42 +- examples/Log/Logw.bat | 22 +- examples/Log/src/Log.cpp | 38 +- examples/Modbus/CMakeLists.txt | 22 +- examples/Modbus/Modbus.sh | 120 +- examples/Modbus/Modbus/Modbus.sln | 62 +- examples/Modbus/Modbus/Modbus.vcxproj | 268 +-- examples/Modbus/Modbus/Modbus.vcxproj.filters | 42 +- examples/Modbus/Modbusw.bat | 22 +- examples/Modbus/src/Modbus.cpp | 138 +- examples/ModbusCmd/CMakeLists.txt | 24 +- examples/ModbusCmd/ModbusCmd.sh | 120 +- examples/ModbusCmd/ModbusCmd/ModbusCmd.sln | 62 +- .../ModbusCmd/ModbusCmd/ModbusCmd.vcxproj | 322 +-- .../ModbusCmd/ModbusCmd.vcxproj.filters | 42 +- examples/ModbusCmd/modbuscmdw.bat | 22 +- examples/ModbusCmd/src/ModbusCmd.cpp | 812 ++++---- examples/Serial/CMakeLists.txt | 18 +- examples/Serial/Serial.sh | 120 +- examples/Serial/Serial/Serial.sln | 62 +- examples/Serial/Serial/Serial.vcxproj | 268 +-- examples/Serial/Serial/Serial.vcxproj.filters | 42 +- examples/Serial/serialw.bat | 22 +- examples/Serial/src/Serial.cpp | 100 +- examples/SerialGui/CMakeLists.txt | 24 +- examples/SerialGui/SerialGui.sh | 120 +- examples/SerialGui/SerialGui/SerialGui.sln | 62 +- .../SerialGui/SerialGui/SerialGui.vcxproj | 322 +-- .../SerialGui/SerialGui.vcxproj.filters | 42 +- examples/SerialGui/serialguiw.bat | 22 +- examples/SerialGui/src/SerialGui.cpp | 884 ++++----- examples/SerialGui/src/sample.xpm | 88 +- examples/Timer/CMakeLists.txt | 22 +- examples/Timer/Timer.sh | 120 +- examples/Timer/Timer/Timer.sln | 62 +- examples/Timer/Timer/Timer.vcxproj | 322 +-- examples/Timer/Timer/Timer.vcxproj.filters | 42 +- examples/Timer/src/Timer.cpp | 62 +- examples/Timer/timerw.bat | 22 +- examples/UDP/CMakeLists.txt | 24 +- examples/UDP/UDP.sh | 120 +- examples/UDP/UDPw.bat | 22 +- examples/UDP/src/UDP.cpp | 88 +- examples/WxSerial/CMakeLists.txt | 24 +- examples/WxSerial/WxSerial.sh | 120 +- examples/WxSerial/src/WxSerial.cpp | 60 +- examples/WxSerial/wxserialw.bat | 22 +- examples/buildall.sh | 14 +- examples/buildallw.bat | 14 +- examples/interface/CMakeLists.txt | 22 +- examples/interface/interface.bat | 22 +- examples/interface/interface.sh | 120 +- examples/interface/src/main.cpp | 58 +- examples/interface/vsprj/interface.sln | 62 +- examples/interface/vsprj/interface.vcxproj | 322 +-- .../interface/vsprj/interface.vcxproj.filters | 42 +- examples/kbhit/CMakeLists.txt | 22 +- examples/kbhit/kbhit.sh | 120 +- examples/kbhit/kbhit/kbhit.sln | 62 +- examples/kbhit/kbhit/kbhit.vcxproj | 322 +-- examples/kbhit/kbhit/kbhit.vcxproj.filters | 42 +- examples/kbhit/kbhitw.bat | 22 +- examples/kbhit/src/main.cpp | 86 +- examples/rsakeygen/CMakeLists.txt | 24 +- examples/rsakeygen/rsakeygen.sh | 120 +- examples/rsakeygen/rsakeygen/rsakeygen.sln | 62 +- .../rsakeygen/rsakeygen/rsakeygen.vcxproj | 274 +-- examples/rsakeygen/rsakeygenw.bat | 22 +- examples/rsakeygen/src/rsakeygen.cpp | 54 +- examples/tcpclient/CMakeLists.txt | 22 +- examples/tcpclient/src/tcpclient.cpp | 424 ++-- examples/tcpclient/tcpclient/tcpclient.sln | 62 +- .../tcpclient/tcpclient/tcpclient.vcxproj | 328 ++-- examples/tcpclient/tcpclientw.bat | 22 +- examples/tcpsvr/src/tcpsvr.cpp | 362 ++-- examples/tcpsvr/tcpsvr/tcpsvr.sln | 62 +- examples/tcpsvr/tcpsvr/tcpsvr.vcxproj | 328 ++-- examples/tcpsvr/tcpsvrw.bat | 22 +- include/ce/ceDES.h | 140 +- include/ce/ceFraChecksum.h | 96 +- include/ce/ceFraCmd.h | 42 +- include/ce/ceInterface.h | 72 +- include/ce/ceMacros.h | 83 +- include/ce/ceMisc.h | 122 +- include/ce/ceMmDateTime.h | 692 +++---- include/ce/ceModbus.h | 88 +- include/ce/ceRSA_OS.h | 124 +- include/ce/ceSHA1.h | 114 +- include/ce/ceTcpServer.h | 55 - include/ce/ceUDP.h | 116 +- include/ce/ceWxSerial.h | 64 +- include/ce/cewxcvMisc.h | 68 +- src/ceDES.cpp | 984 +++++----- src/ceFraChecksum.cpp | 208 +- src/ceFraCmd.cpp | 92 +- src/ceInterface.cpp | 48 +- src/ceMisc.cpp | 436 ++--- src/ceMmDateTime.cpp | 1738 ++++++++--------- src/ceModbus.cpp | 412 ++-- src/ceRSA_OS.cpp | 366 ++-- src/ceSHA1.cpp | 632 +++--- src/ceSerial.cpp | 1234 ++++++------ src/ceTcpServer.cpp | 269 --- src/ceUDP.cpp | 374 ++-- src/ceWxSerial.cpp | 106 +- src/cewxcvMisc.cpp | 88 +- test.sh | 24 +- test/CMakeLists.txt | 34 +- test/testDES/CMakeLists.txt | 30 +- test/testDES/main.cpp | 64 +- test/testJson/CMakeLists.txt | 30 +- test/testJson/main.cpp | 72 +- test/testRSA_OS/CMakeLists.txt | 30 +- test/testRSA_OS/main.cpp | 116 +- test/testSHA1/CMakeLists.txt | 30 +- test/testSHA1/main.cpp | 52 +- testw.bat | 22 +- vcprj/ceutil.sln | 62 +- vcprj/ceutil.vcxproj | 465 +++-- vcprj/ceutil.vcxproj.filters | 317 ++- 137 files changed, 10290 insertions(+), 10610 deletions(-) delete mode 100644 include/ce/ceTcpServer.h delete mode 100644 src/ceTcpServer.cpp diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index be341b7..b76fe72 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -1,57 +1,57 @@ -name: CMake - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] - -env: - # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - BUILD_TYPE: Release - WS_DIR: /__w/ceutil/ceutil - INSTALL_DIR: /usr/local - -jobs: - build: - # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. - # You can convert this to a matrix build if you need cross-platform coverage. - # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix - runs-on: ubuntu-latest - container: yan9a/cebian:latest - - steps: - - uses: actions/checkout@v3 - - - name: Configure CMake for Lib - run: cmake -B ${{env.WS_DIR}}/build -S ${{env.WS_DIR}} -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_INSTALL_PREFIX=${{env.INSTALL_DIR}} - - - name: Build Lib - run: cmake --build ${{env.WS_DIR}}/build --config ${{env.BUILD_TYPE}} - - - name: Install Lib - run: cmake --install ${{env.WS_DIR}}/build --config ${{env.BUILD_TYPE}} - - - name: Configure CMake for unit tests - # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. - # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type - # run: pwd && cmake -B ${{env.WS_DIR}}/test/build -S ${{env.WS_DIR}}/test -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} - run: cmake -B ${{env.WS_DIR}}/test/build -S ${{env.WS_DIR}}/test -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} - - - name: Build unit tests - # Build your program with the given configuration - run: cmake --build ${{env.WS_DIR}}/test/build --config ${{env.BUILD_TYPE}} - - - name: Run unit tests - #working-directory: ${{github.workspace}}/mytests/build - working-directory: ${{env.WS_DIR}}/test/build - # Execute tests defined by the CMake configuration. - # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail - run: ctest -C ${{env.BUILD_TYPE}} - - - name: Configure CMake for examples - run: cmake -B ${{env.WS_DIR}}/examples/build -S ${{env.WS_DIR}}/examples -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} - - - name: Build examples - # Build your program with the given configuration +name: CMake + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +env: + # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) + BUILD_TYPE: Release + WS_DIR: /__w/ceutil/ceutil + INSTALL_DIR: /usr/local + +jobs: + build: + # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. + # You can convert this to a matrix build if you need cross-platform coverage. + # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix + runs-on: ubuntu-latest + container: yan9a/cebian:latest + + steps: + - uses: actions/checkout@v3 + + - name: Configure CMake for Lib + run: cmake -B ${{env.WS_DIR}}/build -S ${{env.WS_DIR}} -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_INSTALL_PREFIX=${{env.INSTALL_DIR}} + + - name: Build Lib + run: cmake --build ${{env.WS_DIR}}/build --config ${{env.BUILD_TYPE}} + + - name: Install Lib + run: cmake --install ${{env.WS_DIR}}/build --config ${{env.BUILD_TYPE}} + + - name: Configure CMake for unit tests + # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. + # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type + # run: pwd && cmake -B ${{env.WS_DIR}}/test/build -S ${{env.WS_DIR}}/test -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} + run: cmake -B ${{env.WS_DIR}}/test/build -S ${{env.WS_DIR}}/test -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} + + - name: Build unit tests + # Build your program with the given configuration + run: cmake --build ${{env.WS_DIR}}/test/build --config ${{env.BUILD_TYPE}} + + - name: Run unit tests + #working-directory: ${{github.workspace}}/mytests/build + working-directory: ${{env.WS_DIR}}/test/build + # Execute tests defined by the CMake configuration. + # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail + run: ctest -C ${{env.BUILD_TYPE}} + + - name: Configure CMake for examples + run: cmake -B ${{env.WS_DIR}}/examples/build -S ${{env.WS_DIR}}/examples -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} + + - name: Build examples + # Build your program with the given configuration run: cmake --build ${{env.WS_DIR}}/examples/build --config ${{env.BUILD_TYPE}} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 3df0c17..f461b87 100644 --- a/.gitignore +++ b/.gitignore @@ -1,47 +1,47 @@ -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app - -out/ -build/ -buildw/ -cmake-build-debug/ -ceutil/ -.vs/ -.vscode/ -.idea/ -x64/ -*.log -*.vcxproj.user -Testing/ -Debug/ -Release/ +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +out/ +build/ +buildw/ +cmake-build-debug/ +ceutil/ +.vs/ +.vscode/ +.idea/ +x64/ +*.log +*.vcxproj.user +Testing/ +Debug/ +Release/ diff --git a/CMakeCPack.txt b/CMakeCPack.txt index 5e783ad..bddaf13 100644 --- a/CMakeCPack.txt +++ b/CMakeCPack.txt @@ -1,5 +1,5 @@ -include(InstallRequiredSystemLibraries) -set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENSE") -# set(CPACK_PROJECT_NAME ${PROJECT_NAME}) -# set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) -include(CPack) +include(InstallRequiredSystemLibraries) +set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENSE") +# set(CPACK_PROJECT_NAME ${PROJECT_NAME}) +# set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) +include(CPack) diff --git a/CMakeLists.txt b/CMakeLists.txt index f6fbff2..b34bbf5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,90 +1,89 @@ -cmake_minimum_required(VERSION 3.0.0) -project (ceutil VERSION 2.1.0) -# version 1.1.0 Added DES, SHA, RSA -# version 2.1.0 Replace wxAppConsole with wxEvtHandler, add TCP server - - -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) -message(STATUS "Project dir = ${PROJECT_SOURCE_DIR}") -message(STATUS "Project version = ${CMAKE_PROJECT_VERSION}") -set(ADDCV YES) -if(WIN32) - # For windows ------------------------------------------------------- - # Set VCPKG_ROOT environmental variable for vcpkg root folder - message(STATUS "vcpkg dir = $ENV{VCPKG_ROOT}") - if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4") - # if 32 bits - message(STATUS "Generator x86-windows") - include_directories($ENV{VCPKG_ROOT}/installed/x86-windows/include) - link_directories($ENV{VCPKG_ROOT}/installed/x86-windows/lib) - else() - # if 64 bits - message(STATUS "Generator x64-windows") - include_directories($ENV{VCPKG_ROOT}/installed/x64-windows/include) - link_directories($ENV{VCPKG_ROOT}/installed/x64-windows/lib) - endif() - find_package(jsoncpp REQUIRED) - set(JSONCPP_LIBRARIES jsoncpp) - find_package(wxWidgets COMPONENTS core net base REQUIRED) - if(ADDCV) - find_package(OpenCV REQUIRED) - endif() - find_package(OpenSSL REQUIRED) - add_definitions(-D_CRT_SECURE_NO_WARNINGS) -else() - # For linux ------------------------------------------------------- - find_package(PkgConfig REQUIRED) - pkg_check_modules(JSONCPP jsoncpp) - link_libraries(${JSONCPP_LIBRARIES}) - include_directories(${JSONCPP_INCLUDE_DIRS}) - find_package(wxWidgets COMPONENTS core net base REQUIRED) - include("${wxWidgets_USE_FILE}") - if(ADDCV) - find_package(OpenCV REQUIRED) - include_directories(${OpenCV_INCLUDE_DIR}) - endif() - find_package(OpenSSL REQUIRED) -endif() -# ------------------------------------------------------------------ -set(LIBS - ${JSONCPP_LIBRARIES} - ${wxWidgets_LIBRARIES} - OpenSSL::SSL OpenSSL::Crypto -) -if(ADDCV) - set(LIBS ${LIBS} ${OpenCV_LIBS}) -endif() -message(STATUS "List of libraries = ${LIBS}") -include_directories(${PROJECT_SOURCE_DIR}/include) -add_library(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/ceDateTime.cpp -${PROJECT_SOURCE_DIR}/src/ceMmDateTime.cpp -${PROJECT_SOURCE_DIR}/src/ceLog.cpp -${PROJECT_SOURCE_DIR}/src/ceSerial.cpp -${PROJECT_SOURCE_DIR}/src/ceWxTmr.cpp -${PROJECT_SOURCE_DIR}/src/ceUDP.cpp -${PROJECT_SOURCE_DIR}/src/ceTcpServer.cpp -${PROJECT_SOURCE_DIR}/src/ceTcpClient.cpp -${PROJECT_SOURCE_DIR}/src/ceMisc.cpp -${PROJECT_SOURCE_DIR}/src/ceFrame.cpp -${PROJECT_SOURCE_DIR}/src/ceFraChecksum.cpp -${PROJECT_SOURCE_DIR}/src/ceFraCmd.cpp -${PROJECT_SOURCE_DIR}/src/ceI2C.cpp -${PROJECT_SOURCE_DIR}/src/cePCA9535.cpp -${PROJECT_SOURCE_DIR}/src/ceConfig.cpp -${PROJECT_SOURCE_DIR}/src/ceModbus.cpp -${PROJECT_SOURCE_DIR}/src/ceWxSerial.cpp -${PROJECT_SOURCE_DIR}/src/cewxcvMisc.cpp -${PROJECT_SOURCE_DIR}/src/ceDES.cpp -${PROJECT_SOURCE_DIR}/src/ceSHA1.cpp -${PROJECT_SOURCE_DIR}/src/ceRSA_OS.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) -install(TARGETS ${PROJECT_NAME} DESTINATION lib) -install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/ce - DESTINATION include - FILES_MATCHING - PATTERN "*.h" -) +cmake_minimum_required(VERSION 3.0.0) +project (ceutil VERSION 2.1.0) +# version 1.1.0 Added DES, SHA, RSA +# version 2.1.0 Replace wxAppConsole with wxEvtHandler, add TCP server + + +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +message(STATUS "Project dir = ${PROJECT_SOURCE_DIR}") +message(STATUS "Project version = ${CMAKE_PROJECT_VERSION}") +set(ADDCV YES) +if(WIN32) + # For windows ------------------------------------------------------- + # Set VCPKG_ROOT environmental variable for vcpkg root folder + message(STATUS "vcpkg dir = $ENV{VCPKG_ROOT}") + if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4") + # if 32 bits + message(STATUS "Generator x86-windows") + include_directories($ENV{VCPKG_ROOT}/installed/x86-windows/include) + link_directories($ENV{VCPKG_ROOT}/installed/x86-windows/lib) + else() + # if 64 bits + message(STATUS "Generator x64-windows") + include_directories($ENV{VCPKG_ROOT}/installed/x64-windows/include) + link_directories($ENV{VCPKG_ROOT}/installed/x64-windows/lib) + endif() + find_package(jsoncpp REQUIRED) + set(JSONCPP_LIBRARIES jsoncpp) + find_package(wxWidgets COMPONENTS core net base REQUIRED) + if(ADDCV) + find_package(OpenCV REQUIRED) + endif() + find_package(OpenSSL REQUIRED) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) +else() + # For linux ------------------------------------------------------- + find_package(PkgConfig REQUIRED) + pkg_check_modules(JSONCPP jsoncpp) + link_libraries(${JSONCPP_LIBRARIES}) + include_directories(${JSONCPP_INCLUDE_DIRS}) + find_package(wxWidgets COMPONENTS core net base REQUIRED) + include("${wxWidgets_USE_FILE}") + if(ADDCV) + find_package(OpenCV REQUIRED) + include_directories(${OpenCV_INCLUDE_DIR}) + endif() + find_package(OpenSSL REQUIRED) +endif() +# ------------------------------------------------------------------ +set(LIBS + ${JSONCPP_LIBRARIES} + ${wxWidgets_LIBRARIES} + OpenSSL::SSL OpenSSL::Crypto +) +if(ADDCV) + set(LIBS ${LIBS} ${OpenCV_LIBS}) +endif() +message(STATUS "List of libraries = ${LIBS}") +include_directories(${PROJECT_SOURCE_DIR}/include) +add_library(${PROJECT_NAME} +${PROJECT_SOURCE_DIR}/src/ceDateTime.cpp +${PROJECT_SOURCE_DIR}/src/ceMmDateTime.cpp +${PROJECT_SOURCE_DIR}/src/ceLog.cpp +${PROJECT_SOURCE_DIR}/src/ceSerial.cpp +${PROJECT_SOURCE_DIR}/src/ceWxTmr.cpp +${PROJECT_SOURCE_DIR}/src/ceUDP.cpp +${PROJECT_SOURCE_DIR}/src/ceTcpClient.cpp +${PROJECT_SOURCE_DIR}/src/ceMisc.cpp +${PROJECT_SOURCE_DIR}/src/ceFrame.cpp +${PROJECT_SOURCE_DIR}/src/ceFraChecksum.cpp +${PROJECT_SOURCE_DIR}/src/ceFraCmd.cpp +${PROJECT_SOURCE_DIR}/src/ceI2C.cpp +${PROJECT_SOURCE_DIR}/src/cePCA9535.cpp +${PROJECT_SOURCE_DIR}/src/ceConfig.cpp +${PROJECT_SOURCE_DIR}/src/ceModbus.cpp +${PROJECT_SOURCE_DIR}/src/ceWxSerial.cpp +${PROJECT_SOURCE_DIR}/src/cewxcvMisc.cpp +${PROJECT_SOURCE_DIR}/src/ceDES.cpp +${PROJECT_SOURCE_DIR}/src/ceSHA1.cpp +${PROJECT_SOURCE_DIR}/src/ceRSA_OS.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) +install(TARGETS ${PROJECT_NAME} DESTINATION lib) +install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/ce + DESTINATION include + FILES_MATCHING + PATTERN "*.h" +) diff --git a/CMakeM1.txt b/CMakeM1.txt index 292a0f5..954a685 100644 --- a/CMakeM1.txt +++ b/CMakeM1.txt @@ -1,62 +1,62 @@ -# CMakeM1 checks ADDCV variable whether to include OpenCV -# together with ceutil, wxWidgets, and jsoncpp -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows - -message(STATUS "Project dir = ${PROJECT_SOURCE_DIR}") -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) -message(STATUS "Project version = ${CMAKE_PROJECT_VERSION}") - -if(WIN32) - # For windows ------------------------------------------------------- - # Set VCPKG_ROOT environmental variable for vcpkg root folder - message(STATUS "vcpkg dir = $ENV{VCPKG_ROOT}") - if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4") - # if 32 bits - message(STATUS "Generator x86-windows") - include_directories($ENV{VCPKG_ROOT}/installed/x86-windows/include) - link_directories($ENV{VCPKG_ROOT}/installed/x86-windows/lib) - else() - # if 64 bits - message(STATUS "Generator x64-windows") - include_directories($ENV{VCPKG_ROOT}/installed/x64-windows/include) - link_directories($ENV{VCPKG_ROOT}/installed/x64-windows/lib) - endif() - find_package(jsoncpp REQUIRED) - set(JSONCPP_LIBRARIES jsoncpp) - find_package(wxWidgets COMPONENTS core net base REQUIRED) - if(ADDCV) - find_package(OpenCV REQUIRED) - endif() - find_package(OpenSSL REQUIRED) - set(WIN32OPT WIN32) - add_definitions(-D_CRT_SECURE_NO_WARNINGS) -else() - # For linux ------------------------------------------------------- - find_package(PkgConfig REQUIRED) - pkg_check_modules(JSONCPP jsoncpp) - link_libraries(${JSONCPP_LIBRARIES}) - include_directories(${JSONCPP_INCLUDE_DIRS}) - find_package(wxWidgets COMPONENTS core net base REQUIRED) - include("${wxWidgets_USE_FILE}") - if(ADDCV) - find_package(OpenCV REQUIRED) - include_directories(${OpenCV_INCLUDE_DIR}) - endif() - find_package(OpenSSL REQUIRED) -endif() -# ------------------------------------------------------------------ -set(LIBS - ceutil - ${JSONCPP_LIBRARIES} - ${wxWidgets_LIBRARIES} - OpenSSL::SSL OpenSSL::Crypto - ) -if(ADDCV) - set(LIBS ${LIBS} ${OpenCV_LIBS}) -endif() - -message(STATUS "LIBS = ${LIBS}") +# CMakeM1 checks ADDCV variable whether to include OpenCV +# together with ceutil, wxWidgets, and jsoncpp +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows + +message(STATUS "Project dir = ${PROJECT_SOURCE_DIR}") +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +message(STATUS "Project version = ${CMAKE_PROJECT_VERSION}") + +if(WIN32) + # For windows ------------------------------------------------------- + # Set VCPKG_ROOT environmental variable for vcpkg root folder + message(STATUS "vcpkg dir = $ENV{VCPKG_ROOT}") + if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4") + # if 32 bits + message(STATUS "Generator x86-windows") + include_directories($ENV{VCPKG_ROOT}/installed/x86-windows/include) + link_directories($ENV{VCPKG_ROOT}/installed/x86-windows/lib) + else() + # if 64 bits + message(STATUS "Generator x64-windows") + include_directories($ENV{VCPKG_ROOT}/installed/x64-windows/include) + link_directories($ENV{VCPKG_ROOT}/installed/x64-windows/lib) + endif() + find_package(jsoncpp REQUIRED) + set(JSONCPP_LIBRARIES jsoncpp) + find_package(wxWidgets COMPONENTS core net base REQUIRED) + if(ADDCV) + find_package(OpenCV REQUIRED) + endif() + find_package(OpenSSL REQUIRED) + set(WIN32OPT WIN32) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) +else() + # For linux ------------------------------------------------------- + find_package(PkgConfig REQUIRED) + pkg_check_modules(JSONCPP jsoncpp) + link_libraries(${JSONCPP_LIBRARIES}) + include_directories(${JSONCPP_INCLUDE_DIRS}) + find_package(wxWidgets COMPONENTS core net base REQUIRED) + include("${wxWidgets_USE_FILE}") + if(ADDCV) + find_package(OpenCV REQUIRED) + include_directories(${OpenCV_INCLUDE_DIR}) + endif() + find_package(OpenSSL REQUIRED) +endif() +# ------------------------------------------------------------------ +set(LIBS + ceutil + ${JSONCPP_LIBRARIES} + ${wxWidgets_LIBRARIES} + OpenSSL::SSL OpenSSL::Crypto + ) +if(ADDCV) + set(LIBS ${LIBS} ${OpenCV_LIBS}) +endif() + +message(STATUS "LIBS = ${LIBS}") message(STATUS "WIN32OPT = ${WIN32OPT}") \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index b71f27d..4a42e47 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,47 +1,47 @@ -FROM debian:bookworm - -# required libs -RUN apt update \ - && apt install --no-install-recommends --no-install-suggests -y build-essential cmake \ - libgtk-3-dev checkinstall libwxgtk3.0-gtk3-dev \ - git pkg-config libavcodec-dev libavformat-dev libswscale-dev libopencv-dev \ - libjsoncpp-dev apt-transport-https ca-certificates \ - autoconf automake libtool - -RUN apt update \ - && apt install --no-install-recommends --no-install-suggests -y curl gdb cmake-extras \ - bc bison flex libssl-dev make \ - libboost-atomic-dev libboost-thread-dev libboost-system-dev libboost-date-time-dev libboost-regex-dev \ - libboost-filesystem-dev libboost-random-dev libboost-chrono-dev libboost-serialization-dev libwebsocketpp-dev \ - openssl ninja-build g++ \ - libcpprest-dev gpiod libgpiod-dev rsync sshpass\ - libpng-dev texlive doxygen - -RUN apt update \ - && apt-cache pkgnames | grep -i crypto++ \ - && apt install --no-install-recommends --no-install-suggests -y libcrypto++8 libcrypto++-utils libcrypto++-dev - -# ceutil lib -RUN git clone --depth 1 https://github.com/yan9a/ceutil.git \ - && cd ceutil && mkdir -p build && cd build \ - && cmake -D CMAKE_BUILD_TYPE=Release -D BUILD_SHARED_LIBS=ON -D CMAKE_INSTALL_PREFIX=/usr/local .. \ - && make && make install \ - && sh -c "echo /usr/local/lib > /etc/ld.so.conf.d/ceutil.conf" \ - && ldconfig && cd ../.. - -# nfc lib -RUN git clone --depth 1 https://github.com/NXPNFCLinux/linux_libnfc-nci.git \ - && cd linux_libnfc-nci && ./bootstrap \ - && ./configure --enable-alt && make && make install \ - && sh -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/nfc-nci.conf" \ - && ldconfig && cd .. - -# zint lib -RUN git clone https://github.com/woo-j/zint.git \ - && cd zint && mkdir -p build && cd build \ - && cmake .. && make && make install \ - && sh -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/zint.conf" \ - && ldconfig && cd ../.. - -EXPOSE 80 443 - +FROM debian:bookworm + +# required libs +RUN apt update \ + && apt install --no-install-recommends --no-install-suggests -y build-essential cmake \ + libgtk-3-dev checkinstall libwxgtk3.0-gtk3-dev \ + git pkg-config libavcodec-dev libavformat-dev libswscale-dev libopencv-dev \ + libjsoncpp-dev apt-transport-https ca-certificates \ + autoconf automake libtool + +RUN apt update \ + && apt install --no-install-recommends --no-install-suggests -y curl gdb cmake-extras \ + bc bison flex libssl-dev make \ + libboost-atomic-dev libboost-thread-dev libboost-system-dev libboost-date-time-dev libboost-regex-dev \ + libboost-filesystem-dev libboost-random-dev libboost-chrono-dev libboost-serialization-dev libwebsocketpp-dev \ + openssl ninja-build g++ \ + libcpprest-dev gpiod libgpiod-dev rsync sshpass\ + libpng-dev texlive doxygen + +RUN apt update \ + && apt-cache pkgnames | grep -i crypto++ \ + && apt install --no-install-recommends --no-install-suggests -y libcrypto++8 libcrypto++-utils libcrypto++-dev + +# ceutil lib +RUN git clone --depth 1 https://github.com/yan9a/ceutil.git \ + && cd ceutil && mkdir -p build && cd build \ + && cmake -D CMAKE_BUILD_TYPE=Release -D BUILD_SHARED_LIBS=ON -D CMAKE_INSTALL_PREFIX=/usr/local .. \ + && make && make install \ + && sh -c "echo /usr/local/lib > /etc/ld.so.conf.d/ceutil.conf" \ + && ldconfig && cd ../.. + +# nfc lib +RUN git clone --depth 1 https://github.com/NXPNFCLinux/linux_libnfc-nci.git \ + && cd linux_libnfc-nci && ./bootstrap \ + && ./configure --enable-alt && make && make install \ + && sh -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/nfc-nci.conf" \ + && ldconfig && cd .. + +# zint lib +RUN git clone https://github.com/woo-j/zint.git \ + && cd zint && mkdir -p build && cd build \ + && cmake .. && make && make install \ + && sh -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/zint.conf" \ + && ldconfig && cd ../.. + +EXPOSE 80 443 + diff --git a/LICENSE b/LICENSE index 7f01584..a6593f0 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,21 @@ -MIT License - -Copyright (c) 2021 Yan Naing Aye - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +MIT License + +Copyright (c) 2021 Yan Naing Aye + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 8f525a9..67a9725 100644 --- a/README.md +++ b/README.md @@ -1,132 +1,132 @@ -# ceutil - -Utilities by Cool-Emerald - -You can get the ceutil source from its repository using the following command. - - git clone --depth 1 https://github.com/yan9a/ceutil.git - -By default, and the IP address type for ceUDP will be wxIPV4address. -If you want to use wxIPV6address for it, you can modify IPAddress definition in ceUDP.h file. - -## Linux Setup - -After cloning the repository, you can use the following command to install the library. - - cd ceutil - ./ceutil.sh install - -If you encounter problems such as "bad interpreter" in running the script, especially when you copied the files from a Windows system, you can try to fix line end and change its mode to be executable as follows. - - sed -i -e 's/\r$//' ceutil.sh - chmod +x ceutil.sh - -Install script prompts the user to add to netdev and dialout groups and also to install required libraries. - -### Setup Visual Studio Code - -There are a few examples in the examples directory to demonstrate about using ceutil library. - -Install visual studio code as follows. - - sudo snap install code - -If you are using WSL, visual code is already there and you don't need the above command. -Go to a directory inside examples in the cloned repository and enter - - code . - -to open visual studio code. Install the following extensions on code IDE. - - * C/C++, Microsoft, C/C++ IntelliSense, debugging, and code browsing. - * C/C++ Extension Pack, Microsoft, Popular extensions for C++ development in Visual Studio Code. - * CMake Tools, Microsoft, Extended CMake support in Visual Studio Code - -Press ctrl+shift+p to open command pallete and choose the following commands. - - CMake: Configure - CMake: Build - CMake: Debug - -## Windows Setup - - -### Setup Visual Studio - -Get the latest visual studio community edition at - - https://visualstudio.microsoft.com/downloads/ - -and install tools for C++. - -For example, the following components can be selected. - - * MSVC vXXX - VS 20XX C++ x64/x86 build tool... - * C++ CMake tools for Windows - -### Setup cmake - -Get the latest cmake at - - https://cmake.org/download/ - -and adding path for it when installing. - -### Setup vcpkg - -We can use vcpkg to install required libraries for ceutil. Install vcpkg and setup required libraries as follows. - - git clone https://github.com/Microsoft/vcpkg.git - cd vcpkg - .\bootstrap-vcpkg.bat - .\vcpkg integrate install - .\vcpkg search opencv - .\vcpkg install opencv:x64-windows - .\vcpkg install jsoncpp:x64-windows - .\vcpkg install wxwidgets:x64-windows - .\vcpkg install openssl:x64-windows - -After cloning the vcpkg repository, add an environmental variable called 'VCPKG_ROOT' for the cloned directory path. For example, if you cloned the repository at "C:\Users\username\vcpkg" and find the bootstrap-vcpkg.bat file in that folder. You can define VCPKG_ROOT as system variables in "Environment Variables" - - System variables - Variable Value - VCPKG_ROOT C:\Users\username\vcpkg - -### Setup ceutil - -#### Visual Studio IDE - -Open visual studio solution in the ceutil sub-directory and build for x64 release and debug configurations. -You might need to add the preprocessor definition WXUSINGDLL if the project did not previously reference wxWidgets. - - - -#### Command Prompt - -You can also compile the library by opening "Command Prompt" and running ceutilw.bat. Currently, generator for cmake is set as - - -G "Visual Studio 17 2022" - -Check with - - cmake -h - -for other options. - -#### Installed Location - -Compiled library will be installed under - - "$(VCPKG_ROOT)\installed\x64-windows\lib" - -under respective configuration. It will also install the include files under - - "$(VCPKG_ROOT)\installed\x64-windows\include". - -### Open an Example Project - -After setting up the requried libraries, you can now open an example solution in examples directory of the cloned repository. - -### Docker - +# ceutil + +Utilities by Cool-Emerald + +You can get the ceutil source from its repository using the following command. + + git clone --depth 1 https://github.com/yan9a/ceutil.git + +By default, and the IP address type for ceUDP will be wxIPV4address. +If you want to use wxIPV6address for it, you can modify IPAddress definition in ceUDP.h file. + +## Linux Setup + +After cloning the repository, you can use the following command to install the library. + + cd ceutil + ./ceutil.sh install + +If you encounter problems such as "bad interpreter" in running the script, especially when you copied the files from a Windows system, you can try to fix line end and change its mode to be executable as follows. + + sed -i -e 's/\r$//' ceutil.sh + chmod +x ceutil.sh + +Install script prompts the user to add to netdev and dialout groups and also to install required libraries. + +### Setup Visual Studio Code + +There are a few examples in the examples directory to demonstrate about using ceutil library. + +Install visual studio code as follows. + + sudo snap install code + +If you are using WSL, visual code is already there and you don't need the above command. +Go to a directory inside examples in the cloned repository and enter + + code . + +to open visual studio code. Install the following extensions on code IDE. + + * C/C++, Microsoft, C/C++ IntelliSense, debugging, and code browsing. + * C/C++ Extension Pack, Microsoft, Popular extensions for C++ development in Visual Studio Code. + * CMake Tools, Microsoft, Extended CMake support in Visual Studio Code + +Press ctrl+shift+p to open command pallete and choose the following commands. + + CMake: Configure + CMake: Build + CMake: Debug + +## Windows Setup + + +### Setup Visual Studio + +Get the latest visual studio community edition at + + https://visualstudio.microsoft.com/downloads/ + +and install tools for C++. + +For example, the following components can be selected. + + * MSVC vXXX - VS 20XX C++ x64/x86 build tool... + * C++ CMake tools for Windows + +### Setup cmake + +Get the latest cmake at + + https://cmake.org/download/ + +and adding path for it when installing. + +### Setup vcpkg + +We can use vcpkg to install required libraries for ceutil. Install vcpkg and setup required libraries as follows. + + git clone https://github.com/Microsoft/vcpkg.git + cd vcpkg + .\bootstrap-vcpkg.bat + .\vcpkg integrate install + .\vcpkg search opencv + .\vcpkg install opencv:x64-windows + .\vcpkg install jsoncpp:x64-windows + .\vcpkg install wxwidgets:x64-windows + .\vcpkg install openssl:x64-windows + +After cloning the vcpkg repository, add an environmental variable called 'VCPKG_ROOT' for the cloned directory path. For example, if you cloned the repository at "C:\Users\username\vcpkg" and find the bootstrap-vcpkg.bat file in that folder. You can define VCPKG_ROOT as system variables in "Environment Variables" + + System variables + Variable Value + VCPKG_ROOT C:\Users\username\vcpkg + +### Setup ceutil + +#### Visual Studio IDE + +Open visual studio solution in the ceutil sub-directory and build for x64 release and debug configurations. +You might need to add the preprocessor definition WXUSINGDLL if the project did not previously reference wxWidgets. + + + +#### Command Prompt + +You can also compile the library by opening "Command Prompt" and running ceutilw.bat. Currently, generator for cmake is set as + + -G "Visual Studio 17 2022" + +Check with + + cmake -h + +for other options. + +#### Installed Location + +Compiled library will be installed under + + "$(VCPKG_ROOT)\installed\x64-windows\lib" + +under respective configuration. It will also install the include files under + + "$(VCPKG_ROOT)\installed\x64-windows\include". + +### Open an Example Project + +After setting up the requried libraries, you can now open an example solution in examples directory of the cloned repository. + +### Docker + Docker image 'yan9a/cebian' has all the required libraries for ceutil setup. Its Dockerfile can also be found in the root folder. \ No newline at end of file diff --git a/ceutilw.bat b/ceutilw.bat index c63516d..a789019 100644 --- a/ceutilw.bat +++ b/ceutilw.bat @@ -1,13 +1,13 @@ -@REM To run the script set VCPKG_ROOT environmental variable for vcpkg root folder -if exist buildw ( -echo deleting -rmdir /s /q buildw -) -cmake -G "Visual Studio 17 2022" -A x64 -B ./buildw -S ./ -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake" -DCMAKE_INSTALL_PREFIX="%VCPKG_ROOT%/installed/x64-windows/" -DCMAKE_DEBUG_POSTFIX=d -cd buildw -cmake --build . --config Release -cmake --install . --config Release -cmake --build . --config Debug -cmake --install . --config Debug - -cd .. +@REM To run the script set VCPKG_ROOT environmental variable for vcpkg root folder +if exist buildw ( +echo deleting +rmdir /s /q buildw +) +cmake -G "Visual Studio 17 2022" -A x64 -B ./buildw -S ./ -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake" -DCMAKE_INSTALL_PREFIX="%VCPKG_ROOT%/installed/x64-windows/" -DCMAKE_DEBUG_POSTFIX=d +cd buildw +cmake --build . --config Release +cmake --install . --config Release +cmake --build . --config Debug +cmake --install . --config Debug + +cd .. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index b00cebb..f4b5e91 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,17 +1,17 @@ -cmake_minimum_required(VERSION 3.0.0) -project (ceutileg) -message(STATUS "Base dir = ${CMAKE_SOURCE_DIR}") - -add_subdirectory(Log) -add_subdirectory(Modbus) -add_subdirectory(ModbusCmd) -add_subdirectory(Serial) -add_subdirectory(SerialGui) -add_subdirectory(Timer) -add_subdirectory(UDP) -add_subdirectory(WxSerial) -if(WIN32) - -else() -add_subdirectory(I2C) -endif() +cmake_minimum_required(VERSION 3.0.0) +project (ceutileg) +message(STATUS "Base dir = ${CMAKE_SOURCE_DIR}") + +add_subdirectory(Log) +add_subdirectory(Modbus) +add_subdirectory(ModbusCmd) +add_subdirectory(Serial) +add_subdirectory(SerialGui) +add_subdirectory(Timer) +add_subdirectory(UDP) +add_subdirectory(WxSerial) +if(WIN32) + +else() +add_subdirectory(I2C) +endif() diff --git a/examples/I2C/CMakeLists.txt b/examples/I2C/CMakeLists.txt index 55e75cc..677e692 100644 --- a/examples/I2C/CMakeLists.txt +++ b/examples/I2C/CMakeLists.txt @@ -1,11 +1,11 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(I2C VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(I2C VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/I2C/I2C.sh b/examples/I2C/I2C.sh index 6979d63..84086f0 100644 --- a/examples/I2C/I2C.sh +++ b/examples/I2C/I2C.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/I2C/src/I2C.cpp b/examples/I2C/src/I2C.cpp index 4539b28..965fca9 100644 --- a/examples/I2C/src/I2C.cpp +++ b/examples/I2C/src/I2C.cpp @@ -1,25 +1,25 @@ -#include "ce/ceUtil.h" -using namespace ce; - -int main(){ - cePCA9535 chip1(1,0x21);// bus = 1, addr = 0x21 - - chip1.Init(0x00, 0xFF, // output p0 all 0, and p1 all 1 - 0x00, 0x00, // p0 active high , p1 active high also - 0x00, 0x00); // configure all as output - - uint8_t o2 = 0x00; - int i=0; - while(1){ - wxMilliSleep(1000); - o2 ^= 0x3F; - chip1.SetReg(o2,PCA9535_OUTPUT_P1_ADDR); - printf("."); - fflush(stdout); - if(++i>10){ - printf("\n"); - break; - } - } - return 0; -} +#include "ce/ceUtil.h" +using namespace ce; + +int main(){ + cePCA9535 chip1(1,0x21);// bus = 1, addr = 0x21 + + chip1.Init(0x00, 0xFF, // output p0 all 0, and p1 all 1 + 0x00, 0x00, // p0 active high , p1 active high also + 0x00, 0x00); // configure all as output + + uint8_t o2 = 0x00; + int i=0; + while(1){ + wxMilliSleep(1000); + o2 ^= 0x3F; + chip1.SetReg(o2,PCA9535_OUTPUT_P1_ADDR); + printf("."); + fflush(stdout); + if(++i>10){ + printf("\n"); + break; + } + } + return 0; +} diff --git a/examples/Log/CMakeLists.txt b/examples/Log/CMakeLists.txt index 5754383..0283d7a 100644 --- a/examples/Log/CMakeLists.txt +++ b/examples/Log/CMakeLists.txt @@ -1,12 +1,12 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(Log VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) - +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(Log VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) + diff --git a/examples/Log/Log.sh b/examples/Log/Log.sh index 6979d63..84086f0 100644 --- a/examples/Log/Log.sh +++ b/examples/Log/Log.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/Log/Log/Log.sln b/examples/Log/Log/Log.sln index 23322e9..c1067ef 100644 --- a/examples/Log/Log/Log.sln +++ b/examples/Log/Log/Log.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Log", "Log.vcxproj", "{FF0CBEC6-2040-4D74-9966-7E4530656E20}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.ActiveCfg = Debug|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.Build.0 = Debug|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.ActiveCfg = Debug|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.Build.0 = Debug|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.ActiveCfg = Release|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.Build.0 = Release|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.ActiveCfg = Release|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {963C9ECC-7676-4360-A9B1-A31048A8D673} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Log", "Log.vcxproj", "{FF0CBEC6-2040-4D74-9966-7E4530656E20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.ActiveCfg = Debug|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.Build.0 = Debug|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.ActiveCfg = Debug|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.Build.0 = Debug|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.ActiveCfg = Release|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.Build.0 = Release|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.ActiveCfg = Release|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {963C9ECC-7676-4360-A9B1-A31048A8D673} + EndGlobalSection +EndGlobal diff --git a/examples/Log/Log/Log.vcxproj b/examples/Log/Log/Log.vcxproj index cd49230..c66c80f 100644 --- a/examples/Log/Log/Log.vcxproj +++ b/examples/Log/Log/Log.vcxproj @@ -1,135 +1,135 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - {FF0CBEC6-2040-4D74-9966-7E4530656E20} - Log - 10.0 - - - - Application - true - v143 - MultiByte - - - Application - false - v143 - true - MultiByte - - - Application - true - v143 - MultiByte - - - Application - false - v143 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - MaxSpeed - true - true - true - true - - - Console - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - Console - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + {FF0CBEC6-2040-4D74-9966-7E4530656E20} + Log + 10.0 + + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + MaxSpeed + true + true + true + true + + + Console + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) + WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + Console + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + + + + \ No newline at end of file diff --git a/examples/Log/Log/Log.vcxproj.filters b/examples/Log/Log/Log.vcxproj.filters index b14fdbe..322bf43 100644 --- a/examples/Log/Log/Log.vcxproj.filters +++ b/examples/Log/Log/Log.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/Log/Logw.bat b/examples/Log/Logw.bat index 6abe9a3..deb31a9 100644 --- a/examples/Log/Logw.bat +++ b/examples/Log/Logw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -Log.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +Log.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/Log/src/Log.cpp b/examples/Log/src/Log.cpp index 60c04a8..f21ec8c 100644 --- a/examples/Log/src/Log.cpp +++ b/examples/Log/src/Log.cpp @@ -1,19 +1,19 @@ -#include -#include "ce/ceUtil.h" -using namespace ce; -int main(){ - ceLog l("./",1); - ceDateTime a; - l.Print(a.ToString("%yyyy-%mm-%dd")); - int i=0; - while(1){ - wxMilliSleep(10); - printf("."); - fflush(stdout); - if(++i>300){ - printf("\n"); - break; - } - } - return 0; -} +#include +#include "ce/ceUtil.h" +using namespace ce; +int main(){ + ceLog l("./",1); + ceDateTime a; + l.Print(a.ToString("%yyyy-%mm-%dd")); + int i=0; + while(1){ + wxMilliSleep(10); + printf("."); + fflush(stdout); + if(++i>300){ + printf("\n"); + break; + } + } + return 0; +} diff --git a/examples/Modbus/CMakeLists.txt b/examples/Modbus/CMakeLists.txt index beb7068..cd1da73 100644 --- a/examples/Modbus/CMakeLists.txt +++ b/examples/Modbus/CMakeLists.txt @@ -1,11 +1,11 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(Modbus VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(Modbus VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/Modbus/Modbus.sh b/examples/Modbus/Modbus.sh index 6979d63..84086f0 100644 --- a/examples/Modbus/Modbus.sh +++ b/examples/Modbus/Modbus.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/Modbus/Modbus/Modbus.sln b/examples/Modbus/Modbus/Modbus.sln index 5463078..7e5e3e0 100644 --- a/examples/Modbus/Modbus/Modbus.sln +++ b/examples/Modbus/Modbus/Modbus.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testModbus", "testModbus.vcxproj", "{850665AF-0AF1-4CF0-9447-2ACC1E2596E3}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x64.ActiveCfg = Debug|x64 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x64.Build.0 = Debug|x64 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x86.ActiveCfg = Debug|Win32 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x86.Build.0 = Debug|Win32 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x64.ActiveCfg = Release|x64 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x64.Build.0 = Release|x64 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x86.ActiveCfg = Release|Win32 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {16967C37-6C30-4296-BE8C-88110AB29EE9} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testModbus", "testModbus.vcxproj", "{850665AF-0AF1-4CF0-9447-2ACC1E2596E3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x64.ActiveCfg = Debug|x64 + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x64.Build.0 = Debug|x64 + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x86.ActiveCfg = Debug|Win32 + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x86.Build.0 = Debug|Win32 + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x64.ActiveCfg = Release|x64 + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x64.Build.0 = Release|x64 + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x86.ActiveCfg = Release|Win32 + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {16967C37-6C30-4296-BE8C-88110AB29EE9} + EndGlobalSection +EndGlobal diff --git a/examples/Modbus/Modbus/Modbus.vcxproj b/examples/Modbus/Modbus/Modbus.vcxproj index 128aae0..ca35e58 100644 --- a/examples/Modbus/Modbus/Modbus.vcxproj +++ b/examples/Modbus/Modbus/Modbus.vcxproj @@ -1,135 +1,135 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3} - testModbus - 10.0 - - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - MaxSpeed - true - true - true - true - - - Console - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - C:\Users\yana\ws\ceutil\include;%(AdditionalIncludeDirectories) - WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - Console - true - true - C:\Users\yana\ws\ceutil\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + {850665AF-0AF1-4CF0-9447-2ACC1E2596E3} + testModbus + 10.0 + + + + Application + true + v142 + MultiByte + + + Application + false + v142 + true + MultiByte + + + Application + true + v142 + MultiByte + + + Application + false + v142 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + MaxSpeed + true + true + true + true + + + Console + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + C:\Users\yana\ws\ceutil\include;%(AdditionalIncludeDirectories) + WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + Console + true + true + C:\Users\yana\ws\ceutil\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + + + + \ No newline at end of file diff --git a/examples/Modbus/Modbus/Modbus.vcxproj.filters b/examples/Modbus/Modbus/Modbus.vcxproj.filters index 985539e..a8e9e67 100644 --- a/examples/Modbus/Modbus/Modbus.vcxproj.filters +++ b/examples/Modbus/Modbus/Modbus.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/Modbus/Modbusw.bat b/examples/Modbus/Modbusw.bat index 3f858fe..c497db9 100644 --- a/examples/Modbus/Modbusw.bat +++ b/examples/Modbus/Modbusw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -Modbus.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +Modbus.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/Modbus/src/Modbus.cpp b/examples/Modbus/src/Modbus.cpp index 68e53a8..888756e 100644 --- a/examples/Modbus/src/Modbus.cpp +++ b/examples/Modbus/src/Modbus.cpp @@ -1,70 +1,70 @@ -// File: testModbus.cpp -// Description: Modbus frame sending and receiving console program for Windows and Linux -// WebSite: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2021 Yan Naing Aye - -#include -#include "ce/ceSerial.h" -#include "ce/ceModbus.h" -#include -using namespace std; -using namespace ce; - -int main() -{ -#ifdef CE_WINDOWS - ceSerial com("\\\\.\\COM17", 9600, 8, 'N', 1); // Windows -#else - ceSerial com("/dev/ttyS0", 9600, 8, 'N', 1); // Linux -#endif - - printf("Opening port %s.\n", com.GetPort().c_str()); - if (com.Open() == 0) { - printf("OK.\n"); - } - else { - printf("Error.\n"); - return 1; - } - ceModbus m; - m.SetControl(1,1,3); - // m.SetReadStatus(1, 1, 4); - printf("Writing %d bytes.\n", int(m.GetTxN())); - - bool successFlag; - successFlag = com.Write(m.GetTxBuf(), (long)m.GetTxN()); - - printf("Waiting ...\n"); - ceSerial::Delay(1000); // delay to wait for reply - - printf("Reading.\n"); - successFlag = true; - - printf("Rx: "); - while (successFlag) { - char c = com.ReadChar(successFlag); // read a char - if (successFlag) { - printf("%02X ", (unsigned int)c & 0xFF); - if (m.ReceiveRxFrame(c)) { - char* buf = m.GetRxBuf(); - size_t rn = m.GetRxN(); - if (buf[1] == 6) { - printf("\nReceived control reply\n"); - } - else if (buf[1] == 3) { - printf("\nReceived read reply\n"); - std::vector rstatus = m.GetStatus(buf,rn); - for (uint16_t& s : rstatus) { - printf("Status: %d\n",s); - } - } - } - } - } - printf("\n"); - - printf("Closing port %s.\n", com.GetPort().c_str()); - com.Close(); - return 0; +// File: testModbus.cpp +// Description: Modbus frame sending and receiving console program for Windows and Linux +// WebSite: http://cool-emerald.blogspot.com +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2021 Yan Naing Aye + +#include +#include "ce/ceSerial.h" +#include "ce/ceModbus.h" +#include +using namespace std; +using namespace ce; + +int main() +{ +#ifdef CE_WINDOWS + ceSerial com("\\\\.\\COM17", 9600, 8, 'N', 1); // Windows +#else + ceSerial com("/dev/ttyS0", 9600, 8, 'N', 1); // Linux +#endif + + printf("Opening port %s.\n", com.GetPort().c_str()); + if (com.Open() == 0) { + printf("OK.\n"); + } + else { + printf("Error.\n"); + return 1; + } + ceModbus m; + m.SetControl(1,1,3); + // m.SetReadStatus(1, 1, 4); + printf("Writing %d bytes.\n", int(m.GetTxN())); + + bool successFlag; + successFlag = com.Write(m.GetTxBuf(), (long)m.GetTxN()); + + printf("Waiting ...\n"); + ceSerial::Delay(1000); // delay to wait for reply + + printf("Reading.\n"); + successFlag = true; + + printf("Rx: "); + while (successFlag) { + char c = com.ReadChar(successFlag); // read a char + if (successFlag) { + printf("%02X ", (unsigned int)c & 0xFF); + if (m.ReceiveRxFrame(c)) { + char* buf = m.GetRxBuf(); + size_t rn = m.GetRxN(); + if (buf[1] == 6) { + printf("\nReceived control reply\n"); + } + else if (buf[1] == 3) { + printf("\nReceived read reply\n"); + std::vector rstatus = m.GetStatus(buf,rn); + for (uint16_t& s : rstatus) { + printf("Status: %d\n",s); + } + } + } + } + } + printf("\n"); + + printf("Closing port %s.\n", com.GetPort().c_str()); + com.Close(); + return 0; } \ No newline at end of file diff --git a/examples/ModbusCmd/CMakeLists.txt b/examples/ModbusCmd/CMakeLists.txt index 83e7482..e5598c9 100644 --- a/examples/ModbusCmd/CMakeLists.txt +++ b/examples/ModbusCmd/CMakeLists.txt @@ -1,12 +1,12 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(ModbusCmd VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(ModbusCmd VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} ${WIN32OPT} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/ModbusCmd/ModbusCmd.sh b/examples/ModbusCmd/ModbusCmd.sh index 6979d63..84086f0 100644 --- a/examples/ModbusCmd/ModbusCmd.sh +++ b/examples/ModbusCmd/ModbusCmd.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/ModbusCmd/ModbusCmd/ModbusCmd.sln b/examples/ModbusCmd/ModbusCmd/ModbusCmd.sln index 6e1b699..d0c5e1a 100644 --- a/examples/ModbusCmd/ModbusCmd/ModbusCmd.sln +++ b/examples/ModbusCmd/ModbusCmd/ModbusCmd.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ModbusCmd", "ModbusCmd.vcxproj", "{D7016C30-0709-40AF-A1B2-24AF8606C639}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x64.ActiveCfg = Debug|x64 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x64.Build.0 = Debug|x64 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x86.ActiveCfg = Debug|Win32 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x86.Build.0 = Debug|Win32 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x64.ActiveCfg = Release|x64 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x64.Build.0 = Release|x64 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x86.ActiveCfg = Release|Win32 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {9BE80EB7-72E9-44FE-B724-BECFCCF2A3ED} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ModbusCmd", "ModbusCmd.vcxproj", "{D7016C30-0709-40AF-A1B2-24AF8606C639}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x64.ActiveCfg = Debug|x64 + {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x64.Build.0 = Debug|x64 + {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x86.ActiveCfg = Debug|Win32 + {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x86.Build.0 = Debug|Win32 + {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x64.ActiveCfg = Release|x64 + {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x64.Build.0 = Release|x64 + {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x86.ActiveCfg = Release|Win32 + {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9BE80EB7-72E9-44FE-B724-BECFCCF2A3ED} + EndGlobalSection +EndGlobal diff --git a/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj b/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj index 7488876..765c28c 100644 --- a/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj +++ b/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj @@ -1,162 +1,162 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {D7016C30-0709-40AF-A1B2-24AF8606C639} - Win32Proj - ModbusCmd - 10.0 - - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {D7016C30-0709-40AF-A1B2-24AF8606C639} + Win32Proj + ModbusCmd + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + Level3 + Disabled + true + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) + + + Windows + true + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj.filters b/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj.filters index 2f43120..7ba81f1 100644 --- a/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj.filters +++ b/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/ModbusCmd/modbuscmdw.bat b/examples/ModbusCmd/modbuscmdw.bat index a3d9688..39d8f22 100644 --- a/examples/ModbusCmd/modbuscmdw.bat +++ b/examples/ModbusCmd/modbuscmdw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -ModbusCmd.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +ModbusCmd.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/ModbusCmd/src/ModbusCmd.cpp b/examples/ModbusCmd/src/ModbusCmd.cpp index b99e839..2abeac1 100644 --- a/examples/ModbusCmd/src/ModbusCmd.cpp +++ b/examples/ModbusCmd/src/ModbusCmd.cpp @@ -1,406 +1,406 @@ -// File: ModbusCmd.cpp -// Description: Modbus RTS communication for RS485 switches -// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2021 Yan Naing Aye - -#include "wx/wx.h" -#include -#include -#include -#include -#include -// ---------------------------------------------------------------------------- -// private classes -#include "ce/ceUtil.h" -using namespace std; -using namespace ce; -// ---------------------------------------------------------------------------- -#define MODBUS_ID_MAX 31 -#define MODBUS_ADDR_MAX 16 -#define MODBUS_ACTION_MAX 8 -#define MODBUS_DURATION_MAX 255 -#define N_LOG_LIST_LINES 30 - -#define MODBUS_DIALOG_BTN_SEND 100 -#define MODBUS_DIALOG_BTN_CMD 101 - -#define MODBUS_DIALOG_SPN_ID 102 -#define MODBUS_DIALOG_SPN_ADDR 103 -#define MODBUS_DIALOG_CBO_FUNC 104 -#define MODBUS_DIALOG_CBO_ACTION 105 -#define MODBUS_DIALOG_SPN_DURATION 106 -#define MODBUS_DIALOG_TXT_CMD 107 -#define ID_BAUDRATE_MNU 108 -#define ID_TIMER 109 -#define ID_WXSERIAL 110 -#define ID_SELPORT_MNU 111 -#define ID_OPEN_MNU 112 -#define ID_CLOSE_MNU 113 -#define ID_CLEAR_MNU 114 -#define GUI_LST_LOG_ID 115 -// wxID_EXIT for quit -// wxID_ABOUT for about -// ---------------------------------------------------------------------------- -class MyFrame; -class MyApp : public wxApp -{ -public: - virtual bool OnInit(); - MyFrame* _fra; - ceWxSerial* _com; - ceModbus* _modbus; - void OnSerialEvent(wxThreadEvent& event); -}; - -// Define a new frame type: this is going to be our main frame -class MyFrame : public wxFrame -{ -public: - // ctor(s) - MyFrame(MyApp* app, const wxString& title); - - // event handlers (these functions should _not_ be virtual) - void OnQuit(wxCommandEvent& event); - void OnAbout(wxCommandEvent& event); - void OnOpen(wxCommandEvent& event); - void OnClose(wxCommandEvent& event); - void SelPort(wxCommandEvent& event); - void SetBaud(wxCommandEvent& event); - void OnClear(wxCommandEvent& event); - void OnSend(wxCommandEvent& event); - void OnTimer(wxTimerEvent& event); - void OnSendHex(wxCommandEvent& event); - void WriteList(std::string mes); - void ModbusControl(uint8_t id, uint8_t func, uint16_t addr, uint8_t action, uint8_t delay); - void ModbusCmd(std::vector cmd); -private: - MyApp* _app; - wxSpinCtrl* spnId; - wxSpinCtrl* spnAddr; - wxSpinCtrl* spnDuration; - wxButton* btnSend; - wxComboBox* cboFunc; - wxComboBox* cboAction; - wxTextCtrl* txtCmd; - wxButton* btnCmd; - wxTimer tmr; - wxListBox* logList; -}; - -IMPLEMENT_APP(MyApp) - -bool MyApp::OnInit() -{ - if ( !wxApp::OnInit() ) - return false; - _fra = new MyFrame(this, wxT("Modbus RS485 Relay Board Control")); - - _modbus = new ceModbus(); - string device; -#if defined(CE_WINDOWS) - device = "\\\\.\\COM1"; -#else - device = "/dev/ttyUSB0"; -#endif - _com = new ceWxSerial(this, ID_WXSERIAL, 10, device, 9600, 8, 'N', 1); - Connect(ID_WXSERIAL, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); - _fra->Show(true); - return true; -} - -void MyApp::OnSerialEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - char ch; - for (int i = 0; i < v.size(); i++) { - ch = v[i]; - // printf("%02X ", (unsigned int)ch & 0xFF); - if (_modbus->ReceiveRxFrame(ch)) { - char* buf = _modbus->GetRxBuf(); - size_t rn = _modbus->GetRxN(); - if (buf[1] == 6) { - _fra->WriteList("Received control reply"); - } - else if (buf[1] == 3) { - _fra->WriteList("Received read reply"); - std::vector rstatus = _modbus->GetStatus(buf, rn); - for (uint16_t& s : rstatus) { - _fra->WriteList("Status: "+ to_string(s)); - } - } - } - } - // wxMessageBox(wxT("Serial event")); -} - -// ---------------------------------------------------------------------------- -// main frame -// ---------------------------------------------------------------------------- - -// frame constructor -MyFrame::MyFrame(MyApp* app, const wxString& title) - : wxFrame(NULL, wxID_ANY, title,wxDefaultPosition,wxSize(480, 600), wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),tmr(this, ID_TIMER), _app(app) -{ - -#if wxUSE_MENUS - // create a menu bar - wxMenu *fileMenu = new wxMenu; - - //Edit menu - wxMenu *editMenu = new wxMenu; - - // the "About" item should be in the help menu - wxMenu *helpMenu = new wxMenu; - - helpMenu->Append(wxID_ABOUT, wxT("&About\tF1"), wxT("Show about dialog")); - Connect(wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnAbout)); - - fileMenu->Append(ID_OPEN_MNU, wxT("&Open\tAlt-O"), wxT("Open serial port")); - Connect(ID_OPEN_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnOpen)); - fileMenu->Append(ID_CLOSE_MNU, wxT("&Close\tAlt-C"), wxT("Close serial port")); - Connect(ID_CLOSE_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnClose)); - editMenu->Append(ID_CLEAR_MNU, wxT("Clea&r\tAlt-R"), wxT("Clear")); - Connect(ID_CLEAR_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnClear)); - fileMenu->Append(ID_SELPORT_MNU, wxT("&Serial Port\tAlt-S"), wxT("Select serial port")); - Connect(ID_SELPORT_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SelPort)); - fileMenu->Append(ID_BAUDRATE_MNU, wxT("&Baud Rate\tAlt-B"), wxT("Set baud rate")); - Connect(ID_BAUDRATE_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetBaud)); - fileMenu->Append(wxID_EXIT, wxT("E&xit\tAlt-X"), wxT("Quit this program")); - Connect(wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnQuit)); - - // now append the freshly created menu to the menu bar... - wxMenuBar *menuBar = new wxMenuBar(); - menuBar->Append(fileMenu, wxT("&File")); - menuBar->Append(editMenu, wxT("&Edit")); - menuBar->Append(helpMenu, wxT("&Help")); - - // ... and attach this menu bar to the frame - SetMenuBar(menuBar); -#endif // wxUSE_MENUS - -#if wxUSE_STATUSBAR - // create a status bar just for fun (by default with 1 pane only) - CreateStatusBar(2); - SetStatusText(wxT("Modbus switch control")); -#endif // wxUSE_STATUSBAR - - // id 0 - 31 - wxStaticText* lblId = new wxStaticText(this, -1, wxT("Board:"), - wxPoint(10, 25), wxSize(55, 30)); - this->spnId = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_ID, wxT("1"), - wxPoint(80, 20), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_ID_MAX, 0, wxT("ID")); - - // function - wxStaticText* lblFunc = new wxStaticText(this, -1, wxT("Func:"), - wxPoint(230, 25), wxSize(55, 30)); - wxArrayString funcList; - funcList.Add("6 - Control"); - funcList.Add("3 - Read"); - cboFunc = new wxComboBox(this, MODBUS_DIALOG_CBO_FUNC, wxT("6 - Control"), - wxPoint(290, 20), wxSize(120, 25), funcList, wxCB_READONLY); - - // Address - wxStaticText* lblAddr = new wxStaticText(this, -1, wxT("Relay:"), - wxPoint(10, 85), wxSize(60, 30)); - this->spnAddr = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_ADDR, wxT("1"), - wxPoint(80, 80), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_ADDR_MAX, 0, wxT("RELAY")); - - // delay - wxStaticText* lblDuration = new wxStaticText(this, -1, wxT("Seconds:"), - wxPoint(10, 145), wxSize(60, 30)); - this->spnDuration = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_DURATION, wxT("0"), - wxPoint(80, 140), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_DURATION_MAX, 500); - - // Action - wxStaticText* lblAction = new wxStaticText(this, -1, wxT("Action:"), - wxPoint(230, 85), wxSize(55, 30)); - wxArrayString actList; - actList.Add("0 - Default"); - actList.Add("1 - Open"); - actList.Add("2 - Close"); - actList.Add("3 - Toggle"); - actList.Add("4 - Latch"); - actList.Add("5 - Momentary"); - actList.Add("6 - Delay"); - actList.Add("7 - Open all"); - actList.Add("8 - Close all"); - cboAction = new wxComboBox(this, MODBUS_DIALOG_CBO_ACTION, wxT("3 - Toggle"), - wxPoint(290, 80), wxSize(120, 30), actList, wxCB_READONLY); - - this->btnSend = new wxButton(this, MODBUS_DIALOG_BTN_SEND, wxT("Send"), - wxPoint(310, 140), wxSize(100, 30)); - Connect(MODBUS_DIALOG_BTN_SEND, wxEVT_COMMAND_BUTTON_CLICKED, - wxCommandEventHandler(MyFrame::OnSend)); - - wxStaticText* lblDes = new wxStaticText(this, -1, wxT("For the following hex cmd, CRC will be appended"), - wxPoint(10, 180), wxSize(-1,-1)); - wxStaticText* lblCmd = new wxStaticText(this, -1, wxT("Cmd:"), - wxPoint(10, 215), wxSize(55, 30)); - this->txtCmd = new wxTextCtrl(this, MODBUS_DIALOG_TXT_CMD, wxT("01 06 00 0A 03 00"), - wxPoint(80, 210), wxSize(210, 30)); - this->btnCmd = new wxButton(this, MODBUS_DIALOG_BTN_CMD, wxT("Send Cmd"), - wxPoint(310, 210), wxSize(100, 30)); - Connect(MODBUS_DIALOG_BTN_CMD, wxEVT_COMMAND_BUTTON_CLICKED, - wxCommandEventHandler(MyFrame::OnSendHex)); - - wxArrayString astr; - logList = new wxListBox(this, GUI_LST_LOG_ID, wxPoint(10,270), wxSize(400, 230), astr, wxLB_HSCROLL); - - Connect(ID_TIMER, wxEVT_TIMER, wxTimerEventHandler(MyFrame::OnTimer)); - tmr.Start(250); -} - -void MyFrame::WriteList(string mes) -{ - int nl = logList->GetCount(); - if (nl >= N_LOG_LIST_LINES) { - logList->Delete(0); - } - wxString wstr = mes; - //wxDateTime wdt; - //wdt.SetToCurrent(); - //wstr = wdt.Format(wxT("%Y-%m-%d %H:%M:%S"), wxDateTime::Local)+" : "+wstr; // add timestamp - wxArrayString astr; - astr.Add(wstr); - nl = logList->GetCount(); - logList->InsertItems(astr, nl); - logList->SetSelection(nl); -} - -// event handlers - -void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) -{ - // true is to force the frame to close - Close(true); -} - -void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) -{ - wxMessageBox(wxString::Format( - wxT("Modbus Switch Command Utility \n ") - wxT("Author: Yan Naing Aye \n ") - wxT("Web: https://github.com/yan9a/serial") - ), - wxT("About Modbus Switch"), - wxOK | wxICON_INFORMATION, - this); -} - -void MyFrame::OnOpen(wxCommandEvent& WXUNUSED(event)) -{ - if(_app->_com->Open()) this->WriteList(wxString::Format(wxT("Error opening port %s.\n"),_app->_com->GetPort()).ToStdString()); - else this->WriteList(wxString::Format(wxT("Port %s is opened.\n"), _app->_com->GetPort()).ToStdString()); -} - -void MyFrame::OnClose(wxCommandEvent& WXUNUSED(event)) -{ - _app->_com->Close(); - this->WriteList(wxString::Format(wxT("Port %s is closed.\n"), _app->_com->GetPort()).ToStdString()); -} - -void MyFrame::SelPort(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - this->WriteList(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort()).ToStdString()); - } - else { - wxString cdev=wxString::Format(wxT("%s"), _app->_com->GetPort()); - wxString device = wxGetTextFromUser(wxT("Enter the port"), wxT("Set Port"), cdev); - string str = device.ToStdString(); - if (str.length() > 0) { - _app->_com->SetPortName(str); - } - - this->WriteList(wxString::Format(wxT("Port: %s\n"), _app->_com->GetPort()).ToStdString()); - } -} - -void MyFrame::SetBaud(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - this->WriteList(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort()).ToStdString()); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the baud rate"), wxT("Baud rate"), wxT("Set Baud Rate"),_app->_com->GetBaudRate(),0, 1000000); - if (n >= 0) { - _app->_com->SetBaudRate(n); - } - this->WriteList(wxString::Format(wxT("Baud rate: %ld\n"), _app->_com->GetBaudRate()).ToStdString()); - } -} - -void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) -{ - uint8_t board = uint8_t(this->spnId->GetValue()); - - uint8_t func; - int v = this->cboFunc->GetSelection(); - if (v == wxNOT_FOUND || v == 0) func = 6; - else func = 3; - - uint16_t addr = uint16_t(this->spnAddr->GetValue()); - - v = this->cboAction->GetSelection(); - if (v == wxNOT_FOUND || func == 3) v = 0; - uint8_t action = uint8_t(v); - - uint8_t delay = uint8_t(this->spnDuration->GetValue()); - if (func == 3) delay = 1; // to read 1 relay when not using custom cmd - else if (action != 6) delay = 0; - this->ModbusControl(board, func, addr, action, delay); -} - -void MyFrame::OnSendHex(wxCommandEvent& WXUNUSED(event)) -{ - wxString ws = this->txtCmd->GetValue(); - std::string str = ws.ToStdString(); - vector v = ceMisc::hex2cvec(str); - vector cmd(v.begin(), v.end()); - this->ModbusCmd(cmd); -} - -void MyFrame::ModbusControl(uint8_t id, uint8_t func, uint16_t addr, uint8_t action, uint8_t delay) -{ - string str = "Board = " + to_string(id) + ", func = " + to_string(func) - + ", switch = " + to_string(addr); - if (func == 6) { - str += ", action = " + to_string(action) + ", delay = " + to_string(delay); - } - - uint8_t ah = uint8_t((addr >> 8) & 0xFF); - uint8_t al = uint8_t(addr & 0xFF); - std::vector cmd = { id,func,ah,al,action,delay }; - this->_app->_modbus->SetCmd(cmd); - if (this->_app->_com->Write(this->_app->_modbus->GetTxBuf(), (long)this->_app->_modbus->GetTxN())) { - this->WriteList(str); - } - else { - this->WriteList("Error in sending command"); - } -} - -void MyFrame::ModbusCmd(vector cmd) -{ - vector v(cmd.begin(), cmd.end()); - string str = "Cmd = " + ceMisc::cvec2hex(v); - this->_app->_modbus->SetCmd(cmd); - if (this->_app->_com->Write(this->_app->_modbus->GetTxBuf(), (long)this->_app->_modbus->GetTxN())) { - this->WriteList(str); - } - else { - this->WriteList("Error in sending command"); - } - -} - -void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event)) -{ - this->_app->_modbus->Tick(); -} - -void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event)) -{ - logList->Clear(); -} +// File: ModbusCmd.cpp +// Description: Modbus RTS communication for RS485 switches +// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2021 Yan Naing Aye + +#include "wx/wx.h" +#include +#include +#include +#include +#include +// ---------------------------------------------------------------------------- +// private classes +#include "ce/ceUtil.h" +using namespace std; +using namespace ce; +// ---------------------------------------------------------------------------- +#define MODBUS_ID_MAX 31 +#define MODBUS_ADDR_MAX 16 +#define MODBUS_ACTION_MAX 8 +#define MODBUS_DURATION_MAX 255 +#define N_LOG_LIST_LINES 30 + +#define MODBUS_DIALOG_BTN_SEND 100 +#define MODBUS_DIALOG_BTN_CMD 101 + +#define MODBUS_DIALOG_SPN_ID 102 +#define MODBUS_DIALOG_SPN_ADDR 103 +#define MODBUS_DIALOG_CBO_FUNC 104 +#define MODBUS_DIALOG_CBO_ACTION 105 +#define MODBUS_DIALOG_SPN_DURATION 106 +#define MODBUS_DIALOG_TXT_CMD 107 +#define ID_BAUDRATE_MNU 108 +#define ID_TIMER 109 +#define ID_WXSERIAL 110 +#define ID_SELPORT_MNU 111 +#define ID_OPEN_MNU 112 +#define ID_CLOSE_MNU 113 +#define ID_CLEAR_MNU 114 +#define GUI_LST_LOG_ID 115 +// wxID_EXIT for quit +// wxID_ABOUT for about +// ---------------------------------------------------------------------------- +class MyFrame; +class MyApp : public wxApp +{ +public: + virtual bool OnInit(); + MyFrame* _fra; + ceWxSerial* _com; + ceModbus* _modbus; + void OnSerialEvent(wxThreadEvent& event); +}; + +// Define a new frame type: this is going to be our main frame +class MyFrame : public wxFrame +{ +public: + // ctor(s) + MyFrame(MyApp* app, const wxString& title); + + // event handlers (these functions should _not_ be virtual) + void OnQuit(wxCommandEvent& event); + void OnAbout(wxCommandEvent& event); + void OnOpen(wxCommandEvent& event); + void OnClose(wxCommandEvent& event); + void SelPort(wxCommandEvent& event); + void SetBaud(wxCommandEvent& event); + void OnClear(wxCommandEvent& event); + void OnSend(wxCommandEvent& event); + void OnTimer(wxTimerEvent& event); + void OnSendHex(wxCommandEvent& event); + void WriteList(std::string mes); + void ModbusControl(uint8_t id, uint8_t func, uint16_t addr, uint8_t action, uint8_t delay); + void ModbusCmd(std::vector cmd); +private: + MyApp* _app; + wxSpinCtrl* spnId; + wxSpinCtrl* spnAddr; + wxSpinCtrl* spnDuration; + wxButton* btnSend; + wxComboBox* cboFunc; + wxComboBox* cboAction; + wxTextCtrl* txtCmd; + wxButton* btnCmd; + wxTimer tmr; + wxListBox* logList; +}; + +IMPLEMENT_APP(MyApp) + +bool MyApp::OnInit() +{ + if ( !wxApp::OnInit() ) + return false; + _fra = new MyFrame(this, wxT("Modbus RS485 Relay Board Control")); + + _modbus = new ceModbus(); + string device; +#if defined(CE_WINDOWS) + device = "\\\\.\\COM1"; +#else + device = "/dev/ttyUSB0"; +#endif + _com = new ceWxSerial(this, ID_WXSERIAL, 10, device, 9600, 8, 'N', 1); + Connect(ID_WXSERIAL, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); + _fra->Show(true); + return true; +} + +void MyApp::OnSerialEvent(wxThreadEvent& event) +{ + std::vector v = event.GetPayload>(); + char ch; + for (int i = 0; i < v.size(); i++) { + ch = v[i]; + // printf("%02X ", (unsigned int)ch & 0xFF); + if (_modbus->ReceiveRxFrame(ch)) { + char* buf = _modbus->GetRxBuf(); + size_t rn = _modbus->GetRxN(); + if (buf[1] == 6) { + _fra->WriteList("Received control reply"); + } + else if (buf[1] == 3) { + _fra->WriteList("Received read reply"); + std::vector rstatus = _modbus->GetStatus(buf, rn); + for (uint16_t& s : rstatus) { + _fra->WriteList("Status: "+ to_string(s)); + } + } + } + } + // wxMessageBox(wxT("Serial event")); +} + +// ---------------------------------------------------------------------------- +// main frame +// ---------------------------------------------------------------------------- + +// frame constructor +MyFrame::MyFrame(MyApp* app, const wxString& title) + : wxFrame(NULL, wxID_ANY, title,wxDefaultPosition,wxSize(480, 600), wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),tmr(this, ID_TIMER), _app(app) +{ + +#if wxUSE_MENUS + // create a menu bar + wxMenu *fileMenu = new wxMenu; + + //Edit menu + wxMenu *editMenu = new wxMenu; + + // the "About" item should be in the help menu + wxMenu *helpMenu = new wxMenu; + + helpMenu->Append(wxID_ABOUT, wxT("&About\tF1"), wxT("Show about dialog")); + Connect(wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnAbout)); + + fileMenu->Append(ID_OPEN_MNU, wxT("&Open\tAlt-O"), wxT("Open serial port")); + Connect(ID_OPEN_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnOpen)); + fileMenu->Append(ID_CLOSE_MNU, wxT("&Close\tAlt-C"), wxT("Close serial port")); + Connect(ID_CLOSE_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnClose)); + editMenu->Append(ID_CLEAR_MNU, wxT("Clea&r\tAlt-R"), wxT("Clear")); + Connect(ID_CLEAR_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnClear)); + fileMenu->Append(ID_SELPORT_MNU, wxT("&Serial Port\tAlt-S"), wxT("Select serial port")); + Connect(ID_SELPORT_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SelPort)); + fileMenu->Append(ID_BAUDRATE_MNU, wxT("&Baud Rate\tAlt-B"), wxT("Set baud rate")); + Connect(ID_BAUDRATE_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetBaud)); + fileMenu->Append(wxID_EXIT, wxT("E&xit\tAlt-X"), wxT("Quit this program")); + Connect(wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnQuit)); + + // now append the freshly created menu to the menu bar... + wxMenuBar *menuBar = new wxMenuBar(); + menuBar->Append(fileMenu, wxT("&File")); + menuBar->Append(editMenu, wxT("&Edit")); + menuBar->Append(helpMenu, wxT("&Help")); + + // ... and attach this menu bar to the frame + SetMenuBar(menuBar); +#endif // wxUSE_MENUS + +#if wxUSE_STATUSBAR + // create a status bar just for fun (by default with 1 pane only) + CreateStatusBar(2); + SetStatusText(wxT("Modbus switch control")); +#endif // wxUSE_STATUSBAR + + // id 0 - 31 + wxStaticText* lblId = new wxStaticText(this, -1, wxT("Board:"), + wxPoint(10, 25), wxSize(55, 30)); + this->spnId = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_ID, wxT("1"), + wxPoint(80, 20), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_ID_MAX, 0, wxT("ID")); + + // function + wxStaticText* lblFunc = new wxStaticText(this, -1, wxT("Func:"), + wxPoint(230, 25), wxSize(55, 30)); + wxArrayString funcList; + funcList.Add("6 - Control"); + funcList.Add("3 - Read"); + cboFunc = new wxComboBox(this, MODBUS_DIALOG_CBO_FUNC, wxT("6 - Control"), + wxPoint(290, 20), wxSize(120, 25), funcList, wxCB_READONLY); + + // Address + wxStaticText* lblAddr = new wxStaticText(this, -1, wxT("Relay:"), + wxPoint(10, 85), wxSize(60, 30)); + this->spnAddr = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_ADDR, wxT("1"), + wxPoint(80, 80), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_ADDR_MAX, 0, wxT("RELAY")); + + // delay + wxStaticText* lblDuration = new wxStaticText(this, -1, wxT("Seconds:"), + wxPoint(10, 145), wxSize(60, 30)); + this->spnDuration = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_DURATION, wxT("0"), + wxPoint(80, 140), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_DURATION_MAX, 500); + + // Action + wxStaticText* lblAction = new wxStaticText(this, -1, wxT("Action:"), + wxPoint(230, 85), wxSize(55, 30)); + wxArrayString actList; + actList.Add("0 - Default"); + actList.Add("1 - Open"); + actList.Add("2 - Close"); + actList.Add("3 - Toggle"); + actList.Add("4 - Latch"); + actList.Add("5 - Momentary"); + actList.Add("6 - Delay"); + actList.Add("7 - Open all"); + actList.Add("8 - Close all"); + cboAction = new wxComboBox(this, MODBUS_DIALOG_CBO_ACTION, wxT("3 - Toggle"), + wxPoint(290, 80), wxSize(120, 30), actList, wxCB_READONLY); + + this->btnSend = new wxButton(this, MODBUS_DIALOG_BTN_SEND, wxT("Send"), + wxPoint(310, 140), wxSize(100, 30)); + Connect(MODBUS_DIALOG_BTN_SEND, wxEVT_COMMAND_BUTTON_CLICKED, + wxCommandEventHandler(MyFrame::OnSend)); + + wxStaticText* lblDes = new wxStaticText(this, -1, wxT("For the following hex cmd, CRC will be appended"), + wxPoint(10, 180), wxSize(-1,-1)); + wxStaticText* lblCmd = new wxStaticText(this, -1, wxT("Cmd:"), + wxPoint(10, 215), wxSize(55, 30)); + this->txtCmd = new wxTextCtrl(this, MODBUS_DIALOG_TXT_CMD, wxT("01 06 00 0A 03 00"), + wxPoint(80, 210), wxSize(210, 30)); + this->btnCmd = new wxButton(this, MODBUS_DIALOG_BTN_CMD, wxT("Send Cmd"), + wxPoint(310, 210), wxSize(100, 30)); + Connect(MODBUS_DIALOG_BTN_CMD, wxEVT_COMMAND_BUTTON_CLICKED, + wxCommandEventHandler(MyFrame::OnSendHex)); + + wxArrayString astr; + logList = new wxListBox(this, GUI_LST_LOG_ID, wxPoint(10,270), wxSize(400, 230), astr, wxLB_HSCROLL); + + Connect(ID_TIMER, wxEVT_TIMER, wxTimerEventHandler(MyFrame::OnTimer)); + tmr.Start(250); +} + +void MyFrame::WriteList(string mes) +{ + int nl = logList->GetCount(); + if (nl >= N_LOG_LIST_LINES) { + logList->Delete(0); + } + wxString wstr = mes; + //wxDateTime wdt; + //wdt.SetToCurrent(); + //wstr = wdt.Format(wxT("%Y-%m-%d %H:%M:%S"), wxDateTime::Local)+" : "+wstr; // add timestamp + wxArrayString astr; + astr.Add(wstr); + nl = logList->GetCount(); + logList->InsertItems(astr, nl); + logList->SetSelection(nl); +} + +// event handlers + +void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) +{ + // true is to force the frame to close + Close(true); +} + +void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) +{ + wxMessageBox(wxString::Format( + wxT("Modbus Switch Command Utility \n ") + wxT("Author: Yan Naing Aye \n ") + wxT("Web: https://github.com/yan9a/serial") + ), + wxT("About Modbus Switch"), + wxOK | wxICON_INFORMATION, + this); +} + +void MyFrame::OnOpen(wxCommandEvent& WXUNUSED(event)) +{ + if(_app->_com->Open()) this->WriteList(wxString::Format(wxT("Error opening port %s.\n"),_app->_com->GetPort()).ToStdString()); + else this->WriteList(wxString::Format(wxT("Port %s is opened.\n"), _app->_com->GetPort()).ToStdString()); +} + +void MyFrame::OnClose(wxCommandEvent& WXUNUSED(event)) +{ + _app->_com->Close(); + this->WriteList(wxString::Format(wxT("Port %s is closed.\n"), _app->_com->GetPort()).ToStdString()); +} + +void MyFrame::SelPort(wxCommandEvent& WXUNUSED(event)) +{ + if (_app->_com->IsOpened()) { + this->WriteList(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort()).ToStdString()); + } + else { + wxString cdev=wxString::Format(wxT("%s"), _app->_com->GetPort()); + wxString device = wxGetTextFromUser(wxT("Enter the port"), wxT("Set Port"), cdev); + string str = device.ToStdString(); + if (str.length() > 0) { + _app->_com->SetPortName(str); + } + + this->WriteList(wxString::Format(wxT("Port: %s\n"), _app->_com->GetPort()).ToStdString()); + } +} + +void MyFrame::SetBaud(wxCommandEvent& WXUNUSED(event)) +{ + if (_app->_com->IsOpened()) { + this->WriteList(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort()).ToStdString()); + } + else { + long n = wxGetNumberFromUser(wxT("Enter the baud rate"), wxT("Baud rate"), wxT("Set Baud Rate"),_app->_com->GetBaudRate(),0, 1000000); + if (n >= 0) { + _app->_com->SetBaudRate(n); + } + this->WriteList(wxString::Format(wxT("Baud rate: %ld\n"), _app->_com->GetBaudRate()).ToStdString()); + } +} + +void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) +{ + uint8_t board = uint8_t(this->spnId->GetValue()); + + uint8_t func; + int v = this->cboFunc->GetSelection(); + if (v == wxNOT_FOUND || v == 0) func = 6; + else func = 3; + + uint16_t addr = uint16_t(this->spnAddr->GetValue()); + + v = this->cboAction->GetSelection(); + if (v == wxNOT_FOUND || func == 3) v = 0; + uint8_t action = uint8_t(v); + + uint8_t delay = uint8_t(this->spnDuration->GetValue()); + if (func == 3) delay = 1; // to read 1 relay when not using custom cmd + else if (action != 6) delay = 0; + this->ModbusControl(board, func, addr, action, delay); +} + +void MyFrame::OnSendHex(wxCommandEvent& WXUNUSED(event)) +{ + wxString ws = this->txtCmd->GetValue(); + std::string str = ws.ToStdString(); + vector v = ceMisc::hex2cvec(str); + vector cmd(v.begin(), v.end()); + this->ModbusCmd(cmd); +} + +void MyFrame::ModbusControl(uint8_t id, uint8_t func, uint16_t addr, uint8_t action, uint8_t delay) +{ + string str = "Board = " + to_string(id) + ", func = " + to_string(func) + + ", switch = " + to_string(addr); + if (func == 6) { + str += ", action = " + to_string(action) + ", delay = " + to_string(delay); + } + + uint8_t ah = uint8_t((addr >> 8) & 0xFF); + uint8_t al = uint8_t(addr & 0xFF); + std::vector cmd = { id,func,ah,al,action,delay }; + this->_app->_modbus->SetCmd(cmd); + if (this->_app->_com->Write(this->_app->_modbus->GetTxBuf(), (long)this->_app->_modbus->GetTxN())) { + this->WriteList(str); + } + else { + this->WriteList("Error in sending command"); + } +} + +void MyFrame::ModbusCmd(vector cmd) +{ + vector v(cmd.begin(), cmd.end()); + string str = "Cmd = " + ceMisc::cvec2hex(v); + this->_app->_modbus->SetCmd(cmd); + if (this->_app->_com->Write(this->_app->_modbus->GetTxBuf(), (long)this->_app->_modbus->GetTxN())) { + this->WriteList(str); + } + else { + this->WriteList("Error in sending command"); + } + +} + +void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event)) +{ + this->_app->_modbus->Tick(); +} + +void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event)) +{ + logList->Clear(); +} diff --git a/examples/Serial/CMakeLists.txt b/examples/Serial/CMakeLists.txt index c395201..794e735 100644 --- a/examples/Serial/CMakeLists.txt +++ b/examples/Serial/CMakeLists.txt @@ -1,9 +1,9 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(Serial VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(Serial VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} ${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/Serial/Serial.sh b/examples/Serial/Serial.sh index 6979d63..84086f0 100644 --- a/examples/Serial/Serial.sh +++ b/examples/Serial/Serial.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/Serial/Serial/Serial.sln b/examples/Serial/Serial/Serial.sln index f09b788..71d3783 100644 --- a/examples/Serial/Serial/Serial.sln +++ b/examples/Serial/Serial/Serial.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Serial", "Serial.vcxproj", "{78C78AC9-F3C1-4551-B5D2-797594E5CB20}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x64.ActiveCfg = Debug|x64 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x64.Build.0 = Debug|x64 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x86.ActiveCfg = Debug|Win32 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x86.Build.0 = Debug|Win32 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x64.ActiveCfg = Release|x64 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x64.Build.0 = Release|x64 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x86.ActiveCfg = Release|Win32 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {CAE2F3A7-6A5E-480F-A7E3-7263E51CA67D} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Serial", "Serial.vcxproj", "{78C78AC9-F3C1-4551-B5D2-797594E5CB20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x64.ActiveCfg = Debug|x64 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x64.Build.0 = Debug|x64 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x86.ActiveCfg = Debug|Win32 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x86.Build.0 = Debug|Win32 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x64.ActiveCfg = Release|x64 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x64.Build.0 = Release|x64 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x86.ActiveCfg = Release|Win32 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {CAE2F3A7-6A5E-480F-A7E3-7263E51CA67D} + EndGlobalSection +EndGlobal diff --git a/examples/Serial/Serial/Serial.vcxproj b/examples/Serial/Serial/Serial.vcxproj index bc5b954..606e3df 100644 --- a/examples/Serial/Serial/Serial.vcxproj +++ b/examples/Serial/Serial/Serial.vcxproj @@ -1,135 +1,135 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20} - Serial - 10.0 - - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - MaxSpeed - true - true - true - true - - - Console - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - C:\Users\yana\ws\ceutil\include;%(AdditionalIncludeDirectories) - WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - Console - true - true - C:\Users\yana\ws\ceutil\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20} + Serial + 10.0 + + + + Application + true + v142 + MultiByte + + + Application + false + v142 + true + MultiByte + + + Application + true + v142 + MultiByte + + + Application + false + v142 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + MaxSpeed + true + true + true + true + + + Console + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + C:\Users\yana\ws\ceutil\include;%(AdditionalIncludeDirectories) + WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + Console + true + true + C:\Users\yana\ws\ceutil\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/Serial/Serial/Serial.vcxproj.filters b/examples/Serial/Serial/Serial.vcxproj.filters index dec564e..96339c1 100644 --- a/examples/Serial/Serial/Serial.vcxproj.filters +++ b/examples/Serial/Serial/Serial.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/Serial/serialw.bat b/examples/Serial/serialw.bat index 23200dc..2e913fe 100644 --- a/examples/Serial/serialw.bat +++ b/examples/Serial/serialw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -Serial.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +Serial.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/Serial/src/Serial.cpp b/examples/Serial/src/Serial.cpp index 66dedc2..0fcd72a 100644 --- a/examples/Serial/src/Serial.cpp +++ b/examples/Serial/src/Serial.cpp @@ -1,51 +1,51 @@ -// File: testSerial.cpp -// Description: Serial communication console program for Windows and Linux -// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -#include -#include "ce/ceSerial.h" -using namespace std; -using namespace ce; - -int main() -{ -#ifdef CE_WINDOWS - ceSerial com("\\\\.\\COM6", 9600, 8, 'N', 1); // Windows -#else - ceSerial com("/dev/ttyS0", 9600, 8, 'N', 1); // Linux -#endif - - printf("Opening port %s.\n", com.GetPort().c_str()); - if (com.Open() == 0) { - printf("OK.\n"); - } - else { - printf("Error.\n"); - return 1; - } - - bool successFlag; - printf("Writing.\n"); - char s[] = "Hello"; - successFlag = com.Write(s); // write string - successFlag = com.WriteChar('!'); // write a character - - printf("Waiting 3 seconds.\n"); - ceSerial::Delay(3000); // delay to wait for a character - - printf("Reading.\n"); - - successFlag = true; - printf("Rx: "); - while (successFlag) { - char c = com.ReadChar(successFlag); // read a char - if (successFlag) printf("%c", c); - } - printf("\n"); - - printf("Closing port %s.\n", com.GetPort().c_str()); - com.Close(); - return 0; +// File: testSerial.cpp +// Description: Serial communication console program for Windows and Linux +// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye + +#include +#include "ce/ceSerial.h" +using namespace std; +using namespace ce; + +int main() +{ +#ifdef CE_WINDOWS + ceSerial com("\\\\.\\COM6", 9600, 8, 'N', 1); // Windows +#else + ceSerial com("/dev/ttyS0", 9600, 8, 'N', 1); // Linux +#endif + + printf("Opening port %s.\n", com.GetPort().c_str()); + if (com.Open() == 0) { + printf("OK.\n"); + } + else { + printf("Error.\n"); + return 1; + } + + bool successFlag; + printf("Writing.\n"); + char s[] = "Hello"; + successFlag = com.Write(s); // write string + successFlag = com.WriteChar('!'); // write a character + + printf("Waiting 3 seconds.\n"); + ceSerial::Delay(3000); // delay to wait for a character + + printf("Reading.\n"); + + successFlag = true; + printf("Rx: "); + while (successFlag) { + char c = com.ReadChar(successFlag); // read a char + if (successFlag) printf("%c", c); + } + printf("\n"); + + printf("Closing port %s.\n", com.GetPort().c_str()); + com.Close(); + return 0; } \ No newline at end of file diff --git a/examples/SerialGui/CMakeLists.txt b/examples/SerialGui/CMakeLists.txt index 603a975..1de8158 100644 --- a/examples/SerialGui/CMakeLists.txt +++ b/examples/SerialGui/CMakeLists.txt @@ -1,12 +1,12 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(SerialGui VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(SerialGui VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} ${WIN32OPT} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/SerialGui/SerialGui.sh b/examples/SerialGui/SerialGui.sh index 6979d63..84086f0 100644 --- a/examples/SerialGui/SerialGui.sh +++ b/examples/SerialGui/SerialGui.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/SerialGui/SerialGui/SerialGui.sln b/examples/SerialGui/SerialGui/SerialGui.sln index f62d92e..d62b793 100644 --- a/examples/SerialGui/SerialGui/SerialGui.sln +++ b/examples/SerialGui/SerialGui/SerialGui.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SerialGui", "SerialGui.vcxproj", "{9E6EFA9E-8164-4807-B820-F97C9CFBFED1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.ActiveCfg = Debug|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.Build.0 = Debug|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.ActiveCfg = Debug|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.Build.0 = Debug|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.ActiveCfg = Release|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.Build.0 = Release|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.ActiveCfg = Release|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {D0A51A18-2F03-4C7F-9C10-DB3BA0B948C1} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SerialGui", "SerialGui.vcxproj", "{9E6EFA9E-8164-4807-B820-F97C9CFBFED1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.ActiveCfg = Debug|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.Build.0 = Debug|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.ActiveCfg = Debug|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.Build.0 = Debug|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.ActiveCfg = Release|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.Build.0 = Release|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.ActiveCfg = Release|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D0A51A18-2F03-4C7F-9C10-DB3BA0B948C1} + EndGlobalSection +EndGlobal diff --git a/examples/SerialGui/SerialGui/SerialGui.vcxproj b/examples/SerialGui/SerialGui/SerialGui.vcxproj index 5bde48e..7ca8b69 100644 --- a/examples/SerialGui/SerialGui/SerialGui.vcxproj +++ b/examples/SerialGui/SerialGui/SerialGui.vcxproj @@ -1,162 +1,162 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1} - Win32Proj - SerialGui - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - NotSet - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1} + Win32Proj + SerialGui + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + NotSet + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + Level3 + Disabled + true + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) + + + Windows + true + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/SerialGui/SerialGui/SerialGui.vcxproj.filters b/examples/SerialGui/SerialGui/SerialGui.vcxproj.filters index 4f343b2..429c563 100644 --- a/examples/SerialGui/SerialGui/SerialGui.vcxproj.filters +++ b/examples/SerialGui/SerialGui/SerialGui.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/SerialGui/serialguiw.bat b/examples/SerialGui/serialguiw.bat index e0c4f0d..718d911 100644 --- a/examples/SerialGui/serialguiw.bat +++ b/examples/SerialGui/serialguiw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -SerialGui.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +SerialGui.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/SerialGui/src/SerialGui.cpp b/examples/SerialGui/src/SerialGui.cpp index 744048f..34ecebf 100644 --- a/examples/SerialGui/src/SerialGui.cpp +++ b/examples/SerialGui/src/SerialGui.cpp @@ -1,442 +1,442 @@ -//File: wxserial.cpp -//Description: Serial communication for wxWidgets -//WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html -//MIT License (https://opensource.org/licenses/MIT) -//Copyright (c) 2017 Yan Naing Aye - -// For compilers that support precompilation, includes "wx/wx.h". -#include "wx/wxprec.h" - -#ifdef __BORLANDC__ - #pragma hdrstop -#endif - -// for all others, include the necessary headers (this file is usually all you -// need because it includes almost all "standard" wxWidgets headers) -#ifndef WX_PRECOMP - #include "wx/wx.h" -#endif - -// the application icon (under Windows and OS/2 it is in resources and even -// though we could still include the XPM here it would be unused) -#ifndef wxHAS_IMAGES_IN_RESOURCES - #include "sample.xpm" -#endif - -#include -// ---------------------------------------------------------------------------- -// private classes -#include "ce/ceWxSerial.h" -using namespace std; -using namespace ce; -// ---------------------------------------------------------------------------- -class MyFrame; -// Define a new application type, each program should derive a class from wxApp -class MyApp : public wxApp -{ -public: - // override base class virtuals - // ---------------------------- - - // this one is called on application startup and is a good place for the app - // initialization (doing it here and not in the ctor allows to have an error - // return: if OnInit() returns false, the application terminates) - virtual bool OnInit(); - MyFrame* _fra; - ceWxSerial* _com; - void OnSerialEvent(wxThreadEvent& event); -}; - -// Define a new frame type: this is going to be our main frame -class MyFrame : public wxFrame -{ -public: - // ctor(s) - MyFrame(MyApp* app, const wxString& title); - MyApp* _app; - wxButton *btnSend; - wxTextCtrl *txtSend; - wxTimer m_timer; - wxTextCtrl *txtRx; - wxCheckBox *chkRTS; - wxCheckBox *chkDTR; - wxCheckBox *chkCTS; - wxCheckBox *chkDSR; - wxCheckBox *chkRI; - wxCheckBox *chkCD; - // event handlers (these functions should _not_ be virtual) - void OnQuit(wxCommandEvent& event); - void OnAbout(wxCommandEvent& event); - void OnOpen(wxCommandEvent& event); - void OnClose(wxCommandEvent& event); - void SelPort(wxCommandEvent& event); - void SetDataSize(wxCommandEvent& event); - void SetParity(wxCommandEvent& event); - void SetStopBits(wxCommandEvent& event); - void SetBaud(wxCommandEvent& event); - void OnSend(wxCommandEvent& event); - void OnTimer(wxTimerEvent& event); - void ProcessChar(char ch); - void ClearText(wxCommandEvent& event); - void OnChkRTS(wxCommandEvent& event); - void OnChkDTR(wxCommandEvent& event); - void UpdateCommStatus(); -private: - -}; - -// ---------------------------------------------------------------------------- -// constants -// ---------------------------------------------------------------------------- - -// IDs for the controls and the menu commands -const int ID_BTNSEND = 101; -const int ID_TXTSEND = 102; -const int ID_CHKRTS = 103; -const int ID_BAUDRATE = 103; -const int ID_TIMER = 104; -const int ID_TXTRX = 105; -const int ID_CHKDTR = 106; -const int ID_SELPORT = 107; -const int ID_CHKCTS = 108; -const int ID_CHKDSR = 109; -const int ID_CHKRI = 110; -const int ID_CHKCD = 111; -const int ID_DATASIZE = 112; -const int ID_PARITY = 113; -const int ID_STOPBITS = 114; -const int ID_WXSERIAL = 115; - -enum -{ - Button_Send = ID_BTNSEND, - Txt_Send = ID_TXTSEND, - Chk_RTS = ID_CHKRTS, - Serial_Baud = ID_BAUDRATE, - Timer1 = ID_TIMER, - Txt_Rx =ID_TXTRX, - Chk_DTR = ID_CHKDTR, - Serial_Port = ID_SELPORT, - Serial_DataSize=ID_DATASIZE, - Serial_Parity=ID_PARITY, - Serial_StopBits=ID_STOPBITS, - Txt_Clear = wxID_CLEAR, - Serial_Open = wxID_OPEN, - Serial_Close = wxID_CLOSE, - Minimal_Quit = wxID_EXIT, - Wx_Serial = ID_WXSERIAL, - - // it is important for the id corresponding to the "About" command to have - // this standard value as otherwise it won't be handled properly under Mac - // (where it is special and put into the "Apple" menu) - Minimal_About = wxID_ABOUT - -}; - -// Create a new application object: this macro will allow wxWidgets to create -// the application object during program execution (it's better than using a -// static object for many reasons) and also implements the accessor function -// wxGetApp() which will return the reference of the right type (i.e. MyApp and -// not wxApp) -IMPLEMENT_APP(MyApp) - -// ============================================================================ -// implementation -// ============================================================================ - -// ---------------------------------------------------------------------------- -// the application class -// ---------------------------------------------------------------------------- - -// 'Main program' equivalent: the program execution "starts" here -bool MyApp::OnInit() -{ - // call the base class initialization method, currently it only parses a - // few common command-line options but it could be do more in the future - if ( !wxApp::OnInit() ) - return false; - - // create the main application window - _fra = new MyFrame(this, wxT("Serial Com")); - - string device; -#if defined(CE_WINDOWS) - device = "\\\\.\\COM6"; -#else - device = "/dev/ttyUSB0"; -#endif - _com = new ceWxSerial(this, ID_WXSERIAL, 10, device, 9600, 8, 'N', 1); - Connect(ID_WXSERIAL, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); - - // and show it (the frames, unlike simple controls, are not shown when - // created initially) - _fra->Show(true); - - - // success: wxApp::OnRun() will be called which will enter the main message - // loop and the application will run. If we returned false here, the - // application would exit immediately. - return true; -} - -void MyApp::OnSerialEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - char ch; - for (int i = 0; i < v.size(); i++) { - ch = v[i]; - _fra->ProcessChar(ch); - } - // wxMessageBox(wxT("Serial event")); -} - -// ---------------------------------------------------------------------------- -// main frame -// ---------------------------------------------------------------------------- - -// frame constructor -MyFrame::MyFrame(MyApp* app, const wxString& title) - : wxFrame(NULL, wxID_ANY, title,wxDefaultPosition,wxSize(390, 280), wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),m_timer(this, ID_TIMER), _app(app) -{ - // set the frame icon - SetIcon(wxICON(sample)); - -#if wxUSE_MENUS - // create a menu bar - wxMenu *fileMenu = new wxMenu; - - //Edit menu - wxMenu *editMenu = new wxMenu; - - // the "About" item should be in the help menu - wxMenu *helpMenu = new wxMenu; - - helpMenu->Append(Minimal_About, wxT("&About\tF1"), wxT("Show about dialog")); - fileMenu->Append(Serial_Open, wxT("&Open\tAlt-O"), wxT("Open serial port")); - fileMenu->Append(Serial_Close, wxT("&Close\tAlt-C"), wxT("Close serial port")); - editMenu->Append(Txt_Clear, wxT("Clea&r\tAlt-R"), wxT("Clear text")); - fileMenu->Append(Serial_Port, wxT("&Serial Port\tAlt-S"), wxT("Select serial port")); - fileMenu->Append(Serial_Baud, wxT("&Baud Rate\tAlt-B"), wxT("Set baud rate")); - fileMenu->Append(Serial_DataSize, wxT("&Data Size\tAlt-D"), wxT("Set data size")); - fileMenu->Append(Serial_Parity, wxT("&Parity\tAlt-P"), wxT("Set parity")); - fileMenu->Append(Serial_StopBits, wxT("S&top Bits\tAlt-t"), wxT("Set stop bits")); - fileMenu->Append(Minimal_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program")); - - - // now append the freshly created menu to the menu bar... - wxMenuBar *menuBar = new wxMenuBar(); - menuBar->Append(fileMenu, wxT("&File")); - menuBar->Append(editMenu, wxT("&Edit")); - menuBar->Append(helpMenu, wxT("&Help")); - - // ... and attach this menu bar to the frame - SetMenuBar(menuBar); -#endif // wxUSE_MENUS - -#if wxUSE_STATUSBAR - // create a status bar just for fun (by default with 1 pane only) - CreateStatusBar(2); - SetStatusText(wxT("Serial Communication")); -#endif // wxUSE_STATUSBAR - btnSend = new wxButton(this,Button_Send,wxT( "Send"), wxPoint(5, 5), wxSize(100, 25)); - txtSend = new wxTextCtrl(this,Txt_Send,wxT("Hello!"),wxPoint(120,5),wxSize(250,25)); - //lblRx = new wxStaticText(this, ID_LBLRX, wxT("Rx:"), wxPoint(5, 75), wxSize(35, 25)); - txtRx = new wxTextCtrl(this, Txt_Rx, wxT(""), wxPoint(5, 35), wxSize(365, 125), wxTE_MULTILINE); - chkRTS = new wxCheckBox(this, Chk_RTS, wxT("RTS"), wxPoint(5, 170), wxDefaultSize); - chkDTR = new wxCheckBox(this, Chk_DTR, wxT("DTR"), wxPoint(55, 170), wxDefaultSize); - chkCTS = new wxCheckBox(this, ID_CHKCTS, wxT("CTS"), wxPoint(155, 170), wxDefaultSize); - chkDSR = new wxCheckBox(this, ID_CHKDSR, wxT("DSR"), wxPoint(205, 170), wxDefaultSize); - chkRI = new wxCheckBox(this, ID_CHKRI, wxT("RI"), wxPoint(255, 170), wxDefaultSize); - chkCD = new wxCheckBox(this, ID_CHKCD, wxT("CD"), wxPoint(305, 170), wxDefaultSize); - - Connect(Button_Send, wxEVT_COMMAND_BUTTON_CLICKED,wxCommandEventHandler(MyFrame::OnSend)); - Connect(Minimal_About,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnAbout)); - Connect(Minimal_Quit,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnQuit)); - Connect(Serial_Open,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnOpen)); - Connect(Serial_Close,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnClose)); - Connect(Serial_Port, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SelPort)); - Connect(Serial_Baud, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetBaud)); - Connect(Serial_DataSize, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetDataSize)); - Connect(Serial_Parity, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetParity)); - Connect(Serial_StopBits, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetStopBits)); - Connect(Timer1,wxEVT_TIMER, wxTimerEventHandler(MyFrame::OnTimer)); - Connect(Txt_Clear, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::ClearText)); - Connect(Chk_RTS,wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkRTS)); - Connect(Chk_DTR,wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkDTR)); - //Bind(wxEVT_MENU, &MyFrame::OnClose, this, Serial_Close); - - chkCTS->Disable(); - chkDSR->Disable(); - chkRI->Disable(); - chkCD->Disable(); - - m_timer.Start(250); -} - - -// event handlers - -void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) -{ - // true is to force the frame to close - Close(true); -} - -void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) -{ - wxMessageBox(wxString::Format( - wxT("Serial Communication! \n ") - wxT("Author: Yan Naing Aye \n ") - wxT("Web: https://github.com/yan9a/serial") - ), - wxT("About Serial Comm"), - wxOK | wxICON_INFORMATION, - this); -} - -void MyFrame::OnOpen(wxCommandEvent& WXUNUSED(event)) -{ - if(_app->_com->Open()) txtRx->AppendText(wxString::Format(wxT("Error opening port %s.\n"),_app->_com->GetPort())); - else txtRx->AppendText(wxString::Format(wxT("Port %s is opened.\n"), _app->_com->GetPort())); -} - -void MyFrame::OnClose(wxCommandEvent& WXUNUSED(event)) -{ - _app->_com->Close(); - txtRx->AppendText(wxString::Format(wxT("Port %s is closed.\n"), _app->_com->GetPort())); -} - -void MyFrame::SelPort(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort())); - } - else { - wxString cdev=wxString::Format(wxT("%s"), _app->_com->GetPort()); - wxString device = wxGetTextFromUser(wxT("Enter the port"), wxT("Set Port"), cdev); - string str = device.ToStdString(); - if (str.length() > 0) { - _app->_com->SetPortName(str); - } - - txtRx->AppendText(wxString::Format(wxT("Port: %s\n"), _app->_com->GetPort())); - } -} - -void MyFrame::SetParity(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort())); - } - else { - wxString cdev = wxString::Format(wxT("%c"), _app->_com->GetParity()); -#if defined(__WINDOWS__) - wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, O, M, or S )"), wxT("Set Parity"), cdev); -#else - wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, or O )"), wxT("Set Parity"), cdev); -#endif - - string pstr = parity.ToStdString(); - if (pstr.length() > 0) { - _app->_com->SetParity(pstr.at(0)); - } - txtRx->AppendText(wxString::Format(wxT("Parity: %c\n"), _app->_com->GetParity())); - } -} - -void MyFrame::SetBaud(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the baud rate"), wxT("Baud rate"), wxT("Set Baud Rate"),_app->_com->GetBaudRate(),0, 1000000); - if (n >= 0) { - _app->_com->SetBaudRate(n); - } - txtRx->AppendText(wxString::Format(wxT("Baud rate: %ld\n"), _app->_com->GetBaudRate())); - } -} - -void MyFrame::SetDataSize(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the data size"), wxT("Data Size"), wxT("Set Data Size"), _app->_com->GetDataSize(), 5, 8); - if (n >= 0) { - _app->_com->SetDataSize(n); - } - txtRx->AppendText(wxString::Format(wxT("Data size: %ld\n"), _app->_com->GetDataSize())); - } -} - -void MyFrame::SetStopBits(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the number of stop bits"), wxT("Data Size"), wxT("Set stop bits"), long(_app->_com->GetStopBits()), 1, 2); - if (n > 0) { - _app->_com->SetStopBits(float(n)); - } - txtRx->AppendText(wxString::Format(wxT("Stop bits: %ld\n"), long(_app->_com->GetStopBits()))); - } -} - -void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) -{ - wxString str = txtSend->GetValue(); - wxCharBuffer buffer = str.ToUTF8(); - if (_app->_com->Write(buffer.data())) { - txtRx->AppendText(str); - } - else { - txtRx->AppendText(wxT("Write error.\n")); - } -} - -void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event)) -{ - UpdateCommStatus(); -} - -void MyFrame::ProcessChar(char ch) -{ - this->txtRx->AppendText(wxString::Format(wxT("%c"), ch)); -} - -void MyFrame::ClearText(wxCommandEvent& WXUNUSED(event)) -{ - txtRx->Clear(); -} - -void MyFrame::OnChkRTS(wxCommandEvent& WXUNUSED(event)) -{ - if (!_app->_com->SetRTS(chkRTS->IsChecked())) { - txtRx->AppendText(wxT("RTS error.\n")); - } -} - -void MyFrame::OnChkDTR(wxCommandEvent& WXUNUSED(event)) -{ - if (!_app->_com->SetDTR(chkDTR->IsChecked())) { - txtRx->AppendText(wxT("DTR error.\n")); - } -} - -void MyFrame::UpdateCommStatus() -{ - bool s; - bool v; - v = _app->_com->GetCTS(s); - if (s) chkCTS->SetValue(v); - v = _app->_com->GetDSR(s); - if (s) chkDSR->SetValue(v); - v = _app->_com->GetRI(s); - if (s) chkRI->SetValue(v); - v = _app->_com->GetCD(s); - if (s) chkCD->SetValue(v); -} +//File: wxserial.cpp +//Description: Serial communication for wxWidgets +//WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html +//MIT License (https://opensource.org/licenses/MIT) +//Copyright (c) 2017 Yan Naing Aye + +// For compilers that support precompilation, includes "wx/wx.h". +#include "wx/wxprec.h" + +#ifdef __BORLANDC__ + #pragma hdrstop +#endif + +// for all others, include the necessary headers (this file is usually all you +// need because it includes almost all "standard" wxWidgets headers) +#ifndef WX_PRECOMP + #include "wx/wx.h" +#endif + +// the application icon (under Windows and OS/2 it is in resources and even +// though we could still include the XPM here it would be unused) +#ifndef wxHAS_IMAGES_IN_RESOURCES + #include "sample.xpm" +#endif + +#include +// ---------------------------------------------------------------------------- +// private classes +#include "ce/ceWxSerial.h" +using namespace std; +using namespace ce; +// ---------------------------------------------------------------------------- +class MyFrame; +// Define a new application type, each program should derive a class from wxApp +class MyApp : public wxApp +{ +public: + // override base class virtuals + // ---------------------------- + + // this one is called on application startup and is a good place for the app + // initialization (doing it here and not in the ctor allows to have an error + // return: if OnInit() returns false, the application terminates) + virtual bool OnInit(); + MyFrame* _fra; + ceWxSerial* _com; + void OnSerialEvent(wxThreadEvent& event); +}; + +// Define a new frame type: this is going to be our main frame +class MyFrame : public wxFrame +{ +public: + // ctor(s) + MyFrame(MyApp* app, const wxString& title); + MyApp* _app; + wxButton *btnSend; + wxTextCtrl *txtSend; + wxTimer m_timer; + wxTextCtrl *txtRx; + wxCheckBox *chkRTS; + wxCheckBox *chkDTR; + wxCheckBox *chkCTS; + wxCheckBox *chkDSR; + wxCheckBox *chkRI; + wxCheckBox *chkCD; + // event handlers (these functions should _not_ be virtual) + void OnQuit(wxCommandEvent& event); + void OnAbout(wxCommandEvent& event); + void OnOpen(wxCommandEvent& event); + void OnClose(wxCommandEvent& event); + void SelPort(wxCommandEvent& event); + void SetDataSize(wxCommandEvent& event); + void SetParity(wxCommandEvent& event); + void SetStopBits(wxCommandEvent& event); + void SetBaud(wxCommandEvent& event); + void OnSend(wxCommandEvent& event); + void OnTimer(wxTimerEvent& event); + void ProcessChar(char ch); + void ClearText(wxCommandEvent& event); + void OnChkRTS(wxCommandEvent& event); + void OnChkDTR(wxCommandEvent& event); + void UpdateCommStatus(); +private: + +}; + +// ---------------------------------------------------------------------------- +// constants +// ---------------------------------------------------------------------------- + +// IDs for the controls and the menu commands +const int ID_BTNSEND = 101; +const int ID_TXTSEND = 102; +const int ID_CHKRTS = 103; +const int ID_BAUDRATE = 103; +const int ID_TIMER = 104; +const int ID_TXTRX = 105; +const int ID_CHKDTR = 106; +const int ID_SELPORT = 107; +const int ID_CHKCTS = 108; +const int ID_CHKDSR = 109; +const int ID_CHKRI = 110; +const int ID_CHKCD = 111; +const int ID_DATASIZE = 112; +const int ID_PARITY = 113; +const int ID_STOPBITS = 114; +const int ID_WXSERIAL = 115; + +enum +{ + Button_Send = ID_BTNSEND, + Txt_Send = ID_TXTSEND, + Chk_RTS = ID_CHKRTS, + Serial_Baud = ID_BAUDRATE, + Timer1 = ID_TIMER, + Txt_Rx =ID_TXTRX, + Chk_DTR = ID_CHKDTR, + Serial_Port = ID_SELPORT, + Serial_DataSize=ID_DATASIZE, + Serial_Parity=ID_PARITY, + Serial_StopBits=ID_STOPBITS, + Txt_Clear = wxID_CLEAR, + Serial_Open = wxID_OPEN, + Serial_Close = wxID_CLOSE, + Minimal_Quit = wxID_EXIT, + Wx_Serial = ID_WXSERIAL, + + // it is important for the id corresponding to the "About" command to have + // this standard value as otherwise it won't be handled properly under Mac + // (where it is special and put into the "Apple" menu) + Minimal_About = wxID_ABOUT + +}; + +// Create a new application object: this macro will allow wxWidgets to create +// the application object during program execution (it's better than using a +// static object for many reasons) and also implements the accessor function +// wxGetApp() which will return the reference of the right type (i.e. MyApp and +// not wxApp) +IMPLEMENT_APP(MyApp) + +// ============================================================================ +// implementation +// ============================================================================ + +// ---------------------------------------------------------------------------- +// the application class +// ---------------------------------------------------------------------------- + +// 'Main program' equivalent: the program execution "starts" here +bool MyApp::OnInit() +{ + // call the base class initialization method, currently it only parses a + // few common command-line options but it could be do more in the future + if ( !wxApp::OnInit() ) + return false; + + // create the main application window + _fra = new MyFrame(this, wxT("Serial Com")); + + string device; +#if defined(CE_WINDOWS) + device = "\\\\.\\COM6"; +#else + device = "/dev/ttyUSB0"; +#endif + _com = new ceWxSerial(this, ID_WXSERIAL, 10, device, 9600, 8, 'N', 1); + Connect(ID_WXSERIAL, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); + + // and show it (the frames, unlike simple controls, are not shown when + // created initially) + _fra->Show(true); + + + // success: wxApp::OnRun() will be called which will enter the main message + // loop and the application will run. If we returned false here, the + // application would exit immediately. + return true; +} + +void MyApp::OnSerialEvent(wxThreadEvent& event) +{ + std::vector v = event.GetPayload>(); + char ch; + for (int i = 0; i < v.size(); i++) { + ch = v[i]; + _fra->ProcessChar(ch); + } + // wxMessageBox(wxT("Serial event")); +} + +// ---------------------------------------------------------------------------- +// main frame +// ---------------------------------------------------------------------------- + +// frame constructor +MyFrame::MyFrame(MyApp* app, const wxString& title) + : wxFrame(NULL, wxID_ANY, title,wxDefaultPosition,wxSize(390, 280), wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),m_timer(this, ID_TIMER), _app(app) +{ + // set the frame icon + SetIcon(wxICON(sample)); + +#if wxUSE_MENUS + // create a menu bar + wxMenu *fileMenu = new wxMenu; + + //Edit menu + wxMenu *editMenu = new wxMenu; + + // the "About" item should be in the help menu + wxMenu *helpMenu = new wxMenu; + + helpMenu->Append(Minimal_About, wxT("&About\tF1"), wxT("Show about dialog")); + fileMenu->Append(Serial_Open, wxT("&Open\tAlt-O"), wxT("Open serial port")); + fileMenu->Append(Serial_Close, wxT("&Close\tAlt-C"), wxT("Close serial port")); + editMenu->Append(Txt_Clear, wxT("Clea&r\tAlt-R"), wxT("Clear text")); + fileMenu->Append(Serial_Port, wxT("&Serial Port\tAlt-S"), wxT("Select serial port")); + fileMenu->Append(Serial_Baud, wxT("&Baud Rate\tAlt-B"), wxT("Set baud rate")); + fileMenu->Append(Serial_DataSize, wxT("&Data Size\tAlt-D"), wxT("Set data size")); + fileMenu->Append(Serial_Parity, wxT("&Parity\tAlt-P"), wxT("Set parity")); + fileMenu->Append(Serial_StopBits, wxT("S&top Bits\tAlt-t"), wxT("Set stop bits")); + fileMenu->Append(Minimal_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program")); + + + // now append the freshly created menu to the menu bar... + wxMenuBar *menuBar = new wxMenuBar(); + menuBar->Append(fileMenu, wxT("&File")); + menuBar->Append(editMenu, wxT("&Edit")); + menuBar->Append(helpMenu, wxT("&Help")); + + // ... and attach this menu bar to the frame + SetMenuBar(menuBar); +#endif // wxUSE_MENUS + +#if wxUSE_STATUSBAR + // create a status bar just for fun (by default with 1 pane only) + CreateStatusBar(2); + SetStatusText(wxT("Serial Communication")); +#endif // wxUSE_STATUSBAR + btnSend = new wxButton(this,Button_Send,wxT( "Send"), wxPoint(5, 5), wxSize(100, 25)); + txtSend = new wxTextCtrl(this,Txt_Send,wxT("Hello!"),wxPoint(120,5),wxSize(250,25)); + //lblRx = new wxStaticText(this, ID_LBLRX, wxT("Rx:"), wxPoint(5, 75), wxSize(35, 25)); + txtRx = new wxTextCtrl(this, Txt_Rx, wxT(""), wxPoint(5, 35), wxSize(365, 125), wxTE_MULTILINE); + chkRTS = new wxCheckBox(this, Chk_RTS, wxT("RTS"), wxPoint(5, 170), wxDefaultSize); + chkDTR = new wxCheckBox(this, Chk_DTR, wxT("DTR"), wxPoint(55, 170), wxDefaultSize); + chkCTS = new wxCheckBox(this, ID_CHKCTS, wxT("CTS"), wxPoint(155, 170), wxDefaultSize); + chkDSR = new wxCheckBox(this, ID_CHKDSR, wxT("DSR"), wxPoint(205, 170), wxDefaultSize); + chkRI = new wxCheckBox(this, ID_CHKRI, wxT("RI"), wxPoint(255, 170), wxDefaultSize); + chkCD = new wxCheckBox(this, ID_CHKCD, wxT("CD"), wxPoint(305, 170), wxDefaultSize); + + Connect(Button_Send, wxEVT_COMMAND_BUTTON_CLICKED,wxCommandEventHandler(MyFrame::OnSend)); + Connect(Minimal_About,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnAbout)); + Connect(Minimal_Quit,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnQuit)); + Connect(Serial_Open,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnOpen)); + Connect(Serial_Close,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnClose)); + Connect(Serial_Port, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SelPort)); + Connect(Serial_Baud, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetBaud)); + Connect(Serial_DataSize, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetDataSize)); + Connect(Serial_Parity, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetParity)); + Connect(Serial_StopBits, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetStopBits)); + Connect(Timer1,wxEVT_TIMER, wxTimerEventHandler(MyFrame::OnTimer)); + Connect(Txt_Clear, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::ClearText)); + Connect(Chk_RTS,wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkRTS)); + Connect(Chk_DTR,wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkDTR)); + //Bind(wxEVT_MENU, &MyFrame::OnClose, this, Serial_Close); + + chkCTS->Disable(); + chkDSR->Disable(); + chkRI->Disable(); + chkCD->Disable(); + + m_timer.Start(250); +} + + +// event handlers + +void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) +{ + // true is to force the frame to close + Close(true); +} + +void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) +{ + wxMessageBox(wxString::Format( + wxT("Serial Communication! \n ") + wxT("Author: Yan Naing Aye \n ") + wxT("Web: https://github.com/yan9a/serial") + ), + wxT("About Serial Comm"), + wxOK | wxICON_INFORMATION, + this); +} + +void MyFrame::OnOpen(wxCommandEvent& WXUNUSED(event)) +{ + if(_app->_com->Open()) txtRx->AppendText(wxString::Format(wxT("Error opening port %s.\n"),_app->_com->GetPort())); + else txtRx->AppendText(wxString::Format(wxT("Port %s is opened.\n"), _app->_com->GetPort())); +} + +void MyFrame::OnClose(wxCommandEvent& WXUNUSED(event)) +{ + _app->_com->Close(); + txtRx->AppendText(wxString::Format(wxT("Port %s is closed.\n"), _app->_com->GetPort())); +} + +void MyFrame::SelPort(wxCommandEvent& WXUNUSED(event)) +{ + if (_app->_com->IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort())); + } + else { + wxString cdev=wxString::Format(wxT("%s"), _app->_com->GetPort()); + wxString device = wxGetTextFromUser(wxT("Enter the port"), wxT("Set Port"), cdev); + string str = device.ToStdString(); + if (str.length() > 0) { + _app->_com->SetPortName(str); + } + + txtRx->AppendText(wxString::Format(wxT("Port: %s\n"), _app->_com->GetPort())); + } +} + +void MyFrame::SetParity(wxCommandEvent& WXUNUSED(event)) +{ + if (_app->_com->IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort())); + } + else { + wxString cdev = wxString::Format(wxT("%c"), _app->_com->GetParity()); +#if defined(__WINDOWS__) + wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, O, M, or S )"), wxT("Set Parity"), cdev); +#else + wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, or O )"), wxT("Set Parity"), cdev); +#endif + + string pstr = parity.ToStdString(); + if (pstr.length() > 0) { + _app->_com->SetParity(pstr.at(0)); + } + txtRx->AppendText(wxString::Format(wxT("Parity: %c\n"), _app->_com->GetParity())); + } +} + +void MyFrame::SetBaud(wxCommandEvent& WXUNUSED(event)) +{ + if (_app->_com->IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); + } + else { + long n = wxGetNumberFromUser(wxT("Enter the baud rate"), wxT("Baud rate"), wxT("Set Baud Rate"),_app->_com->GetBaudRate(),0, 1000000); + if (n >= 0) { + _app->_com->SetBaudRate(n); + } + txtRx->AppendText(wxString::Format(wxT("Baud rate: %ld\n"), _app->_com->GetBaudRate())); + } +} + +void MyFrame::SetDataSize(wxCommandEvent& WXUNUSED(event)) +{ + if (_app->_com->IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); + } + else { + long n = wxGetNumberFromUser(wxT("Enter the data size"), wxT("Data Size"), wxT("Set Data Size"), _app->_com->GetDataSize(), 5, 8); + if (n >= 0) { + _app->_com->SetDataSize(n); + } + txtRx->AppendText(wxString::Format(wxT("Data size: %ld\n"), _app->_com->GetDataSize())); + } +} + +void MyFrame::SetStopBits(wxCommandEvent& WXUNUSED(event)) +{ + if (_app->_com->IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); + } + else { + long n = wxGetNumberFromUser(wxT("Enter the number of stop bits"), wxT("Data Size"), wxT("Set stop bits"), long(_app->_com->GetStopBits()), 1, 2); + if (n > 0) { + _app->_com->SetStopBits(float(n)); + } + txtRx->AppendText(wxString::Format(wxT("Stop bits: %ld\n"), long(_app->_com->GetStopBits()))); + } +} + +void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) +{ + wxString str = txtSend->GetValue(); + wxCharBuffer buffer = str.ToUTF8(); + if (_app->_com->Write(buffer.data())) { + txtRx->AppendText(str); + } + else { + txtRx->AppendText(wxT("Write error.\n")); + } +} + +void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event)) +{ + UpdateCommStatus(); +} + +void MyFrame::ProcessChar(char ch) +{ + this->txtRx->AppendText(wxString::Format(wxT("%c"), ch)); +} + +void MyFrame::ClearText(wxCommandEvent& WXUNUSED(event)) +{ + txtRx->Clear(); +} + +void MyFrame::OnChkRTS(wxCommandEvent& WXUNUSED(event)) +{ + if (!_app->_com->SetRTS(chkRTS->IsChecked())) { + txtRx->AppendText(wxT("RTS error.\n")); + } +} + +void MyFrame::OnChkDTR(wxCommandEvent& WXUNUSED(event)) +{ + if (!_app->_com->SetDTR(chkDTR->IsChecked())) { + txtRx->AppendText(wxT("DTR error.\n")); + } +} + +void MyFrame::UpdateCommStatus() +{ + bool s; + bool v; + v = _app->_com->GetCTS(s); + if (s) chkCTS->SetValue(v); + v = _app->_com->GetDSR(s); + if (s) chkDSR->SetValue(v); + v = _app->_com->GetRI(s); + if (s) chkRI->SetValue(v); + v = _app->_com->GetCD(s); + if (s) chkCD->SetValue(v); +} diff --git a/examples/SerialGui/src/sample.xpm b/examples/SerialGui/src/sample.xpm index 58913cb..9c0a107 100644 --- a/examples/SerialGui/src/sample.xpm +++ b/examples/SerialGui/src/sample.xpm @@ -1,44 +1,44 @@ -/* XPM */ -static const char *const sample_xpm[] = { -/* columns rows colors chars-per-pixel */ -"32 32 6 1", -" c black", -". c navy", -"X c red", -"o c yellow", -"O c gray100", -"+ c None", -/* pixels */ -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++ ++++++++++", -"++++++++ ............ ++++++++++", -"++++++++ ............ ++++++++++", -"++++++++ .OO......... ++++++++++", -"++++++++ .OO......... ++++++++++", -"++++++++ .OO......... ++++++++++", -"++++++++ .OO...... ", -"++++++++ .OO...... oooooooooooo ", -" .OO...... oooooooooooo ", -" XXXXXXX .OO...... oOOooooooooo ", -" XXXXXXX .OO...... oOOooooooooo ", -" XOOXXXX ......... oOOooooooooo ", -" XOOXXXX ......... oOOooooooooo ", -" XOOXXXX oOOooooooooo ", -" XOOXXXXXXXXX ++++ oOOooooooooo ", -" XOOXXXXXXXXX ++++ oOOooooooooo ", -" XOOXXXXXXXXX ++++ oOOooooooooo ", -" XOOXXXXXXXXX ++++ oooooooooooo ", -" XOOXXXXXXXXX ++++ oooooooooooo ", -" XXXXXXXXXXXX ++++ ", -" XXXXXXXXXXXX ++++++++++++++++++", -" ++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++" -}; +/* XPM */ +static const char *const sample_xpm[] = { +/* columns rows colors chars-per-pixel */ +"32 32 6 1", +" c black", +". c navy", +"X c red", +"o c yellow", +"O c gray100", +"+ c None", +/* pixels */ +"++++++++++++++++++++++++++++++++", +"++++++++++++++++++++++++++++++++", +"++++++++++++++++++++++++++++++++", +"++++++++++++++++++++++++++++++++", +"++++++++++++++++++++++++++++++++", +"++++++++ ++++++++++", +"++++++++ ............ ++++++++++", +"++++++++ ............ ++++++++++", +"++++++++ .OO......... ++++++++++", +"++++++++ .OO......... ++++++++++", +"++++++++ .OO......... ++++++++++", +"++++++++ .OO...... ", +"++++++++ .OO...... oooooooooooo ", +" .OO...... oooooooooooo ", +" XXXXXXX .OO...... oOOooooooooo ", +" XXXXXXX .OO...... oOOooooooooo ", +" XOOXXXX ......... oOOooooooooo ", +" XOOXXXX ......... oOOooooooooo ", +" XOOXXXX oOOooooooooo ", +" XOOXXXXXXXXX ++++ oOOooooooooo ", +" XOOXXXXXXXXX ++++ oOOooooooooo ", +" XOOXXXXXXXXX ++++ oOOooooooooo ", +" XOOXXXXXXXXX ++++ oooooooooooo ", +" XOOXXXXXXXXX ++++ oooooooooooo ", +" XXXXXXXXXXXX ++++ ", +" XXXXXXXXXXXX ++++++++++++++++++", +" ++++++++++++++++++", +"++++++++++++++++++++++++++++++++", +"++++++++++++++++++++++++++++++++", +"++++++++++++++++++++++++++++++++", +"++++++++++++++++++++++++++++++++", +"++++++++++++++++++++++++++++++++" +}; diff --git a/examples/Timer/CMakeLists.txt b/examples/Timer/CMakeLists.txt index a8a0b04..b38146d 100644 --- a/examples/Timer/CMakeLists.txt +++ b/examples/Timer/CMakeLists.txt @@ -1,11 +1,11 @@ -cmake_minimum_required(VERSION 3.0.0) -project(Timer VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +project(Timer VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} ${WIN32OPT} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/Timer/Timer.sh b/examples/Timer/Timer.sh index 6979d63..84086f0 100644 --- a/examples/Timer/Timer.sh +++ b/examples/Timer/Timer.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/Timer/Timer/Timer.sln b/examples/Timer/Timer/Timer.sln index dd72af3..10d800e 100644 --- a/examples/Timer/Timer/Timer.sln +++ b/examples/Timer/Timer/Timer.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Timer", "Timer.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Timer", "Timer.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} + EndGlobalSection +EndGlobal diff --git a/examples/Timer/Timer/Timer.vcxproj b/examples/Timer/Timer/Timer.vcxproj index f6de967..3ba5c6e 100644 --- a/examples/Timer/Timer/Timer.vcxproj +++ b/examples/Timer/Timer/Timer.vcxproj @@ -1,162 +1,162 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} - Win32Proj - Timer - 10.0 - - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include - - - Windows - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} + Win32Proj + Timer + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + Level3 + Disabled + true + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + $(SolutionDir)..\..\..\include + + + Windows + true + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/Timer/Timer/Timer.vcxproj.filters b/examples/Timer/Timer/Timer.vcxproj.filters index ad2b0d7..ff3b72e 100644 --- a/examples/Timer/Timer/Timer.vcxproj.filters +++ b/examples/Timer/Timer/Timer.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/Timer/src/Timer.cpp b/examples/Timer/src/Timer.cpp index c769b06..5f958a5 100644 --- a/examples/Timer/src/Timer.cpp +++ b/examples/Timer/src/Timer.cpp @@ -1,32 +1,32 @@ -#include -#include "ce/ceUtil.h" -#include -using namespace ce; -#define TMR_ID1 201 -class MyApp : public wxAppConsole -{ - public: - virtual bool OnInit(); - void OnTmrEvent(wxThreadEvent& event); - ceLog* _log; -}; -IMPLEMENT_APP(MyApp) -bool MyApp::OnInit() -{ - this->_log = new ceLog("./", 1); - this->_log->SetEnPrintf(true); - ceWxTmr* t = new ceWxTmr(this,TMR_ID1,2000);// 2 seconds - t->Start(); - Connect(TMR_ID1, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnTmrEvent)); - return true; -} - -void MyApp::OnTmrEvent(wxThreadEvent& event) -{ - static int c = 0; - std::vector v = event.GetPayload>(); - this->_log->Print("Ev = "+ std::to_string(int(v[0]))); - if(++c >= 3){ - Exit(); - } +#include +#include "ce/ceUtil.h" +#include +using namespace ce; +#define TMR_ID1 201 +class MyApp : public wxAppConsole +{ + public: + virtual bool OnInit(); + void OnTmrEvent(wxThreadEvent& event); + ceLog* _log; +}; +IMPLEMENT_APP(MyApp) +bool MyApp::OnInit() +{ + this->_log = new ceLog("./", 1); + this->_log->SetEnPrintf(true); + ceWxTmr* t = new ceWxTmr(this,TMR_ID1,2000);// 2 seconds + t->Start(); + Connect(TMR_ID1, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnTmrEvent)); + return true; +} + +void MyApp::OnTmrEvent(wxThreadEvent& event) +{ + static int c = 0; + std::vector v = event.GetPayload>(); + this->_log->Print("Ev = "+ std::to_string(int(v[0]))); + if(++c >= 3){ + Exit(); + } } \ No newline at end of file diff --git a/examples/Timer/timerw.bat b/examples/Timer/timerw.bat index 2962bc0..736e72e 100644 --- a/examples/Timer/timerw.bat +++ b/examples/Timer/timerw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -Timer.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +Timer.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/UDP/CMakeLists.txt b/examples/UDP/CMakeLists.txt index bb256a2..fecff2c 100644 --- a/examples/UDP/CMakeLists.txt +++ b/examples/UDP/CMakeLists.txt @@ -1,12 +1,12 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(UDP VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(UDP VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} ${WIN32OPT} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/UDP/UDP.sh b/examples/UDP/UDP.sh index 6979d63..84086f0 100644 --- a/examples/UDP/UDP.sh +++ b/examples/UDP/UDP.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/UDP/UDPw.bat b/examples/UDP/UDPw.bat index 644e4dc..16c1828 100644 --- a/examples/UDP/UDPw.bat +++ b/examples/UDP/UDPw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -UDP.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +UDP.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/UDP/src/UDP.cpp b/examples/UDP/src/UDP.cpp index 5d9a474..b1b2142 100644 --- a/examples/UDP/src/UDP.cpp +++ b/examples/UDP/src/UDP.cpp @@ -1,44 +1,44 @@ -#include "ce/ceUtil.h" -using namespace ce; -#define CE_TMR_ID1 202 -#define CE_UDP_ID1 203 -class MyApp : public wxAppConsole -{ -private: - wxTimer* _tmr1; - ceUDP* _udp; -public: - virtual bool OnInit(); - void OnTimer1(wxTimerEvent& WXUNUSED(event)); - void OnUdpEvent(wxThreadEvent& event); -}; -IMPLEMENT_APP(MyApp) -bool MyApp::OnInit() -{ - this->_tmr1 = new wxTimer(this,CE_TMR_ID1); - this->_udp = new ceUDP(this,CE_UDP_ID1,10101,10102); - this->_udp->Open(); - Connect(CE_TMR_ID1, wxEVT_TIMER, wxTimerEventHandler(MyApp::OnTimer1)); - Connect(CE_UDP_ID1, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnUdpEvent)); - this->_tmr1->Start(3000); - return true; -} - -void MyApp::OnTimer1(wxTimerEvent& WXUNUSED(event)) -{ - static int c = 0; - printf("Tmr ev...\n"); - std::vector vc = {'U','D','P'}; - this->_udp->Tx(vc); - if(++c>=3){ - Exit(); - } -} - -void MyApp::OnUdpEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - std::string s = event.GetString().ToStdString(); - int i = event.GetInt(); - printf("UDP vec = %s, ip =%s, port = %d\n",ceMisc::cvec2hex(v).c_str(),s.c_str(),i); -} +#include "ce/ceUtil.h" +using namespace ce; +#define CE_TMR_ID1 202 +#define CE_UDP_ID1 203 +class MyApp : public wxAppConsole +{ +private: + wxTimer* _tmr1; + ceUDP* _udp; +public: + virtual bool OnInit(); + void OnTimer1(wxTimerEvent& WXUNUSED(event)); + void OnUdpEvent(wxThreadEvent& event); +}; +IMPLEMENT_APP(MyApp) +bool MyApp::OnInit() +{ + this->_tmr1 = new wxTimer(this,CE_TMR_ID1); + this->_udp = new ceUDP(this,CE_UDP_ID1,10101,10102); + this->_udp->Open(); + Connect(CE_TMR_ID1, wxEVT_TIMER, wxTimerEventHandler(MyApp::OnTimer1)); + Connect(CE_UDP_ID1, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnUdpEvent)); + this->_tmr1->Start(3000); + return true; +} + +void MyApp::OnTimer1(wxTimerEvent& WXUNUSED(event)) +{ + static int c = 0; + printf("Tmr ev...\n"); + std::vector vc = {'U','D','P'}; + this->_udp->Tx(vc); + if(++c>=3){ + Exit(); + } +} + +void MyApp::OnUdpEvent(wxThreadEvent& event) +{ + std::vector v = event.GetPayload>(); + std::string s = event.GetString().ToStdString(); + int i = event.GetInt(); + printf("UDP vec = %s, ip =%s, port = %d\n",ceMisc::cvec2hex(v).c_str(),s.c_str(),i); +} diff --git a/examples/WxSerial/CMakeLists.txt b/examples/WxSerial/CMakeLists.txt index 75888d9..00596a4 100644 --- a/examples/WxSerial/CMakeLists.txt +++ b/examples/WxSerial/CMakeLists.txt @@ -1,12 +1,12 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(WxSerial VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(WxSerial VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} ${WIN32OPT} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/WxSerial/WxSerial.sh b/examples/WxSerial/WxSerial.sh index 6979d63..84086f0 100644 --- a/examples/WxSerial/WxSerial.sh +++ b/examples/WxSerial/WxSerial.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/WxSerial/src/WxSerial.cpp b/examples/WxSerial/src/WxSerial.cpp index 75ca7ee..cbe7103 100644 --- a/examples/WxSerial/src/WxSerial.cpp +++ b/examples/WxSerial/src/WxSerial.cpp @@ -1,31 +1,31 @@ -#include -#include "ce/ceUtil.h" -#include -using namespace ce; -#define WXSERIAL_ID1 201 -class MyApp : public wxAppConsole -{ - public: - virtual bool OnInit(); - void OnSerialEvent(wxThreadEvent& event); - ceLog* _log; -}; -IMPLEMENT_APP(MyApp) -bool MyApp::OnInit() -{ - this->_log = new ceLog("./", 1); - this->_log->SetEnPrintf(true); - ceWxSerial* com = new ceWxSerial(this,WXSERIAL_ID1,100,"/dev/ttyS6",9600,8,'N',1); - com->Open(); - Connect(WXSERIAL_ID1, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); - char tx[] = "Hello"; - com->Write(tx); - return true; -} - -void MyApp::OnSerialEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - this->_log->Print("Ev = "+ ceMisc::cvec2str(v)); - Exit(); +#include +#include "ce/ceUtil.h" +#include +using namespace ce; +#define WXSERIAL_ID1 201 +class MyApp : public wxAppConsole +{ + public: + virtual bool OnInit(); + void OnSerialEvent(wxThreadEvent& event); + ceLog* _log; +}; +IMPLEMENT_APP(MyApp) +bool MyApp::OnInit() +{ + this->_log = new ceLog("./", 1); + this->_log->SetEnPrintf(true); + ceWxSerial* com = new ceWxSerial(this,WXSERIAL_ID1,100,"/dev/ttyS6",9600,8,'N',1); + com->Open(); + Connect(WXSERIAL_ID1, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); + char tx[] = "Hello"; + com->Write(tx); + return true; +} + +void MyApp::OnSerialEvent(wxThreadEvent& event) +{ + std::vector v = event.GetPayload>(); + this->_log->Print("Ev = "+ ceMisc::cvec2str(v)); + Exit(); } \ No newline at end of file diff --git a/examples/WxSerial/wxserialw.bat b/examples/WxSerial/wxserialw.bat index 92054d4..75d5922 100644 --- a/examples/WxSerial/wxserialw.bat +++ b/examples/WxSerial/wxserialw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -WxSerial.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +WxSerial.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/buildall.sh b/examples/buildall.sh index dfb9a86..dca53a6 100644 --- a/examples/buildall.sh +++ b/examples/buildall.sh @@ -1,7 +1,7 @@ -#!/bin/bash -if [[ ! -d "./build" ]]; then - mkdir -p build -fi -rm -r ./build/* -cmake -B ./build -S . -DCMAKE_BUILD_TYPE=Release -cmake --build ./build --config Release +#!/bin/bash +if [[ ! -d "./build" ]]; then + mkdir -p build +fi +rm -r ./build/* +cmake -B ./build -S . -DCMAKE_BUILD_TYPE=Release +cmake --build ./build --config Release diff --git a/examples/buildallw.bat b/examples/buildallw.bat index de8bb70..6d82c29 100644 --- a/examples/buildallw.bat +++ b/examples/buildallw.bat @@ -1,7 +1,7 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake &&^ -cmake --build ./buildw --config Release - +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake &&^ +cmake --build ./buildw --config Release + diff --git a/examples/interface/CMakeLists.txt b/examples/interface/CMakeLists.txt index f52191a..25c02c2 100644 --- a/examples/interface/CMakeLists.txt +++ b/examples/interface/CMakeLists.txt @@ -1,11 +1,11 @@ -cmake_minimum_required(VERSION 3.0.0) -project(interface VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/main.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +project(interface VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} +${PROJECT_SOURCE_DIR}/src/main.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/interface/interface.bat b/examples/interface/interface.bat index ff95850..3c521a3 100644 --- a/examples/interface/interface.bat +++ b/examples/interface/interface.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -interface.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +interface.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/interface/interface.sh b/examples/interface/interface.sh index 6979d63..84086f0 100644 --- a/examples/interface/interface.sh +++ b/examples/interface/interface.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/interface/src/main.cpp b/examples/interface/src/main.cpp index 31caa73..56cff89 100644 --- a/examples/interface/src/main.cpp +++ b/examples/interface/src/main.cpp @@ -1,29 +1,29 @@ - #include -#include "ce/ceMacros.h" -#include "ce/ceMisc.h" -#include -using namespace std; -using namespace ce; - -#define TMR_ID1 201 -class MyApp : public wxAppConsole -{ - public: - virtual bool OnInit(); - void OnTmrEvent(wxTimerEvent& WXUNUSED(event)); -}; -IMPLEMENT_APP(MyApp) -bool MyApp::OnInit() -{ - wxTimer* t = new wxTimer(this,TMR_ID1); - t->Start(1000); - Connect(TMR_ID1, wxEVT_TIMER, wxTimerEventHandler(MyApp::OnTmrEvent)); - return true; -} - -void MyApp::OnTmrEvent(wxTimerEvent& WXUNUSED(event)) -{ - std::cout << "tmr ev" << std::endl; - -} - + #include +#include "ce/ceMacros.h" +#include "ce/ceMisc.h" +#include +using namespace std; +using namespace ce; + +#define TMR_ID1 201 +class MyApp : public wxAppConsole +{ + public: + virtual bool OnInit(); + void OnTmrEvent(wxTimerEvent& WXUNUSED(event)); +}; +IMPLEMENT_APP(MyApp) +bool MyApp::OnInit() +{ + wxTimer* t = new wxTimer(this,TMR_ID1); + t->Start(1000); + Connect(TMR_ID1, wxEVT_TIMER, wxTimerEventHandler(MyApp::OnTmrEvent)); + return true; +} + +void MyApp::OnTmrEvent(wxTimerEvent& WXUNUSED(event)) +{ + std::cout << "tmr ev" << std::endl; + +} + diff --git a/examples/interface/vsprj/interface.sln b/examples/interface/vsprj/interface.sln index 03976e1..8e00a41 100644 --- a/examples/interface/vsprj/interface.sln +++ b/examples/interface/vsprj/interface.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "interface", "interface.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "interface", "interface.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} + EndGlobalSection +EndGlobal diff --git a/examples/interface/vsprj/interface.vcxproj b/examples/interface/vsprj/interface.vcxproj index 1a8379b..0b9725f 100644 --- a/examples/interface/vsprj/interface.vcxproj +++ b/examples/interface/vsprj/interface.vcxproj @@ -1,162 +1,162 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} - Win32Proj - interface - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(VCPKG_ROOT)\installed\include - - - Windows - true - true - true - $(VCPKG_ROOT)\installed\Release - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} + Win32Proj + interface + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + Disabled + true + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + $(VCPKG_ROOT)\installed\include + + + Windows + true + true + true + $(VCPKG_ROOT)\installed\Release + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/interface/vsprj/interface.vcxproj.filters b/examples/interface/vsprj/interface.vcxproj.filters index 1e69fa7..bf96c1c 100644 --- a/examples/interface/vsprj/interface.vcxproj.filters +++ b/examples/interface/vsprj/interface.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/kbhit/CMakeLists.txt b/examples/kbhit/CMakeLists.txt index aeb5eb7..f0aa45a 100644 --- a/examples/kbhit/CMakeLists.txt +++ b/examples/kbhit/CMakeLists.txt @@ -1,11 +1,11 @@ -cmake_minimum_required(VERSION 3.0.0) -project(kbhit VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/main.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) +cmake_minimum_required(VERSION 3.0.0) +project(kbhit VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} +${PROJECT_SOURCE_DIR}/src/main.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/kbhit/kbhit.sh b/examples/kbhit/kbhit.sh index 6979d63..84086f0 100644 --- a/examples/kbhit/kbhit.sh +++ b/examples/kbhit/kbhit.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/kbhit/kbhit/kbhit.sln b/examples/kbhit/kbhit/kbhit.sln index 042c6a6..df33992 100644 --- a/examples/kbhit/kbhit/kbhit.sln +++ b/examples/kbhit/kbhit/kbhit.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbhit", "kbhit.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbhit", "kbhit.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} + EndGlobalSection +EndGlobal diff --git a/examples/kbhit/kbhit/kbhit.vcxproj b/examples/kbhit/kbhit/kbhit.vcxproj index d898b2d..10712c1 100644 --- a/examples/kbhit/kbhit/kbhit.vcxproj +++ b/examples/kbhit/kbhit/kbhit.vcxproj @@ -1,162 +1,162 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} - Win32Proj - kbhit - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include - - - Console - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} + Win32Proj + kbhit + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + Disabled + true + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + $(SolutionDir)..\..\..\include + + + Console + true + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/kbhit/kbhit/kbhit.vcxproj.filters b/examples/kbhit/kbhit/kbhit.vcxproj.filters index 1e69fa7..bf96c1c 100644 --- a/examples/kbhit/kbhit/kbhit.vcxproj.filters +++ b/examples/kbhit/kbhit/kbhit.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/kbhit/kbhitw.bat b/examples/kbhit/kbhitw.bat index 2fe7343..209b6f7 100644 --- a/examples/kbhit/kbhitw.bat +++ b/examples/kbhit/kbhitw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -kbhit.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +kbhit.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/kbhit/src/main.cpp b/examples/kbhit/src/main.cpp index 75483e1..6f0890d 100644 --- a/examples/kbhit/src/main.cpp +++ b/examples/kbhit/src/main.cpp @@ -1,43 +1,43 @@ -#include -#include "ce/ceMacros.h" -#include "ce/ceMisc.h" -#include -using namespace std; -using namespace ce; -#if defined(CE_WINDOWS) -int main() -{ - cout << "Press anykey to test kbhit!" << endl; - while (1) { - if (ceMisc::kb_hit()) { - char c = ceMisc::get_ch(); - std::cout << ("Key pressed: " + std::to_string(c)) << std::endl; - } - } - return 0; -} -#else -#define TMR_ID1 201 -class MyApp : public wxAppConsole -{ - public: - virtual bool OnInit(); - void OnTmrEvent(wxTimerEvent& WXUNUSED(event)); -}; -IMPLEMENT_APP(MyApp) -bool MyApp::OnInit() -{ - wxTimer* t = new wxTimer(this,TMR_ID1); - t->Start(10); - Connect(TMR_ID1, wxEVT_TIMER, wxTimerEventHandler(MyApp::OnTmrEvent)); - return true; -} - -void MyApp::OnTmrEvent(wxTimerEvent& WXUNUSED(event)) -{ - if (ceMisc::kb_hit()) { - char c = ceMisc::get_ch(); - std::cout << ("Key pressed: " + std::to_string(c)) << std::endl; - } -} -#endif +#include +#include "ce/ceMacros.h" +#include "ce/ceMisc.h" +#include +using namespace std; +using namespace ce; +#if defined(CE_WINDOWS) +int main() +{ + cout << "Press anykey to test kbhit!" << endl; + while (1) { + if (ceMisc::kb_hit()) { + char c = ceMisc::get_ch(); + std::cout << ("Key pressed: " + std::to_string(c)) << std::endl; + } + } + return 0; +} +#else +#define TMR_ID1 201 +class MyApp : public wxAppConsole +{ + public: + virtual bool OnInit(); + void OnTmrEvent(wxTimerEvent& WXUNUSED(event)); +}; +IMPLEMENT_APP(MyApp) +bool MyApp::OnInit() +{ + wxTimer* t = new wxTimer(this,TMR_ID1); + t->Start(10); + Connect(TMR_ID1, wxEVT_TIMER, wxTimerEventHandler(MyApp::OnTmrEvent)); + return true; +} + +void MyApp::OnTmrEvent(wxTimerEvent& WXUNUSED(event)) +{ + if (ceMisc::kb_hit()) { + char c = ceMisc::get_ch(); + std::cout << ("Key pressed: " + std::to_string(c)) << std::endl; + } +} +#endif diff --git a/examples/rsakeygen/CMakeLists.txt b/examples/rsakeygen/CMakeLists.txt index 9112ce9..dd83e54 100644 --- a/examples/rsakeygen/CMakeLists.txt +++ b/examples/rsakeygen/CMakeLists.txt @@ -1,12 +1,12 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(rsakeygen VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) - +cmake_minimum_required(VERSION 3.0.0) +# directory name to be used as project name +project(rsakeygen VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) + diff --git a/examples/rsakeygen/rsakeygen.sh b/examples/rsakeygen/rsakeygen.sh index 6979d63..84086f0 100644 --- a/examples/rsakeygen/rsakeygen.sh +++ b/examples/rsakeygen/rsakeygen.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/rsakeygen/rsakeygen/rsakeygen.sln b/examples/rsakeygen/rsakeygen/rsakeygen.sln index 120577c..802a57c 100644 --- a/examples/rsakeygen/rsakeygen/rsakeygen.sln +++ b/examples/rsakeygen/rsakeygen/rsakeygen.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rsakeygen", "rsakeygen.vcxproj", "{FF0CBEC6-2040-4D74-9966-7E4530656E20}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.ActiveCfg = Debug|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.Build.0 = Debug|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.ActiveCfg = Debug|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.Build.0 = Debug|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.ActiveCfg = Release|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.Build.0 = Release|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.ActiveCfg = Release|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {963C9ECC-7676-4360-A9B1-A31048A8D673} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rsakeygen", "rsakeygen.vcxproj", "{FF0CBEC6-2040-4D74-9966-7E4530656E20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.ActiveCfg = Debug|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.Build.0 = Debug|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.ActiveCfg = Debug|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.Build.0 = Debug|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.ActiveCfg = Release|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.Build.0 = Release|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.ActiveCfg = Release|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {963C9ECC-7676-4360-A9B1-A31048A8D673} + EndGlobalSection +EndGlobal diff --git a/examples/rsakeygen/rsakeygen/rsakeygen.vcxproj b/examples/rsakeygen/rsakeygen/rsakeygen.vcxproj index e2fbbf6..fef9a65 100644 --- a/examples/rsakeygen/rsakeygen/rsakeygen.vcxproj +++ b/examples/rsakeygen/rsakeygen/rsakeygen.vcxproj @@ -1,138 +1,138 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - {FF0CBEC6-2040-4D74-9966-7E4530656E20} - rsakeygen - 10.0 - - - - Application - true - v143 - MultiByte - - - Application - false - v143 - true - MultiByte - - - Application - true - v143 - MultiByte - - - Application - false - v143 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - Disabled - true - true - $(SolutionDir)..\..\..\include; - - - Console - ceUtil.lib;%(AdditionalDependencies) - $CEDIR\ceutil\x64\Debug;%(AdditionalLibraryDirectories) - - - - - Level3 - MaxSpeed - true - true - true - true - - - Console - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - Console - true - true - $CEDIR\ceutil\x64\Release;%(AdditionalLibraryDirectories) - ceutil.lib;%(AdditionalDependencies) - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + {FF0CBEC6-2040-4D74-9966-7E4530656E20} + rsakeygen + 10.0 + + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + Disabled + true + true + $(SolutionDir)..\..\..\include; + + + Console + ceUtil.lib;%(AdditionalDependencies) + $CEDIR\ceutil\x64\Debug;%(AdditionalLibraryDirectories) + + + + + Level3 + MaxSpeed + true + true + true + true + + + Console + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) + WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + Console + true + true + $CEDIR\ceutil\x64\Release;%(AdditionalLibraryDirectories) + ceutil.lib;%(AdditionalDependencies) + + + + + + + + \ No newline at end of file diff --git a/examples/rsakeygen/rsakeygenw.bat b/examples/rsakeygen/rsakeygenw.bat index a7a9326..b3b7ea8 100644 --- a/examples/rsakeygen/rsakeygenw.bat +++ b/examples/rsakeygen/rsakeygenw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -rsakeygen.exe -@REM cpack --verbose -cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +rsakeygen.exe +@REM cpack --verbose +cd ../.. diff --git a/examples/rsakeygen/src/rsakeygen.cpp b/examples/rsakeygen/src/rsakeygen.cpp index d564714..84f615c 100644 --- a/examples/rsakeygen/src/rsakeygen.cpp +++ b/examples/rsakeygen/src/rsakeygen.cpp @@ -1,27 +1,27 @@ -#include -#include "ce/ceUtil.h" -#include -using namespace ce; -using namespace std; -int main(){ - ceLog l("./",30); - int bit_len,exp; - - cout << "Enter bit length of the key [2048]: "; - cin >> bit_len; - - cout << "Enter exponent [3]: "; - cin >> exp; - // RSA* private_key = ceRSA_OS::generateKeyPair("public_key.pem", "private_key.pem", bit_len, exp); // use this to save key files - RSA* private_key = ceRSA_OS::generateKeyPair(bit_len, exp); - - string dstr; - string estr; - string nstr; - ceRSA_OS::getBN(private_key, dstr, nstr, estr); - std::cout << "RSA d (Len " << dstr.length() << "): " << ceMisc::ToStr16(dstr) << std::endl; - std::cout << "RSA e (Len " << estr.length() << "): " << ceMisc::ToStr16(estr) << std::endl; - std::cout << "RSA n (Len " << nstr.length() << "): " << ceMisc::ToStr16(nstr) << std::endl; - - return 0; -} +#include +#include "ce/ceUtil.h" +#include +using namespace ce; +using namespace std; +int main(){ + ceLog l("./",30); + int bit_len,exp; + + cout << "Enter bit length of the key [2048]: "; + cin >> bit_len; + + cout << "Enter exponent [3]: "; + cin >> exp; + // RSA* private_key = ceRSA_OS::generateKeyPair("public_key.pem", "private_key.pem", bit_len, exp); // use this to save key files + RSA* private_key = ceRSA_OS::generateKeyPair(bit_len, exp); + + string dstr; + string estr; + string nstr; + ceRSA_OS::getBN(private_key, dstr, nstr, estr); + std::cout << "RSA d (Len " << dstr.length() << "): " << ceMisc::ToStr16(dstr) << std::endl; + std::cout << "RSA e (Len " << estr.length() << "): " << ceMisc::ToStr16(estr) << std::endl; + std::cout << "RSA n (Len " << nstr.length() << "): " << ceMisc::ToStr16(nstr) << std::endl; + + return 0; +} diff --git a/examples/tcpclient/CMakeLists.txt b/examples/tcpclient/CMakeLists.txt index de42d95..f9b87ba 100644 --- a/examples/tcpclient/CMakeLists.txt +++ b/examples/tcpclient/CMakeLists.txt @@ -1,12 +1,12 @@ -cmake_minimum_required(VERSION 3.15.0) -# directory name to be used as project name -project(tcpclient VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) +cmake_minimum_required(VERSION 3.15.0) +# directory name to be used as project name +project(tcpclient VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +# and also set WIN32OPT variable with WIN32 for Windows +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +add_executable(${PROJECT_NAME} ${WIN32OPT} +${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp +) target_link_libraries(${PROJECT_NAME} ${LIBS}) \ No newline at end of file diff --git a/examples/tcpclient/src/tcpclient.cpp b/examples/tcpclient/src/tcpclient.cpp index 5c25c3f..f5bd547 100644 --- a/examples/tcpclient/src/tcpclient.cpp +++ b/examples/tcpclient/src/tcpclient.cpp @@ -1,213 +1,213 @@ -// File: tcpclient.cpp -// Description: A simple wxWidgets TCP client sample -// Author: Yan Naing Aye -// Web: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -// References -// [1] Guillermo Rodriguez Garcia, Vadim Zeitlin, "Server for wxSocket demo", -// https://github.com/wxWidgets/wxWidgets/blob/master/samples/sockets/server.cpp, 2009. -// [2] Julian Smart and Kevin Hock, "Cross-Platform GUI Programming with wxWidgets," -// Pearson Education, Inc. 2006. ISBN: 0-13-147381-6. - -#include "ce/ceUtil.h" -using namespace ce; -// IDs for the controls and the menu commandscm -enum -{ - ID_BTNSEND = 101, - ID_TXTSEND, - ID_TXTRX, - SOCKET_ID, - CLIENT_OPEN = wxID_OPEN, - CLIENT_CLOSE = wxID_CLOSE, - // menu items - Minimal_Quit = wxID_EXIT, - Minimal_About = wxID_ABOUT -}; - -class MyFrame; -class MyApp : public wxApp -{ - MyFrame *frame; -public: - ceTcpClient* _tcpclient; - void OnTcpSocketEvent(wxThreadEvent& event); - virtual bool OnInit(); -}; - -// Define a new frame type: this is going to be our main frame -class MyFrame : public wxFrame -{ -public: - // ctor(s) - MyFrame(MyApp* app, const wxString& title); - ~MyFrame(); - // event handlers (these functions should _not_ be virtual) - void OnQuit(wxCommandEvent& event); - void OnAbout(wxCommandEvent& event); - void Print(std::string str); - void OnOpenConnection(wxCommandEvent& event); - void OnCloseConnection(wxCommandEvent& event); - void OnSend(wxCommandEvent& event); - void UpdateStatusBar(); -private: - MyApp* _app; - wxButton* btnSend; - wxTextCtrl* txtSend; - wxTextCtrl *txtRx; - wxMenu* fileMenu; - wxMenu* helpMenu; - // any class wishing to process wxWidgets events must use this macro - wxDECLARE_EVENT_TABLE(); -}; - -// event tables and other macros for wxWidgets -wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) - EVT_MENU(Minimal_Quit, MyFrame::OnQuit) - EVT_MENU(Minimal_About, MyFrame::OnAbout) - EVT_MENU(CLIENT_OPEN, MyFrame::OnOpenConnection) - EVT_MENU(CLIENT_CLOSE, MyFrame::OnCloseConnection) -wxEND_EVENT_TABLE() - -IMPLEMENT_APP(MyApp) - -// 'Main program' equivalent: the program execution "starts" here -bool MyApp::OnInit() -{ - if ( !wxApp::OnInit() ) - return false; - - // depending on your system, some ports such as 3000, 8000, 8080 should be used with cautions - this->_tcpclient = new ceTcpClient(this,SOCKET_ID); - this->_tcpclient->SetRemote("localhost",7225); - Connect(SOCKET_ID, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnTcpSocketEvent)); - frame = new MyFrame(this,"TCP Client using ceUtil lib"); - frame->Show(true); - this->frame->Print("Click Open Session menu to start a connection"); - return true; -} - -void MyApp::OnTcpSocketEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - std::string s = event.GetString().ToStdString(); - int i = event.GetInt(); - std::string str = "Socket event: Rx vec = "+ceMisc::cvec2hex(v)+", ip ="+s+", port = "+ std::to_string(i); - printf("%s\n",str.c_str()); - this->frame->Print(str); -} - -// frame constructor -MyFrame::MyFrame(MyApp* app, const wxString& title) -: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(390, 280), - wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),_app(app) -{ -#if wxUSE_MENUS -// create a menu bar -wxMenu *fileMenu = new wxMenu; - -// the "About" item should be in the help menu -wxMenu *helpMenu = new wxMenu; -helpMenu->Append(Minimal_About, "&About\tF1", "Show about dialog"); - -fileMenu->Append(CLIENT_OPEN, "&Open session\tAlt-O", "Connect to server"); -fileMenu->Append(CLIENT_CLOSE, "&Close session\tAlt-C", "Close connection"); -fileMenu->Append(Minimal_Quit, "E&xit\tAlt-X", "Quit this program"); - -// now append the freshly created menu to the menu bar... -wxMenuBar *menuBar = new wxMenuBar(); -menuBar->Append(fileMenu, "&File"); -menuBar->Append(helpMenu, "&Help"); - -// ... and attach this menu bar to the frame -SetMenuBar(menuBar); -#endif // wxUSE_MENUS - -#if wxUSE_STATUSBAR -// create a status bar just for fun (by default with 1 pane only) -CreateStatusBar(2); -SetStatusText("TCP client using ceUtil lib"); -#endif // wxUSE_STATUSBAR -btnSend = new wxButton(this, ID_BTNSEND, wxT("Send"), - wxPoint(5, 5), wxSize(100, 25)); -txtSend = new wxTextCtrl(this, ID_TXTSEND, wxT("Hello!"), - wxPoint(120, 5), wxSize(250, 25)); -txtRx = new wxTextCtrl(this, ID_TXTRX, wxT(""), - wxPoint(5, 35), wxSize(365, 125), wxTE_MULTILINE); - -Connect(ID_BTNSEND, wxEVT_COMMAND_BUTTON_CLICKED, - wxCommandEventHandler(MyFrame::OnSend)); -} - -MyFrame::~MyFrame() -{ - // No delayed deletion here, as the frame is dying anyway -} - -// event handlers -void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) -{ -// true is to force the frame to close -Close(true); -} - -void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) -{ -wxMessageBox(wxString::Format -( -"ceUtil TCP client sample\n" -"\n" -"Author: Yan Naing Aye \n" -"Web: http://cool-emerald.blogspot.com" -), -"About ceUtil TCP client sample", -wxOK | wxICON_INFORMATION, -this); -} - -void MyFrame::Print(std::string str) -{ - txtRx->AppendText(wxString::Format(wxT("%s\n"),str)); -} - -void MyFrame::UpdateStatusBar() -{ - //fileMenu->Enable(CLIENT_OPEN, !_app->_tcpclient->IsConnected()); - //fileMenu->Enable(CLIENT_CLOSE, _app->_tcpclient->IsConnected()); - //if (_app->_tcpclient->IsConnected()) { - // //SetStatusText(wxString::Format(wxT("%s:%u"), - // // addr.IPAddress(), addr.Service()), 1); - // SetStatusText(wxString::Format(wxT("Connected")), 1); - //} - //else { - // SetStatusText(wxString::Format(wxT("Not connected")), 1); - //} -} - -void MyFrame::OnOpenConnection(wxCommandEvent& WXUNUSED(event)) -{ - _app->_tcpclient->Open(); - // fileMenu->Enable(CLIENT_OPEN, false); - // fileMenu->Enable(CLIENT_CLOSE, false); - //update status - this->UpdateStatusBar(); -} - -void MyFrame::OnCloseConnection(wxCommandEvent& WXUNUSED(event)) -{ - _app->_tcpclient->Close(); - - //update status - this->UpdateStatusBar(); -} - -void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) -{ - wxString str = txtSend->GetValue(); - wxCharBuffer buffer = str.ToUTF8(); - size_t txn = buffer.length();//for non-ASCII chars, having more than one byte per char - std::vector vc{buffer.data(), buffer.data()+txn}; - _app->_tcpclient->Tx(vc); +// File: tcpclient.cpp +// Description: A simple wxWidgets TCP client sample +// Author: Yan Naing Aye +// Web: http://cool-emerald.blogspot.com +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye + +// References +// [1] Guillermo Rodriguez Garcia, Vadim Zeitlin, "Server for wxSocket demo", +// https://github.com/wxWidgets/wxWidgets/blob/master/samples/sockets/server.cpp, 2009. +// [2] Julian Smart and Kevin Hock, "Cross-Platform GUI Programming with wxWidgets," +// Pearson Education, Inc. 2006. ISBN: 0-13-147381-6. + +#include "ce/ceUtil.h" +using namespace ce; +// IDs for the controls and the menu commandscm +enum +{ + ID_BTNSEND = 101, + ID_TXTSEND, + ID_TXTRX, + SOCKET_ID, + CLIENT_OPEN = wxID_OPEN, + CLIENT_CLOSE = wxID_CLOSE, + // menu items + Minimal_Quit = wxID_EXIT, + Minimal_About = wxID_ABOUT +}; + +class MyFrame; +class MyApp : public wxApp +{ + MyFrame *frame; +public: + ceTcpClient* _tcpclient; + void OnTcpSocketEvent(wxThreadEvent& event); + virtual bool OnInit(); +}; + +// Define a new frame type: this is going to be our main frame +class MyFrame : public wxFrame +{ +public: + // ctor(s) + MyFrame(MyApp* app, const wxString& title); + ~MyFrame(); + // event handlers (these functions should _not_ be virtual) + void OnQuit(wxCommandEvent& event); + void OnAbout(wxCommandEvent& event); + void Print(std::string str); + void OnOpenConnection(wxCommandEvent& event); + void OnCloseConnection(wxCommandEvent& event); + void OnSend(wxCommandEvent& event); + void UpdateStatusBar(); +private: + MyApp* _app; + wxButton* btnSend; + wxTextCtrl* txtSend; + wxTextCtrl *txtRx; + wxMenu* fileMenu; + wxMenu* helpMenu; + // any class wishing to process wxWidgets events must use this macro + wxDECLARE_EVENT_TABLE(); +}; + +// event tables and other macros for wxWidgets +wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) + EVT_MENU(Minimal_Quit, MyFrame::OnQuit) + EVT_MENU(Minimal_About, MyFrame::OnAbout) + EVT_MENU(CLIENT_OPEN, MyFrame::OnOpenConnection) + EVT_MENU(CLIENT_CLOSE, MyFrame::OnCloseConnection) +wxEND_EVENT_TABLE() + +IMPLEMENT_APP(MyApp) + +// 'Main program' equivalent: the program execution "starts" here +bool MyApp::OnInit() +{ + if ( !wxApp::OnInit() ) + return false; + + // depending on your system, some ports such as 3000, 8000, 8080 should be used with cautions + this->_tcpclient = new ceTcpClient(this,SOCKET_ID); + this->_tcpclient->SetRemote("localhost",7225); + Connect(SOCKET_ID, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnTcpSocketEvent)); + frame = new MyFrame(this,"TCP Client using ceUtil lib"); + frame->Show(true); + this->frame->Print("Click Open Session menu to start a connection"); + return true; +} + +void MyApp::OnTcpSocketEvent(wxThreadEvent& event) +{ + std::vector v = event.GetPayload>(); + std::string s = event.GetString().ToStdString(); + int i = event.GetInt(); + std::string str = "Socket event: Rx vec = "+ceMisc::cvec2hex(v)+", ip ="+s+", port = "+ std::to_string(i); + printf("%s\n",str.c_str()); + this->frame->Print(str); +} + +// frame constructor +MyFrame::MyFrame(MyApp* app, const wxString& title) +: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(390, 280), + wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),_app(app) +{ +#if wxUSE_MENUS +// create a menu bar +wxMenu *fileMenu = new wxMenu; + +// the "About" item should be in the help menu +wxMenu *helpMenu = new wxMenu; +helpMenu->Append(Minimal_About, "&About\tF1", "Show about dialog"); + +fileMenu->Append(CLIENT_OPEN, "&Open session\tAlt-O", "Connect to server"); +fileMenu->Append(CLIENT_CLOSE, "&Close session\tAlt-C", "Close connection"); +fileMenu->Append(Minimal_Quit, "E&xit\tAlt-X", "Quit this program"); + +// now append the freshly created menu to the menu bar... +wxMenuBar *menuBar = new wxMenuBar(); +menuBar->Append(fileMenu, "&File"); +menuBar->Append(helpMenu, "&Help"); + +// ... and attach this menu bar to the frame +SetMenuBar(menuBar); +#endif // wxUSE_MENUS + +#if wxUSE_STATUSBAR +// create a status bar just for fun (by default with 1 pane only) +CreateStatusBar(2); +SetStatusText("TCP client using ceUtil lib"); +#endif // wxUSE_STATUSBAR +btnSend = new wxButton(this, ID_BTNSEND, wxT("Send"), + wxPoint(5, 5), wxSize(100, 25)); +txtSend = new wxTextCtrl(this, ID_TXTSEND, wxT("Hello!"), + wxPoint(120, 5), wxSize(250, 25)); +txtRx = new wxTextCtrl(this, ID_TXTRX, wxT(""), + wxPoint(5, 35), wxSize(365, 125), wxTE_MULTILINE); + +Connect(ID_BTNSEND, wxEVT_COMMAND_BUTTON_CLICKED, + wxCommandEventHandler(MyFrame::OnSend)); +} + +MyFrame::~MyFrame() +{ + // No delayed deletion here, as the frame is dying anyway +} + +// event handlers +void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) +{ +// true is to force the frame to close +Close(true); +} + +void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) +{ +wxMessageBox(wxString::Format +( +"ceUtil TCP client sample\n" +"\n" +"Author: Yan Naing Aye \n" +"Web: http://cool-emerald.blogspot.com" +), +"About ceUtil TCP client sample", +wxOK | wxICON_INFORMATION, +this); +} + +void MyFrame::Print(std::string str) +{ + txtRx->AppendText(wxString::Format(wxT("%s\n"),str)); +} + +void MyFrame::UpdateStatusBar() +{ + //fileMenu->Enable(CLIENT_OPEN, !_app->_tcpclient->IsConnected()); + //fileMenu->Enable(CLIENT_CLOSE, _app->_tcpclient->IsConnected()); + //if (_app->_tcpclient->IsConnected()) { + // //SetStatusText(wxString::Format(wxT("%s:%u"), + // // addr.IPAddress(), addr.Service()), 1); + // SetStatusText(wxString::Format(wxT("Connected")), 1); + //} + //else { + // SetStatusText(wxString::Format(wxT("Not connected")), 1); + //} +} + +void MyFrame::OnOpenConnection(wxCommandEvent& WXUNUSED(event)) +{ + _app->_tcpclient->Open(); + // fileMenu->Enable(CLIENT_OPEN, false); + // fileMenu->Enable(CLIENT_CLOSE, false); + //update status + this->UpdateStatusBar(); +} + +void MyFrame::OnCloseConnection(wxCommandEvent& WXUNUSED(event)) +{ + _app->_tcpclient->Close(); + + //update status + this->UpdateStatusBar(); +} + +void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) +{ + wxString str = txtSend->GetValue(); + wxCharBuffer buffer = str.ToUTF8(); + size_t txn = buffer.length();//for non-ASCII chars, having more than one byte per char + std::vector vc{buffer.data(), buffer.data()+txn}; + _app->_tcpclient->Tx(vc); } \ No newline at end of file diff --git a/examples/tcpclient/tcpclient/tcpclient.sln b/examples/tcpclient/tcpclient/tcpclient.sln index 8955428..9e4c1da 100644 --- a/examples/tcpclient/tcpclient/tcpclient.sln +++ b/examples/tcpclient/tcpclient/tcpclient.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.8.34330.188 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tcpclient", "tcpclient.vcxproj", "{9E6EFA9E-8164-4807-B820-F97C9CFBFED1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.ActiveCfg = Debug|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.Build.0 = Debug|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.ActiveCfg = Debug|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.Build.0 = Debug|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.ActiveCfg = Release|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.Build.0 = Release|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.ActiveCfg = Release|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {D0A51A18-2F03-4C7F-9C10-DB3BA0B948C1} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34330.188 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tcpclient", "tcpclient.vcxproj", "{9E6EFA9E-8164-4807-B820-F97C9CFBFED1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.ActiveCfg = Debug|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.Build.0 = Debug|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.ActiveCfg = Debug|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.Build.0 = Debug|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.ActiveCfg = Release|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.Build.0 = Release|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.ActiveCfg = Release|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D0A51A18-2F03-4C7F-9C10-DB3BA0B948C1} + EndGlobalSection +EndGlobal diff --git a/examples/tcpclient/tcpclient/tcpclient.vcxproj b/examples/tcpclient/tcpclient/tcpclient.vcxproj index 52e2417..5aa46b2 100644 --- a/examples/tcpclient/tcpclient/tcpclient.vcxproj +++ b/examples/tcpclient/tcpclient/tcpclient.vcxproj @@ -1,165 +1,165 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1} - Win32Proj - tcpclient - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - NotSet - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions);WXUSINGDLL;_CRT_SECURE_NO_WARNINGS - true - $(VCPKG_ROOT)\installed\include; - - - Windows - true - $(VCPKG_ROOT)\installed\$(Platform)-windows\lib - $(CoreLibraryDependencies);%(AdditionalDependencies);ceutild.lib - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1} + Win32Proj + tcpclient + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + NotSet + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + Level3 + Disabled + true + _DEBUG;_WINDOWS;%(PreprocessorDefinitions);WXUSINGDLL;_CRT_SECURE_NO_WARNINGS + true + $(VCPKG_ROOT)\installed\include; + + + Windows + true + $(VCPKG_ROOT)\installed\$(Platform)-windows\lib + $(CoreLibraryDependencies);%(AdditionalDependencies);ceutild.lib + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) + + + Windows + true + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/tcpclient/tcpclientw.bat b/examples/tcpclient/tcpclientw.bat index 3141271..c5bf256 100644 --- a/examples/tcpclient/tcpclientw.bat +++ b/examples/tcpclient/tcpclientw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake" -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -tcpclient.exe -@REM cpack --verbose -@REM cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake" -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +tcpclient.exe +@REM cpack --verbose +@REM cd ../.. diff --git a/examples/tcpsvr/src/tcpsvr.cpp b/examples/tcpsvr/src/tcpsvr.cpp index 56b0471..9d958f8 100644 --- a/examples/tcpsvr/src/tcpsvr.cpp +++ b/examples/tcpsvr/src/tcpsvr.cpp @@ -1,177 +1,185 @@ -// File: tcpsvr.cpp -// Description: A simple wxWidgets TCP server sample -// Author: Yan Naing Aye -// Web: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -// References -// [1] Guillermo Rodriguez Garcia, Vadim Zeitlin, "Server for wxSocket demo", -// https://github.com/wxWidgets/wxWidgets/blob/master/samples/sockets/server.cpp, 2009. -// [2] Julian Smart and Kevin Hock, "Cross-Platform GUI Programming with wxWidgets," -// Pearson Education, Inc. 2006. ISBN: 0-13-147381-6. - -#include "ce/ceUtil.h" -// #include "myicon.xpm" -using namespace ce; -// IDs for the controls and the menu commands -enum -{ - ID_TXTRX=101, - SOCKET_ID, - SERVER_ID, - // menu items - Minimal_Quit = wxID_EXIT, - Minimal_About = wxID_ABOUT -}; - -class MyFrame; -class MyApp : public wxApp -{ - ceTcpServer* _tcpsvr; - MyFrame *frame; -public: - void OnTcpServerEvent(wxThreadEvent& event); - void OnTcpSocketEvent(wxThreadEvent& event); - virtual bool OnInit(); -}; - -// Define a new frame type: this is going to be our main frame -class MyFrame : public wxFrame -{ -public: - // ctor(s) - MyFrame(const wxString& title); - ~MyFrame(); - // event handlers (these functions should _not_ be virtual) - void OnQuit(wxCommandEvent& event); - void OnAbout(wxCommandEvent& event); - void Print(std::string str); -private: - wxTextCtrl *txtRx; - // any class wishing to process wxWidgets events must use this macro - wxDECLARE_EVENT_TABLE(); -}; - -// event tables and other macros for wxWidgets -wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) - EVT_MENU(Minimal_Quit, MyFrame::OnQuit) - EVT_MENU(Minimal_About, MyFrame::OnAbout) -wxEND_EVENT_TABLE() - -IMPLEMENT_APP(MyApp) - -// 'Main program' equivalent: the program execution "starts" here -bool MyApp::OnInit() -{ - if ( !wxApp::OnInit() ) - return false; - - // depending on your system, some ports such as 3000, 8000, 8080 should be used with cautions - this->_tcpsvr = new ceTcpServer(this,SERVER_ID,SOCKET_ID,7225); - this->_tcpsvr->Open(); - Connect(SERVER_ID, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnTcpServerEvent)); - Connect(SOCKET_ID, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnTcpSocketEvent)); - frame = new MyFrame("TCP Server using ceUtil lib"); - frame->Show(true); - this->frame->Print("TCP Server listening"); - return true; -} - -void MyApp::OnTcpServerEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - std::string s = event.GetString().ToStdString(); - int i = event.GetInt(); - std::string str = "Server event: ip ="+s+", port = "+ std::to_string(i)+ (v[0]?", connected, clients: ":", disconnected, clients: ") + std::to_string(v[1]); - printf("%s\n",str.c_str()); - this->frame->Print(str); -} - -void MyApp::OnTcpSocketEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - std::string s = event.GetString().ToStdString(); - int i = event.GetInt(); - std::string str = "Socket event: Rx vec = "+ceMisc::cvec2hex(v)+", ip ="+s+", port = "+ std::to_string(i); - printf("%s\n",str.c_str()); - this->frame->Print(str); - - // write back - std::vector tb{'O','K'}; - this->_tcpsvr->Tx(tb); - this->frame->Print("Tx: "+ ce::ceMisc::cvec2hex(tb)); -} - -// frame constructor -MyFrame::MyFrame(const wxString& title) -: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(390, 280), - wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER) -{ -// // set the frame icon -// SetIcon(wxICON(sample)); - -#if wxUSE_MENUS -// create a menu bar -wxMenu *fileMenu = new wxMenu; - -// the "About" item should be in the help menu -wxMenu *helpMenu = new wxMenu; -helpMenu->Append(Minimal_About, "&About\tF1", "Show about dialog"); - -fileMenu->Append(Minimal_Quit, "E&xit\tAlt-X", "Quit this program"); - -// now append the freshly created menu to the menu bar... -wxMenuBar *menuBar = new wxMenuBar(); -menuBar->Append(fileMenu, "&File"); -menuBar->Append(helpMenu, "&Help"); - -// ... and attach this menu bar to the frame -SetMenuBar(menuBar); -#endif // wxUSE_MENUS - -#if wxUSE_STATUSBAR -// create a status bar just for fun (by default with 1 pane only) -CreateStatusBar(2); -SetStatusText("TCP server using ceUtil lib"); -#endif // wxUSE_STATUSBAR -txtRx = new wxTextCtrl(this, ID_TXTRX, wxT(""), wxPoint(5, 5), - wxSize(365, 125), wxTE_MULTILINE); - - -} - -MyFrame::~MyFrame() -{ - // No delayed deletion here, as the frame is dying anyway - //delete _tcpsvr; -} - -// event handlers -void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) -{ -// true is to force the frame to close -Close(true); -} - -void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) -{ -wxMessageBox(wxString::Format -( -"ceUtil TCP server sample\n" -"\n" -"Author: Yan Naing Aye \n" -"Web: http://cool-emerald.blogspot.com" -), -"About ceUtil TCP server sample", -wxOK | wxICON_INFORMATION, -this); -} - -void MyFrame::Print(std::string str) -{ - txtRx->AppendText(wxString::Format(wxT("%s\n"),str)); -} - - - +// File: tcpsvr.cpp +// Description: A simple wxWidgets TCP server sample +// Author: Yan Naing Aye +// Web: http://cool-emerald.blogspot.com +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye + +// References +// [1] Guillermo Rodriguez Garcia, Vadim Zeitlin, "Server for wxSocket demo", +// https://github.com/wxWidgets/wxWidgets/blob/master/samples/sockets/server.cpp, 2009. +// [2] Julian Smart and Kevin Hock, "Cross-Platform GUI Programming with wxWidgets," +// Pearson Education, Inc. 2006. ISBN: 0-13-147381-6. + +#include "ce/cetcpsvr.h" +#include "ce/ceMisc.h" + +// #include "myicon.xpm" +using namespace ce; + +#define MAX_SOCKET_N 2 +// IDs for the controls and the menu commands +enum +{ + ID_TXTRX=101, + SERVER_ID=102, + SOCKET_ID=200, + SOCKET_ID1=201, + // menu items + Minimal_Quit = wxID_EXIT, + Minimal_About = wxID_ABOUT +}; + +class MyFrame; +class MyApp : public wxApp +{ + ceTcpServer* _tcpsvr; + MyFrame *frame; +public: + void OnTcpServerEvent(wxThreadEvent& event); + void OnTcpSocketEvent(wxThreadEvent& event); + virtual bool OnInit(); +}; + +// Define a new frame type: this is going to be our main frame +class MyFrame : public wxFrame +{ +public: + // ctor(s) + MyFrame(const wxString& title); + ~MyFrame(); + // event handlers (these functions should _not_ be virtual) + void OnQuit(wxCommandEvent& event); + void OnAbout(wxCommandEvent& event); + void Print(std::string str); +private: + wxTextCtrl *txtRx; + // any class wishing to process wxWidgets events must use this macro + wxDECLARE_EVENT_TABLE(); +}; + +// event tables and other macros for wxWidgets +wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) + EVT_MENU(Minimal_Quit, MyFrame::OnQuit) + EVT_MENU(Minimal_About, MyFrame::OnAbout) +wxEND_EVENT_TABLE() + +IMPLEMENT_APP(MyApp) + +// 'Main program' equivalent: the program execution "starts" here +bool MyApp::OnInit() +{ + if ( !wxApp::OnInit() ) + return false; + + // depending on your system, some ports such as 3000, 8000, 8080 should be used with cautions + int port = 7225; + this->_tcpsvr = new ceTcpServer(this,SERVER_ID,SOCKET_ID,port,2); + this->_tcpsvr->Open(); + Connect(SERVER_ID, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnTcpServerEvent)); + for(int i=0; iShow(true); + this->frame->Print("TCP Server listening:"+std::to_string(port)); + return true; +} + +void MyApp::OnTcpServerEvent(wxThreadEvent& event) +{ + std::vector v = event.GetPayload>(); + std::string s = event.GetString().ToStdString(); + int i = event.GetInt(); + std::string str = "Server event: ip ="+s+", port = "+ std::to_string(i)+ (v[0]?", connected, clients: ":", disconnected, clients: ") + std::to_string(v[1])+ ", id: " + std::to_string(SOCKET_ID+int(v[2])); + printf("%s\n",str.c_str()); + this->frame->Print(str); +} + +void MyApp::OnTcpSocketEvent(wxThreadEvent& event) +{ + std::vector v = event.GetPayload>(); + std::string s = event.GetString().ToStdString(); + int i = event.GetInt(); + std::string str = "Socket event: Rx vec = "+ceMisc::cvec2hex(v)+", ip ="+s+", port = "+ std::to_string(i)+ ", id: " + std::to_string(event.GetId()); + printf("%s\n",str.c_str()); + this->frame->Print(str); + + // write back + std::vector tb{'O','K'}; + this->_tcpsvr->Tx(event.GetId(),tb); + this->frame->Print("Tx: "+ ce::ceMisc::cvec2hex(tb)); +} + +// frame constructor +MyFrame::MyFrame(const wxString& title) +: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(390, 280), + wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER) +{ +// // set the frame icon +// SetIcon(wxICON(sample)); + +#if wxUSE_MENUS +// create a menu bar +wxMenu *fileMenu = new wxMenu; + +// the "About" item should be in the help menu +wxMenu *helpMenu = new wxMenu; +helpMenu->Append(Minimal_About, "&About\tF1", "Show about dialog"); + +fileMenu->Append(Minimal_Quit, "E&xit\tAlt-X", "Quit this program"); + +// now append the freshly created menu to the menu bar... +wxMenuBar *menuBar = new wxMenuBar(); +menuBar->Append(fileMenu, "&File"); +menuBar->Append(helpMenu, "&Help"); + +// ... and attach this menu bar to the frame +SetMenuBar(menuBar); +#endif // wxUSE_MENUS + +#if wxUSE_STATUSBAR +// create a status bar just for fun (by default with 1 pane only) +CreateStatusBar(2); +SetStatusText("TCP server using ceUtil lib"); +#endif // wxUSE_STATUSBAR +txtRx = new wxTextCtrl(this, ID_TXTRX, wxT(""), wxPoint(5, 5), + wxSize(365, 125), wxTE_MULTILINE); + + +} + +MyFrame::~MyFrame() +{ + // No delayed deletion here, as the frame is dying anyway + //delete _tcpsvr; +} + +// event handlers +void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) +{ +// true is to force the frame to close +Close(true); +} + +void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) +{ +wxMessageBox(wxString::Format +( +"ceUtil TCP server sample\n" +"\n" +"Author: Yan Naing Aye \n" +"Web: http://cool-emerald.blogspot.com" +), +"About ceUtil TCP server sample", +wxOK | wxICON_INFORMATION, +this); +} + +void MyFrame::Print(std::string str) +{ + txtRx->AppendText(wxString::Format(wxT("%s\n"),str)); +} + + + diff --git a/examples/tcpsvr/tcpsvr/tcpsvr.sln b/examples/tcpsvr/tcpsvr/tcpsvr.sln index 4967f48..dce576e 100644 --- a/examples/tcpsvr/tcpsvr/tcpsvr.sln +++ b/examples/tcpsvr/tcpsvr/tcpsvr.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.8.34330.188 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tcpsvr", "tcpsvr.vcxproj", "{9E6EFA9E-8164-4807-B820-F97C9CFBFED1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.ActiveCfg = Debug|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.Build.0 = Debug|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.ActiveCfg = Debug|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.Build.0 = Debug|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.ActiveCfg = Release|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.Build.0 = Release|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.ActiveCfg = Release|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {D0A51A18-2F03-4C7F-9C10-DB3BA0B948C1} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34330.188 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tcpsvr", "tcpsvr.vcxproj", "{9E6EFA9E-8164-4807-B820-F97C9CFBFED1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.ActiveCfg = Debug|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.Build.0 = Debug|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.ActiveCfg = Debug|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.Build.0 = Debug|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.ActiveCfg = Release|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.Build.0 = Release|x64 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.ActiveCfg = Release|Win32 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D0A51A18-2F03-4C7F-9C10-DB3BA0B948C1} + EndGlobalSection +EndGlobal diff --git a/examples/tcpsvr/tcpsvr/tcpsvr.vcxproj b/examples/tcpsvr/tcpsvr/tcpsvr.vcxproj index af50cd4..d95cba0 100644 --- a/examples/tcpsvr/tcpsvr/tcpsvr.vcxproj +++ b/examples/tcpsvr/tcpsvr/tcpsvr.vcxproj @@ -1,165 +1,165 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1} - Win32Proj - tcpsvr - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - NotSet - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions);WXUSINGDLL;_CRT_SECURE_NO_WARNINGS - true - $(VCPKG_ROOT)\installed\include; - - - Windows - true - $(VCPKG_ROOT)\installed\$(Platform)-windows\lib - $(CoreLibraryDependencies);%(AdditionalDependencies);ceutild.lib - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {9E6EFA9E-8164-4807-B820-F97C9CFBFED1} + Win32Proj + tcpsvr + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + NotSet + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + Level3 + Disabled + true + _DEBUG;_WINDOWS;%(PreprocessorDefinitions);WXUSINGDLL;_CRT_SECURE_NO_WARNINGS + true + $(VCPKG_ROOT)\installed\include; + + + Windows + true + $(VCPKG_ROOT)\installed\$(Platform)-windows\lib + $(CoreLibraryDependencies);%(AdditionalDependencies);ceutild.lib + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) + + + Windows + true + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/tcpsvr/tcpsvrw.bat b/examples/tcpsvr/tcpsvrw.bat index 423d503..9980145 100644 --- a/examples/tcpsvr/tcpsvrw.bat +++ b/examples/tcpsvr/tcpsvrw.bat @@ -1,11 +1,11 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake" -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -tcpsvr.exe -@REM cpack --verbose -@REM cd ../.. +@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder +if exist ./buildw/ ( +rmdir /s /q ./buildw +) +cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake" -D CMAKE_INSTALL_PREFIX=./installed/ &&^ +cmake --build ./buildw --config Release +@REM cmake --install ./buildw --config Release +cd buildw/Release +tcpsvr.exe +@REM cpack --verbose +@REM cd ../.. diff --git a/include/ce/ceDES.h b/include/ce/ceDES.h index ce1862f..798348f 100644 --- a/include/ce/ceDES.h +++ b/include/ce/ceDES.h @@ -1,71 +1,71 @@ -// Description: Simple functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) -// Class implementation of the following repository: https://github.com/yan9a/ceDES -// WebSite: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2023 Yan Naing Aye - -// Related links -// https://www.rapidtables.com/convert/number/ascii-to-hex.html -// https://emvlab.org/descalc/ -// https://paymentcardtools.com/crypto-calculators/des-calculator -// https://github.com/yan9a/cecpp/blob/master/des_cryptopp/main.cpp - -#ifndef CEDES_H -#define CEDES_H - -#include - -namespace ce { - class ceDES { - private: - //----------------------------------------------------------------------------- - // Init permutation table - // 64 bit data -> 64 bit data - static const unsigned char IP_table[64]; - //----------------------------------------------------------------------------- - //Permuted Choice 1 - // Key permutation table - // 64 bit key data -> 56 bit key data - static const unsigned char PC1_table[56]; - //----------------------------------------------------------------------------- - // Key shift table - static const unsigned char LeftShift_table[16]; - //----------------------------------------------------------------------------- - // Key Compression permutation table - // 56 bit key data -> 48 bit - static const unsigned char PC2_table[48]; - //----------------------------------------------------------------------------- - // Expansion permutation table - // 32 bit data -> 48 bit data - static const unsigned char E_table[48]; - //----------------------------------------------------------------------------- - static const unsigned char S[8][4][16]; - //----------------------------------------------------------------------------- - // Strait permutation table - // 32 bit data -> 32 bit data - static const unsigned char P_table[32]; - //----------------------------------------------------------------------------- - // Inverse permutation table - // 64 bit data -> 64 bit data - static const unsigned char InverseIP_table[64]; - //----------------------------------------------------------------------------- - static unsigned char Kn[7]; - static unsigned char Rn_1[6]; - //----------------------------------------------------------------------------- - static void Permutate(unsigned char* pData, unsigned char ni, - unsigned char* pTable, unsigned char no); - static void LeftShift(unsigned char* nKey, unsigned char b); - static void RightShift(unsigned char* nKey, unsigned char b); - static void Expand(unsigned char* R); - static void F(unsigned char* R, unsigned char* K); - //----------------------------------------------------------------------------- - static void Encrypt(unsigned char* dMes, unsigned char* dKey); // DES encryption - static void Decrypt(unsigned char* dMes, unsigned char* dKey); // DES decryption - static void Encrypt(unsigned char* dMes, unsigned char* dKeyL, unsigned char* dKeyR);// TDES encryption - static void Decrypt(unsigned char* dMes, unsigned char* dKeyL, unsigned char* dKeyR);// TDES decryption - public: - static std::string Encrypt(std::string dMes, std::string dKey); // DES encryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes - static std::string Decrypt(std::string dMes, std::string dKey); // DES decryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes - }; -} // namespace ce +// Description: Simple functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) +// Class implementation of the following repository: https://github.com/yan9a/ceDES +// WebSite: http://cool-emerald.blogspot.com +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2023 Yan Naing Aye + +// Related links +// https://www.rapidtables.com/convert/number/ascii-to-hex.html +// https://emvlab.org/descalc/ +// https://paymentcardtools.com/crypto-calculators/des-calculator +// https://github.com/yan9a/cecpp/blob/master/des_cryptopp/main.cpp + +#ifndef CEDES_H +#define CEDES_H + +#include + +namespace ce { + class ceDES { + private: + //----------------------------------------------------------------------------- + // Init permutation table + // 64 bit data -> 64 bit data + static const unsigned char IP_table[64]; + //----------------------------------------------------------------------------- + //Permuted Choice 1 + // Key permutation table + // 64 bit key data -> 56 bit key data + static const unsigned char PC1_table[56]; + //----------------------------------------------------------------------------- + // Key shift table + static const unsigned char LeftShift_table[16]; + //----------------------------------------------------------------------------- + // Key Compression permutation table + // 56 bit key data -> 48 bit + static const unsigned char PC2_table[48]; + //----------------------------------------------------------------------------- + // Expansion permutation table + // 32 bit data -> 48 bit data + static const unsigned char E_table[48]; + //----------------------------------------------------------------------------- + static const unsigned char S[8][4][16]; + //----------------------------------------------------------------------------- + // Strait permutation table + // 32 bit data -> 32 bit data + static const unsigned char P_table[32]; + //----------------------------------------------------------------------------- + // Inverse permutation table + // 64 bit data -> 64 bit data + static const unsigned char InverseIP_table[64]; + //----------------------------------------------------------------------------- + static unsigned char Kn[7]; + static unsigned char Rn_1[6]; + //----------------------------------------------------------------------------- + static void Permutate(unsigned char* pData, unsigned char ni, + unsigned char* pTable, unsigned char no); + static void LeftShift(unsigned char* nKey, unsigned char b); + static void RightShift(unsigned char* nKey, unsigned char b); + static void Expand(unsigned char* R); + static void F(unsigned char* R, unsigned char* K); + //----------------------------------------------------------------------------- + static void Encrypt(unsigned char* dMes, unsigned char* dKey); // DES encryption + static void Decrypt(unsigned char* dMes, unsigned char* dKey); // DES decryption + static void Encrypt(unsigned char* dMes, unsigned char* dKeyL, unsigned char* dKeyR);// TDES encryption + static void Decrypt(unsigned char* dMes, unsigned char* dKeyL, unsigned char* dKeyR);// TDES decryption + public: + static std::string Encrypt(std::string dMes, std::string dKey); // DES encryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes + static std::string Decrypt(std::string dMes, std::string dKey); // DES decryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes + }; +} // namespace ce #endif // CEDES_H \ No newline at end of file diff --git a/include/ce/ceFraChecksum.h b/include/ce/ceFraChecksum.h index 741fd64..30389b2 100644 --- a/include/ce/ceFraChecksum.h +++ b/include/ce/ceFraChecksum.h @@ -1,49 +1,49 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceFraChecksum.h -// Description: Byte stuffing- sending and receiving frames with checksum -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_FRACHECKSUM_H -#define CE_FRACHECKSUM_H - -#include - -#define STX 0x02 -#define ETX 0x03 -#define DLE 0x10 - -#define CE_FRAME_TX_BUF_SIZE 1024 -#define CE_FRAME_RX_BUF_SIZE 1024 - -// frame state definition -#define CE_FRAME_IGNORE 0 -#define CE_FRAME_RECEIVING 1 -#define CE_FRAME_ESCAPE 2 -#define CE_FRAME_CHKSUM 3 - -namespace ce { - -//----------------------------------------------------------------------------- -class ceFraChecksum { - int rState; -protected: - size_t TxN;//number of transmitting bytes - size_t RxN;//number of receiving bytes - char tb[CE_FRAME_TX_BUF_SIZE];//transmit buffer - char rb[CE_FRAME_RX_BUF_SIZE];//receiving data -public: - ceFraChecksum(); - size_t GetTxN(); - size_t GetRxN(); - char* GetTxBuf(); - char* GetRxBuf(); - virtual size_t SetTxFrame(char* d, size_t n); - virtual uint8_t Checksum(char* s, size_t len); - virtual size_t ReceiveRxFrame(char c);//get receiving frame from received char -}; -//----------------------------------------------------------------------------- -} // namespace ce - +///////////////////////////////////////////////////////////////////////////// +// Name: ceFraChecksum.h +// Description: Byte stuffing- sending and receiving frames with checksum +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_FRACHECKSUM_H +#define CE_FRACHECKSUM_H + +#include + +#define STX 0x02 +#define ETX 0x03 +#define DLE 0x10 + +#define CE_FRAME_TX_BUF_SIZE 1024 +#define CE_FRAME_RX_BUF_SIZE 1024 + +// frame state definition +#define CE_FRAME_IGNORE 0 +#define CE_FRAME_RECEIVING 1 +#define CE_FRAME_ESCAPE 2 +#define CE_FRAME_CHKSUM 3 + +namespace ce { + +//----------------------------------------------------------------------------- +class ceFraChecksum { + int rState; +protected: + size_t TxN;//number of transmitting bytes + size_t RxN;//number of receiving bytes + char tb[CE_FRAME_TX_BUF_SIZE];//transmit buffer + char rb[CE_FRAME_RX_BUF_SIZE];//receiving data +public: + ceFraChecksum(); + size_t GetTxN(); + size_t GetRxN(); + char* GetTxBuf(); + char* GetRxBuf(); + virtual size_t SetTxFrame(char* d, size_t n); + virtual uint8_t Checksum(char* s, size_t len); + virtual size_t ReceiveRxFrame(char c);//get receiving frame from received char +}; +//----------------------------------------------------------------------------- +} // namespace ce + #endif // CE_FRACHECKSUM_H \ No newline at end of file diff --git a/include/ce/ceFraCmd.h b/include/ce/ceFraCmd.h index 8a66941..a2c36e1 100644 --- a/include/ce/ceFraCmd.h +++ b/include/ce/ceFraCmd.h @@ -1,22 +1,22 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceFraCmd.h -// Description: Byte stuffing- sending and receiving commands as frames -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_FRACMD_H -#define CE_FRACMD_H -#include "ce/ceFrame.h" -namespace ce { -//----------------------------------------------------------------------------- -class ceFraCmd : public ceFrame { -public: - ceFraCmd(); - size_t SetTxFrame(char* d, size_t n) override; - size_t ReceiveRxFrame(char ch) override;//get receiving frame from received char -}; -//----------------------------------------------------------------------------- -} // namespace ce - +///////////////////////////////////////////////////////////////////////////// +// Name: ceFraCmd.h +// Description: Byte stuffing- sending and receiving commands as frames +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_FRACMD_H +#define CE_FRACMD_H +#include "ce/ceFrame.h" +namespace ce { +//----------------------------------------------------------------------------- +class ceFraCmd : public ceFrame { +public: + ceFraCmd(); + size_t SetTxFrame(char* d, size_t n) override; + size_t ReceiveRxFrame(char ch) override;//get receiving frame from received char +}; +//----------------------------------------------------------------------------- +} // namespace ce + #endif // CE_FRACMD_H \ No newline at end of file diff --git a/include/ce/ceInterface.h b/include/ce/ceInterface.h index 911ede9..5c551ce 100644 --- a/include/ce/ceInterface.h +++ b/include/ce/ceInterface.h @@ -1,36 +1,36 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceInterface.h -// Description: Interface to communitcate modules -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_INTERFACE_H -#define CE_INTERFACE_H - -#include -#include -#include -#include -#include -#include -#include - -namespace ce { -class ceInterface { -public: - ceInterface(); - ceInterface(ceInterface* if, std::function,std::string,int>)> cbf); - virtual ~ceInterface(); - void check(); // to regularly check message queue (e.g. 10 ms) to trigger callback function - int send(std::tuple,std::string,int>); - void setRxCallback(std::function,std::string,int>)> cbf); - void setIf2Connect(ceInterface* if); -private: - std::queue,std::string,int>> _mes; - std::function,std::string,int>)> _cbf; - ceInterface* _if = nullptr; -}; - - -} // namespace ce -#endif // CE_INTERFACE_H +///////////////////////////////////////////////////////////////////////////// +// Name: ceInterface.h +// Description: Interface to communitcate modules +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_INTERFACE_H +#define CE_INTERFACE_H + +#include +#include +#include +#include +#include +#include +#include + +namespace ce { +class ceInterface { +public: + ceInterface(); + ceInterface(ceInterface* if, std::function,std::string,int>)> cbf); + virtual ~ceInterface(); + void check(); // to regularly check message queue (e.g. 10 ms) to trigger callback function + int send(std::tuple,std::string,int>); + void setRxCallback(std::function,std::string,int>)> cbf); + void setIf2Connect(ceInterface* if); +private: + std::queue,std::string,int>> _mes; + std::function,std::string,int>)> _cbf; + ceInterface* _if = nullptr; +}; + + +} // namespace ce +#endif // CE_INTERFACE_H diff --git a/include/ce/ceMacros.h b/include/ce/ceMacros.h index c7fd9cc..2299f55 100644 --- a/include/ce/ceMacros.h +++ b/include/ce/ceMacros.h @@ -1,42 +1,43 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceMacros.h -// Description: Predefined macros for ceUtil -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_MACROS_H -#define CE_MACROS_H - -#define CE_JSON 1 // include JSON -#define CE_WX 1 // include WX -#define CE_CV 1 // include CV - -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif -#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif -#else - #ifndef CE_NOS - #define CE_NOS - #endif -#endif - -#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) - #ifndef CE_x86_64 - #define CE_x86_64 - #endif -#elif defined(__arm__) || defined(_M_ARM) - #ifndef CE_ARM - #define CE_ARM - #endif -#else - #ifndef CE_NARCH - #define CE_NARCH - #endif -#endif - +///////////////////////////////////////////////////////////////////////////// +// Name: ceMacros.h +// Description: Predefined macros for ceUtil +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_JSON 1 // include JSON +#define CE_WX 1 // include WX +#define CE_CV 1 // include CV +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + #endif // CE_MACROS_H \ No newline at end of file diff --git a/include/ce/ceMisc.h b/include/ce/ceMisc.h index 02a4de5..83ad009 100644 --- a/include/ce/ceMisc.h +++ b/include/ce/ceMisc.h @@ -1,61 +1,61 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceMisc.h -// Description: utility module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEMISC_H -#define CEMISC_H - -#include -#include -#include -#include -#include -#include -#include "ce/ceMacros.h" // macros - -#if defined(CE_WINDOWS) -#include -#include // for kbhit -#else -#include -#include -#include // for kbhit -#include // " -#endif - -namespace ce { -class ceMisc { -private: -public: - static std::string alnum(std::string str); // filter the string for alphanumeric characters only - static std::vector hex2cvec(std::string str); // convert hex string to char vector - static std::string hex2str(std::string str); // convert hex string to byte string - static std::string cvec2hex(std::vector bv); // convert char vector to hex string - - static std::string ToStr16(unsigned int u);// to hexadecimal string - static std::string ToStr16(int u);// to hexadecimal string - static std::string ToStr16(unsigned char c);// to hexadecimal string - static std::string ToStr16(char c);// to hexadecimal string - static std::string ToStr16(std::vector bv, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string - static std::string ToStr16(std::vector bv, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string - static std::string ToStr16(std::string str, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string - - static std::string cvec2str(std::vector bv); // convert char vector to string - static std::vector cptr2cvec(char* cstr, int n); // char* to char vector - static std::string cptr2str(char* cstr, int n); // convert char* to string - static void cvec2cptr(std::vector& v,char*&cstr, int& n); // character vector to char* - static std::vector str2cvec(std::string str); // string to char vector - static std::string f2s(float f, int n = 1); // float to string - static std::vector splitStr(std::string str, std::string delimiter); - - static std::string exepath(); // get the path of executing binary program - static std::string exedir(); // get the directory of executing binary program - - static bool kb_hit(); // check keyboard hit - static char get_ch(); // get char -}; - -} // namespace ce -#endif // CEMISC_H +///////////////////////////////////////////////////////////////////////////// +// Name: ceMisc.h +// Description: utility module +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEMISC_H +#define CEMISC_H + +#include +#include +#include +#include +#include +#include +#include "ce/ceMacros.h" // macros + +#if defined(CE_WINDOWS) +#include +#include // for kbhit +#else +#include +#include +#include // for kbhit +#include // " +#endif + +namespace ce { +class ceMisc { +private: +public: + static std::string alnum(std::string str); // filter the string for alphanumeric characters only + static std::vector hex2cvec(std::string str); // convert hex string to char vector + static std::string hex2str(std::string str); // convert hex string to byte string + static std::string cvec2hex(std::vector bv); // convert char vector to hex string + + static std::string ToStr16(unsigned int u);// to hexadecimal string + static std::string ToStr16(int u);// to hexadecimal string + static std::string ToStr16(unsigned char c);// to hexadecimal string + static std::string ToStr16(char c);// to hexadecimal string + static std::string ToStr16(std::vector bv, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string + static std::string ToStr16(std::vector bv, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string + static std::string ToStr16(std::string str, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string + + static std::string cvec2str(std::vector bv); // convert char vector to string + static std::vector cptr2cvec(char* cstr, int n); // char* to char vector + static std::string cptr2str(char* cstr, int n); // convert char* to string + static void cvec2cptr(std::vector& v,char*&cstr, int& n); // character vector to char* + static std::vector str2cvec(std::string str); // string to char vector + static std::string f2s(float f, int n = 1); // float to string + static std::vector splitStr(std::string str, std::string delimiter); + + static std::string exepath(); // get the path of executing binary program + static std::string exedir(); // get the directory of executing binary program + + static bool kb_hit(); // check keyboard hit + static char get_ch(); // get char +}; + +} // namespace ce +#endif // CEMISC_H diff --git a/include/ce/ceMmDateTime.h b/include/ce/ceMmDateTime.h index 9fb77bf..3dae4df 100644 --- a/include/ce/ceMmDateTime.h +++ b/include/ce/ceMmDateTime.h @@ -1,347 +1,347 @@ -// File: ceMmDateTime.h -// Description: Modern Myanmar Calendrical Calculations -// WebSite: https://yan9a.github.io/mmcal/ -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye -// Doc: http://cool-emerald.blogspot.com/2013/06/algorithm-program-and-calculation-of.html -//------------------------------------------------------------------------- -#ifndef CEMMDATETIME_H -#define CEMMDATETIME_H - -#include"ce/ceDateTime.h" -#include -#include -namespace ce { - -class ceMmDateTime : public ceDateTime -{ -private: -public: - //------------------------------------------------------------------------- - // default constructor - ceMmDateTime(); - //------------------------------------------------------------------------- - // Get Myanmar year constants depending on era - // Thanks to Myo Zarny and Wunna Ko for earlier Myanmar years data - // input: my -myanmar year - // output: - // EI = Myanmar calendar era id [1-3] : calculations methods/constants depends on era - // WO = watat offset to compensate - // NM = number of months to find excess days - // EW = exception in watat year - static void GetMyConst(long my,double& EI,double& WO,double& NM,long& EW); - //------------------------------------------------------------------------- - // Search first dimension in a 2D array - // input: (k=key,A=array,u=size) - // output: (i=index) - static long bSearch2(long k,long (*A)[2], long u); - //----------------------------------------------------------------------------- - // Search a 1D array - // input: (k=key,A=array,u=size) - // output: (i=index) - static long bSearch1(long k,long* A, long u); - //------------------------------------------------------------------------- - // Check watat (intercalary month) - // input: (my -myanmar year) - // output: ( - // watat - intercalary month [1=watat, 0=common] - // fm - full moon day of 2nd Waso in jdn_mm (jdn+6.5 for MMT) - // [only valid when watat=1]) - // dependency: GetMyConst(my) - static void cal_watat(long my, long& watat, long& fm); //get data for respective era - //------------------------------------------------------------------------- - // Check Myanmar Year - // input: (my -myanmar year) - // output: ( myt :year type [0=common, 1=little watat, 2=big watat], - // tg1 : the 1st day of Tagu as jdn_mm (Julian Day Number for MMT) - // fm : full moon day of [2nd] Waso as Julain Day Number - // werr: watat error [0=ok, 1= error]) - // dependency: cal_watat(my) - static void cal_my(long my, long& myt, long& tg1, long& fm, long& werr); - //------------------------------------------------------------------------- - // Julian day number to Myanmar date - // input: (jdn -julian day number) - // output: ( - // myt =year type [0=common, 1=little watat, 2=big watat], - // my = year, - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md = day of the month [1 to 30]) - // dependency: cal_my(my) - static void j2m(double jd, long& myt, long& my, long& mm, long& md); - //------------------------------------------------------------------------- - // Get moon phase from day of the month, month, and year type. - // input: ( - // md= day of the month [1-30], - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // myt = year type [0=common, 1=little watat, 2=big watat]) - // output: (mp =moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon]) - static long cal_mp(long md,long mm,long myt); - //------------------------------------------------------------------------- - // Get length of month from month, and year type. - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // myt = year type [0=common, 1=little watat, 2=big watat]) - // output: (mml = length of the month [29 or 30 days]) - static long cal_mml(long mm,long myt); - //------------------------------------------------------------------------- - // Get the apparent length of the year from year type. - // input: ( myt = year type [0=common, 1=little watat, 2=big watat]) - // output: ( myl= year length [354, 384, or 385 days]) - static long cal_myl(long myt); - //------------------------------------------------------------------------- - // Get fortnight day from month day - // input: ( md= day of the month [1-30]) - // output: (mf= fortnight day [1 to 15]) - static long cal_mf(long md); - //------------------------------------------------------------------------- - // Get day of month from fortnight day, moon phase, and length of the month - // input: ( - // mf = fortnight day [1 to 15], - // mp = moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // myt = year type [0=common, 1=little watat, 2=big watat]) - // output: ( md = day of the month [1-30]) - static long cal_md(long mf,long mp,long mm,long myt); - //------------------------------------------------------------------------- - // Myanmar date to Julian day number - // input: ( - // my = year, - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12 , Late Tagu=13, Late Kason=14 ], - // md = day of the month [1-30] - // output: (jd -julian day number) - // dependency: cal_my(my) - static long m2j(long my,long mm,long md); - //------------------------------------------------------------------------- - // Checking Astrological days - // More details @ http://cool-emerald.blogspot.sg/2013/12/myanmar-astrological-calendar-days.html - //------------------------------------------------------------------------- - // Get sabbath day and sabbath eve from day of the month, month, and year type. - // input: ( - // md= day of the month [1-30], - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // myt = year type [0=common, 1=little watat, 2=big watat]) - // output: ( [1=sabbath, 2=sabbath eve, 0=else]) - static long cal_sabbath(long md, long mm, long myt); - //------------------------------------------------------------------------- - // Get yatyaza from month, and weekday - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=yatyaza, 0=else]) - static long cal_yatyaza(long mm, long wd); - //------------------------------------------------------------------------- - // Get pyathada from month, and weekday - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=pyathada, 2=afternoon pyathada, 0=else]) - static long cal_pyathada(long mm, long wd); - //------------------------------------------------------------------------- - // nagahle - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ]) - // output: ( [0=west, 1=north, 2=east, 3=south]) - static long cal_nagahle(long mm); - //------------------------------------------------------------------------- - // mahabote - // input: ( - // my = year, - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [0=Binga, 1=Atun, 2=Yaza, 3=Adipati, 4= Marana, 5=Thike, 6=Puti]) - static long cal_mahabote(long my, long wd); - //------------------------------------------------------------------------- - // nakhat - // input: ( my = year ) - // output: ( [0=orc, 1=elf, 2=human] ) - static long cal_nakhat(long my); - //------------------------------------------------------------------------- - // thamanyo - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=thamanyo, 0=else]) - static long cal_thamanyo(long mm, long wd); - //------------------------------------------------------------------------- - // Get amyeittasote - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=amyeittasote, 0=else]) - static long cal_amyeittasote(long md, long wd); - //------------------------------------------------------------------------- - // Get warameittugyi - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=warameittugyi, 0=else]) - static long cal_warameittugyi(long md, long wd); - //------------------------------------------------------------------------- - // Get warameittunge - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=warameittunge, 0=else]) - static long cal_warameittunge(long md, long wd); - //------------------------------------------------------------------------- - // Get yatpote - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=yatpote, 0=else]) - static long cal_yatpote(long md, long wd); - //------------------------------------------------------------------------- - // Get thamaphyu - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=thamaphyu, 0=else]) - static long cal_thamaphyu(long md, long wd); - //------------------------------------------------------------------------- - // Get nagapor - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=nagapor, 0=else]) - static long cal_nagapor(long md, long wd); - //------------------------------------------------------------------------- - // yatyotema - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md= day of the month [1-30]) - // output: ( [1=yatyotema, 0=else]) - static long cal_yatyotema(long mm, long md); - //------------------------------------------------------------------------- - // mahayatkyan - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md= day of the month [1-30]) - // output: ( [1=mahayatkyan, 0=else]) - static long cal_mahayatkyan(long mm, long md); - //------------------------------------------------------------------------- - // shanyat - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md= day of the month [1-30]) - // output: ( [1=shanyat, 0=else]) - static long cal_shanyat(long mm, long md); - //------------------------------------------------------------------------- - // get astrological information - // input: (jdn: Julian Day Number) - // output: (array of strings) - static std::vector cal_astro(long jdn); - // End of checking Astrological days - //------------------------------------------------------------------------- - // Get holidays - // input: (jdn=Julian Day Number) - // output: ( array of strings) - // Thanks to Ye Lin Kyaw and Aye Nyein for the knowledge about - // the Myanmar calendar and the new year - static std::vector cal_holiday(long jdn); - //------------------------------------------------------------------------- - // DoE : Date of Easter using "Meeus/Jones/Butcher" algorithm - // Reference: Peter Duffett-Smith, Jonathan Zwart', - // "Practical Astronomy with your Calculator or Spreadsheet," - // 4th Etd, Cambridge university press, 2011. Page-4. - // input: (y=year) - // output: (j=julian day number) - // dependency: w2j() - static long DoE(long y); - //------------------------------------------------------------------------- - // Get other holidays - // input: (jdn: Julian Day Number) - // output: (array of strings) - // dependency: DoE(), j2w() - static std::vector cal_holiday2(long jdn); - //------------------------------------------------------------------------- - // jd to date string in Myanmar calendar - // input: (jd:julian date, - // fs: format string [Optional argument: "&y &M &P &ff"] - // tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) - // output: date string in Myanmar calendar according to fm - // where formatting strings are as follows - // &yyyy : Myanmar year [0000-9999, e.g. 1380] - // &YYYY : Sasana year [0000-9999, e.g. 2562] - // &y : Myanmar year [0-9999, e.g. 138] - // &mm : month with zero padding [01-14] - // &M : month [e.g. January] - // &m : month [1-14] - // &P : moon phase [e.g. waxing, waning, full moon, or new moon] - // &dd : day of the month with zero padding [01-31] - // &d : day of the month [1-31] - // &ff : fortnight day with zero padding [01-15] - // &f : fortnight day [1-15] - static std::string j2ms(double jd, std::string fs="&y &M &P &ff", double tz=0); - //------------------------------------------------------------------------- - // get properties - long myt(); // Myanmar year type - long my(); // Myanmar year - long sy(); // Sasana year - std::string my_name(); // Myanmar year name - - long mm(); // Myanmar month [1-14] - // [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ] - - long md(); // Myanmar day of the month [1-30] - long mp(); // Moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] - long mf(); // Fortnight day [1-15] - std::string sabbath(); // get sabbath string - std::string yatyaza(); // get yatyaza string - std::string pyathada(); // get pyathada string - std::string nagahle(); // get nagahle direction - std::string mahabote(); // get mahabote direction - std::vector astro(); // get the array of astrological days - std::vector holidays(); // get the array of public holidays - std::vector holidays2(); // get the array of other holidays - //------------------------------------------------------------------------- - // get Myanmar Date String - // input: ( - // fs: format string [Optional argument: "&y &M &P &ff"] - // tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) - // output: date string in Myanmar calendar according to fm - // where formatting strings are as follows - // &yyyy : Myanmar year [0000-9999, e.g. 1380] - // &YYYY : Sasana year [0000-9999, e.g. 2562] - // &y : Myanmar year [0-9999, e.g. 138] - // &mm : month with zero padding [01-14] - // &M : month [e.g. January] - // &m : month [1-14] - // &P : moon phase [e.g. waxing, waning, full moon, or new moon] - // &dd : day of the month with zero padding [01-31] - // &d : day of the month [1-31] - // &ff : fortnight day with zero padding [01-15] - // &f : fortnight day [1-15] - std::string ToMString(std::string fs="&y &M &P &ff"); - //------------------------------------------------------------------------- -}; - -} // namespace ce - +// File: ceMmDateTime.h +// Description: Modern Myanmar Calendrical Calculations +// WebSite: https://yan9a.github.io/mmcal/ +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye +// Doc: http://cool-emerald.blogspot.com/2013/06/algorithm-program-and-calculation-of.html +//------------------------------------------------------------------------- +#ifndef CEMMDATETIME_H +#define CEMMDATETIME_H + +#include"ce/ceDateTime.h" +#include +#include +namespace ce { + +class ceMmDateTime : public ceDateTime +{ +private: +public: + //------------------------------------------------------------------------- + // default constructor + ceMmDateTime(); + //------------------------------------------------------------------------- + // Get Myanmar year constants depending on era + // Thanks to Myo Zarny and Wunna Ko for earlier Myanmar years data + // input: my -myanmar year + // output: + // EI = Myanmar calendar era id [1-3] : calculations methods/constants depends on era + // WO = watat offset to compensate + // NM = number of months to find excess days + // EW = exception in watat year + static void GetMyConst(long my,double& EI,double& WO,double& NM,long& EW); + //------------------------------------------------------------------------- + // Search first dimension in a 2D array + // input: (k=key,A=array,u=size) + // output: (i=index) + static long bSearch2(long k,long (*A)[2], long u); + //----------------------------------------------------------------------------- + // Search a 1D array + // input: (k=key,A=array,u=size) + // output: (i=index) + static long bSearch1(long k,long* A, long u); + //------------------------------------------------------------------------- + // Check watat (intercalary month) + // input: (my -myanmar year) + // output: ( + // watat - intercalary month [1=watat, 0=common] + // fm - full moon day of 2nd Waso in jdn_mm (jdn+6.5 for MMT) + // [only valid when watat=1]) + // dependency: GetMyConst(my) + static void cal_watat(long my, long& watat, long& fm); //get data for respective era + //------------------------------------------------------------------------- + // Check Myanmar Year + // input: (my -myanmar year) + // output: ( myt :year type [0=common, 1=little watat, 2=big watat], + // tg1 : the 1st day of Tagu as jdn_mm (Julian Day Number for MMT) + // fm : full moon day of [2nd] Waso as Julain Day Number + // werr: watat error [0=ok, 1= error]) + // dependency: cal_watat(my) + static void cal_my(long my, long& myt, long& tg1, long& fm, long& werr); + //------------------------------------------------------------------------- + // Julian day number to Myanmar date + // input: (jdn -julian day number) + // output: ( + // myt =year type [0=common, 1=little watat, 2=big watat], + // my = year, + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // md = day of the month [1 to 30]) + // dependency: cal_my(my) + static void j2m(double jd, long& myt, long& my, long& mm, long& md); + //------------------------------------------------------------------------- + // Get moon phase from day of the month, month, and year type. + // input: ( + // md= day of the month [1-30], + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // myt = year type [0=common, 1=little watat, 2=big watat]) + // output: (mp =moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon]) + static long cal_mp(long md,long mm,long myt); + //------------------------------------------------------------------------- + // Get length of month from month, and year type. + // input: ( + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // myt = year type [0=common, 1=little watat, 2=big watat]) + // output: (mml = length of the month [29 or 30 days]) + static long cal_mml(long mm,long myt); + //------------------------------------------------------------------------- + // Get the apparent length of the year from year type. + // input: ( myt = year type [0=common, 1=little watat, 2=big watat]) + // output: ( myl= year length [354, 384, or 385 days]) + static long cal_myl(long myt); + //------------------------------------------------------------------------- + // Get fortnight day from month day + // input: ( md= day of the month [1-30]) + // output: (mf= fortnight day [1 to 15]) + static long cal_mf(long md); + //------------------------------------------------------------------------- + // Get day of month from fortnight day, moon phase, and length of the month + // input: ( + // mf = fortnight day [1 to 15], + // mp = moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // myt = year type [0=common, 1=little watat, 2=big watat]) + // output: ( md = day of the month [1-30]) + static long cal_md(long mf,long mp,long mm,long myt); + //------------------------------------------------------------------------- + // Myanmar date to Julian day number + // input: ( + // my = year, + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12 , Late Tagu=13, Late Kason=14 ], + // md = day of the month [1-30] + // output: (jd -julian day number) + // dependency: cal_my(my) + static long m2j(long my,long mm,long md); + //------------------------------------------------------------------------- + // Checking Astrological days + // More details @ http://cool-emerald.blogspot.sg/2013/12/myanmar-astrological-calendar-days.html + //------------------------------------------------------------------------- + // Get sabbath day and sabbath eve from day of the month, month, and year type. + // input: ( + // md= day of the month [1-30], + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // myt = year type [0=common, 1=little watat, 2=big watat]) + // output: ( [1=sabbath, 2=sabbath eve, 0=else]) + static long cal_sabbath(long md, long mm, long myt); + //------------------------------------------------------------------------- + // Get yatyaza from month, and weekday + // input: ( + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=yatyaza, 0=else]) + static long cal_yatyaza(long mm, long wd); + //------------------------------------------------------------------------- + // Get pyathada from month, and weekday + // input: ( + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=pyathada, 2=afternoon pyathada, 0=else]) + static long cal_pyathada(long mm, long wd); + //------------------------------------------------------------------------- + // nagahle + // input: ( + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ]) + // output: ( [0=west, 1=north, 2=east, 3=south]) + static long cal_nagahle(long mm); + //------------------------------------------------------------------------- + // mahabote + // input: ( + // my = year, + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [0=Binga, 1=Atun, 2=Yaza, 3=Adipati, 4= Marana, 5=Thike, 6=Puti]) + static long cal_mahabote(long my, long wd); + //------------------------------------------------------------------------- + // nakhat + // input: ( my = year ) + // output: ( [0=orc, 1=elf, 2=human] ) + static long cal_nakhat(long my); + //------------------------------------------------------------------------- + // thamanyo + // input: ( + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=thamanyo, 0=else]) + static long cal_thamanyo(long mm, long wd); + //------------------------------------------------------------------------- + // Get amyeittasote + // input: ( + // md= day of the month [1-30], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=amyeittasote, 0=else]) + static long cal_amyeittasote(long md, long wd); + //------------------------------------------------------------------------- + // Get warameittugyi + // input: ( + // md= day of the month [1-30], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=warameittugyi, 0=else]) + static long cal_warameittugyi(long md, long wd); + //------------------------------------------------------------------------- + // Get warameittunge + // input: ( + // md= day of the month [1-30], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=warameittunge, 0=else]) + static long cal_warameittunge(long md, long wd); + //------------------------------------------------------------------------- + // Get yatpote + // input: ( + // md= day of the month [1-30], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=yatpote, 0=else]) + static long cal_yatpote(long md, long wd); + //------------------------------------------------------------------------- + // Get thamaphyu + // input: ( + // md= day of the month [1-30], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=thamaphyu, 0=else]) + static long cal_thamaphyu(long md, long wd); + //------------------------------------------------------------------------- + // Get nagapor + // input: ( + // md= day of the month [1-30], + // wd= weekday [0=sat, 1=sun, ..., 6=fri]) + // output: ( [1=nagapor, 0=else]) + static long cal_nagapor(long md, long wd); + //------------------------------------------------------------------------- + // yatyotema + // input: ( + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // md= day of the month [1-30]) + // output: ( [1=yatyotema, 0=else]) + static long cal_yatyotema(long mm, long md); + //------------------------------------------------------------------------- + // mahayatkyan + // input: ( + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // md= day of the month [1-30]) + // output: ( [1=mahayatkyan, 0=else]) + static long cal_mahayatkyan(long mm, long md); + //------------------------------------------------------------------------- + // shanyat + // input: ( + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // md= day of the month [1-30]) + // output: ( [1=shanyat, 0=else]) + static long cal_shanyat(long mm, long md); + //------------------------------------------------------------------------- + // get astrological information + // input: (jdn: Julian Day Number) + // output: (array of strings) + static std::vector cal_astro(long jdn); + // End of checking Astrological days + //------------------------------------------------------------------------- + // Get holidays + // input: (jdn=Julian Day Number) + // output: ( array of strings) + // Thanks to Ye Lin Kyaw and Aye Nyein for the knowledge about + // the Myanmar calendar and the new year + static std::vector cal_holiday(long jdn); + //------------------------------------------------------------------------- + // DoE : Date of Easter using "Meeus/Jones/Butcher" algorithm + // Reference: Peter Duffett-Smith, Jonathan Zwart', + // "Practical Astronomy with your Calculator or Spreadsheet," + // 4th Etd, Cambridge university press, 2011. Page-4. + // input: (y=year) + // output: (j=julian day number) + // dependency: w2j() + static long DoE(long y); + //------------------------------------------------------------------------- + // Get other holidays + // input: (jdn: Julian Day Number) + // output: (array of strings) + // dependency: DoE(), j2w() + static std::vector cal_holiday2(long jdn); + //------------------------------------------------------------------------- + // jd to date string in Myanmar calendar + // input: (jd:julian date, + // fs: format string [Optional argument: "&y &M &P &ff"] + // tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) + // output: date string in Myanmar calendar according to fm + // where formatting strings are as follows + // &yyyy : Myanmar year [0000-9999, e.g. 1380] + // &YYYY : Sasana year [0000-9999, e.g. 2562] + // &y : Myanmar year [0-9999, e.g. 138] + // &mm : month with zero padding [01-14] + // &M : month [e.g. January] + // &m : month [1-14] + // &P : moon phase [e.g. waxing, waning, full moon, or new moon] + // &dd : day of the month with zero padding [01-31] + // &d : day of the month [1-31] + // &ff : fortnight day with zero padding [01-15] + // &f : fortnight day [1-15] + static std::string j2ms(double jd, std::string fs="&y &M &P &ff", double tz=0); + //------------------------------------------------------------------------- + // get properties + long myt(); // Myanmar year type + long my(); // Myanmar year + long sy(); // Sasana year + std::string my_name(); // Myanmar year name + + long mm(); // Myanmar month [1-14] + // [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ] + + long md(); // Myanmar day of the month [1-30] + long mp(); // Moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] + long mf(); // Fortnight day [1-15] + std::string sabbath(); // get sabbath string + std::string yatyaza(); // get yatyaza string + std::string pyathada(); // get pyathada string + std::string nagahle(); // get nagahle direction + std::string mahabote(); // get mahabote direction + std::vector astro(); // get the array of astrological days + std::vector holidays(); // get the array of public holidays + std::vector holidays2(); // get the array of other holidays + //------------------------------------------------------------------------- + // get Myanmar Date String + // input: ( + // fs: format string [Optional argument: "&y &M &P &ff"] + // tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) + // output: date string in Myanmar calendar according to fm + // where formatting strings are as follows + // &yyyy : Myanmar year [0000-9999, e.g. 1380] + // &YYYY : Sasana year [0000-9999, e.g. 2562] + // &y : Myanmar year [0-9999, e.g. 138] + // &mm : month with zero padding [01-14] + // &M : month [e.g. January] + // &m : month [1-14] + // &P : moon phase [e.g. waxing, waning, full moon, or new moon] + // &dd : day of the month with zero padding [01-31] + // &d : day of the month [1-31] + // &ff : fortnight day with zero padding [01-15] + // &f : fortnight day [1-15] + std::string ToMString(std::string fs="&y &M &P &ff"); + //------------------------------------------------------------------------- +}; + +} // namespace ce + #endif // CEMMDATETIME_H \ No newline at end of file diff --git a/include/ce/ceModbus.h b/include/ce/ceModbus.h index 2fa7176..6915cf1 100644 --- a/include/ce/ceModbus.h +++ b/include/ce/ceModbus.h @@ -1,45 +1,45 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceModbus.h -// Description: Sending and receiving modbus frames -// Modbus RTU frame format (primarily used on asynchronous serial data lines like RS-485/EIA-485) -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_MODBUS_H -#define CE_MODBUS_H -#include "ce/ceFrame.h" -#define CR 0x0D -#define LF 0x0A -#define CE_NUMBER_OF_TICKS_TO_RESET 10 -#include -#include -namespace ce { -//----------------------------------------------------------------------------- -class ceModbus : public ceFrame { -private: -protected: - size_t _count; // receiving count - size_t _frameSize;// frame size - int _tick_n; - int _reset_tick; -public: - ceModbus(); - size_t SetTxFrame(char* d, size_t n) override; - uint16_t CRC16(char* s, size_t len, uint16_t crc) override; - size_t ReceiveRxFrame(char c) override;//get receiving frame from received char - int Tick();// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx - void SetCmd(std::vector v); - void SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data); - void SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay=0); - void SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len); - std::vector GetStatus(char* d, size_t n); - std::vector GetTxVec(); - std::vector GetRxVec(); - void SetResetTickCount(int n); - int GetResetTickCount(); -}; -//----------------------------------------------------------------------------- -} // namespace ce - +///////////////////////////////////////////////////////////////////////////// +// Name: ceModbus.h +// Description: Sending and receiving modbus frames +// Modbus RTU frame format (primarily used on asynchronous serial data lines like RS-485/EIA-485) +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_MODBUS_H +#define CE_MODBUS_H +#include "ce/ceFrame.h" +#define CR 0x0D +#define LF 0x0A +#define CE_NUMBER_OF_TICKS_TO_RESET 10 +#include +#include +namespace ce { +//----------------------------------------------------------------------------- +class ceModbus : public ceFrame { +private: +protected: + size_t _count; // receiving count + size_t _frameSize;// frame size + int _tick_n; + int _reset_tick; +public: + ceModbus(); + size_t SetTxFrame(char* d, size_t n) override; + uint16_t CRC16(char* s, size_t len, uint16_t crc) override; + size_t ReceiveRxFrame(char c) override;//get receiving frame from received char + int Tick();// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx + void SetCmd(std::vector v); + void SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data); + void SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay=0); + void SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len); + std::vector GetStatus(char* d, size_t n); + std::vector GetTxVec(); + std::vector GetRxVec(); + void SetResetTickCount(int n); + int GetResetTickCount(); +}; +//----------------------------------------------------------------------------- +} // namespace ce + #endif // CE_MODBUS_H \ No newline at end of file diff --git a/include/ce/ceRSA_OS.h b/include/ce/ceRSA_OS.h index d1eb744..44e0451 100644 --- a/include/ce/ceRSA_OS.h +++ b/include/ce/ceRSA_OS.h @@ -1,62 +1,62 @@ -#ifndef CERSA_OS_H -#define CERSA_OS_H - - // Description: Functions to calculate RSA using OpenSSL crypto lib - // Class implementation of the following example: https://github.com/yan9a/cecpp/blob/master/rsa_openssl/main.cpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -namespace ce { - class ceRSA_OS { - public: - // ---------------------------------------------------------------------------- - static std::string bn2str(BIGNUM* bigN); - - // Load public key from file - static RSA* loadPublicKey(std::string publicKeyFile); - - // Load private key from file - static RSA* loadPrivateKey(std::string privateKeyFile); - - // Encrypt data using public key - static std::string encrypt(const std::string& message, RSA* rsa_key); - - // Decrypt data using private key - static std::string decrypt(const std::string& ciphertext, RSA* rsa_key); - - // Generate a public-private key pair and save to files - static RSA* generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t bit_len = 2048, uint32_t exp = 3); - - // Generate a public-private key pair and returns RSA - static RSA* generateKeyPair(uint32_t bit_len = 2048, uint32_t exp = 3); - - // Encrypt data using public key - static std::string encrypt(const std::string& message, std::string publicKeyFile); - - // Decrypt data using private key - static std::string decrypt(const std::string& ciphertext, std::string privateKeyFile); - - // Encrypt data using modulus n and exponent e - static std::string encrypt(const std::string& message, std::string n, std::string e); - - // Decrypt data using secret number d, modulus n and exponent e - static std::string decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e); - - // Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key - static void getBN(RSA* key, std::string& d, std::string& n, std::string& e); - }; -} // namespace ce - -#endif // CERSA_OS_H +#ifndef CERSA_OS_H +#define CERSA_OS_H + + // Description: Functions to calculate RSA using OpenSSL crypto lib + // Class implementation of the following example: https://github.com/yan9a/cecpp/blob/master/rsa_openssl/main.cpp + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace ce { + class ceRSA_OS { + public: + // ---------------------------------------------------------------------------- + static std::string bn2str(BIGNUM* bigN); + + // Load public key from file + static RSA* loadPublicKey(std::string publicKeyFile); + + // Load private key from file + static RSA* loadPrivateKey(std::string privateKeyFile); + + // Encrypt data using public key + static std::string encrypt(const std::string& message, RSA* rsa_key); + + // Decrypt data using private key + static std::string decrypt(const std::string& ciphertext, RSA* rsa_key); + + // Generate a public-private key pair and save to files + static RSA* generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t bit_len = 2048, uint32_t exp = 3); + + // Generate a public-private key pair and returns RSA + static RSA* generateKeyPair(uint32_t bit_len = 2048, uint32_t exp = 3); + + // Encrypt data using public key + static std::string encrypt(const std::string& message, std::string publicKeyFile); + + // Decrypt data using private key + static std::string decrypt(const std::string& ciphertext, std::string privateKeyFile); + + // Encrypt data using modulus n and exponent e + static std::string encrypt(const std::string& message, std::string n, std::string e); + + // Decrypt data using secret number d, modulus n and exponent e + static std::string decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e); + + // Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key + static void getBN(RSA* key, std::string& d, std::string& n, std::string& e); + }; +} // namespace ce + +#endif // CERSA_OS_H diff --git a/include/ce/ceSHA1.h b/include/ce/ceSHA1.h index b44c74f..7a0c4fe 100644 --- a/include/ce/ceSHA1.h +++ b/include/ce/ceSHA1.h @@ -1,57 +1,57 @@ -#ifndef SHA1_H -#define SHA1_H - -/* - SHA-1 in C - By Steve Reid - 100% Public Domain - */ - // Description: Functions to calculate SHA1 - // Class implementation of the following repository: https://github.com/clibs/sha1 - -#include "stdint.h" -#include - - namespace ce { - typedef struct - { - uint32_t state[5]; - uint32_t count[2]; - unsigned char buffer[64]; - } SHA1_CTX; - - class ceSHA1 { - private: - SHA1_CTX sha; - //----------------------------------------------------------------------------- - void SHA1Transform( - uint32_t state[5], - const unsigned char buffer[64] - ); - - void SHA1Init( - SHA1_CTX* context - ); - - void SHA1Update( - SHA1_CTX* context, - const unsigned char* data, - uint32_t len - ); - - void SHA1Final( - unsigned char digest[20], - SHA1_CTX* context - ); - void SHA1( - char* hash_out, - const char* str, - uint32_t len); - public: - void Init(); - void Update(std::string str); - std::string Final(); - }; - } // namespace ce - -#endif /* SHA1_H */ +#ifndef SHA1_H +#define SHA1_H + +/* + SHA-1 in C + By Steve Reid + 100% Public Domain + */ + // Description: Functions to calculate SHA1 + // Class implementation of the following repository: https://github.com/clibs/sha1 + +#include "stdint.h" +#include + + namespace ce { + typedef struct + { + uint32_t state[5]; + uint32_t count[2]; + unsigned char buffer[64]; + } SHA1_CTX; + + class ceSHA1 { + private: + SHA1_CTX sha; + //----------------------------------------------------------------------------- + void SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] + ); + + void SHA1Init( + SHA1_CTX* context + ); + + void SHA1Update( + SHA1_CTX* context, + const unsigned char* data, + uint32_t len + ); + + void SHA1Final( + unsigned char digest[20], + SHA1_CTX* context + ); + void SHA1( + char* hash_out, + const char* str, + uint32_t len); + public: + void Init(); + void Update(std::string str); + std::string Final(); + }; + } // namespace ce + +#endif /* SHA1_H */ diff --git a/include/ce/ceTcpServer.h b/include/ce/ceTcpServer.h deleted file mode 100644 index ec7acdd..0000000 --- a/include/ce/ceTcpServer.h +++ /dev/null @@ -1,55 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceTcpServer.h -// Description: TCP server module -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CETCPSVR_H -#define CETCPSVR_H -#include "ce/ceMacros.h" // macros -#if CE_WX==1 -#include -#include -#include -#include "wx/wx.h" -#include "wx/socket.h" -#include "ce/ceMisc.h" // utilities -// this example is currently written to use only IP or only IPv4 sockets, it -// should be extended to allow using either in the future -//#if wxUSE_IPV6 -//typedef wxIPV6address IPaddress; -//#else -typedef wxIPV4address IPaddress; -//#endif -#define CE_TCPSVR_RX_BUF_SIZE 32768 - -namespace ce { -class ceTcpServer : public wxEvtHandler { -public: - ceTcpServer(wxEvtHandler* app, int serverid, int socketid, int port); // port = listening port number - ~ceTcpServer(); - - bool Open(); // return true = success, false = error - bool Close(); - - // Transmit (write) - int Tx(std::vector bv); // return 0 = success, 1 = error - // Receive (read) will raise receive event -private: - void OnServerEvent(wxSocketEvent& event); - void OnSocketEvent(wxSocketEvent& event); - wxEvtHandler* _app; - int _socket_id; - int _server_id; - int _port; - bool _listening{false}; - wxSocketServer* _socketServer{}; - wxSocketBase* _socketBase{}; - void PrintLog(std::string str); - int _connected_n{0}; -}; - -} // namespace ce -#endif // CE_WX -#endif // CETCPSVR_H diff --git a/include/ce/ceUDP.h b/include/ce/ceUDP.h index 4d8d4f7..188edd0 100644 --- a/include/ce/ceUDP.h +++ b/include/ce/ceUDP.h @@ -1,58 +1,58 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceUDP.h -// Description: UDP communication module -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEUDP_H -#define CEUDP_H - -#include "ce/ceMacros.h" // macros -#if CE_WX==1 -#include -#include -#include -#include "wx/wx.h" -#include "wx/socket.h" -// this example is currently written to use only IP or only IPv4 sockets, it -// should be extended to allow using either in the future -//#if wxUSE_IPV6 -//typedef wxIPV6address IPaddress; -//#else -typedef wxIPV4address IPaddress; -//#endif - -#define CE_UDP_RX_BUF_SIZE 32768 - -namespace ce { -class ceUDP : public wxEvtHandler { -public: - ceUDP(wxEvtHandler* app, int socketid, int rx_port); // rx_port = 0 for not listening - ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port); - ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost); - int Tx(std::vector bv); // return 0 = success, 1 = error - int Tx(std::vector bv, std::string remoteHost, int txPort); // return 0 = success, 1 = error - int Open(); // return 0 = success, 1 = error - void Close(); - int GetRxPort(); - void SetRxPort(int rx_port); - int GetTxPort(); - void SetTxPort(int tx_port); - std::string GetRemotehost(); - void SetRemotehost(std::string remoteHost); -private: - void Rx(int socketid, std::vector bv, std::string ip, int port); - void OnSocketEvent(wxSocketEvent& event); - wxEvtHandler* _app; - int SOCKET_ID; - int udp_port_rx; - int udp_port_tx; - std::string udp_remote_host; - wxDatagramSocket *sock; - int _ok; -}; - -} // namespace ce -#endif // CE_WX -#endif // CEUDP_H +///////////////////////////////////////////////////////////////////////////// +// Name: ceUDP.h +// Description: UDP communication module +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEUDP_H +#define CEUDP_H + +#include "ce/ceMacros.h" // macros +#if CE_WX==1 +#include +#include +#include +#include "wx/wx.h" +#include "wx/socket.h" +// this example is currently written to use only IP or only IPv4 sockets, it +// should be extended to allow using either in the future +//#if wxUSE_IPV6 +//typedef wxIPV6address IPaddress; +//#else +typedef wxIPV4address IPaddress; +//#endif + +#define CE_UDP_RX_BUF_SIZE 32768 + +namespace ce { +class ceUDP : public wxEvtHandler { +public: + ceUDP(wxEvtHandler* app, int socketid, int rx_port); // rx_port = 0 for not listening + ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port); + ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost); + int Tx(std::vector bv); // return 0 = success, 1 = error + int Tx(std::vector bv, std::string remoteHost, int txPort); // return 0 = success, 1 = error + int Open(); // return 0 = success, 1 = error + void Close(); + int GetRxPort(); + void SetRxPort(int rx_port); + int GetTxPort(); + void SetTxPort(int tx_port); + std::string GetRemotehost(); + void SetRemotehost(std::string remoteHost); +private: + void Rx(int socketid, std::vector bv, std::string ip, int port); + void OnSocketEvent(wxSocketEvent& event); + wxEvtHandler* _app; + int SOCKET_ID; + int udp_port_rx; + int udp_port_tx; + std::string udp_remote_host; + wxDatagramSocket *sock; + int _ok; +}; + +} // namespace ce +#endif // CE_WX +#endif // CEUDP_H diff --git a/include/ce/ceWxSerial.h b/include/ce/ceWxSerial.h index cc2a74f..8b850d2 100644 --- a/include/ce/ceWxSerial.h +++ b/include/ce/ceWxSerial.h @@ -1,32 +1,32 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceWxSerial.h -// Description: Serial module for wxWidgets -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEWXSERIAL_H -#define CEWXSERIAL_H -#include "ce/ceMacros.h" // macros -#if CE_WX==1 -#include "wx/wx.h" -#include -#include "ce/ceSerial.h" -namespace ce { - -class ceWxSerial : public wxEvtHandler, public ce::ceSerial { -public: - ceWxSerial(wxEvtHandler* app,int id, int interval, - std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits); - ~ceWxSerial(); - void OnTimer(wxTimerEvent& event); - std::vector Chk(); -private: - wxTimer* _timer; - wxEvtHandler* _app; - int _id; - int _interval; -}; - -} // namespace ce -#endif // CE_WX -#endif // CEWXSERIAL_H +///////////////////////////////////////////////////////////////////////////// +// Name: ceWxSerial.h +// Description: Serial module for wxWidgets +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEWXSERIAL_H +#define CEWXSERIAL_H +#include "ce/ceMacros.h" // macros +#if CE_WX==1 +#include "wx/wx.h" +#include +#include "ce/ceSerial.h" +namespace ce { + +class ceWxSerial : public wxEvtHandler, public ce::ceSerial { +public: + ceWxSerial(wxEvtHandler* app,int id, int interval, + std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits); + ~ceWxSerial(); + void OnTimer(wxTimerEvent& event); + std::vector Chk(); +private: + wxTimer* _timer; + wxEvtHandler* _app; + int _id; + int _interval; +}; + +} // namespace ce +#endif // CE_WX +#endif // CEWXSERIAL_H diff --git a/include/ce/cewxcvMisc.h b/include/ce/cewxcvMisc.h index 369d0ac..6a140fe 100644 --- a/include/ce/cewxcvMisc.h +++ b/include/ce/cewxcvMisc.h @@ -1,34 +1,34 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: cewxcvMisc.h -// Description: utility module using wxWidgets and OpenCV -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEWXCVMISC_H -#define CEWXCVMISC_H - -#include -#include "ce/ceMacros.h" // macros -#if CE_WX==1 -#include "wx/wx.h" -#endif // CE_WX -#if CE_CV==1 -#include -using namespace cv; -#endif // CE_WX -namespace ce { -class cewxcvMisc { -private: -public: -#if CE_WX==1 - // wxWidgets - static void printTime(); -#if CE_CV==1 - static wxImage wx_from_mat(cv::Mat &img); - static cv::Mat mat_from_wx(wxImage &wx); -#endif // CE_CV -#endif // CE_WX -}; - -} // namespace ce -#endif // CEWXCVMISC_H +///////////////////////////////////////////////////////////////////////////// +// Name: cewxcvMisc.h +// Description: utility module using wxWidgets and OpenCV +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEWXCVMISC_H +#define CEWXCVMISC_H + +#include +#include "ce/ceMacros.h" // macros +#if CE_WX==1 +#include "wx/wx.h" +#endif // CE_WX +#if CE_CV==1 +#include +using namespace cv; +#endif // CE_WX +namespace ce { +class cewxcvMisc { +private: +public: +#if CE_WX==1 + // wxWidgets + static void printTime(); +#if CE_CV==1 + static wxImage wx_from_mat(cv::Mat &img); + static cv::Mat mat_from_wx(wxImage &wx); +#endif // CE_CV +#endif // CE_WX +}; + +} // namespace ce +#endif // CEWXCVMISC_H diff --git a/src/ceDES.cpp b/src/ceDES.cpp index e0d6974..96735ba 100644 --- a/src/ceDES.cpp +++ b/src/ceDES.cpp @@ -1,493 +1,493 @@ -// Description: Simple functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) -// Class implementation of the following repository: https://github.com/yan9a/ceDES -// WebSite: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2023 Yan Naing Aye - -// Related links -// https://www.rapidtables.com/convert/number/ascii-to-hex.html -// https://emvlab.org/descalc/ -// https://paymentcardtools.com/crypto-calculators/des-calculator -// https://github.com/yan9a/cecpp/blob/master/des_cryptopp/main.cpp - -#include -#include "ce/ceDES.h" -namespace ce { - //----------------------------------------------------------------------------- - // Init permutation table - // 64 bit data -> 64 bit data - const unsigned char ceDES::IP_table[64] = { - 58, 50, 42, 34, 26, 18, 10, 2, - 60, 52, 44, 36, 28, 20, 12, 4, - 62, 54, 46, 38, 30, 22, 14, 6, - 64, 56, 48, 40, 32, 24, 16, 8, - 57, 49, 41, 33, 25, 17, 9, 1, - 59, 51, 43, 35, 27, 19, 11, 3, - 61, 53, 45, 37, 29, 21, 13, 5, - 63, 55, 47, 39, 31, 23, 15, 7 }; - //----------------------------------------------------------------------------- - //Permuted Choice 1 - // Key permutation table - // 64 bit key data -> 56 bit key data - const unsigned char ceDES::PC1_table[56] = { - 57, 49, 41, 33, 25, 17, 9, - 1, 58, 50, 42, 34, 26, 18, - 10, 2, 59, 51, 43, 35, 27, - 19, 11, 3, 60, 52, 44, 36, - 63, 55, 47, 39, 31, 23, 15, - 7, 62, 54, 46, 38, 30, 22, - 14, 6, 61, 53, 45, 37, 29, - 21, 13, 5, 28, 20, 12, 4 }; - //----------------------------------------------------------------------------- - // Key shift table - const unsigned char ceDES::LeftShift_table[16] = { - 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; - //----------------------------------------------------------------------------- - // Key Compression permutation table - // 56 bit key data -> 48 bit - const unsigned char ceDES::PC2_table[48] = { - 14, 17, 11, 24, 1, 5, 3, 28, - 15, 6, 21, 10, 23, 19, 12, 4, - 26, 8, 16, 7, 27, 20, 13, 2, - 41, 52, 31, 37, 47, 55, 30, 40, - 51, 45, 33, 48, 44, 49, 39, 56, - 34, 53, 46, 42, 50, 36, 29, 32 }; - //----------------------------------------------------------------------------- - // Expansion permutation table - // 32 bit data -> 48 bit data - const unsigned char ceDES::E_table[48] = { - 32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9, 10, 11, 12, 13, - 12, 13, 14, 15, 16, 17, - 16, 17, 18, 19, 20, 21, - 20, 21, 22, 23, 24, 25, - 24, 25, 26, 27, 28, 29, - 28, 29, 30, 31, 32, 1 }; - //----------------------------------------------------------------------------- - const unsigned char ceDES::S[8][4][16] = { - { - {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, - {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, - {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, - {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} - }, - { - {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, - {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, - {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, - {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} - }, - { - {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, - {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, - {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, - {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} - }, - { - {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, - {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, - {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, - {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} - }, - { - {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, - {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, - {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, - {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} - }, - { - {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, - {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, - {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, - {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} - }, - { - {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, - {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, - {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, - {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} - }, - { - {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, - {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, - {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, - {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} - } - }; - //----------------------------------------------------------------------------- - // Strait permutation table - // 32 bit data -> 32 bit data - const unsigned char ceDES::P_table[32] = { - 16, 7, 20, 21, 29, 12, 28, 17, - 1, 15, 23, 26, 5, 18, 31, 10, - 2, 8, 24, 14, 32, 27, 3, 9, - 19, 13, 30, 6, 22, 11, 4, 25 }; - //----------------------------------------------------------------------------- - // Inverse permutation table - // 64 bit data -> 64 bit data - const unsigned char ceDES::InverseIP_table[64] = { - 40, 8, 48, 16, 56, 24, 64, 32, - 39, 7, 47, 15, 55, 23, 63, 31, - 38, 6, 46, 14, 54, 22, 62, 30, - 37, 5, 45, 13, 53, 21, 61, 29, - 36, 4, 44, 12, 52, 20, 60, 28, - 35, 3, 43, 11, 51, 19, 59, 27, - 34, 2, 42, 10, 50, 18, 58, 26, - 33, 1, 41, 9, 49, 17, 57, 25 }; - //----------------------------------------------------------------------------- - unsigned char ceDES::Kn[7]; - unsigned char ceDES::Rn_1[6]; -//----------------------------------------------------------------------------- -//dMes=Message to encrypt -//dKey=Key -void ceDES::Encrypt(unsigned char *dMes,unsigned char *dKey) -{ - unsigned char n,i; - unsigned char dKeyC[8]; - for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key - - Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output - Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output - for(n=0;n<16;n++) - { - LeftShift(dKeyC,LeftShift_table[n]); - for(i=0;i<7;i++) Kn[i]=dKeyC[i]; - Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output - for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; - F(Rn_1,Kn); - - if(n>=15) - { - for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; - break; - } - for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; - for(i=0;i<4;i++) dMes[i]=dMes[i+4]; - for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; - } - Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output -} -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//dMes=Message to decrypt -//dKey=Key -void ceDES::Decrypt(unsigned char *dMes,unsigned char *dKey) -{ - unsigned char n,i; - unsigned char dKeyC[8]; - for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key - - Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output - Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output - - for(n=0;n<16;n++) - { - for(i=0;i<7;i++) Kn[i]=dKeyC[i]; - Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output - for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; - F(Rn_1,Kn); - - if(n>=15) - { - for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; - break; - } - for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; - for(i=0;i<4;i++) dMes[i]=dMes[i+4]; - for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; - RightShift(dKeyC,LeftShift_table[15-n]); - } - Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output -} -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//pData =input to permutate -//ni =number of input bytes -//pTable =permutation table -//no =number of output bytes -void ceDES::Permutate(unsigned char *pData,unsigned char ni, - unsigned char *pTable,unsigned char no) -{ - unsigned char temp[8]; - unsigned char i,j,x; - unsigned char ByteI,BitIndex; - - for(i=0;i>3];//divided by 8 - BitIndex =7-(BitIndex & 7);//mod 8 - x|=((ByteI>>BitIndex) & 0x01); - } - *pData=x; - } - -} -//----------------------------------------------------------------------------- -//nKey -Key to shift -//b -number of bits -//priority to speed rather than code size -void ceDES::LeftShift(unsigned char *nKey,unsigned char b) -{ - unsigned char x,y,c; - c=8-b; - - //avoid loop to get linear code - x=nKey[6]; - nKey[6]=x<>c; - - x=nKey[5]; - nKey[5]=(x<>c; - - x=nKey[4]; - nKey[4]=(x<>c; - - x=nKey[3]; - nKey[3]=(x<>c; - - x<<=4; - nKey[6]|=x>>c; - - x=nKey[2]; - nKey[2]=(x<>c; - - x=nKey[1]; - nKey[1]=(x<>c; - - x=nKey[0]; - nKey[0]=(x<>c; - - x=(b==1)?0xEF:0xCF; - x &=nKey[3]; - nKey[3]=x|(y<<4); -} -//----------------------------------------------------------------------------- -//nKey -Key to shift -//b -number of bits -//written for speed -void ceDES::RightShift(unsigned char *nKey,unsigned char b) -{ - unsigned char x,y,c; - c=8-b; - - //avoid loop to get linear code - x=nKey[0]; - nKey[0]=x>>b; - y=x<>b)|y; - y=x<>b)|y; - y=x<>b)|y; - y=x<>=4; - nKey[0]|=x<>b)|y; - y=x<>b)|y; - y=x<>b)|y; - y=x<>4); -} -//----------------------------------------------------------------------------- -//written for speed -void ceDES::Expand(unsigned char *R) -{ - unsigned char a,b,c,d,x; - a=R[0]; - b=R[1]; - c=R[2]; - d=R[3]; - - x=(d<<7) & 0x80;//bit 32 to 1 - x|=((a>>1) & 0x7C); - x|=((a>>3) & 0x03); - R[0]=x; - - x=(a<<5) & 0xE0; - x|=(b>>3) & 0x10; - x|=(a<<3) & 0x08; - x|=(b>>5) & 0x07; - R[1]=x; - - x=(b<<3) & 0xC0; - x|=((b<<1) & 0x3E); - x|=((c>>7) & 0x01); - R[2]=x; - - x=(b<<7) & 0x80; - x|=((c>>1) & 0x7C); - x|=((c>>3) & 0x03); - R[3]=x; - - x=(c<<5) & 0xE0; - x|=(d>>3) & 0x10; - x|=(c<<3) & 0x08; - x|=(d>>5) & 0x07; - R[4]=x; - - x=(d<<3) & 0xC0; - x|=((d<<1) & 0x3E); - x|=((a>>7) & 0x01); - R[5]=x; -} -//----------------------------------------------------------------------------- -//written for speed -void ceDES::F(unsigned char *R,unsigned char *K) -{ - unsigned char i,r,c; - - //special function for expansion to improve speed - Expand(R); - - for(i=0;i<6;i++) K[i]^=R[i]; - - //R[0]=S0 S1 - c=(K[0]>>3) & 0x0F; - r=(K[0]>>2) & 1; - r|=(K[0]>>6) & 2; - R[0]=(S[0][r][c])<<4; - - c=(K[0]<<3) & 0x08; - c |=(K[1]>>5) & 0x07; - r=(K[1]>>4) & 1; - r|=(K[0] & 2); - R[0]|=(S[1][r][c]); - - //R[1]=S2 S3 - c=(K[1]<<1) & 0x0E; - c|=(K[2]>>7) & 1; - r=(K[2]>>6) & 1; - r|=(K[1]>>2) & 2; - R[1]=(S[2][r][c])<<4; - - c=(K[2]>>1) & 0x0F; - r=K[2] & 1; - r|=(K[2]>>4) & 2; - R[1]|=(S[3][r][c]); - - //R[2]=S4 S5 - c=(K[3]>>3) & 0x0F; - r=(K[3]>>2) & 1; - r|=(K[3]>>6) & 2; - R[2]=(S[4][r][c])<<4; - - c=(K[3]<<3) & 0x08; - c |=(K[4]>>5) & 0x07; - r=(K[4]>>4) & 1; - r|=(K[3] & 2); - R[2]|=(S[5][r][c]); - - //R[3]=S6 S7 - c=(K[4]<<1) & 0x0E; - c|=(K[5]>>7) & 1; - r=(K[5]>>6) & 1; - r|=(K[4]>>2) & 2; - R[3]=(S[6][r][c])<<4; - - c=(K[5]>>1) & 0x0F; - r=K[5] & 1; - r|=(K[5]>>4) & 2; - R[3]|=(S[7][r][c]); - - //Permutate the S box output - Permutate(R,4,(unsigned char *)P_table,4);//32 bit output -} -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//dMes=Message to encrypt -//dKeyL=KeyLeft -//dKeyR=KeyRight -void ceDES::Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) -{ - Encrypt(dMes,dKeyL); - Decrypt(dMes,dKeyR); - Encrypt(dMes,dKeyL); -} -//----------------------------------------------------------------------------- -//dMes=Message to decrypt -//dKeyL=KeyLeft -//dKeyR=KeyRight -void ceDES::Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) -{ - Decrypt(dMes,dKeyL); - Encrypt(dMes,dKeyR); - Decrypt(dMes,dKeyL); -} -//----------------------------------------------------------------------------- -// DES encryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes -std::string ceDES::Encrypt(std::string dMes, std::string dKey) -{ - unsigned char buf[8]; - dMes.resize(8,'\0'); - memcpy(buf, dMes.c_str(), 8); - - dKey.resize(std::max(dKey.length(), 8), '\0'); - - // check if TDES to use - if (dKey.length() > 8) { - dKey.resize(std::max(dKey.length(), 16), '\0'); - Encrypt(buf, (unsigned char*)(dKey.c_str()), (unsigned char*)(dKey.c_str() + 8)); - } - // for DES - else { - Encrypt(buf, (unsigned char*)(dKey.c_str())); - } - std::string r((char*)buf, 8); - return r; -} -//----------------------------------------------------------------------------- -// DES decryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes -std::string ceDES::Decrypt(std::string dMes, std::string dKey) -{ - unsigned char buf[8]; - dMes.resize(8, '\0'); - memcpy(buf, dMes.c_str(), 8); - - dKey.resize(std::max(dKey.length(), 8), '\0'); - - // check if TDES to use - if (dKey.length() > 8) { - dKey.resize(std::max(dKey.length(), 16), '\0'); - Decrypt(buf, (unsigned char*)(dKey.c_str()), (unsigned char*)(dKey.c_str() + 8)); - } - // for DES - else { - Decrypt(buf, (unsigned char*)(dKey.c_str())); - } - std::string r((char*)buf, 8); - return r; -} -//----------------------------------------------------------------------------- +// Description: Simple functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) +// Class implementation of the following repository: https://github.com/yan9a/ceDES +// WebSite: http://cool-emerald.blogspot.com +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2023 Yan Naing Aye + +// Related links +// https://www.rapidtables.com/convert/number/ascii-to-hex.html +// https://emvlab.org/descalc/ +// https://paymentcardtools.com/crypto-calculators/des-calculator +// https://github.com/yan9a/cecpp/blob/master/des_cryptopp/main.cpp + +#include +#include "ce/ceDES.h" +namespace ce { + //----------------------------------------------------------------------------- + // Init permutation table + // 64 bit data -> 64 bit data + const unsigned char ceDES::IP_table[64] = { + 58, 50, 42, 34, 26, 18, 10, 2, + 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, + 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, + 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, + 63, 55, 47, 39, 31, 23, 15, 7 }; + //----------------------------------------------------------------------------- + //Permuted Choice 1 + // Key permutation table + // 64 bit key data -> 56 bit key data + const unsigned char ceDES::PC1_table[56] = { + 57, 49, 41, 33, 25, 17, 9, + 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, + 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, + 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, + 21, 13, 5, 28, 20, 12, 4 }; + //----------------------------------------------------------------------------- + // Key shift table + const unsigned char ceDES::LeftShift_table[16] = { + 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; + //----------------------------------------------------------------------------- + // Key Compression permutation table + // 56 bit key data -> 48 bit + const unsigned char ceDES::PC2_table[48] = { + 14, 17, 11, 24, 1, 5, 3, 28, + 15, 6, 21, 10, 23, 19, 12, 4, + 26, 8, 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, 30, 40, + 51, 45, 33, 48, 44, 49, 39, 56, + 34, 53, 46, 42, 50, 36, 29, 32 }; + //----------------------------------------------------------------------------- + // Expansion permutation table + // 32 bit data -> 48 bit data + const unsigned char ceDES::E_table[48] = { + 32, 1, 2, 3, 4, 5, + 4, 5, 6, 7, 8, 9, + 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, + 16, 17, 18, 19, 20, 21, + 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, + 28, 29, 30, 31, 32, 1 }; + //----------------------------------------------------------------------------- + const unsigned char ceDES::S[8][4][16] = { + { + {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, + {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, + {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, + {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} + }, + { + {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, + {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, + {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, + {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} + }, + { + {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, + {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, + {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, + {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} + }, + { + {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, + {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, + {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, + {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} + }, + { + {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, + {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, + {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, + {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} + }, + { + {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, + {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, + {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, + {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} + }, + { + {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, + {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, + {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, + {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} + }, + { + {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, + {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, + {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, + {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} + } + }; + //----------------------------------------------------------------------------- + // Strait permutation table + // 32 bit data -> 32 bit data + const unsigned char ceDES::P_table[32] = { + 16, 7, 20, 21, 29, 12, 28, 17, + 1, 15, 23, 26, 5, 18, 31, 10, + 2, 8, 24, 14, 32, 27, 3, 9, + 19, 13, 30, 6, 22, 11, 4, 25 }; + //----------------------------------------------------------------------------- + // Inverse permutation table + // 64 bit data -> 64 bit data + const unsigned char ceDES::InverseIP_table[64] = { + 40, 8, 48, 16, 56, 24, 64, 32, + 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, + 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, + 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, + 33, 1, 41, 9, 49, 17, 57, 25 }; + //----------------------------------------------------------------------------- + unsigned char ceDES::Kn[7]; + unsigned char ceDES::Rn_1[6]; +//----------------------------------------------------------------------------- +//dMes=Message to encrypt +//dKey=Key +void ceDES::Encrypt(unsigned char *dMes,unsigned char *dKey) +{ + unsigned char n,i; + unsigned char dKeyC[8]; + for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key + + Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output + Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output + for(n=0;n<16;n++) + { + LeftShift(dKeyC,LeftShift_table[n]); + for(i=0;i<7;i++) Kn[i]=dKeyC[i]; + Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output + for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; + F(Rn_1,Kn); + + if(n>=15) + { + for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; + break; + } + for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; + for(i=0;i<4;i++) dMes[i]=dMes[i+4]; + for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; + } + Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output +} +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//dMes=Message to decrypt +//dKey=Key +void ceDES::Decrypt(unsigned char *dMes,unsigned char *dKey) +{ + unsigned char n,i; + unsigned char dKeyC[8]; + for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key + + Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output + Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output + + for(n=0;n<16;n++) + { + for(i=0;i<7;i++) Kn[i]=dKeyC[i]; + Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output + for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; + F(Rn_1,Kn); + + if(n>=15) + { + for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; + break; + } + for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; + for(i=0;i<4;i++) dMes[i]=dMes[i+4]; + for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; + RightShift(dKeyC,LeftShift_table[15-n]); + } + Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output +} +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//pData =input to permutate +//ni =number of input bytes +//pTable =permutation table +//no =number of output bytes +void ceDES::Permutate(unsigned char *pData,unsigned char ni, + unsigned char *pTable,unsigned char no) +{ + unsigned char temp[8]; + unsigned char i,j,x; + unsigned char ByteI,BitIndex; + + for(i=0;i>3];//divided by 8 + BitIndex =7-(BitIndex & 7);//mod 8 + x|=((ByteI>>BitIndex) & 0x01); + } + *pData=x; + } + +} +//----------------------------------------------------------------------------- +//nKey -Key to shift +//b -number of bits +//priority to speed rather than code size +void ceDES::LeftShift(unsigned char *nKey,unsigned char b) +{ + unsigned char x,y,c; + c=8-b; + + //avoid loop to get linear code + x=nKey[6]; + nKey[6]=x<>c; + + x=nKey[5]; + nKey[5]=(x<>c; + + x=nKey[4]; + nKey[4]=(x<>c; + + x=nKey[3]; + nKey[3]=(x<>c; + + x<<=4; + nKey[6]|=x>>c; + + x=nKey[2]; + nKey[2]=(x<>c; + + x=nKey[1]; + nKey[1]=(x<>c; + + x=nKey[0]; + nKey[0]=(x<>c; + + x=(b==1)?0xEF:0xCF; + x &=nKey[3]; + nKey[3]=x|(y<<4); +} +//----------------------------------------------------------------------------- +//nKey -Key to shift +//b -number of bits +//written for speed +void ceDES::RightShift(unsigned char *nKey,unsigned char b) +{ + unsigned char x,y,c; + c=8-b; + + //avoid loop to get linear code + x=nKey[0]; + nKey[0]=x>>b; + y=x<>b)|y; + y=x<>b)|y; + y=x<>b)|y; + y=x<>=4; + nKey[0]|=x<>b)|y; + y=x<>b)|y; + y=x<>b)|y; + y=x<>4); +} +//----------------------------------------------------------------------------- +//written for speed +void ceDES::Expand(unsigned char *R) +{ + unsigned char a,b,c,d,x; + a=R[0]; + b=R[1]; + c=R[2]; + d=R[3]; + + x=(d<<7) & 0x80;//bit 32 to 1 + x|=((a>>1) & 0x7C); + x|=((a>>3) & 0x03); + R[0]=x; + + x=(a<<5) & 0xE0; + x|=(b>>3) & 0x10; + x|=(a<<3) & 0x08; + x|=(b>>5) & 0x07; + R[1]=x; + + x=(b<<3) & 0xC0; + x|=((b<<1) & 0x3E); + x|=((c>>7) & 0x01); + R[2]=x; + + x=(b<<7) & 0x80; + x|=((c>>1) & 0x7C); + x|=((c>>3) & 0x03); + R[3]=x; + + x=(c<<5) & 0xE0; + x|=(d>>3) & 0x10; + x|=(c<<3) & 0x08; + x|=(d>>5) & 0x07; + R[4]=x; + + x=(d<<3) & 0xC0; + x|=((d<<1) & 0x3E); + x|=((a>>7) & 0x01); + R[5]=x; +} +//----------------------------------------------------------------------------- +//written for speed +void ceDES::F(unsigned char *R,unsigned char *K) +{ + unsigned char i,r,c; + + //special function for expansion to improve speed + Expand(R); + + for(i=0;i<6;i++) K[i]^=R[i]; + + //R[0]=S0 S1 + c=(K[0]>>3) & 0x0F; + r=(K[0]>>2) & 1; + r|=(K[0]>>6) & 2; + R[0]=(S[0][r][c])<<4; + + c=(K[0]<<3) & 0x08; + c |=(K[1]>>5) & 0x07; + r=(K[1]>>4) & 1; + r|=(K[0] & 2); + R[0]|=(S[1][r][c]); + + //R[1]=S2 S3 + c=(K[1]<<1) & 0x0E; + c|=(K[2]>>7) & 1; + r=(K[2]>>6) & 1; + r|=(K[1]>>2) & 2; + R[1]=(S[2][r][c])<<4; + + c=(K[2]>>1) & 0x0F; + r=K[2] & 1; + r|=(K[2]>>4) & 2; + R[1]|=(S[3][r][c]); + + //R[2]=S4 S5 + c=(K[3]>>3) & 0x0F; + r=(K[3]>>2) & 1; + r|=(K[3]>>6) & 2; + R[2]=(S[4][r][c])<<4; + + c=(K[3]<<3) & 0x08; + c |=(K[4]>>5) & 0x07; + r=(K[4]>>4) & 1; + r|=(K[3] & 2); + R[2]|=(S[5][r][c]); + + //R[3]=S6 S7 + c=(K[4]<<1) & 0x0E; + c|=(K[5]>>7) & 1; + r=(K[5]>>6) & 1; + r|=(K[4]>>2) & 2; + R[3]=(S[6][r][c])<<4; + + c=(K[5]>>1) & 0x0F; + r=K[5] & 1; + r|=(K[5]>>4) & 2; + R[3]|=(S[7][r][c]); + + //Permutate the S box output + Permutate(R,4,(unsigned char *)P_table,4);//32 bit output +} +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//dMes=Message to encrypt +//dKeyL=KeyLeft +//dKeyR=KeyRight +void ceDES::Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) +{ + Encrypt(dMes,dKeyL); + Decrypt(dMes,dKeyR); + Encrypt(dMes,dKeyL); +} +//----------------------------------------------------------------------------- +//dMes=Message to decrypt +//dKeyL=KeyLeft +//dKeyR=KeyRight +void ceDES::Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) +{ + Decrypt(dMes,dKeyL); + Encrypt(dMes,dKeyR); + Decrypt(dMes,dKeyL); +} +//----------------------------------------------------------------------------- +// DES encryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes +std::string ceDES::Encrypt(std::string dMes, std::string dKey) +{ + unsigned char buf[8]; + dMes.resize(8,'\0'); + memcpy(buf, dMes.c_str(), 8); + + dKey.resize(std::max(dKey.length(), 8), '\0'); + + // check if TDES to use + if (dKey.length() > 8) { + dKey.resize(std::max(dKey.length(), 16), '\0'); + Encrypt(buf, (unsigned char*)(dKey.c_str()), (unsigned char*)(dKey.c_str() + 8)); + } + // for DES + else { + Encrypt(buf, (unsigned char*)(dKey.c_str())); + } + std::string r((char*)buf, 8); + return r; +} +//----------------------------------------------------------------------------- +// DES decryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes +std::string ceDES::Decrypt(std::string dMes, std::string dKey) +{ + unsigned char buf[8]; + dMes.resize(8, '\0'); + memcpy(buf, dMes.c_str(), 8); + + dKey.resize(std::max(dKey.length(), 8), '\0'); + + // check if TDES to use + if (dKey.length() > 8) { + dKey.resize(std::max(dKey.length(), 16), '\0'); + Decrypt(buf, (unsigned char*)(dKey.c_str()), (unsigned char*)(dKey.c_str() + 8)); + } + // for DES + else { + Decrypt(buf, (unsigned char*)(dKey.c_str())); + } + std::string r((char*)buf, 8); + return r; +} +//----------------------------------------------------------------------------- } // namespace ce \ No newline at end of file diff --git a/src/ceFraChecksum.cpp b/src/ceFraChecksum.cpp index c2fb7ed..2a9815f 100644 --- a/src/ceFraChecksum.cpp +++ b/src/ceFraChecksum.cpp @@ -1,105 +1,105 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceFraChecksum.cpp -// Description: Byte stuffing- sending and receiving frames with checksum -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceFraChecksum.h" -namespace ce { -//----------------------------------------------------------------------------- -ceFraChecksum::ceFraChecksum() :TxN(0), RxN(0), rState(CE_FRAME_IGNORE) { - rb[0] = 0; - tb[0] = 0; -} -//----------------------------------------------------------------------------- -char* ceFraChecksum::GetTxBuf() { - return tb; -} -//----------------------------------------------------------------------------- -char* ceFraChecksum::GetRxBuf() { - return rb; -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -size_t ceFraChecksum::SetTxFrame(char* d, size_t n) -{ - char c; - int i = 0, j = 0; - tb[i++] = STX;//start of frame - for (j = 0; j < n; j++) { - c = d[j]; - if ((c == STX) || (c == ETX) || (c == DLE)) tb[i++] = (DLE); - tb[i++] = c; - } - tb[i++] = (ETX);//end of frame - tb[i++] = Checksum(d, n);//calculate CS - TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -//Inputs -//s : pointer to input char string -//len: string len - -//Output -//Returns calculated Checksum -uint8_t ceFraChecksum::Checksum(char* s, size_t len) -{ - uint8_t cs = 0; // check sum - for (size_t i = 0; i < len; i++, s++) { - cs ^= (uint8_t)(*s); - } - return cs; -} -//----------------------------------------------------------------------------- -//get number of transmitting bytes -size_t ceFraChecksum::GetTxN() -{ - return TxN; -} -//----------------------------------------------------------------------------- -//get number of receiving bytes -size_t ceFraChecksum::GetRxN() -{ - return RxN; -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -size_t ceFraChecksum::ReceiveRxFrame(char c) -{ - uint8_t cs; - uint8_t rxcs; - switch (rState) { - case CE_FRAME_RECEIVING: - if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } - else if (c == ETX) { rState = CE_FRAME_CHKSUM; } - else if (c == DLE) { rState = CE_FRAME_ESCAPE; } - else { rb[RxN++] = c; } - break; - case CE_FRAME_ESCAPE: - rb[RxN++] = c; rState = CE_FRAME_RECEIVING; - break; - case CE_FRAME_CHKSUM: - rxcs = c; - rState = CE_FRAME_IGNORE; - cs = Checksum(rb, RxN);//calculate crc - //printf("cs: %x rxcs: %x \n",cs,rxcs); - if (rxcs == cs) { return RxN; }//if cs is correct - else { RxN = 0; }//discard the frame - break; - default: //case CE_FRAME_IGNORE: - if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } - break; - } - - if (RxN >= CE_FRAME_RX_BUF_SIZE) { - RxN = 0; - rState = CE_FRAME_IGNORE; - } - - return 0; -} - +///////////////////////////////////////////////////////////////////////////// +// Name: ceFraChecksum.cpp +// Description: Byte stuffing- sending and receiving frames with checksum +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html +///////////////////////////////////////////////////////////////////////////// +#include +#include "ce/ceFraChecksum.h" +namespace ce { +//----------------------------------------------------------------------------- +ceFraChecksum::ceFraChecksum() :TxN(0), RxN(0), rState(CE_FRAME_IGNORE) { + rb[0] = 0; + tb[0] = 0; +} +//----------------------------------------------------------------------------- +char* ceFraChecksum::GetTxBuf() { + return tb; +} +//----------------------------------------------------------------------------- +char* ceFraChecksum::GetRxBuf() { + return rb; +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +size_t ceFraChecksum::SetTxFrame(char* d, size_t n) +{ + char c; + int i = 0, j = 0; + tb[i++] = STX;//start of frame + for (j = 0; j < n; j++) { + c = d[j]; + if ((c == STX) || (c == ETX) || (c == DLE)) tb[i++] = (DLE); + tb[i++] = c; + } + tb[i++] = (ETX);//end of frame + tb[i++] = Checksum(d, n);//calculate CS + TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +//Inputs +//s : pointer to input char string +//len: string len + +//Output +//Returns calculated Checksum +uint8_t ceFraChecksum::Checksum(char* s, size_t len) +{ + uint8_t cs = 0; // check sum + for (size_t i = 0; i < len; i++, s++) { + cs ^= (uint8_t)(*s); + } + return cs; +} +//----------------------------------------------------------------------------- +//get number of transmitting bytes +size_t ceFraChecksum::GetTxN() +{ + return TxN; +} +//----------------------------------------------------------------------------- +//get number of receiving bytes +size_t ceFraChecksum::GetRxN() +{ + return RxN; +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +size_t ceFraChecksum::ReceiveRxFrame(char c) +{ + uint8_t cs; + uint8_t rxcs; + switch (rState) { + case CE_FRAME_RECEIVING: + if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } + else if (c == ETX) { rState = CE_FRAME_CHKSUM; } + else if (c == DLE) { rState = CE_FRAME_ESCAPE; } + else { rb[RxN++] = c; } + break; + case CE_FRAME_ESCAPE: + rb[RxN++] = c; rState = CE_FRAME_RECEIVING; + break; + case CE_FRAME_CHKSUM: + rxcs = c; + rState = CE_FRAME_IGNORE; + cs = Checksum(rb, RxN);//calculate crc + //printf("cs: %x rxcs: %x \n",cs,rxcs); + if (rxcs == cs) { return RxN; }//if cs is correct + else { RxN = 0; }//discard the frame + break; + default: //case CE_FRAME_IGNORE: + if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } + break; + } + + if (RxN >= CE_FRAME_RX_BUF_SIZE) { + RxN = 0; + rState = CE_FRAME_IGNORE; + } + + return 0; +} + } // namespace ce \ No newline at end of file diff --git a/src/ceFraCmd.cpp b/src/ceFraCmd.cpp index 4b6db71..502d4be 100644 --- a/src/ceFraCmd.cpp +++ b/src/ceFraCmd.cpp @@ -1,47 +1,47 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceFraCmd.cpp -// Description: Byte stuffing- sending and receiving commands as frames -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceFraCmd.h" -namespace ce { -//----------------------------------------------------------------------------- -ceFraCmd::ceFraCmd():ceFrame(){ - -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -size_t ceFraCmd::SetTxFrame(char* d, size_t n) -{ - int i = 0; - if (n >= CE_FRAME_TX_BUF_SIZE) n = CE_FRAME_TX_BUF_SIZE - 1; //discard policy - for (int j = 0; j < n; j++) { - tb[i++] = d[j]; - } - tb[i++] = 0x0D;//end of frame - TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -size_t ceFraCmd::ReceiveRxFrame(char ch) -{ - static int n = 0; - if (ch >= 32 && ch <= 126) { - this->rb[n++] = ch; - this->RxN = 0; - } - - if (ch == 0x0D || n >= (CE_FRAME_RX_BUF_SIZE -1)) { - this->RxN = n; - this->rb[n] = 0;//null termination - n = 0; - return this->RxN; - } - return 0; -} - +///////////////////////////////////////////////////////////////////////////// +// Name: ceFraCmd.cpp +// Description: Byte stuffing- sending and receiving commands as frames +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html +///////////////////////////////////////////////////////////////////////////// +#include +#include "ce/ceFraCmd.h" +namespace ce { +//----------------------------------------------------------------------------- +ceFraCmd::ceFraCmd():ceFrame(){ + +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +size_t ceFraCmd::SetTxFrame(char* d, size_t n) +{ + int i = 0; + if (n >= CE_FRAME_TX_BUF_SIZE) n = CE_FRAME_TX_BUF_SIZE - 1; //discard policy + for (int j = 0; j < n; j++) { + tb[i++] = d[j]; + } + tb[i++] = 0x0D;//end of frame + TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +size_t ceFraCmd::ReceiveRxFrame(char ch) +{ + static int n = 0; + if (ch >= 32 && ch <= 126) { + this->rb[n++] = ch; + this->RxN = 0; + } + + if (ch == 0x0D || n >= (CE_FRAME_RX_BUF_SIZE -1)) { + this->RxN = n; + this->rb[n] = 0;//null termination + n = 0; + return this->RxN; + } + return 0; +} + } // namespace ce \ No newline at end of file diff --git a/src/ceInterface.cpp b/src/ceInterface.cpp index 308a4c8..3da89ce 100644 --- a/src/ceInterface.cpp +++ b/src/ceInterface.cpp @@ -1,25 +1,25 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceInterface.h -// Description: Interface to communitcate modules -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/ceInterface.h" -namespace ce { -//----------------------------------------------------------------------------- -ceInterface::ceInterface() { - -} -//----------------------------------------------------------------------------- -ceInterface::ceInterface(std::function,std::string,int>)> cbf): _cbf(cbf) { - -} -//----------------------------------------------------------------------------- -void ceInterface::setRxCallback(std::function,std::string,int>)> cbf) { - _cbf = cbf; -} -//----------------------------------------------------------------------------- -void ceInterface::check(){ - -} -//----------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// +// Name: ceInterface.h +// Description: Interface to communitcate modules +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// +#include "ce/ceInterface.h" +namespace ce { +//----------------------------------------------------------------------------- +ceInterface::ceInterface() { + +} +//----------------------------------------------------------------------------- +ceInterface::ceInterface(std::function,std::string,int>)> cbf): _cbf(cbf) { + +} +//----------------------------------------------------------------------------- +void ceInterface::setRxCallback(std::function,std::string,int>)> cbf) { + _cbf = cbf; +} +//----------------------------------------------------------------------------- +void ceInterface::check(){ + +} +//----------------------------------------------------------------------------- } // namespace ce \ No newline at end of file diff --git a/src/ceMisc.cpp b/src/ceMisc.cpp index 1994a0d..50d8de6 100644 --- a/src/ceMisc.cpp +++ b/src/ceMisc.cpp @@ -1,219 +1,219 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceMisc.cpp -// Description: utility module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/ceMisc.h" -using namespace std; -namespace ce { - -// filter the string for alphanumeric characters only -string ceMisc::alnum(string str) -{ - str.erase(remove_if(str.begin(), str.end(), [](char ch) { - return !( - (ch >= '0' && ch <= '9') || - (ch >= 'A' && ch <= 'Z') || - (ch >= 'a' && ch <= 'z')); }), str.end()); - return str; -} - -// convert hex string to char vector -vector ceMisc::hex2cvec(string str) -{ - vector v; - str = ceMisc::alnum(str);// filter for alphanumeric characters - int n = (int)str.length(); - for (int i = 0; i < n; i += 2) - v.push_back((char)stoi(str.substr(i, 2), NULL, 16)); - return v; -} - -// convert hex string to byte string -std::string ceMisc::hex2str(std::string str) -{ - return ceMisc::cvec2str(ceMisc::hex2cvec(str)); -} - -// convert to hexadecimal string -std::string ceMisc::ToStr16(unsigned int u) -{ - ostringstream ss; - ss << setfill('0') << setw(2) << uppercase << hex << u; - return ss.str(); -} - -std::string ceMisc::ToStr16(int i) -{ - return ceMisc::ToStr16((unsigned int)i); -} - -std::string ceMisc::ToStr16(unsigned char c) -{ - return ceMisc::ToStr16((unsigned int)c); -} - -std::string ceMisc::ToStr16(char c) -{ - return ceMisc::ToStr16((unsigned char)c); -} - -// convert vector to hexadecimal string -std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { - std::vector uv(bv.begin(), bv.end()); - return ceMisc::ToStr16(uv,separator,prefix,postfix); -} - -// convert vector to hexadecimal string -std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { - ostringstream ss; - unsigned int u; - for (auto& c : bv) { - u = (unsigned char)c; - ss << prefix; - ss << setfill('0') << setw(2) << uppercase << hex << u << postfix; - if (&c != &bv.back()) ss << separator; - } - return ss.str(); -} - -// to hexadecimal string -std::string ceMisc::ToStr16(std::string str, std::string separator, std::string prefix, std::string postfix) -{ - return ceMisc::ToStr16(ceMisc::str2cvec(str), separator, prefix, postfix); -} - -// convert char vector to hex string -string ceMisc::cvec2hex(vector bv) { - ostringstream ss; - unsigned int u; - for (char& c : bv) { - u = (unsigned char)c; - ss << setfill('0') << setw(2) << uppercase << hex << u << " "; - } - return ss.str(); -} - -// convert char vector to string -string ceMisc::cvec2str(vector bv) { - ostringstream ss; - for (char& c : bv) { - ss << c; - } - return ss.str(); -} - - -// character vector to char* -void ceMisc::cvec2cptr(vector& v, char*& cstr, int& n) { - n = (int)v.size(); - cstr = v.data(); // reinterpret_cast(v.data()); -} - -// char* to char vector -vector ceMisc::cptr2cvec(char* cstr,int n) { - vector v(cstr, cstr + n); - return v; -} - -// convert char* to string -string ceMisc::cptr2str(char* cstr, int n) { - ostringstream ss; - for (int i = 0; i < n;i++) { - ss << cstr[i]; - } - return ss.str(); -} - -// string to char vector -vector ceMisc::str2cvec(string str) { - vector v(str.begin(), str.end()); - return v; -} - -string ceMisc::f2s(float f, int n) { - stringstream ss; - ss< ceMisc::splitStr(string str, string delimiter) -{ - size_t pos = 0; - vector tokens; - while ((pos = str.find(delimiter)) != string::npos) { - tokens.push_back(str.substr(0, pos)); - str.erase(0, pos + delimiter.length()); - } - tokens.push_back(str); - return tokens; -} - -std::string ceMisc::exepath() -{ -#ifdef CE_WINDOWS - char result[MAX_PATH]; - return std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); -#else - char result[PATH_MAX]; - ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); - return std::string(result, (count > 0) ? count : 0); -#endif -} - -std::string ceMisc::exedir() -{ - std::string str = exepath(); - std::size_t found = str.find_last_of("/\\"); - return str.substr(0, found + 1); -} - -bool ceMisc::kb_hit() // check keyboard hit -{ -#if defined(CE_WINDOWS) - return _kbhit(); -#else - // https://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux - termios term; - tcgetattr(0, &term); - - termios term2 = term; - term2.c_lflag &= ~ICANON; - tcsetattr(0, TCSANOW, &term2); - - int byteswaiting; - ioctl(0, FIONREAD, &byteswaiting); - - tcsetattr(0, TCSANOW, &term); - - return byteswaiting > 0; -#endif -} - -char ceMisc::get_ch() // get char -{ -#if defined(CE_WINDOWS) - return _getch(); -#else - //https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed - char buf = 0; - struct termios old = { 0 }; - if (tcgetattr(0, &old) < 0) - perror("tcsetattr()"); - old.c_lflag &= ~ICANON; - old.c_lflag &= ~ECHO; - old.c_cc[VMIN] = 1; - old.c_cc[VTIME] = 0; - if (tcsetattr(0, TCSANOW, &old) < 0) - perror("tcsetattr ICANON"); - if (read(0, &buf, 1) < 0) - perror("read()"); - old.c_lflag |= ICANON; - old.c_lflag |= ECHO; - if (tcsetattr(0, TCSADRAIN, &old) < 0) - perror("tcsetattr ~ICANON"); - return (buf); -#endif -} - +///////////////////////////////////////////////////////////////////////////// +// Name: ceMisc.cpp +// Description: utility module +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// +#include "ce/ceMisc.h" +using namespace std; +namespace ce { + +// filter the string for alphanumeric characters only +string ceMisc::alnum(string str) +{ + str.erase(remove_if(str.begin(), str.end(), [](char ch) { + return !( + (ch >= '0' && ch <= '9') || + (ch >= 'A' && ch <= 'Z') || + (ch >= 'a' && ch <= 'z')); }), str.end()); + return str; +} + +// convert hex string to char vector +vector ceMisc::hex2cvec(string str) +{ + vector v; + str = ceMisc::alnum(str);// filter for alphanumeric characters + int n = (int)str.length(); + for (int i = 0; i < n; i += 2) + v.push_back((char)stoi(str.substr(i, 2), NULL, 16)); + return v; +} + +// convert hex string to byte string +std::string ceMisc::hex2str(std::string str) +{ + return ceMisc::cvec2str(ceMisc::hex2cvec(str)); +} + +// convert to hexadecimal string +std::string ceMisc::ToStr16(unsigned int u) +{ + ostringstream ss; + ss << setfill('0') << setw(2) << uppercase << hex << u; + return ss.str(); +} + +std::string ceMisc::ToStr16(int i) +{ + return ceMisc::ToStr16((unsigned int)i); +} + +std::string ceMisc::ToStr16(unsigned char c) +{ + return ceMisc::ToStr16((unsigned int)c); +} + +std::string ceMisc::ToStr16(char c) +{ + return ceMisc::ToStr16((unsigned char)c); +} + +// convert vector to hexadecimal string +std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { + std::vector uv(bv.begin(), bv.end()); + return ceMisc::ToStr16(uv,separator,prefix,postfix); +} + +// convert vector to hexadecimal string +std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { + ostringstream ss; + unsigned int u; + for (auto& c : bv) { + u = (unsigned char)c; + ss << prefix; + ss << setfill('0') << setw(2) << uppercase << hex << u << postfix; + if (&c != &bv.back()) ss << separator; + } + return ss.str(); +} + +// to hexadecimal string +std::string ceMisc::ToStr16(std::string str, std::string separator, std::string prefix, std::string postfix) +{ + return ceMisc::ToStr16(ceMisc::str2cvec(str), separator, prefix, postfix); +} + +// convert char vector to hex string +string ceMisc::cvec2hex(vector bv) { + ostringstream ss; + unsigned int u; + for (char& c : bv) { + u = (unsigned char)c; + ss << setfill('0') << setw(2) << uppercase << hex << u << " "; + } + return ss.str(); +} + +// convert char vector to string +string ceMisc::cvec2str(vector bv) { + ostringstream ss; + for (char& c : bv) { + ss << c; + } + return ss.str(); +} + + +// character vector to char* +void ceMisc::cvec2cptr(vector& v, char*& cstr, int& n) { + n = (int)v.size(); + cstr = v.data(); // reinterpret_cast(v.data()); +} + +// char* to char vector +vector ceMisc::cptr2cvec(char* cstr,int n) { + vector v(cstr, cstr + n); + return v; +} + +// convert char* to string +string ceMisc::cptr2str(char* cstr, int n) { + ostringstream ss; + for (int i = 0; i < n;i++) { + ss << cstr[i]; + } + return ss.str(); +} + +// string to char vector +vector ceMisc::str2cvec(string str) { + vector v(str.begin(), str.end()); + return v; +} + +string ceMisc::f2s(float f, int n) { + stringstream ss; + ss< ceMisc::splitStr(string str, string delimiter) +{ + size_t pos = 0; + vector tokens; + while ((pos = str.find(delimiter)) != string::npos) { + tokens.push_back(str.substr(0, pos)); + str.erase(0, pos + delimiter.length()); + } + tokens.push_back(str); + return tokens; +} + +std::string ceMisc::exepath() +{ +#ifdef CE_WINDOWS + char result[MAX_PATH]; + return std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); +#else + char result[PATH_MAX]; + ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); + return std::string(result, (count > 0) ? count : 0); +#endif +} + +std::string ceMisc::exedir() +{ + std::string str = exepath(); + std::size_t found = str.find_last_of("/\\"); + return str.substr(0, found + 1); +} + +bool ceMisc::kb_hit() // check keyboard hit +{ +#if defined(CE_WINDOWS) + return _kbhit(); +#else + // https://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux + termios term; + tcgetattr(0, &term); + + termios term2 = term; + term2.c_lflag &= ~ICANON; + tcsetattr(0, TCSANOW, &term2); + + int byteswaiting; + ioctl(0, FIONREAD, &byteswaiting); + + tcsetattr(0, TCSANOW, &term); + + return byteswaiting > 0; +#endif +} + +char ceMisc::get_ch() // get char +{ +#if defined(CE_WINDOWS) + return _getch(); +#else + //https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed + char buf = 0; + struct termios old = { 0 }; + if (tcgetattr(0, &old) < 0) + perror("tcsetattr()"); + old.c_lflag &= ~ICANON; + old.c_lflag &= ~ECHO; + old.c_cc[VMIN] = 1; + old.c_cc[VTIME] = 0; + if (tcsetattr(0, TCSANOW, &old) < 0) + perror("tcsetattr ICANON"); + if (read(0, &buf, 1) < 0) + perror("read()"); + old.c_lflag |= ICANON; + old.c_lflag |= ECHO; + if (tcsetattr(0, TCSADRAIN, &old) < 0) + perror("tcsetattr ~ICANON"); + return (buf); +#endif +} + } // namespace ce \ No newline at end of file diff --git a/src/ceMmDateTime.cpp b/src/ceMmDateTime.cpp index 3863870..ad7fd85 100644 --- a/src/ceMmDateTime.cpp +++ b/src/ceMmDateTime.cpp @@ -1,870 +1,870 @@ -// File: ceMmDateTime.cpp -// Description: Modern Myanmar Calendrical Calculations -// WebSite: https://yan9a.github.io/mcal/ -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye -// Doc: http://cool-emerald.blogspot.com/2013/06/algorithm-program-and-calculation-of.html -//------------------------------------------------------------------------- -#include"ce/ceMmDateTime.h" -#include - -using namespace std; - -namespace ce { -//------------------------------------------------------------------------- -// default constructor -ceMmDateTime::ceMmDateTime():ceDateTime() -{ - -} -//------------------------------------------------------------------------- -// Get Myanmar year constants depending on era -// Thanks to Myo Zarny and Wunna Ko for earlier Myanmar years data -// input: my -myanmar year -// output: -// EI = Myanmar calendar era id [1-3] : calculations methods/constants depends on era -// WO = watat offset to compensate -// NM = number of months to find excess days -// EW = exception in watat year -void ceMmDateTime::GetMyConst(long my, double& EI, double& WO, double& NM, long& EW) -{ - EW = 0; long (*fme)[2]; long* wte; long i=-1,uf,uw; - // The third era (the era after Independence 1312 ME and after) - if (my >= 1312) { - EI = 3; WO = -0.5; NM = 8; - long fme3[][2] = { {1377, 1} }; - long wte3[] = { 1344, 1345 }; - fme = fme3; wte = wte3; - uf=long(sizeof(fme3)/sizeof(fme3[0])); - uw=long(sizeof(wte3)/sizeof(wte3[0])); - } - // The second era (the era under British colony: 1217 ME - 1311 ME) - else if (my >= 1217) { - EI = 2; WO = -1; NM = 4; - long fme2[][2] = { {1234, 1},{1261, -1} }; - long wte2[] = { 1263, 1264 }; - fme = fme2; wte = wte2; - uf=long(sizeof(fme2)/sizeof(fme2[0])); - uw=long(sizeof(wte2)/sizeof(wte2[0])); - } - // The first era (the era of Myanmar kings: ME1216 and before) - // Thandeikta (ME 1100 - 1216) - else if (my >= 1100) { - EI = 1.3; WO = -0.85; NM = -1; - long fme13[][2] = {{1120, 1}, {1126, -1}, {1150, 1}, {1172, -1}, {1207, 1}}; - long wte13[] = {1201, 1202}; - fme = fme13; wte = wte13; - uf=long(sizeof(fme13)/sizeof(fme13[0])); - uw=long(sizeof(wte13)/sizeof(wte13[0])); - } - // Makaranta system 2 (ME 798 - 1099) - else if (my >= 798) { - EI = 1.2; WO = -1.1; NM = -1; - long fme12[][2] = {{813, -1}, {849, -1}, {851, -1}, {854, -1}, {927, -1}, - {933, -1}, {936, -1}, {938, -1}, {949, -1}, {952, -1}, {963, -1}, {968, -1}, {1039, -1}}; - long wte12[] = {-9999}; - fme = fme12; wte = wte12; - uf=long(sizeof(fme12)/sizeof(fme12[0])); - uw=long(sizeof(wte12)/sizeof(wte12[0])); - } - // Makaranta system 1 (ME 0 - 797) - else { - EI = 1.1; WO = -1.1; NM = -1; - long fme11[][2] = {{205, 1}, {246, 1}, {471, 1}, {572, -1}, {651, 1}, - {653, 2}, {656, 1}, {672, 1}, {729, 1}, {767, -1}}; - long wte11[] = {-9999}; - fme = fme11; wte = wte11; - uf=long(sizeof(fme11)/sizeof(fme11[0])); - uw=long(sizeof(wte11)/sizeof(wte11[0])); - } - i = ceMmDateTime::bSearch2(my, fme,uf); if (i >= 0) WO += fme[i][1]; // full moon day offset exceptions - i = ceMmDateTime::bSearch1(my, wte,uw); if (i >= 0) EW = 1; //correct watat exceptions -} -//---------------------------------------------------------------------------- -// Search first dimension in a 2D array -// input: (k=key,A=array,u=size) -// output: (i=index) -long ceMmDateTime::bSearch2(long k,long (*A)[2], long u) { - long i = 0; long l = 0; u--; - while(u>=l) { - i=long(floor((l+u)/2)); - if (A[i][0]>k) u=i-1; - else if (A[i][0]=l) { - i=long(floor((l+u)/2)); - if (A[i]>k) u=i-1; - else if (A[i]= 2) {//if 2nd era or later find watat based on excess days - TW=LM-(SY/12-LM)*NM; - if(ed >= TW) watat=1; - } - else {//if 1st era,find watat by 19 years metonic cycle - //Myanmar year is divided by 19 and there is intercalary month - //if the remainder is 2,5,7,10,13,15,18 - //https://github.com/kanasimi/CeJS/blob/master/data/date/calendar.js#L2330 - watat=(my*7+2)%19; if (watat < 0) watat+=19; - watat=long(floor(watat/12)); - } - watat^=EW;//correct watat exceptions -} -//------------------------------------------------------------------------- -// Check Myanmar Year -// input: (my -myanmar year) -// output: ( myt :year type [0=common, 1=little watat, 2=big watat], -// tg1 : the 1st day of Tagu as jdn_mm (Julian Day Number for MMT) -// fm : full moon day of [2nd] Waso as Julain Day Number -// werr: watat error [0=ok, 1= error]) -// dependency: cal_watat(my) -void ceMmDateTime::cal_my(long my, long& myt, long& tg1, long& fm, long& werr) { - long yd = 0, nd = 0, y1watat, y1fm, y2watat, y2fm; werr = 0; - ceMmDateTime::cal_watat(my,y2watat,y2fm); myt = y2watat; - do { yd++; ceMmDateTime::cal_watat(my - yd,y1watat,y1fm); } while (y1watat == 0 && yd < 3); - if (myt) { - nd = (y2fm - y1fm) % 354; myt = long(floor(nd / 31)+ 1); - fm = y2fm; if (nd != 30 && nd != 31) { werr = 1; } - } - else fm = y1fm + 354 * yd; - tg1 = y1fm + 354 * yd - 102; -} -//------------------------------------------------------------------------- -// Julian day number to Myanmar date -// input: (jdn -julian day number) -// output: ( - // myt =year type [0=common, 1=little watat, 2=big watat], - // my = year, - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md = day of the month [1 to 30]) -// dependency: cal_my(my) -void ceMmDateTime::j2m(double jd, long& myt, long& my, long& mm, long& md) { - long jdn=long(round(jd));//convert jdn to integer - double SY=1577917828.0/4320000.0; //solar year (365.2587565) - double MO=1954168.050623; //beginning of 0 ME - long dd,myl,mmt,a,b,c,e,f; - long tg1,fm,werr; - my=long(floor((jdn-0.5-MO)/SY));//Myanmar year - ceMmDateTime::cal_my(my,myt,tg1,fm,werr);//check year - dd=jdn-tg1+1;//day count - b=long(floor(myt/2)); c=long(floor(1/(myt+1))); //big wa and common yr - myl=354+(1-c)*30+b;//year length - mmt=long(floor((dd-1)/myl));//month type: late =1 or early = 0 - dd-=mmt*myl; a=long(floor((dd+423)/512)); //adjust day count and threshold - mm=long(floor((dd-b*a+c*a*30+29.26)/29.544));//month - e=long(floor((mm+12)/16)); f=long(floor((mm+11)/16)); - md=dd-long(floor(29.544*mm-29.26))-b*e+c*f*30;//day - mm+=f*3-e*4+12*mmt; // adjust month numbers for late months -} -//------------------------------------------------------------------------- -// Get moon phase from day of the month, month, and year type. -// input: ( -// md= day of the month [1-30], -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// myt = year type [0=common, 1=little watat, 2=big watat]) -// output: (mp =moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon]) -long ceMmDateTime::cal_mp(long md,long mm,long myt) { - long mml=ceMmDateTime::cal_mml(mm,myt); - return long(floor((md+1)/16)+floor(md/16)+floor(md/mml)); -} -//------------------------------------------------------------------------- -// Get length of month from month, and year type. -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// myt = year type [0=common, 1=little watat, 2=big watat]) -// output: (mml = length of the month [29 or 30 days]) -long ceMmDateTime::cal_mml(long mm,long myt) { - long mml=30-mm%2;//month length - if(mm==3) mml+=long(floor(myt/2));//adjust if Nayon in big watat - return mml; -} -//------------------------------------------------------------------------- -// Get the apparent length of the year from year type. -// input: ( myt = year type [0=common, 1=little watat, 2=big watat]) -// output: ( myl= year length [354, 384, or 385 days]) -long ceMmDateTime::cal_myl(long myt) { - return (354+(1-long(floor(1/(myt+1))))*30+long(floor(myt/2))); -} -//------------------------------------------------------------------------- -// Get fortnight day from month day -// input: ( md= day of the month [1-30]) -// output: (mf= fortnight day [1 to 15]) -long ceMmDateTime::cal_mf(long md) { - return (md-15*long(floor(md/16))); -} -//------------------------------------------------------------------------- -// Get day of month from fortnight day, moon phase, and length of the month -// input: ( -// mf = fortnight day [1 to 15], -// mp = moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// myt = year type [0=common, 1=little watat, 2=big watat]) -// output: ( md = day of the month [1-30]) -long ceMmDateTime::cal_md(long mf,long mp,long mm,long myt) { - long mml=ceMmDateTime::cal_mml(mm,myt); - long m1=mp%2; long m2=long(floor(mp/2)); - return (m1*(15+m2*(mml-15))+(1-m1)*(mf+15*m2)); -} -//------------------------------------------------------------------------- -// Myanmar date to Julian day number -// input: ( -// my = year, -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12 , Late Tagu=13, Late Kason=14 ], -// md = day of the month [1-30] -// output: (jd -julian day number) -// dependency: cal_my(my) -long ceMmDateTime::m2j(long my,long mm,long md) { - long b,c,dd,myl,mmt; - long myt,tg1,fm,werr; - ceMmDateTime::cal_my(my,myt,tg1,fm,werr);//check year - mmt=long(floor(mm/13)); mm=mm%13+mmt; // to 1-12 with month type - b=long(floor(myt/2)); c=1-long(floor((myt+1)/2)); //if big watat and common year - mm+=4-long(floor((mm+15)/16))*4+long(floor((mm+12)/16));//adjust month - dd=md+long(floor(29.544*mm-29.26))-c*long(floor((mm+11)/16))*30 - +b*long(floor((mm+12)/16)); - myl=354+(1-c)*30+b; dd+=mmt*myl;//adjust day count with year length - return (dd+tg1-1); -} -//------------------------------------------------------------------------- -//Checking Astrological days -// More details @ http://cool-emerald.blogspot.sg/2013/12/myanmar-astrological-calendar-days.html -//------------------------------------------------------------------------- -// Get sabbath day and sabbath eve from day of the month, month, and year type. -// input: ( -// md= day of the month [1-30], -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// myt = year type [0=common, 1=little watat, 2=big watat]) -// output: ( [1=sabbath, 2=sabbath eve, 0=else]) -long ceMmDateTime::cal_sabbath(long md, long mm, long myt) { - long mml = ceMmDateTime::cal_mml(mm, myt); - long s = 0; if ((md == 8) || (md == 15) || (md == 23) || (md == mml)) s = 1; - if ((md == 7) || (md == 14) || (md == 22) || (md == (mml - 1))) s = 2; - return s; -} -//------------------------------------------------------------------------- -// Get yatyaza from month, and weekday -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=yatyaza, 0=else]) -long ceMmDateTime::cal_yatyaza(long mm, long wd) { - //first waso is considered waso - long m1 = mm % 4; long yatyaza = 0; long wd1 = long(floor(m1 / 2)) + 4; - long wd2 = ((1 - long(floor(m1 / 2))) + m1 % 2)*(1 + 2 * (m1 % 2)); - if ((wd == wd1) || (wd == wd2)) yatyaza = 1; - return yatyaza; -} -//------------------------------------------------------------------------- -// Get pyathada from month, and weekday -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=pyathada, 2=afternoon pyathada, 0=else]) -long ceMmDateTime::cal_pyathada(long mm, long wd) { - //first waso is considered waso - long m1 = mm % 4; long pyathada = 0; long wda[] = { 1, 3, 3, 0, 2, 1, 2 }; - if ((m1 == 0) && (wd == 4)) pyathada = 2;//afternoon pyathada - if (m1 == wda[wd]) pyathada = 1; - return pyathada; -} -//------------------------------------------------------------------------- -// nagahle -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ]) -// output: ( [0=west, 1=north, 2=east, 3=south]) -long ceMmDateTime::cal_nagahle(long mm) { - if (mm <= 0) mm = 4;//first waso is considered waso - return long(floor((mm % 12) / 3)); -} -//------------------------------------------------------------------------- -// mahabote -// input: ( -// my = year, -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [0=Binga, 1=Atun, 2=Yaza, 3=Adipati, 4= Marana, 5=Thike, 6=Puti]) -long ceMmDateTime::cal_mahabote(long my, long wd) { return ((my - wd) % 7); } -//------------------------------------------------------------------------- -// nakhat -// input: ( my = year ) -// output: ( [0=orc, 1=elf, 2=human] ) -long ceMmDateTime::cal_nakhat(long my) { return (my % 3); } -//------------------------------------------------------------------------- -// thamanyo -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=thamanyo, 0=else]) -long ceMmDateTime::cal_thamanyo(long mm, long wd) { - long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type - if (mm <= 0) mm = 4;//first waso is considered waso (looks no need here) - long thamanyo = 0; - long m1 = mm - 1 - (long)floor(mm / 9); - long wd1 = (m1 * 2 - (long)floor(m1 / 8)) % 7; - long wd2 = (wd + 7 - wd1) % 7; - if (wd2 <= 1) thamanyo = 1; - return thamanyo; -} -//------------------------------------------------------------------------- -// Get amyeittasote -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=amyeittasote, 0=else]) -long ceMmDateTime::cal_amyeittasote(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long amyeittasote = 0; long wda[] = { 5, 8, 3, 7, 2, 4, 1 }; - if (mf == wda[wd]) amyeittasote = 1; - return amyeittasote; -} -//------------------------------------------------------------------------- -// Get warameittugyi -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=warameittugyi, 0=else]) -long ceMmDateTime::cal_warameittugyi(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long warameittugyi = 0; long wda[] = { 7, 1, 4, 8, 9, 6, 3 }; - if (mf == wda[wd]) warameittugyi = 1; - return warameittugyi; -} -//------------------------------------------------------------------------- -// Get warameittunge -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=warameittunge, 0=else]) -long ceMmDateTime::cal_warameittunge(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long warameittunge = 0; long wn = (wd + 6) % 7; - if ((12 - mf) == wn) warameittunge = 1; - return warameittunge; -} -//------------------------------------------------------------------------- -// Get yatpote -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=yatpote, 0=else]) -long ceMmDateTime::cal_yatpote(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long yatpote = 0; long wda[] = { 8, 1, 4, 6, 9, 8, 7 }; - if (mf == wda[wd]) yatpote = 1; - return yatpote; -} -//------------------------------------------------------------------------- -// Get thamaphyu -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=thamaphyu, 0=else]) -long ceMmDateTime::cal_thamaphyu(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long thamaphyu = 0; long wda[] = { 1, 2, 6, 6, 5, 6, 7 }; - if (mf == wda[wd]) thamaphyu = 1; - long wdb[] = { 0, 1, 0, 0, 0, 3, 3 }; if (mf == wdb[wd]) thamaphyu = 1; - if ((mf == 4) && (wd == 5)) thamaphyu = 1; - return thamaphyu; -} -//------------------------------------------------------------------------- -// Get nagapor -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=nagapor, 0=else]) -long ceMmDateTime::cal_nagapor(long md, long wd) { - long nagapor = 0; long wda[] = { 26, 21, 2, 10, 18, 2, 21 }; - if (md == wda[wd]) nagapor = 1; - long wdb[] = { 17, 19, 1, 0, 9, 0, 0 }; if (md == wdb[wd]) nagapor = 1; - if (((md == 2) && (wd == 1)) || (((md == 12) || (md == 4) || (md == 18)) && (wd == 2))) nagapor = 1; - return nagapor; -} -//------------------------------------------------------------------------- -// yatyotema -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// md= day of the month [1-30]) -// output: ( [1=yatyotema, 0=else]) -long ceMmDateTime::cal_yatyotema(long mm, long md) { - long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type - if (mm <= 0) mm = 4;//first waso is considered waso - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long yatyotema = 0; long m1 = (mm % 2) ? mm : ((mm + 9) % 12); - m1 = (m1 + 4) % 12 + 1; if (mf == m1) yatyotema = 1; - return yatyotema; -} -//------------------------------------------------------------------------- -// mahayatkyan -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// md= day of the month [1-30]) -// output: ( [1=mahayatkyan, 0=else]) -long ceMmDateTime::cal_mahayatkyan(long mm, long md) { - if (mm <= 0) mm = 4;//first waso is considered waso - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long mahayatkyan = 0; long m1 = ((long)floor((mm % 12) / 2) + 4) % 6 + 1; - if (mf == m1) mahayatkyan = 1; - return mahayatkyan; -} -//------------------------------------------------------------------------- -// shanyat -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// md= day of the month [1-30]) -// output: ( [1=shanyat, 0=else]) -long ceMmDateTime::cal_shanyat(long mm, long md) { - long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type - if (mm <= 0) mm = 4;//first waso is considered waso - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long shanyat = 0; long sya[] = { 8, 8, 2, 2, 9, 3, 3, 5, 1, 4, 7, 4 }; - if (mf == sya[mm - 1]) shanyat = 1; - return shanyat; -} -//------------------------------------------------------------------------- -// get astrological information -// input: (jdn: Julian Day Number) -// output: (array of strings) -std::vector ceMmDateTime::cal_astro(long jdn) { - // jdn=(long)round(jdn); - long myt,my,mm,md; vector hs; - ceMmDateTime::j2m(jdn,myt,my,mm,md); - long wd=(jdn+2)%7;//week day [0=sat, 1=sun, ..., 6=fri] - if(ceMmDateTime::cal_thamanyo(mm,wd)) {hs.push_back("thamanyo");} - if(ceMmDateTime::cal_amyeittasote(md,wd)) {hs.push_back("amyeittasote");} - if(ceMmDateTime::cal_warameittugyi(md,wd)) {hs.push_back("warameittugyi");} - if(ceMmDateTime::cal_warameittunge(md,wd)) {hs.push_back("warameittunge");} - if(ceMmDateTime::cal_yatpote(md,wd)) {hs.push_back("yatpote");} - if(ceMmDateTime::cal_thamaphyu(md,wd)) {hs.push_back("thamaphyu");} - if(ceMmDateTime::cal_nagapor(md,wd)) {hs.push_back("nagapor");} - if(ceMmDateTime::cal_yatyotema(mm,md)) {hs.push_back("yatyotema");} - if(ceMmDateTime::cal_mahayatkyan(mm,md)) {hs.push_back("mahayatkyan");} - if(ceMmDateTime::cal_shanyat(mm,md)) {hs.push_back("shanyat");} - return hs; -} -//End of core functions ############################################################### - -//Start of checking holidays ################################################## -// Get holidays -// input: (jdn=Julian Day Number) -// output: ( array of strings) -// Thanks to Ye Lin Kyaw and Aye Nyein for the knowledge about -// the Myanmar calendar and the new year -std::vector ceMmDateTime::cal_holiday(long jdn) { - // jdn=(long)round(jdn); - long myt,my,mm,md,mp,mmt,gy,gm,gd,gh,gn; double gs; - ceMmDateTime::j2m(jdn,myt,my,mm,md); - mp=ceMmDateTime::cal_mp(md,mm,myt); - mmt=(long)floor(mm/13); vector hs; - ceDateTime::j2w(jdn,gy,gm,gd,gh,gn,gs); - //--------------------------------- - // Thingyan - double SY=1577917828.0/4320000.0; //solar year (365.2587565) - double MO=1954168.050623; //beginning of 0 ME - long BGNTG=1100, SE3=1312;//start of Thingyan and third era - long akn,atn; double ja,jk; - ja=SY*(my+mmt)+MO; // atat time - if (my >= SE3) jk=ja-2.169918982; // akya time - else jk=ja-2.1675; - akn=(long)round(jk); atn=(long)round(ja); - if(jdn==(atn+1)) {hs.push_back("Myanmar New Year Day");} - if ((my+mmt)>=BGNTG) { - if(jdn==atn) {hs.push_back("Thingyan Atat");} - else if((jdn>akn)&&(jdn=1369)&&((my+mmt)<1379)&&((jdn==(akn-2))|| - ((jdn>=(atn+2))&&(jdn<=(akn+7))))) {hs.push_back("Holiday");} - } - //--------------------------------- - // holidays on gregorian calendar - if((gy>=2018) && (gm==1) && (gd==1)) {hs.push_back("New Year Day");} - else if((gy>=1948) && (gm==1) && (gd==4)) {hs.push_back("Independence Day");} - else if((gy>=1947) && (gm==2) && (gd==12)) {hs.push_back("Union Day");} - else if((gy>=1958) && (gm==3) && (gd==2)) {hs.push_back("Peasants Day");} - else if((gy>=1945) && (gm==3) && (gd==27)) {hs.push_back("Resistance Day");} - else if((gy>=1923) && (gm==5) && (gd==1)) {hs.push_back("Labour Day");} - else if((gy>=1947) && (gm==7) && (gd==19)) {hs.push_back("Martyrs Day");} - else if((gy>=1752) && (gm==12) && (gd==25)) {hs.push_back("Christmas Day");} - else if((gy==2017) && (gm==12) && (gd==30)) {hs.push_back("Holiday");} - else if((gy>=2017) && (gm==12) && (gd==31)) {hs.push_back("Holiday");} - //--------------------------------- - // holidays on myanmar calendar - if((mm==2) && (mp==1)) {hs.push_back("Buddha Day");}//Vesak day - else if((mm==4)&& (mp==1)) {hs.push_back("Start of Buddhist Lent");}//Warso day - else if((mm==7) && (mp==1)) {hs.push_back("End of Buddhist Lent");} - else if((my>=1379) && (mm==7) && (md==14||md==16)) {hs.push_back("Holiday");} - else if((mm==8) && (mp==1)) {hs.push_back("Tazaungdaing");} - else if((my>=1379) && (mm==8) && (md==14)) {hs.push_back("Holiday");} - else if((my>=1282) && (mm==8) && (md==25)) {hs.push_back("National Day");} - else if((mm==10) && (md==1)) {hs.push_back("Karen New Year Day");} - else if((mm==12) && (mp==1)) {hs.push_back("Tabaung Pwe");} - //--------------------------------- - // //other holidays - // long ghEid[]={2456513,2456867,2457221,2457576,2457930,2458285,2458640}; - // if(ceMmDateTime::bSearch1(jdn,ghEid,long(sizeof(ghEid)/sizeof(ghEid[0])))>=0) - // {hs.push_back("Eid");} - - // // long ghDiwali[]={2456599,2456953,2457337,2457691,2458045,2458430,2458784}; - // // if(ceMmDateTime::bSearch1(jdn,ghDiwali,long(sizeof(ghDiwali)/sizeof(ghDiwali[0])))>=0) - // // {hs.push_back("Diwali");} - // if((mm==7) && (mp==3)) {hs.push_back("~Diwali");} - //--------------------------------- - return hs; -} -//------------------------------------------------------------------------- -// DoE : Date of Easter using "Meeus/Jones/Butcher" algorithm -// Reference: Peter Duffett-Smith, Jonathan Zwart', -// "Practical Astronomy with your Calculator or Spreadsheet," -// 4th Etd, Cambridge university press, 2011. Page-4. -// input: (y=year) -// output: (j=julian day number) -// dependency: w2j() -long ceMmDateTime::DoE(long y) { - long a,b,c,d,e,f,g,h,i,k,l,m,p,q,n; - a=y%19; - b=(long)floor(y/100); c=y%100; - d=(long)floor(b/4); e=b%4; - f=(long)floor((b+8)/25); - g=(long)floor((b-f+1)/3); - h=(19*a+b-d-g+15)%30; - i=(long)floor(c/4); k=c%4; - l=(32+2*e+2*i-h-k)%7; - m=(long)floor((a+11*h+22*l)/451); - q=h+l-7*m+114; p=(q%31)+1; n=(long)floor(q/31); - return (long)round(ceDateTime::w2j(y,n,p,12,0,0,1));// this is for Gregorian -} -//------------------------------------------------------------------------- -// Get other holidays -// input: (jdn: Julian Day Number) -// output: (array of strings) -// dependency: DoE(), j2w() -std::vector ceMmDateTime::cal_holiday2(long jdn) { - // jdn=(long)round(jdn); - long myt,my,mm,md,mp,mmt,gy,gm,gd,gh,gn; double gs; - ceMmDateTime::j2m(jdn,myt,my,mm,md); - mp=ceMmDateTime::cal_mp(md,mm,myt); - mmt=(long)floor(mm/13); vector hs; - ceDateTime::j2w(jdn,gy,gm,gd,gh,gn,gs); - //--------------------------------- - // holidays on gregorian calendar - long doe=ceMmDateTime::DoE(gy); - if((gy<=2017) && (gm==1) && (gd==1)) {hs.push_back("New Year Day");} - else if((gy>=1915) && (gm==2) && (gd==13)) {hs.push_back("G. Aung San BD");} - else if((gy>=1969) && (gm==2) && (gd==14)) {hs.push_back("Valentines Day");} - else if((gy>=1970) && (gm==4) && (gd==22)) {hs.push_back("Earth Day");} - else if((gy>=1392) && (gm==4) && (gd==1)) {hs.push_back("April Fools Day");} - else if((gy>=1948) && (gm==5) && (gd==8)) {hs.push_back("Red Cross Day");} - else if((gy>=1994) && (gm==10) && (gd==5)) {hs.push_back("World Teachers Day");} - else if((gy>=1947) && (gm==10) && (gd==24)) {hs.push_back("United Nations Day");} - else if((gy>=1753) && (gm==10) && (gd==31)) {hs.push_back("Halloween");} - if((gy>=1876) && (jdn==doe)) {hs.push_back("Easter");} - else if((gy>=1876) && (jdn==(doe-2))) {hs.push_back("Good Friday");} - //--------------------------------- - // holidays on myanmar calendar - if((my>=1309) && (mm==11) && (md==16)) - {hs.push_back("Mon National Day");}//the ancient founding of Hanthawady - else if((mm==9) && (md==1)) { - hs.push_back("Shan New Year Day"); - if(my>=1306) {hs.push_back("Authors Day");} - }//Nadaw waxing moon 1 - else if((mm==3) && (mp==1)) {hs.push_back("Mahathamaya Day");}//Nayon full moon - else if((mm==6)&&(mp==1)){hs.push_back("Garudhamma Day");}//Tawthalin full moon - else if((my>=1356) && (mm==10) && (mp==1)) - {hs.push_back("Mothers Day");}//Pyatho full moon - else if((my>=1370) && (mm==12) && (mp==1)) - {hs.push_back("Fathers Day");}//Tabaung full moon - else if((mm==5) && (mp==1)) {hs.push_back("Metta Day");}//Waguang full moon - else if((mm==5) && (md==10)) {hs.push_back("Taungpyone Pwe");}//Taung Pyone Pwe - else if((mm==5) && (md==23)) {hs.push_back("Yadanagu Pwe");}//Yadanagu Pwe - //---------------------------------------------------------------------------- - // //other holidays - // long ghEid2[]={2456936,2457290,2457644,2457998,2458353,2458707}; - // long ghCNY[]={2456689,2456690,2457073,2457074,2457427,2457428,2457782, - // 2457783,2458166,2458167,2458520,2458521}; - // if(ceMmDateTime::bSearch1(jdn,ghEid2,long(sizeof(ghEid2)/sizeof(ghEid2[0])))>=0) - // {hs.push_back("Eid");} - // if(ceMmDateTime::bSearch1(jdn,ghCNY,long(sizeof(ghCNY)/sizeof(ghCNY[0])))>=0) - // {hs.push_back("Chinese New Year");} - //---------------------------------------------------------------------------- - return hs; -} - -//----------------------------------------------------------------------------- -//End of checking holidays #################################################### -//------------------------------------------------------------------------- -// jd to date string in Myanmar calendar -// input: (jd:julian date, -// fs: format string [Optional argument: "&y &M &P &ff"] -// tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) -// output: date string in Myanmar calendar according to fm -// where formatting strings are as follows -// &yyyy : Myanmar year [0000-9999, e.g. 1380] -// &YYYY : Sasana year [0000-9999, e.g. 2562] -// &y : Myanmar year [0-9999, e.g. 138] -// &mm : month with zero padding [01-14] -// &M : month [e.g. January] -// &m : month [1-14] -// &P : moon phase [e.g. waxing, waning, full moon, or new moon] -// &dd : day of the month with zero padding [01-31] -// &d : day of the month [1-31] -// &ff : fortnight day with zero padding [01-15] -// &f : fortnight day [1-15] -std::string ceMmDateTime::j2ms(double jd, std::string fs, double tz) { - jd+=tz/24.0; - long jdn=(long)round(jd); - long myt,my,mm,md,mp,mf; - ceMmDateTime::j2m(jdn,myt,my,mm,md); - mp=ceMmDateTime::cal_mp(md,mm,myt); - mf=ceMmDateTime::cal_mf(md); - string mma[]={"First Waso","Tagu","Kason","Nayon","Waso","Wagaung","Tawthalin", - "Thadingyut","Tazaungmon","Nadaw","Pyatho","Tabodwe","Tabaung","Late Tagu","Late Kason"}; - string mpa[]={"Waxing","Full Moon","Waning","New Moon"}; - // replace format string with values - string fm=fs; string fstr,rstr; - //-------------------------------------------------------- - fstr = "&yyyy"; - rstr = string(4, '0') + to_string(my); - rstr = rstr.substr(rstr.length() - 4); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - long sy=my+1182; //Sasana year - fstr = "&YYYY"; - rstr = string(4, '0') + to_string(my); - rstr = rstr.substr(rstr.length() - 4); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&y"; - rstr = to_string(my); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&mm"; - rstr = string(2, '0') + to_string(mm); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&M"; - rstr = mma[mm]; if(mm==4 && myt>0){rstr="Second "+rstr;} - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&m"; - rstr = to_string(mm); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&P"; - rstr = mpa[mp]; - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&dd"; - rstr = string(2, '0') + to_string(md); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&d"; - rstr = to_string(md); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&ff"; - rstr = string(2, '0') + to_string(mf); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&f"; - rstr = to_string(mf); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - return fm; -} -//------------------------------------------------------------------------- -// get properties - -// Myanmar year type -long ceMmDateTime::myt(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return myt; -} - -// Myanmar year -long ceMmDateTime::my(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return my; -} - -// Sasana year -long ceMmDateTime::sy(){ - long sy=this->my()+1182; - return sy; -} - -// Myanmar year name -string ceMmDateTime::my_name(){ - // "ပုဿနှစ်","မာခနှစ်","ဖ္လကိုန်နှစ်","စယ်နှစ်", - // "ပိသျက်နှစ်","စိဿနှစ်","အာသတ်နှစ်","သရဝန်နှစ်", - // "ဘဒြနှစ်","အာသိန်နှစ်","ကြတိုက်နှစ်","မြိက္ကသိုဝ်နှစ်" - string yna[]={"Hpusha","Magha","Phalguni","Chitra", - "Visakha","Jyeshtha","Ashadha","Sravana", - "Bhadrapaha","Asvini","Krittika","Mrigasiras"}; - return yna[this->my()%12]; -} - -// Myanmar month [1-14] -// [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ] -long ceMmDateTime::mm(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return mm; -} - -// Myanmar day of the month [1-30] -long ceMmDateTime::md(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return md; -} - -// Moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] -long ceMmDateTime::mp(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return ceMmDateTime::cal_mp(md,mm,myt); -} - -// Fortnight day [1-15] -long ceMmDateTime::mf() { - return ceMmDateTime::cal_mf(this->md()); -} - -// get sabbath string -string ceMmDateTime::sabbath() { - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - long sb=ceMmDateTime::cal_sabbath(md,mm,myt); - string str=""; - if(sb==1) str="Sabbath"; - else if(sb==2) str="Sabbath Eve"; - return str; -} - -// get yatyaza string -string ceMmDateTime::yatyaza() { - long v=ceMmDateTime::cal_yatyaza(this->mm(),this->w()); - return (v?"Yatyaza":""); -} - -// get pyathada string -string ceMmDateTime::pyathada() { - long v=ceMmDateTime::cal_pyathada(this->mm(),this->w()); - string pa[]={"","Pyathada","Afternoon Pyathada"}; - return pa[v%3]; -} - -// get nagahle direction -string ceMmDateTime::nagahle() { - long v=ceMmDateTime::cal_nagahle(this->mm()); - string pa[]={"West","North","East","South"}; - return pa[v%4]; -} - -// get mahabote direction -string ceMmDateTime::mahabote() { - long v=ceMmDateTime::cal_mahabote(this->my(),this->w()); - string pa[]={"Binga","Atun","Yaza","Adipati","Marana","Thike","Puti"}; - return pa[v%7]; -} - -// get the array of astrological days -vector ceMmDateTime::astro() { - return ceMmDateTime::cal_astro(this->jdnl()); -} - -// get the array of public holidays -vector ceMmDateTime::holidays() { - return ceMmDateTime::cal_holiday(this->jdnl()); -} - -// get the array of other holidays -vector ceMmDateTime::holidays2() { - return ceMmDateTime::cal_holiday2(this->jdnl()); -} - -//------------------------------------------------------------------------- -// get Myanmar Date String -// input: ( -// fs: format string [Optional argument: "&y &M &P &ff"] -// tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) -// output: date string in Myanmar calendar according to fm -// where formatting strings are as follows -// &yyyy : Myanmar year [0000-9999, e.g. 1380] -// &YYYY : Sasana year [0000-9999, e.g. 2562] -// &y : Myanmar year [0-9999, e.g. 138] -// &mm : month with zero padding [01-14] -// &M : month [e.g. January] -// &m : month [1-14] -// &P : moon phase [e.g. waxing, waning, full moon, or new moon] -// &dd : day of the month with zero padding [01-31] -// &d : day of the month [1-31] -// &ff : fortnight day with zero padding [01-15] -// &f : fortnight day [1-15] -string ceMmDateTime::ToMString(string fs) { - return ceMmDateTime::j2ms(this->jd(),fs,this->tz()); -} -//------------------------------------------------------------------------- - +// File: ceMmDateTime.cpp +// Description: Modern Myanmar Calendrical Calculations +// WebSite: https://yan9a.github.io/mcal/ +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye +// Doc: http://cool-emerald.blogspot.com/2013/06/algorithm-program-and-calculation-of.html +//------------------------------------------------------------------------- +#include"ce/ceMmDateTime.h" +#include + +using namespace std; + +namespace ce { +//------------------------------------------------------------------------- +// default constructor +ceMmDateTime::ceMmDateTime():ceDateTime() +{ + +} +//------------------------------------------------------------------------- +// Get Myanmar year constants depending on era +// Thanks to Myo Zarny and Wunna Ko for earlier Myanmar years data +// input: my -myanmar year +// output: +// EI = Myanmar calendar era id [1-3] : calculations methods/constants depends on era +// WO = watat offset to compensate +// NM = number of months to find excess days +// EW = exception in watat year +void ceMmDateTime::GetMyConst(long my, double& EI, double& WO, double& NM, long& EW) +{ + EW = 0; long (*fme)[2]; long* wte; long i=-1,uf,uw; + // The third era (the era after Independence 1312 ME and after) + if (my >= 1312) { + EI = 3; WO = -0.5; NM = 8; + long fme3[][2] = { {1377, 1} }; + long wte3[] = { 1344, 1345 }; + fme = fme3; wte = wte3; + uf=long(sizeof(fme3)/sizeof(fme3[0])); + uw=long(sizeof(wte3)/sizeof(wte3[0])); + } + // The second era (the era under British colony: 1217 ME - 1311 ME) + else if (my >= 1217) { + EI = 2; WO = -1; NM = 4; + long fme2[][2] = { {1234, 1},{1261, -1} }; + long wte2[] = { 1263, 1264 }; + fme = fme2; wte = wte2; + uf=long(sizeof(fme2)/sizeof(fme2[0])); + uw=long(sizeof(wte2)/sizeof(wte2[0])); + } + // The first era (the era of Myanmar kings: ME1216 and before) + // Thandeikta (ME 1100 - 1216) + else if (my >= 1100) { + EI = 1.3; WO = -0.85; NM = -1; + long fme13[][2] = {{1120, 1}, {1126, -1}, {1150, 1}, {1172, -1}, {1207, 1}}; + long wte13[] = {1201, 1202}; + fme = fme13; wte = wte13; + uf=long(sizeof(fme13)/sizeof(fme13[0])); + uw=long(sizeof(wte13)/sizeof(wte13[0])); + } + // Makaranta system 2 (ME 798 - 1099) + else if (my >= 798) { + EI = 1.2; WO = -1.1; NM = -1; + long fme12[][2] = {{813, -1}, {849, -1}, {851, -1}, {854, -1}, {927, -1}, + {933, -1}, {936, -1}, {938, -1}, {949, -1}, {952, -1}, {963, -1}, {968, -1}, {1039, -1}}; + long wte12[] = {-9999}; + fme = fme12; wte = wte12; + uf=long(sizeof(fme12)/sizeof(fme12[0])); + uw=long(sizeof(wte12)/sizeof(wte12[0])); + } + // Makaranta system 1 (ME 0 - 797) + else { + EI = 1.1; WO = -1.1; NM = -1; + long fme11[][2] = {{205, 1}, {246, 1}, {471, 1}, {572, -1}, {651, 1}, + {653, 2}, {656, 1}, {672, 1}, {729, 1}, {767, -1}}; + long wte11[] = {-9999}; + fme = fme11; wte = wte11; + uf=long(sizeof(fme11)/sizeof(fme11[0])); + uw=long(sizeof(wte11)/sizeof(wte11[0])); + } + i = ceMmDateTime::bSearch2(my, fme,uf); if (i >= 0) WO += fme[i][1]; // full moon day offset exceptions + i = ceMmDateTime::bSearch1(my, wte,uw); if (i >= 0) EW = 1; //correct watat exceptions +} +//---------------------------------------------------------------------------- +// Search first dimension in a 2D array +// input: (k=key,A=array,u=size) +// output: (i=index) +long ceMmDateTime::bSearch2(long k,long (*A)[2], long u) { + long i = 0; long l = 0; u--; + while(u>=l) { + i=long(floor((l+u)/2)); + if (A[i][0]>k) u=i-1; + else if (A[i][0]=l) { + i=long(floor((l+u)/2)); + if (A[i]>k) u=i-1; + else if (A[i]= 2) {//if 2nd era or later find watat based on excess days + TW=LM-(SY/12-LM)*NM; + if(ed >= TW) watat=1; + } + else {//if 1st era,find watat by 19 years metonic cycle + //Myanmar year is divided by 19 and there is intercalary month + //if the remainder is 2,5,7,10,13,15,18 + //https://github.com/kanasimi/CeJS/blob/master/data/date/calendar.js#L2330 + watat=(my*7+2)%19; if (watat < 0) watat+=19; + watat=long(floor(watat/12)); + } + watat^=EW;//correct watat exceptions +} +//------------------------------------------------------------------------- +// Check Myanmar Year +// input: (my -myanmar year) +// output: ( myt :year type [0=common, 1=little watat, 2=big watat], +// tg1 : the 1st day of Tagu as jdn_mm (Julian Day Number for MMT) +// fm : full moon day of [2nd] Waso as Julain Day Number +// werr: watat error [0=ok, 1= error]) +// dependency: cal_watat(my) +void ceMmDateTime::cal_my(long my, long& myt, long& tg1, long& fm, long& werr) { + long yd = 0, nd = 0, y1watat, y1fm, y2watat, y2fm; werr = 0; + ceMmDateTime::cal_watat(my,y2watat,y2fm); myt = y2watat; + do { yd++; ceMmDateTime::cal_watat(my - yd,y1watat,y1fm); } while (y1watat == 0 && yd < 3); + if (myt) { + nd = (y2fm - y1fm) % 354; myt = long(floor(nd / 31)+ 1); + fm = y2fm; if (nd != 30 && nd != 31) { werr = 1; } + } + else fm = y1fm + 354 * yd; + tg1 = y1fm + 354 * yd - 102; +} +//------------------------------------------------------------------------- +// Julian day number to Myanmar date +// input: (jdn -julian day number) +// output: ( + // myt =year type [0=common, 1=little watat, 2=big watat], + // my = year, + // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, + // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, + // Tabaung=12, Late Tagu=13, Late Kason=14 ], + // md = day of the month [1 to 30]) +// dependency: cal_my(my) +void ceMmDateTime::j2m(double jd, long& myt, long& my, long& mm, long& md) { + long jdn=long(round(jd));//convert jdn to integer + double SY=1577917828.0/4320000.0; //solar year (365.2587565) + double MO=1954168.050623; //beginning of 0 ME + long dd,myl,mmt,a,b,c,e,f; + long tg1,fm,werr; + my=long(floor((jdn-0.5-MO)/SY));//Myanmar year + ceMmDateTime::cal_my(my,myt,tg1,fm,werr);//check year + dd=jdn-tg1+1;//day count + b=long(floor(myt/2)); c=long(floor(1/(myt+1))); //big wa and common yr + myl=354+(1-c)*30+b;//year length + mmt=long(floor((dd-1)/myl));//month type: late =1 or early = 0 + dd-=mmt*myl; a=long(floor((dd+423)/512)); //adjust day count and threshold + mm=long(floor((dd-b*a+c*a*30+29.26)/29.544));//month + e=long(floor((mm+12)/16)); f=long(floor((mm+11)/16)); + md=dd-long(floor(29.544*mm-29.26))-b*e+c*f*30;//day + mm+=f*3-e*4+12*mmt; // adjust month numbers for late months +} +//------------------------------------------------------------------------- +// Get moon phase from day of the month, month, and year type. +// input: ( +// md= day of the month [1-30], +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// myt = year type [0=common, 1=little watat, 2=big watat]) +// output: (mp =moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon]) +long ceMmDateTime::cal_mp(long md,long mm,long myt) { + long mml=ceMmDateTime::cal_mml(mm,myt); + return long(floor((md+1)/16)+floor(md/16)+floor(md/mml)); +} +//------------------------------------------------------------------------- +// Get length of month from month, and year type. +// input: ( +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// myt = year type [0=common, 1=little watat, 2=big watat]) +// output: (mml = length of the month [29 or 30 days]) +long ceMmDateTime::cal_mml(long mm,long myt) { + long mml=30-mm%2;//month length + if(mm==3) mml+=long(floor(myt/2));//adjust if Nayon in big watat + return mml; +} +//------------------------------------------------------------------------- +// Get the apparent length of the year from year type. +// input: ( myt = year type [0=common, 1=little watat, 2=big watat]) +// output: ( myl= year length [354, 384, or 385 days]) +long ceMmDateTime::cal_myl(long myt) { + return (354+(1-long(floor(1/(myt+1))))*30+long(floor(myt/2))); +} +//------------------------------------------------------------------------- +// Get fortnight day from month day +// input: ( md= day of the month [1-30]) +// output: (mf= fortnight day [1 to 15]) +long ceMmDateTime::cal_mf(long md) { + return (md-15*long(floor(md/16))); +} +//------------------------------------------------------------------------- +// Get day of month from fortnight day, moon phase, and length of the month +// input: ( +// mf = fortnight day [1 to 15], +// mp = moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// myt = year type [0=common, 1=little watat, 2=big watat]) +// output: ( md = day of the month [1-30]) +long ceMmDateTime::cal_md(long mf,long mp,long mm,long myt) { + long mml=ceMmDateTime::cal_mml(mm,myt); + long m1=mp%2; long m2=long(floor(mp/2)); + return (m1*(15+m2*(mml-15))+(1-m1)*(mf+15*m2)); +} +//------------------------------------------------------------------------- +// Myanmar date to Julian day number +// input: ( +// my = year, +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12 , Late Tagu=13, Late Kason=14 ], +// md = day of the month [1-30] +// output: (jd -julian day number) +// dependency: cal_my(my) +long ceMmDateTime::m2j(long my,long mm,long md) { + long b,c,dd,myl,mmt; + long myt,tg1,fm,werr; + ceMmDateTime::cal_my(my,myt,tg1,fm,werr);//check year + mmt=long(floor(mm/13)); mm=mm%13+mmt; // to 1-12 with month type + b=long(floor(myt/2)); c=1-long(floor((myt+1)/2)); //if big watat and common year + mm+=4-long(floor((mm+15)/16))*4+long(floor((mm+12)/16));//adjust month + dd=md+long(floor(29.544*mm-29.26))-c*long(floor((mm+11)/16))*30 + +b*long(floor((mm+12)/16)); + myl=354+(1-c)*30+b; dd+=mmt*myl;//adjust day count with year length + return (dd+tg1-1); +} +//------------------------------------------------------------------------- +//Checking Astrological days +// More details @ http://cool-emerald.blogspot.sg/2013/12/myanmar-astrological-calendar-days.html +//------------------------------------------------------------------------- +// Get sabbath day and sabbath eve from day of the month, month, and year type. +// input: ( +// md= day of the month [1-30], +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// myt = year type [0=common, 1=little watat, 2=big watat]) +// output: ( [1=sabbath, 2=sabbath eve, 0=else]) +long ceMmDateTime::cal_sabbath(long md, long mm, long myt) { + long mml = ceMmDateTime::cal_mml(mm, myt); + long s = 0; if ((md == 8) || (md == 15) || (md == 23) || (md == mml)) s = 1; + if ((md == 7) || (md == 14) || (md == 22) || (md == (mml - 1))) s = 2; + return s; +} +//------------------------------------------------------------------------- +// Get yatyaza from month, and weekday +// input: ( +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=yatyaza, 0=else]) +long ceMmDateTime::cal_yatyaza(long mm, long wd) { + //first waso is considered waso + long m1 = mm % 4; long yatyaza = 0; long wd1 = long(floor(m1 / 2)) + 4; + long wd2 = ((1 - long(floor(m1 / 2))) + m1 % 2)*(1 + 2 * (m1 % 2)); + if ((wd == wd1) || (wd == wd2)) yatyaza = 1; + return yatyaza; +} +//------------------------------------------------------------------------- +// Get pyathada from month, and weekday +// input: ( +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=pyathada, 2=afternoon pyathada, 0=else]) +long ceMmDateTime::cal_pyathada(long mm, long wd) { + //first waso is considered waso + long m1 = mm % 4; long pyathada = 0; long wda[] = { 1, 3, 3, 0, 2, 1, 2 }; + if ((m1 == 0) && (wd == 4)) pyathada = 2;//afternoon pyathada + if (m1 == wda[wd]) pyathada = 1; + return pyathada; +} +//------------------------------------------------------------------------- +// nagahle +// input: ( +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ]) +// output: ( [0=west, 1=north, 2=east, 3=south]) +long ceMmDateTime::cal_nagahle(long mm) { + if (mm <= 0) mm = 4;//first waso is considered waso + return long(floor((mm % 12) / 3)); +} +//------------------------------------------------------------------------- +// mahabote +// input: ( +// my = year, +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [0=Binga, 1=Atun, 2=Yaza, 3=Adipati, 4= Marana, 5=Thike, 6=Puti]) +long ceMmDateTime::cal_mahabote(long my, long wd) { return ((my - wd) % 7); } +//------------------------------------------------------------------------- +// nakhat +// input: ( my = year ) +// output: ( [0=orc, 1=elf, 2=human] ) +long ceMmDateTime::cal_nakhat(long my) { return (my % 3); } +//------------------------------------------------------------------------- +// thamanyo +// input: ( +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=thamanyo, 0=else]) +long ceMmDateTime::cal_thamanyo(long mm, long wd) { + long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type + if (mm <= 0) mm = 4;//first waso is considered waso (looks no need here) + long thamanyo = 0; + long m1 = mm - 1 - (long)floor(mm / 9); + long wd1 = (m1 * 2 - (long)floor(m1 / 8)) % 7; + long wd2 = (wd + 7 - wd1) % 7; + if (wd2 <= 1) thamanyo = 1; + return thamanyo; +} +//------------------------------------------------------------------------- +// Get amyeittasote +// input: ( +// md= day of the month [1-30], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=amyeittasote, 0=else]) +long ceMmDateTime::cal_amyeittasote(long md, long wd) { + long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] + long amyeittasote = 0; long wda[] = { 5, 8, 3, 7, 2, 4, 1 }; + if (mf == wda[wd]) amyeittasote = 1; + return amyeittasote; +} +//------------------------------------------------------------------------- +// Get warameittugyi +// input: ( +// md= day of the month [1-30], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=warameittugyi, 0=else]) +long ceMmDateTime::cal_warameittugyi(long md, long wd) { + long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] + long warameittugyi = 0; long wda[] = { 7, 1, 4, 8, 9, 6, 3 }; + if (mf == wda[wd]) warameittugyi = 1; + return warameittugyi; +} +//------------------------------------------------------------------------- +// Get warameittunge +// input: ( +// md= day of the month [1-30], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=warameittunge, 0=else]) +long ceMmDateTime::cal_warameittunge(long md, long wd) { + long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] + long warameittunge = 0; long wn = (wd + 6) % 7; + if ((12 - mf) == wn) warameittunge = 1; + return warameittunge; +} +//------------------------------------------------------------------------- +// Get yatpote +// input: ( +// md= day of the month [1-30], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=yatpote, 0=else]) +long ceMmDateTime::cal_yatpote(long md, long wd) { + long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] + long yatpote = 0; long wda[] = { 8, 1, 4, 6, 9, 8, 7 }; + if (mf == wda[wd]) yatpote = 1; + return yatpote; +} +//------------------------------------------------------------------------- +// Get thamaphyu +// input: ( +// md= day of the month [1-30], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=thamaphyu, 0=else]) +long ceMmDateTime::cal_thamaphyu(long md, long wd) { + long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] + long thamaphyu = 0; long wda[] = { 1, 2, 6, 6, 5, 6, 7 }; + if (mf == wda[wd]) thamaphyu = 1; + long wdb[] = { 0, 1, 0, 0, 0, 3, 3 }; if (mf == wdb[wd]) thamaphyu = 1; + if ((mf == 4) && (wd == 5)) thamaphyu = 1; + return thamaphyu; +} +//------------------------------------------------------------------------- +// Get nagapor +// input: ( +// md= day of the month [1-30], +// wd= weekday [0=sat, 1=sun, ..., 6=fri]) +// output: ( [1=nagapor, 0=else]) +long ceMmDateTime::cal_nagapor(long md, long wd) { + long nagapor = 0; long wda[] = { 26, 21, 2, 10, 18, 2, 21 }; + if (md == wda[wd]) nagapor = 1; + long wdb[] = { 17, 19, 1, 0, 9, 0, 0 }; if (md == wdb[wd]) nagapor = 1; + if (((md == 2) && (wd == 1)) || (((md == 12) || (md == 4) || (md == 18)) && (wd == 2))) nagapor = 1; + return nagapor; +} +//------------------------------------------------------------------------- +// yatyotema +// input: ( +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// md= day of the month [1-30]) +// output: ( [1=yatyotema, 0=else]) +long ceMmDateTime::cal_yatyotema(long mm, long md) { + long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type + if (mm <= 0) mm = 4;//first waso is considered waso + long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] + long yatyotema = 0; long m1 = (mm % 2) ? mm : ((mm + 9) % 12); + m1 = (m1 + 4) % 12 + 1; if (mf == m1) yatyotema = 1; + return yatyotema; +} +//------------------------------------------------------------------------- +// mahayatkyan +// input: ( +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// md= day of the month [1-30]) +// output: ( [1=mahayatkyan, 0=else]) +long ceMmDateTime::cal_mahayatkyan(long mm, long md) { + if (mm <= 0) mm = 4;//first waso is considered waso + long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] + long mahayatkyan = 0; long m1 = ((long)floor((mm % 12) / 2) + 4) % 6 + 1; + if (mf == m1) mahayatkyan = 1; + return mahayatkyan; +} +//------------------------------------------------------------------------- +// shanyat +// input: ( +// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ], +// md= day of the month [1-30]) +// output: ( [1=shanyat, 0=else]) +long ceMmDateTime::cal_shanyat(long mm, long md) { + long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type + if (mm <= 0) mm = 4;//first waso is considered waso + long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] + long shanyat = 0; long sya[] = { 8, 8, 2, 2, 9, 3, 3, 5, 1, 4, 7, 4 }; + if (mf == sya[mm - 1]) shanyat = 1; + return shanyat; +} +//------------------------------------------------------------------------- +// get astrological information +// input: (jdn: Julian Day Number) +// output: (array of strings) +std::vector ceMmDateTime::cal_astro(long jdn) { + // jdn=(long)round(jdn); + long myt,my,mm,md; vector hs; + ceMmDateTime::j2m(jdn,myt,my,mm,md); + long wd=(jdn+2)%7;//week day [0=sat, 1=sun, ..., 6=fri] + if(ceMmDateTime::cal_thamanyo(mm,wd)) {hs.push_back("thamanyo");} + if(ceMmDateTime::cal_amyeittasote(md,wd)) {hs.push_back("amyeittasote");} + if(ceMmDateTime::cal_warameittugyi(md,wd)) {hs.push_back("warameittugyi");} + if(ceMmDateTime::cal_warameittunge(md,wd)) {hs.push_back("warameittunge");} + if(ceMmDateTime::cal_yatpote(md,wd)) {hs.push_back("yatpote");} + if(ceMmDateTime::cal_thamaphyu(md,wd)) {hs.push_back("thamaphyu");} + if(ceMmDateTime::cal_nagapor(md,wd)) {hs.push_back("nagapor");} + if(ceMmDateTime::cal_yatyotema(mm,md)) {hs.push_back("yatyotema");} + if(ceMmDateTime::cal_mahayatkyan(mm,md)) {hs.push_back("mahayatkyan");} + if(ceMmDateTime::cal_shanyat(mm,md)) {hs.push_back("shanyat");} + return hs; +} +//End of core functions ############################################################### + +//Start of checking holidays ################################################## +// Get holidays +// input: (jdn=Julian Day Number) +// output: ( array of strings) +// Thanks to Ye Lin Kyaw and Aye Nyein for the knowledge about +// the Myanmar calendar and the new year +std::vector ceMmDateTime::cal_holiday(long jdn) { + // jdn=(long)round(jdn); + long myt,my,mm,md,mp,mmt,gy,gm,gd,gh,gn; double gs; + ceMmDateTime::j2m(jdn,myt,my,mm,md); + mp=ceMmDateTime::cal_mp(md,mm,myt); + mmt=(long)floor(mm/13); vector hs; + ceDateTime::j2w(jdn,gy,gm,gd,gh,gn,gs); + //--------------------------------- + // Thingyan + double SY=1577917828.0/4320000.0; //solar year (365.2587565) + double MO=1954168.050623; //beginning of 0 ME + long BGNTG=1100, SE3=1312;//start of Thingyan and third era + long akn,atn; double ja,jk; + ja=SY*(my+mmt)+MO; // atat time + if (my >= SE3) jk=ja-2.169918982; // akya time + else jk=ja-2.1675; + akn=(long)round(jk); atn=(long)round(ja); + if(jdn==(atn+1)) {hs.push_back("Myanmar New Year Day");} + if ((my+mmt)>=BGNTG) { + if(jdn==atn) {hs.push_back("Thingyan Atat");} + else if((jdn>akn)&&(jdn=1369)&&((my+mmt)<1379)&&((jdn==(akn-2))|| + ((jdn>=(atn+2))&&(jdn<=(akn+7))))) {hs.push_back("Holiday");} + } + //--------------------------------- + // holidays on gregorian calendar + if((gy>=2018) && (gm==1) && (gd==1)) {hs.push_back("New Year Day");} + else if((gy>=1948) && (gm==1) && (gd==4)) {hs.push_back("Independence Day");} + else if((gy>=1947) && (gm==2) && (gd==12)) {hs.push_back("Union Day");} + else if((gy>=1958) && (gm==3) && (gd==2)) {hs.push_back("Peasants Day");} + else if((gy>=1945) && (gm==3) && (gd==27)) {hs.push_back("Resistance Day");} + else if((gy>=1923) && (gm==5) && (gd==1)) {hs.push_back("Labour Day");} + else if((gy>=1947) && (gm==7) && (gd==19)) {hs.push_back("Martyrs Day");} + else if((gy>=1752) && (gm==12) && (gd==25)) {hs.push_back("Christmas Day");} + else if((gy==2017) && (gm==12) && (gd==30)) {hs.push_back("Holiday");} + else if((gy>=2017) && (gm==12) && (gd==31)) {hs.push_back("Holiday");} + //--------------------------------- + // holidays on myanmar calendar + if((mm==2) && (mp==1)) {hs.push_back("Buddha Day");}//Vesak day + else if((mm==4)&& (mp==1)) {hs.push_back("Start of Buddhist Lent");}//Warso day + else if((mm==7) && (mp==1)) {hs.push_back("End of Buddhist Lent");} + else if((my>=1379) && (mm==7) && (md==14||md==16)) {hs.push_back("Holiday");} + else if((mm==8) && (mp==1)) {hs.push_back("Tazaungdaing");} + else if((my>=1379) && (mm==8) && (md==14)) {hs.push_back("Holiday");} + else if((my>=1282) && (mm==8) && (md==25)) {hs.push_back("National Day");} + else if((mm==10) && (md==1)) {hs.push_back("Karen New Year Day");} + else if((mm==12) && (mp==1)) {hs.push_back("Tabaung Pwe");} + //--------------------------------- + // //other holidays + // long ghEid[]={2456513,2456867,2457221,2457576,2457930,2458285,2458640}; + // if(ceMmDateTime::bSearch1(jdn,ghEid,long(sizeof(ghEid)/sizeof(ghEid[0])))>=0) + // {hs.push_back("Eid");} + + // // long ghDiwali[]={2456599,2456953,2457337,2457691,2458045,2458430,2458784}; + // // if(ceMmDateTime::bSearch1(jdn,ghDiwali,long(sizeof(ghDiwali)/sizeof(ghDiwali[0])))>=0) + // // {hs.push_back("Diwali");} + // if((mm==7) && (mp==3)) {hs.push_back("~Diwali");} + //--------------------------------- + return hs; +} +//------------------------------------------------------------------------- +// DoE : Date of Easter using "Meeus/Jones/Butcher" algorithm +// Reference: Peter Duffett-Smith, Jonathan Zwart', +// "Practical Astronomy with your Calculator or Spreadsheet," +// 4th Etd, Cambridge university press, 2011. Page-4. +// input: (y=year) +// output: (j=julian day number) +// dependency: w2j() +long ceMmDateTime::DoE(long y) { + long a,b,c,d,e,f,g,h,i,k,l,m,p,q,n; + a=y%19; + b=(long)floor(y/100); c=y%100; + d=(long)floor(b/4); e=b%4; + f=(long)floor((b+8)/25); + g=(long)floor((b-f+1)/3); + h=(19*a+b-d-g+15)%30; + i=(long)floor(c/4); k=c%4; + l=(32+2*e+2*i-h-k)%7; + m=(long)floor((a+11*h+22*l)/451); + q=h+l-7*m+114; p=(q%31)+1; n=(long)floor(q/31); + return (long)round(ceDateTime::w2j(y,n,p,12,0,0,1));// this is for Gregorian +} +//------------------------------------------------------------------------- +// Get other holidays +// input: (jdn: Julian Day Number) +// output: (array of strings) +// dependency: DoE(), j2w() +std::vector ceMmDateTime::cal_holiday2(long jdn) { + // jdn=(long)round(jdn); + long myt,my,mm,md,mp,mmt,gy,gm,gd,gh,gn; double gs; + ceMmDateTime::j2m(jdn,myt,my,mm,md); + mp=ceMmDateTime::cal_mp(md,mm,myt); + mmt=(long)floor(mm/13); vector hs; + ceDateTime::j2w(jdn,gy,gm,gd,gh,gn,gs); + //--------------------------------- + // holidays on gregorian calendar + long doe=ceMmDateTime::DoE(gy); + if((gy<=2017) && (gm==1) && (gd==1)) {hs.push_back("New Year Day");} + else if((gy>=1915) && (gm==2) && (gd==13)) {hs.push_back("G. Aung San BD");} + else if((gy>=1969) && (gm==2) && (gd==14)) {hs.push_back("Valentines Day");} + else if((gy>=1970) && (gm==4) && (gd==22)) {hs.push_back("Earth Day");} + else if((gy>=1392) && (gm==4) && (gd==1)) {hs.push_back("April Fools Day");} + else if((gy>=1948) && (gm==5) && (gd==8)) {hs.push_back("Red Cross Day");} + else if((gy>=1994) && (gm==10) && (gd==5)) {hs.push_back("World Teachers Day");} + else if((gy>=1947) && (gm==10) && (gd==24)) {hs.push_back("United Nations Day");} + else if((gy>=1753) && (gm==10) && (gd==31)) {hs.push_back("Halloween");} + if((gy>=1876) && (jdn==doe)) {hs.push_back("Easter");} + else if((gy>=1876) && (jdn==(doe-2))) {hs.push_back("Good Friday");} + //--------------------------------- + // holidays on myanmar calendar + if((my>=1309) && (mm==11) && (md==16)) + {hs.push_back("Mon National Day");}//the ancient founding of Hanthawady + else if((mm==9) && (md==1)) { + hs.push_back("Shan New Year Day"); + if(my>=1306) {hs.push_back("Authors Day");} + }//Nadaw waxing moon 1 + else if((mm==3) && (mp==1)) {hs.push_back("Mahathamaya Day");}//Nayon full moon + else if((mm==6)&&(mp==1)){hs.push_back("Garudhamma Day");}//Tawthalin full moon + else if((my>=1356) && (mm==10) && (mp==1)) + {hs.push_back("Mothers Day");}//Pyatho full moon + else if((my>=1370) && (mm==12) && (mp==1)) + {hs.push_back("Fathers Day");}//Tabaung full moon + else if((mm==5) && (mp==1)) {hs.push_back("Metta Day");}//Waguang full moon + else if((mm==5) && (md==10)) {hs.push_back("Taungpyone Pwe");}//Taung Pyone Pwe + else if((mm==5) && (md==23)) {hs.push_back("Yadanagu Pwe");}//Yadanagu Pwe + //---------------------------------------------------------------------------- + // //other holidays + // long ghEid2[]={2456936,2457290,2457644,2457998,2458353,2458707}; + // long ghCNY[]={2456689,2456690,2457073,2457074,2457427,2457428,2457782, + // 2457783,2458166,2458167,2458520,2458521}; + // if(ceMmDateTime::bSearch1(jdn,ghEid2,long(sizeof(ghEid2)/sizeof(ghEid2[0])))>=0) + // {hs.push_back("Eid");} + // if(ceMmDateTime::bSearch1(jdn,ghCNY,long(sizeof(ghCNY)/sizeof(ghCNY[0])))>=0) + // {hs.push_back("Chinese New Year");} + //---------------------------------------------------------------------------- + return hs; +} + +//----------------------------------------------------------------------------- +//End of checking holidays #################################################### +//------------------------------------------------------------------------- +// jd to date string in Myanmar calendar +// input: (jd:julian date, +// fs: format string [Optional argument: "&y &M &P &ff"] +// tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) +// output: date string in Myanmar calendar according to fm +// where formatting strings are as follows +// &yyyy : Myanmar year [0000-9999, e.g. 1380] +// &YYYY : Sasana year [0000-9999, e.g. 2562] +// &y : Myanmar year [0-9999, e.g. 138] +// &mm : month with zero padding [01-14] +// &M : month [e.g. January] +// &m : month [1-14] +// &P : moon phase [e.g. waxing, waning, full moon, or new moon] +// &dd : day of the month with zero padding [01-31] +// &d : day of the month [1-31] +// &ff : fortnight day with zero padding [01-15] +// &f : fortnight day [1-15] +std::string ceMmDateTime::j2ms(double jd, std::string fs, double tz) { + jd+=tz/24.0; + long jdn=(long)round(jd); + long myt,my,mm,md,mp,mf; + ceMmDateTime::j2m(jdn,myt,my,mm,md); + mp=ceMmDateTime::cal_mp(md,mm,myt); + mf=ceMmDateTime::cal_mf(md); + string mma[]={"First Waso","Tagu","Kason","Nayon","Waso","Wagaung","Tawthalin", + "Thadingyut","Tazaungmon","Nadaw","Pyatho","Tabodwe","Tabaung","Late Tagu","Late Kason"}; + string mpa[]={"Waxing","Full Moon","Waning","New Moon"}; + // replace format string with values + string fm=fs; string fstr,rstr; + //-------------------------------------------------------- + fstr = "&yyyy"; + rstr = string(4, '0') + to_string(my); + rstr = rstr.substr(rstr.length() - 4); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + long sy=my+1182; //Sasana year + fstr = "&YYYY"; + rstr = string(4, '0') + to_string(my); + rstr = rstr.substr(rstr.length() - 4); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&y"; + rstr = to_string(my); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&mm"; + rstr = string(2, '0') + to_string(mm); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&M"; + rstr = mma[mm]; if(mm==4 && myt>0){rstr="Second "+rstr;} + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&m"; + rstr = to_string(mm); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&P"; + rstr = mpa[mp]; + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&dd"; + rstr = string(2, '0') + to_string(md); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&d"; + rstr = to_string(md); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&ff"; + rstr = string(2, '0') + to_string(mf); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "&f"; + rstr = to_string(mf); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + return fm; +} +//------------------------------------------------------------------------- +// get properties + +// Myanmar year type +long ceMmDateTime::myt(){ + long myt,my,mm,md; + ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); + return myt; +} + +// Myanmar year +long ceMmDateTime::my(){ + long myt,my,mm,md; + ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); + return my; +} + +// Sasana year +long ceMmDateTime::sy(){ + long sy=this->my()+1182; + return sy; +} + +// Myanmar year name +string ceMmDateTime::my_name(){ + // "ပုဿနှစ်","မာခနှစ်","ဖ္လကိုန်နှစ်","စယ်နှစ်", + // "ပိသျက်နှစ်","စိဿနှစ်","အာသတ်နှစ်","သရဝန်နှစ်", + // "ဘဒြနှစ်","အာသိန်နှစ်","ကြတိုက်နှစ်","မြိက္ကသိုဝ်နှစ်" + string yna[]={"Hpusha","Magha","Phalguni","Chitra", + "Visakha","Jyeshtha","Ashadha","Sravana", + "Bhadrapaha","Asvini","Krittika","Mrigasiras"}; + return yna[this->my()%12]; +} + +// Myanmar month [1-14] +// [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, +// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, +// Tabaung=12, Late Tagu=13, Late Kason=14 ] +long ceMmDateTime::mm(){ + long myt,my,mm,md; + ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); + return mm; +} + +// Myanmar day of the month [1-30] +long ceMmDateTime::md(){ + long myt,my,mm,md; + ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); + return md; +} + +// Moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] +long ceMmDateTime::mp(){ + long myt,my,mm,md; + ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); + return ceMmDateTime::cal_mp(md,mm,myt); +} + +// Fortnight day [1-15] +long ceMmDateTime::mf() { + return ceMmDateTime::cal_mf(this->md()); +} + +// get sabbath string +string ceMmDateTime::sabbath() { + long myt,my,mm,md; + ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); + long sb=ceMmDateTime::cal_sabbath(md,mm,myt); + string str=""; + if(sb==1) str="Sabbath"; + else if(sb==2) str="Sabbath Eve"; + return str; +} + +// get yatyaza string +string ceMmDateTime::yatyaza() { + long v=ceMmDateTime::cal_yatyaza(this->mm(),this->w()); + return (v?"Yatyaza":""); +} + +// get pyathada string +string ceMmDateTime::pyathada() { + long v=ceMmDateTime::cal_pyathada(this->mm(),this->w()); + string pa[]={"","Pyathada","Afternoon Pyathada"}; + return pa[v%3]; +} + +// get nagahle direction +string ceMmDateTime::nagahle() { + long v=ceMmDateTime::cal_nagahle(this->mm()); + string pa[]={"West","North","East","South"}; + return pa[v%4]; +} + +// get mahabote direction +string ceMmDateTime::mahabote() { + long v=ceMmDateTime::cal_mahabote(this->my(),this->w()); + string pa[]={"Binga","Atun","Yaza","Adipati","Marana","Thike","Puti"}; + return pa[v%7]; +} + +// get the array of astrological days +vector ceMmDateTime::astro() { + return ceMmDateTime::cal_astro(this->jdnl()); +} + +// get the array of public holidays +vector ceMmDateTime::holidays() { + return ceMmDateTime::cal_holiday(this->jdnl()); +} + +// get the array of other holidays +vector ceMmDateTime::holidays2() { + return ceMmDateTime::cal_holiday2(this->jdnl()); +} + +//------------------------------------------------------------------------- +// get Myanmar Date String +// input: ( +// fs: format string [Optional argument: "&y &M &P &ff"] +// tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) +// output: date string in Myanmar calendar according to fm +// where formatting strings are as follows +// &yyyy : Myanmar year [0000-9999, e.g. 1380] +// &YYYY : Sasana year [0000-9999, e.g. 2562] +// &y : Myanmar year [0-9999, e.g. 138] +// &mm : month with zero padding [01-14] +// &M : month [e.g. January] +// &m : month [1-14] +// &P : moon phase [e.g. waxing, waning, full moon, or new moon] +// &dd : day of the month with zero padding [01-31] +// &d : day of the month [1-31] +// &ff : fortnight day with zero padding [01-15] +// &f : fortnight day [1-15] +string ceMmDateTime::ToMString(string fs) { + return ceMmDateTime::j2ms(this->jd(),fs,this->tz()); +} +//------------------------------------------------------------------------- + } //namespace ce \ No newline at end of file diff --git a/src/ceModbus.cpp b/src/ceModbus.cpp index 6d456ba..1917c2a 100644 --- a/src/ceModbus.cpp +++ b/src/ceModbus.cpp @@ -1,207 +1,207 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceModbus.cpp -// Description: Byte stuffing- sending and receiving frames -// Modbus RTU frame format (primarily used on asynchronous serial data lines like RS-485/EIA-485) -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceModbus.h" -namespace ce { -//----------------------------------------------------------------------------- -ceModbus::ceModbus():ceFrame(),_count(0), _frameSize(8), _tick_n(0), _reset_tick(CE_NUMBER_OF_TICKS_TO_RESET) { -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -size_t ceModbus::SetTxFrame(char* d, size_t n) -{ - if (n > (CE_FRAME_TX_BUF_SIZE - 2)) return 0;// size error - uint16_t txcrc = 0xFFFF;//initialize crc - char c; - size_t i = 0, j = 0; - for (j = 0; j < n; j++) { - c = d[j]; - // no need to check c in building Modbus frame - this->tb[i++] = c; - } - txcrc = this->CRC16((char*)d, n, txcrc);//calculate crc - this->tb[i++] = txcrc & 0xFF; - this->tb[i++] = (txcrc >> 8) & 0xFF; - this->TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -//Inputs -//s : pointer to input char string -//len: string len (maximum 255) -//crc: initial CRC value - -//Output -//Returns calculated CRC - -// Ref: http://cool-emerald.blogspot.com/2009/09/crc-calculation-in-vb-and-c.html -uint16_t ceModbus::CRC16(char* s, size_t len, uint16_t crc) -{ - //CRC Order: 16 - //CRC Poly: 0x8005 <=> A001 - //Operational initial value: 0xFFFF - //Final xor value: 0 - size_t i, j; - for (i = 0; i < len; i++, s++) { - crc ^= ((unsigned int)(*s)) & 0xFF; - for (j = 0; j < 8; j++) { - if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; - else crc >>= 1; - } - } - return (crc & 0xFFFF);//truncate last 16 bit -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -// CRC16 is also included -size_t ceModbus::ReceiveRxFrame(char c) -{ - // accept any value even 0x0D to get 8 bytes - // (not using start and end 28 bit length mark condition) - this->_tick_n = 0; // reset for every rx ch - this->RxN = 0; - this->rb[this->_count++] = c; - - if (this->_count == 3) { - // check function - if (this->rb[1] == 0x06) { - this->_frameSize = 8; // reply for control cmd - } - else if (this->rb[1] == 0x03) { - uint8_t len = (uint8_t)this->rb[2]; - this->_frameSize = 5 + len; // reply for read cmd - } - } - - // instead use frame size for particular frame - if (this->_count >= this->_frameSize) { - this->rb[this->_count] = 0;//null termination - this->RxN = this->_count; - this->_count = 0; - this->_frameSize = 8;// default - this->_tick_n = 0; // will clear RxN when time out - // for (int i = 0; i < this->RxN; i++) printf("%02X ", (unsigned int)this->rb[i] & 0xFF); - // uint16_t rxcrc = ((uint16_t)this->rb[this->RxN-1] << 8 | ((uint16_t)this->rb[this->RxN - 2] & 0xFF)) & 0xFFFF;//get received crc - uint16_t computed_crc = 0xFFFF;//initialize CRC - computed_crc = this->CRC16(rb, RxN, computed_crc);//calculate crc - // printf("\nComputed crc: %02X \n",computed_crc); - if (computed_crc == 0) { - //this->RxN -= 2; - return (this->RxN); //if crc is correct return bytes including crc - } - else { this->RxN = 0; }//discard the frame - } - return 0; -} - -// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx -// return = 0 : if no reset, 1 : if reset -int ceModbus::Tick() -{ - if (this->_tick_n <= this->_reset_tick) { - this->_tick_n++; - } - else { - this->_count = 0; - this->_frameSize = 8;// default - this->RxN = 0; - } - return this->_tick_n; -} - -// command vector without CRC16 -// CRC16 will be calculated and appended -void ceModbus::SetCmd(std::vector v) -{ - this->SetTxFrame((char*)v.data(), v.size()); -} - -void ceModbus::SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data) -{ - uint8_t ah = uint8_t((addr >> 8) & 0xFF); - uint8_t al = uint8_t(addr & 0xFF); - std::vector v = {slaveid,func,ah,al}; - v.insert(v.end(), data.begin(), data.end()); - this->SetCmd(v); -} - -void ceModbus::SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay) -{ - uint8_t ah = uint8_t((addr >> 8) & 0xFF); - uint8_t al = uint8_t(addr & 0xFF); - std::vector v = { slaveid,0x06,ah,al,command,delay }; - this->SetCmd(v); -} - -void ceModbus::SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len) -{ - uint8_t ah = uint8_t((startAddr >> 8) & 0xFF); - uint8_t al = uint8_t(startAddr & 0xFF); - uint8_t lh = uint8_t((len >> 8) & 0xFF); - uint8_t ll = uint8_t(len & 0xFF); - std::vector v = { slaveid,0x03,ah,al,lh,ll }; - this->SetCmd(v); -} - -// extract vector of status from received byte array -// crc16 bytes will be neglected if included -std::vector ceModbus::GetStatus(char* d, size_t n) -{ - std::vector v; - if (n < 3) { - // perror("Modbus frame error in getting status"); - return v; - } - - if (d[1] != 0x03) { - // perror("Frame must be Modbus read status return to get status"); - return v; - } - - uint8_t len = (uint8_t)d[2]; // get len - if (n < ((size_t)len+3)) { - // perror("Modbus frame length error in getting status"); - return v; - } - - uint16_t s; - uint8_t count = len >> 1;// 2 bytes each - for (uint8_t i = 0; i < count; i++) { - // for big endian - s = (uint8_t)d[3 + ((uint64_t)i<<1)]; - s <<= 8; - s |= (uint8_t)d[4 + ((uint64_t)i << 1)]; - v.push_back(s); - } - return v; -} - -std::vector ceModbus::GetTxVec() -{ - std::vector v((char*)tb, (char*)tb + this->TxN); - return v; -} - -std::vector ceModbus::GetRxVec() -{ - std::vector v((char*)rb, (char*)rb + this->RxN); - return v; -} - -void ceModbus::SetResetTickCount(int n) -{ - this->_reset_tick = n; -} - -int ceModbus::GetResetTickCount() -{ - return this->_reset_tick; -} - +///////////////////////////////////////////////////////////////////////////// +// Name: ceModbus.cpp +// Description: Byte stuffing- sending and receiving frames +// Modbus RTU frame format (primarily used on asynchronous serial data lines like RS-485/EIA-485) +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com +///////////////////////////////////////////////////////////////////////////// +#include +#include "ce/ceModbus.h" +namespace ce { +//----------------------------------------------------------------------------- +ceModbus::ceModbus():ceFrame(),_count(0), _frameSize(8), _tick_n(0), _reset_tick(CE_NUMBER_OF_TICKS_TO_RESET) { +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +size_t ceModbus::SetTxFrame(char* d, size_t n) +{ + if (n > (CE_FRAME_TX_BUF_SIZE - 2)) return 0;// size error + uint16_t txcrc = 0xFFFF;//initialize crc + char c; + size_t i = 0, j = 0; + for (j = 0; j < n; j++) { + c = d[j]; + // no need to check c in building Modbus frame + this->tb[i++] = c; + } + txcrc = this->CRC16((char*)d, n, txcrc);//calculate crc + this->tb[i++] = txcrc & 0xFF; + this->tb[i++] = (txcrc >> 8) & 0xFF; + this->TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +//Inputs +//s : pointer to input char string +//len: string len (maximum 255) +//crc: initial CRC value + +//Output +//Returns calculated CRC + +// Ref: http://cool-emerald.blogspot.com/2009/09/crc-calculation-in-vb-and-c.html +uint16_t ceModbus::CRC16(char* s, size_t len, uint16_t crc) +{ + //CRC Order: 16 + //CRC Poly: 0x8005 <=> A001 + //Operational initial value: 0xFFFF + //Final xor value: 0 + size_t i, j; + for (i = 0; i < len; i++, s++) { + crc ^= ((unsigned int)(*s)) & 0xFF; + for (j = 0; j < 8; j++) { + if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; + else crc >>= 1; + } + } + return (crc & 0xFFFF);//truncate last 16 bit +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +// CRC16 is also included +size_t ceModbus::ReceiveRxFrame(char c) +{ + // accept any value even 0x0D to get 8 bytes + // (not using start and end 28 bit length mark condition) + this->_tick_n = 0; // reset for every rx ch + this->RxN = 0; + this->rb[this->_count++] = c; + + if (this->_count == 3) { + // check function + if (this->rb[1] == 0x06) { + this->_frameSize = 8; // reply for control cmd + } + else if (this->rb[1] == 0x03) { + uint8_t len = (uint8_t)this->rb[2]; + this->_frameSize = 5 + len; // reply for read cmd + } + } + + // instead use frame size for particular frame + if (this->_count >= this->_frameSize) { + this->rb[this->_count] = 0;//null termination + this->RxN = this->_count; + this->_count = 0; + this->_frameSize = 8;// default + this->_tick_n = 0; // will clear RxN when time out + // for (int i = 0; i < this->RxN; i++) printf("%02X ", (unsigned int)this->rb[i] & 0xFF); + // uint16_t rxcrc = ((uint16_t)this->rb[this->RxN-1] << 8 | ((uint16_t)this->rb[this->RxN - 2] & 0xFF)) & 0xFFFF;//get received crc + uint16_t computed_crc = 0xFFFF;//initialize CRC + computed_crc = this->CRC16(rb, RxN, computed_crc);//calculate crc + // printf("\nComputed crc: %02X \n",computed_crc); + if (computed_crc == 0) { + //this->RxN -= 2; + return (this->RxN); //if crc is correct return bytes including crc + } + else { this->RxN = 0; }//discard the frame + } + return 0; +} + +// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx +// return = 0 : if no reset, 1 : if reset +int ceModbus::Tick() +{ + if (this->_tick_n <= this->_reset_tick) { + this->_tick_n++; + } + else { + this->_count = 0; + this->_frameSize = 8;// default + this->RxN = 0; + } + return this->_tick_n; +} + +// command vector without CRC16 +// CRC16 will be calculated and appended +void ceModbus::SetCmd(std::vector v) +{ + this->SetTxFrame((char*)v.data(), v.size()); +} + +void ceModbus::SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data) +{ + uint8_t ah = uint8_t((addr >> 8) & 0xFF); + uint8_t al = uint8_t(addr & 0xFF); + std::vector v = {slaveid,func,ah,al}; + v.insert(v.end(), data.begin(), data.end()); + this->SetCmd(v); +} + +void ceModbus::SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay) +{ + uint8_t ah = uint8_t((addr >> 8) & 0xFF); + uint8_t al = uint8_t(addr & 0xFF); + std::vector v = { slaveid,0x06,ah,al,command,delay }; + this->SetCmd(v); +} + +void ceModbus::SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len) +{ + uint8_t ah = uint8_t((startAddr >> 8) & 0xFF); + uint8_t al = uint8_t(startAddr & 0xFF); + uint8_t lh = uint8_t((len >> 8) & 0xFF); + uint8_t ll = uint8_t(len & 0xFF); + std::vector v = { slaveid,0x03,ah,al,lh,ll }; + this->SetCmd(v); +} + +// extract vector of status from received byte array +// crc16 bytes will be neglected if included +std::vector ceModbus::GetStatus(char* d, size_t n) +{ + std::vector v; + if (n < 3) { + // perror("Modbus frame error in getting status"); + return v; + } + + if (d[1] != 0x03) { + // perror("Frame must be Modbus read status return to get status"); + return v; + } + + uint8_t len = (uint8_t)d[2]; // get len + if (n < ((size_t)len+3)) { + // perror("Modbus frame length error in getting status"); + return v; + } + + uint16_t s; + uint8_t count = len >> 1;// 2 bytes each + for (uint8_t i = 0; i < count; i++) { + // for big endian + s = (uint8_t)d[3 + ((uint64_t)i<<1)]; + s <<= 8; + s |= (uint8_t)d[4 + ((uint64_t)i << 1)]; + v.push_back(s); + } + return v; +} + +std::vector ceModbus::GetTxVec() +{ + std::vector v((char*)tb, (char*)tb + this->TxN); + return v; +} + +std::vector ceModbus::GetRxVec() +{ + std::vector v((char*)rb, (char*)rb + this->RxN); + return v; +} + +void ceModbus::SetResetTickCount(int n) +{ + this->_reset_tick = n; +} + +int ceModbus::GetResetTickCount() +{ + return this->_reset_tick; +} + } // namespace ce \ No newline at end of file diff --git a/src/ceRSA_OS.cpp b/src/ceRSA_OS.cpp index ee04acd..d282b34 100644 --- a/src/ceRSA_OS.cpp +++ b/src/ceRSA_OS.cpp @@ -1,184 +1,184 @@ -// Description: Functions to calculate SHA1 -// Class implementation of the following repository: https://github.com/clibs/sha1 - -#include "ce/ceMacros.h" -#include "ce/ceRSA_OS.h" - -#ifdef CE_WINDOWS -#ifdef _MSC_VER -#pragma warning(disable : 4996) -#endif -#endif - -using namespace std; -namespace ce { -// ---------------------------------------------------------------------------- - -// Load public key from file -RSA* ceRSA_OS::loadPublicKey(std::string publicKeyFile) { - RSA* keypair = RSA_new(); - FILE* publicKey = fopen(publicKeyFile.c_str(), "r"); - PEM_read_RSAPublicKey(publicKey, &keypair, NULL, NULL); - fclose(publicKey); - return keypair; -} - -// Load private key from file -RSA* ceRSA_OS::loadPrivateKey(std::string privateKeyFile) { - RSA* keypair = RSA_new(); - FILE* bigN = fopen(privateKeyFile.c_str(), "r"); - PEM_read_RSAPrivateKey(bigN, &keypair, NULL, NULL); - fclose(bigN); - return keypair; -} - -// Encrypt data using public key -std::string ceRSA_OS::encrypt(const std::string& message, RSA* rsa_key) { - int rsa_size = RSA_size(rsa_key); - std::vector ciphertext(rsa_size); - - int len = RSA_public_encrypt(message.size(), reinterpret_cast(message.data()), - ciphertext.data(), rsa_key, RSA_NO_PADDING); - //ciphertext.data(), rsa_key, RSA_PKCS1_PADDING); - - if (len < 0) { - // std::cerr << "Encryption failed" << std::endl; - return ""; - } - - return std::string(reinterpret_cast(ciphertext.data()), len); -} - -// Decrypt data using private key -std::string ceRSA_OS::decrypt(const std::string& ciphertext, RSA* rsa_key) { - int rsa_size = RSA_size(rsa_key); - std::vector message(rsa_size); - - int len = RSA_private_decrypt(ciphertext.size(), reinterpret_cast(ciphertext.data()), - message.data(), rsa_key, RSA_NO_PADDING); - - if (len < 0) { - // std::cerr << "Decryption failed" << std::endl; - return ""; - } - - return std::string(reinterpret_cast(message.data()), len); -} - -string ceRSA_OS::bn2str(BIGNUM* bigN) -{ - // Convert BIGNUM to binary representation - size_t bnSize = BN_num_bytes(bigN); - unsigned char* bnStr = new unsigned char[bnSize]; - BN_bn2bin(bigN, bnStr); - string bnString((char*)bnStr, bnSize); - return bnString; -} - -// ---------------------------------------------------------------------------- - -// Generate a public-private key pair and save to files -RSA* ceRSA_OS::generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t keyLength, uint32_t exp) { - RSA* keypair = RSA_new(); - BIGNUM* e = BN_new(); - BN_set_word(e, exp); - - RSA_generate_key_ex(keypair, keyLength, e, NULL); - FILE* publicKey = fopen(publicKeyFile.c_str(), "w"); - PEM_write_RSAPublicKey(publicKey, keypair); - fclose(publicKey); - - FILE* bigN = fopen(privateKeyFile.c_str(), "w"); - PEM_write_RSAPrivateKey(bigN, keypair, NULL, NULL, 0, NULL, NULL); - fclose(bigN); - - BN_free(e); - return keypair; -} - -// Generate a public-private key pair and returns RSA -RSA* ceRSA_OS::generateKeyPair(uint32_t keyLength, uint32_t exp) { - RSA* keypair = RSA_new(); - BIGNUM* e = BN_new(); - BN_set_word(e, exp); - RSA_generate_key_ex(keypair, keyLength, e, NULL); - BN_free(e); - return keypair; -} - -// Encrypt data using public key -std::string ceRSA_OS::encrypt(const std::string& message, std::string publicKeyFile) -{ - // Load public key - RSA* public_key = loadPublicKey(publicKeyFile); - std::string encrypted = encrypt(message, public_key); - return encrypted; -} - -// Decrypt data using private key -std::string ceRSA_OS::decrypt(const std::string& ciphertext, std::string privateKeyFile) -{ - // Load private key - RSA* private_key = loadPrivateKey(privateKeyFile); - std::string decrypted = decrypt(ciphertext, private_key); - return decrypted; -} - -// Encrypt data using modulus n and exponent e -std::string ceRSA_OS::encrypt(const std::string& message, std::string n, std::string e) -{ - BIGNUM* bn_e3 = BN_new(); - BIGNUM* bn_n3 = BN_new(); - - if (BN_bin2bn((const unsigned char*)e.c_str(), e.length(), bn_e3) == NULL) { - printf("Failed to convert modulus"); - } - if (BN_bin2bn((const unsigned char*)n.c_str(), n.length(), bn_n3) == NULL) { - printf("Failed to convert exponent"); - } - - RSA* public_key3 = RSA_new(); - RSA_set0_key(public_key3, bn_n3, bn_e3, NULL); - - std::string encrypted = encrypt(message, public_key3); - return encrypted; -} - -// Decrypt data using secret number d, modulus n and exponent e -std::string ceRSA_OS::decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e) -{ - BIGNUM* bn_d3 = BN_new(); - BIGNUM* bn_e3 = BN_new(); - BIGNUM* bn_n3 = BN_new(); - if (BN_bin2bn((const unsigned char*)d.c_str(), d.length(), bn_d3) == NULL) { - printf("Failed to convert d"); - } - if (BN_bin2bn((const unsigned char*)e.c_str(), e.length(), bn_e3) == NULL) { - printf("Failed to convert modulus"); - } - if (BN_bin2bn((const unsigned char*)n.c_str(), n.length(), bn_n3) == NULL) { - printf("Failed to convert exponent"); - } - - RSA* private_key3 = RSA_new(); - RSA_set0_key(private_key3, bn_n3, bn_e3, bn_d3); - - std::string decrypted = decrypt(ciphertext, private_key3); - return decrypted; -} - -// Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key -void ceRSA_OS::getBN(RSA* key, std::string& d, std::string& n, std::string& e) -{ - // Obtain the key components as BIGNUM - BIGNUM* bn_d = BN_dup(RSA_get0_d(key)); - BIGNUM* bn_e = BN_dup(RSA_get0_e(key)); - BIGNUM* bn_n = BN_dup(RSA_get0_n(key)); - - d = bn2str(bn_d); - e = bn2str(bn_e); - n = bn2str(bn_n); -} - -// ---------------------------------------------------------------------------- +// Description: Functions to calculate SHA1 +// Class implementation of the following repository: https://github.com/clibs/sha1 + +#include "ce/ceMacros.h" +#include "ce/ceRSA_OS.h" + +#ifdef CE_WINDOWS +#ifdef _MSC_VER +#pragma warning(disable : 4996) +#endif +#endif + +using namespace std; +namespace ce { +// ---------------------------------------------------------------------------- + +// Load public key from file +RSA* ceRSA_OS::loadPublicKey(std::string publicKeyFile) { + RSA* keypair = RSA_new(); + FILE* publicKey = fopen(publicKeyFile.c_str(), "r"); + PEM_read_RSAPublicKey(publicKey, &keypair, NULL, NULL); + fclose(publicKey); + return keypair; +} + +// Load private key from file +RSA* ceRSA_OS::loadPrivateKey(std::string privateKeyFile) { + RSA* keypair = RSA_new(); + FILE* bigN = fopen(privateKeyFile.c_str(), "r"); + PEM_read_RSAPrivateKey(bigN, &keypair, NULL, NULL); + fclose(bigN); + return keypair; +} + +// Encrypt data using public key +std::string ceRSA_OS::encrypt(const std::string& message, RSA* rsa_key) { + int rsa_size = RSA_size(rsa_key); + std::vector ciphertext(rsa_size); + + int len = RSA_public_encrypt(message.size(), reinterpret_cast(message.data()), + ciphertext.data(), rsa_key, RSA_NO_PADDING); + //ciphertext.data(), rsa_key, RSA_PKCS1_PADDING); + + if (len < 0) { + // std::cerr << "Encryption failed" << std::endl; + return ""; + } + + return std::string(reinterpret_cast(ciphertext.data()), len); +} + +// Decrypt data using private key +std::string ceRSA_OS::decrypt(const std::string& ciphertext, RSA* rsa_key) { + int rsa_size = RSA_size(rsa_key); + std::vector message(rsa_size); + + int len = RSA_private_decrypt(ciphertext.size(), reinterpret_cast(ciphertext.data()), + message.data(), rsa_key, RSA_NO_PADDING); + + if (len < 0) { + // std::cerr << "Decryption failed" << std::endl; + return ""; + } + + return std::string(reinterpret_cast(message.data()), len); +} + +string ceRSA_OS::bn2str(BIGNUM* bigN) +{ + // Convert BIGNUM to binary representation + size_t bnSize = BN_num_bytes(bigN); + unsigned char* bnStr = new unsigned char[bnSize]; + BN_bn2bin(bigN, bnStr); + string bnString((char*)bnStr, bnSize); + return bnString; +} + +// ---------------------------------------------------------------------------- + +// Generate a public-private key pair and save to files +RSA* ceRSA_OS::generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t keyLength, uint32_t exp) { + RSA* keypair = RSA_new(); + BIGNUM* e = BN_new(); + BN_set_word(e, exp); + + RSA_generate_key_ex(keypair, keyLength, e, NULL); + FILE* publicKey = fopen(publicKeyFile.c_str(), "w"); + PEM_write_RSAPublicKey(publicKey, keypair); + fclose(publicKey); + + FILE* bigN = fopen(privateKeyFile.c_str(), "w"); + PEM_write_RSAPrivateKey(bigN, keypair, NULL, NULL, 0, NULL, NULL); + fclose(bigN); + + BN_free(e); + return keypair; +} + +// Generate a public-private key pair and returns RSA +RSA* ceRSA_OS::generateKeyPair(uint32_t keyLength, uint32_t exp) { + RSA* keypair = RSA_new(); + BIGNUM* e = BN_new(); + BN_set_word(e, exp); + RSA_generate_key_ex(keypair, keyLength, e, NULL); + BN_free(e); + return keypair; +} + +// Encrypt data using public key +std::string ceRSA_OS::encrypt(const std::string& message, std::string publicKeyFile) +{ + // Load public key + RSA* public_key = loadPublicKey(publicKeyFile); + std::string encrypted = encrypt(message, public_key); + return encrypted; +} + +// Decrypt data using private key +std::string ceRSA_OS::decrypt(const std::string& ciphertext, std::string privateKeyFile) +{ + // Load private key + RSA* private_key = loadPrivateKey(privateKeyFile); + std::string decrypted = decrypt(ciphertext, private_key); + return decrypted; +} + +// Encrypt data using modulus n and exponent e +std::string ceRSA_OS::encrypt(const std::string& message, std::string n, std::string e) +{ + BIGNUM* bn_e3 = BN_new(); + BIGNUM* bn_n3 = BN_new(); + + if (BN_bin2bn((const unsigned char*)e.c_str(), e.length(), bn_e3) == NULL) { + printf("Failed to convert modulus"); + } + if (BN_bin2bn((const unsigned char*)n.c_str(), n.length(), bn_n3) == NULL) { + printf("Failed to convert exponent"); + } + + RSA* public_key3 = RSA_new(); + RSA_set0_key(public_key3, bn_n3, bn_e3, NULL); + + std::string encrypted = encrypt(message, public_key3); + return encrypted; +} + +// Decrypt data using secret number d, modulus n and exponent e +std::string ceRSA_OS::decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e) +{ + BIGNUM* bn_d3 = BN_new(); + BIGNUM* bn_e3 = BN_new(); + BIGNUM* bn_n3 = BN_new(); + if (BN_bin2bn((const unsigned char*)d.c_str(), d.length(), bn_d3) == NULL) { + printf("Failed to convert d"); + } + if (BN_bin2bn((const unsigned char*)e.c_str(), e.length(), bn_e3) == NULL) { + printf("Failed to convert modulus"); + } + if (BN_bin2bn((const unsigned char*)n.c_str(), n.length(), bn_n3) == NULL) { + printf("Failed to convert exponent"); + } + + RSA* private_key3 = RSA_new(); + RSA_set0_key(private_key3, bn_n3, bn_e3, bn_d3); + + std::string decrypted = decrypt(ciphertext, private_key3); + return decrypted; +} + +// Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key +void ceRSA_OS::getBN(RSA* key, std::string& d, std::string& n, std::string& e) +{ + // Obtain the key components as BIGNUM + BIGNUM* bn_d = BN_dup(RSA_get0_d(key)); + BIGNUM* bn_e = BN_dup(RSA_get0_e(key)); + BIGNUM* bn_n = BN_dup(RSA_get0_n(key)); + + d = bn2str(bn_d); + e = bn2str(bn_e); + n = bn2str(bn_n); +} + +// ---------------------------------------------------------------------------- } // namespace ce \ No newline at end of file diff --git a/src/ceSHA1.cpp b/src/ceSHA1.cpp index 583a189..e82861e 100644 --- a/src/ceSHA1.cpp +++ b/src/ceSHA1.cpp @@ -1,317 +1,317 @@ -// Description: Functions to calculate SHA1 -// Class implementation of the following repository: https://github.com/clibs/sha1 - -/* -SHA-1 in C -By Steve Reid -100% Public Domain - -Test Vectors (from FIPS PUB 180-1) -"abc" - A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D -"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 -A million repetitions of "a" - 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F -*/ - -/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ -/* #define SHA1HANDSOFF * Copies data before messing with it. */ - -#define SHA1HANDSOFF - -#include -#include - -/* for uint32_t */ -#include - -#include "ce/ceSHA1.h" - - -#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -/* blk0() and blk() perform the initial expand. */ -/* I got the idea of expanding during the round function from SSLeay */ -#if BYTE_ORDER == LITTLE_ENDIAN -#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ - |(rol(block->l[i],8)&0x00FF00FF)) -#elif BYTE_ORDER == BIG_ENDIAN -#define blk0(i) block->l[i] -#else -#error "Endianness not defined!" -#endif -#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ - ^block->l[(i+2)&15]^block->l[i&15],1)) - -/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ -#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); -#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); -#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); - -namespace ce { -/* Hash a single 512-bit block. This is the core of the algorithm. */ - -void ceSHA1::SHA1Transform( - uint32_t state[5], - const unsigned char buffer[64] -) -{ - uint32_t a, b, c, d, e; - - typedef union - { - unsigned char c[64]; - uint32_t l[16]; - } CHAR64LONG16; - -#ifdef SHA1HANDSOFF - CHAR64LONG16 block[1]; /* use array to appear as a pointer */ - - memcpy(block, buffer, 64); -#else - /* The following had better never be used because it causes the - * pointer-to-const buffer to be cast into a pointer to non-const. - * And the result is written through. I threw a "const" in, hoping - * this will cause a diagnostic. - */ - CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer; -#endif - /* Copy context->state[] to working vars */ - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - /* 4 rounds of 20 operations each. Loop unrolled. */ - R0(a, b, c, d, e, 0); - R0(e, a, b, c, d, 1); - R0(d, e, a, b, c, 2); - R0(c, d, e, a, b, 3); - R0(b, c, d, e, a, 4); - R0(a, b, c, d, e, 5); - R0(e, a, b, c, d, 6); - R0(d, e, a, b, c, 7); - R0(c, d, e, a, b, 8); - R0(b, c, d, e, a, 9); - R0(a, b, c, d, e, 10); - R0(e, a, b, c, d, 11); - R0(d, e, a, b, c, 12); - R0(c, d, e, a, b, 13); - R0(b, c, d, e, a, 14); - R0(a, b, c, d, e, 15); - R1(e, a, b, c, d, 16); - R1(d, e, a, b, c, 17); - R1(c, d, e, a, b, 18); - R1(b, c, d, e, a, 19); - R2(a, b, c, d, e, 20); - R2(e, a, b, c, d, 21); - R2(d, e, a, b, c, 22); - R2(c, d, e, a, b, 23); - R2(b, c, d, e, a, 24); - R2(a, b, c, d, e, 25); - R2(e, a, b, c, d, 26); - R2(d, e, a, b, c, 27); - R2(c, d, e, a, b, 28); - R2(b, c, d, e, a, 29); - R2(a, b, c, d, e, 30); - R2(e, a, b, c, d, 31); - R2(d, e, a, b, c, 32); - R2(c, d, e, a, b, 33); - R2(b, c, d, e, a, 34); - R2(a, b, c, d, e, 35); - R2(e, a, b, c, d, 36); - R2(d, e, a, b, c, 37); - R2(c, d, e, a, b, 38); - R2(b, c, d, e, a, 39); - R3(a, b, c, d, e, 40); - R3(e, a, b, c, d, 41); - R3(d, e, a, b, c, 42); - R3(c, d, e, a, b, 43); - R3(b, c, d, e, a, 44); - R3(a, b, c, d, e, 45); - R3(e, a, b, c, d, 46); - R3(d, e, a, b, c, 47); - R3(c, d, e, a, b, 48); - R3(b, c, d, e, a, 49); - R3(a, b, c, d, e, 50); - R3(e, a, b, c, d, 51); - R3(d, e, a, b, c, 52); - R3(c, d, e, a, b, 53); - R3(b, c, d, e, a, 54); - R3(a, b, c, d, e, 55); - R3(e, a, b, c, d, 56); - R3(d, e, a, b, c, 57); - R3(c, d, e, a, b, 58); - R3(b, c, d, e, a, 59); - R4(a, b, c, d, e, 60); - R4(e, a, b, c, d, 61); - R4(d, e, a, b, c, 62); - R4(c, d, e, a, b, 63); - R4(b, c, d, e, a, 64); - R4(a, b, c, d, e, 65); - R4(e, a, b, c, d, 66); - R4(d, e, a, b, c, 67); - R4(c, d, e, a, b, 68); - R4(b, c, d, e, a, 69); - R4(a, b, c, d, e, 70); - R4(e, a, b, c, d, 71); - R4(d, e, a, b, c, 72); - R4(c, d, e, a, b, 73); - R4(b, c, d, e, a, 74); - R4(a, b, c, d, e, 75); - R4(e, a, b, c, d, 76); - R4(d, e, a, b, c, 77); - R4(c, d, e, a, b, 78); - R4(b, c, d, e, a, 79); - /* Add the working vars back into context.state[] */ - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - /* Wipe variables */ - a = b = c = d = e = 0; -#ifdef SHA1HANDSOFF - memset(block, '\0', sizeof(block)); -#endif -} - - -/* SHA1Init - Initialize new context */ - -void ceSHA1::SHA1Init( - SHA1_CTX * context -) -{ - /* SHA1 initialization constants */ - context->state[0] = 0x67452301; - context->state[1] = 0xEFCDAB89; - context->state[2] = 0x98BADCFE; - context->state[3] = 0x10325476; - context->state[4] = 0xC3D2E1F0; - context->count[0] = context->count[1] = 0; -} - - -/* Run your data through this. */ - -void ceSHA1::SHA1Update( - SHA1_CTX * context, - const unsigned char *data, - uint32_t len -) -{ - uint32_t i; - - uint32_t j; - - j = context->count[0]; - if ((context->count[0] += len << 3) < j) - context->count[1]++; - context->count[1] += (len >> 29); - j = (j >> 3) & 63; - if ((j + len) > 63) - { - memcpy(&context->buffer[j], data, (i = 64 - j)); - SHA1Transform(context->state, context->buffer); - for (; i + 63 < len; i += 64) - { - SHA1Transform(context->state, &data[i]); - } - j = 0; - } - else - i = 0; - memcpy(&context->buffer[j], &data[i], len - i); -} - - -/* Add padding and return the message digest. */ - -void ceSHA1::SHA1Final( - unsigned char digest[20], - SHA1_CTX * context -) -{ - unsigned i; - - unsigned char finalcount[8]; - - unsigned char c; - -#if 0 /* untested "improvement" by DHR */ - /* Convert context->count to a sequence of bytes - * in finalcount. Second element first, but - * big-endian order within element. - * But we do it all backwards. - */ - unsigned char *fcp = &finalcount[8]; - - for (i = 0; i < 2; i++) - { - uint32_t t = context->count[i]; - - int j; - - for (j = 0; j < 4; t >>= 8, j++) - *--fcp = (unsigned char) t} -#else - for (i = 0; i < 8; i++) - { - finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ - } -#endif - c = 0200; - SHA1Update(context, &c, 1); - while ((context->count[0] & 504) != 448) - { - c = 0000; - SHA1Update(context, &c, 1); - } - SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ - for (i = 0; i < 20; i++) - { - digest[i] = (unsigned char) - ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); - } - /* Wipe variables */ - memset(context, '\0', sizeof(*context)); - memset(&finalcount, '\0', sizeof(finalcount)); -} - -void ceSHA1::SHA1( - char *hash_out, - const char *str, - uint32_t len) -{ - SHA1_CTX ctx; - unsigned int ii; - - SHA1Init(&ctx); - for (ii=0; ii +100% Public Domain + +Test Vectors (from FIPS PUB 180-1) +"abc" + A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D +"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 +A million repetitions of "a" + 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F +*/ + +/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ +/* #define SHA1HANDSOFF * Copies data before messing with it. */ + +#define SHA1HANDSOFF + +#include +#include + +/* for uint32_t */ +#include + +#include "ce/ceSHA1.h" + + +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) + +/* blk0() and blk() perform the initial expand. */ +/* I got the idea of expanding during the round function from SSLeay */ +#if BYTE_ORDER == LITTLE_ENDIAN +#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ + |(rol(block->l[i],8)&0x00FF00FF)) +#elif BYTE_ORDER == BIG_ENDIAN +#define blk0(i) block->l[i] +#else +#error "Endianness not defined!" +#endif +#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ + ^block->l[(i+2)&15]^block->l[i&15],1)) + +/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ +#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); +#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); +#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); + +namespace ce { +/* Hash a single 512-bit block. This is the core of the algorithm. */ + +void ceSHA1::SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] +) +{ + uint32_t a, b, c, d, e; + + typedef union + { + unsigned char c[64]; + uint32_t l[16]; + } CHAR64LONG16; + +#ifdef SHA1HANDSOFF + CHAR64LONG16 block[1]; /* use array to appear as a pointer */ + + memcpy(block, buffer, 64); +#else + /* The following had better never be used because it causes the + * pointer-to-const buffer to be cast into a pointer to non-const. + * And the result is written through. I threw a "const" in, hoping + * this will cause a diagnostic. + */ + CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer; +#endif + /* Copy context->state[] to working vars */ + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + /* 4 rounds of 20 operations each. Loop unrolled. */ + R0(a, b, c, d, e, 0); + R0(e, a, b, c, d, 1); + R0(d, e, a, b, c, 2); + R0(c, d, e, a, b, 3); + R0(b, c, d, e, a, 4); + R0(a, b, c, d, e, 5); + R0(e, a, b, c, d, 6); + R0(d, e, a, b, c, 7); + R0(c, d, e, a, b, 8); + R0(b, c, d, e, a, 9); + R0(a, b, c, d, e, 10); + R0(e, a, b, c, d, 11); + R0(d, e, a, b, c, 12); + R0(c, d, e, a, b, 13); + R0(b, c, d, e, a, 14); + R0(a, b, c, d, e, 15); + R1(e, a, b, c, d, 16); + R1(d, e, a, b, c, 17); + R1(c, d, e, a, b, 18); + R1(b, c, d, e, a, 19); + R2(a, b, c, d, e, 20); + R2(e, a, b, c, d, 21); + R2(d, e, a, b, c, 22); + R2(c, d, e, a, b, 23); + R2(b, c, d, e, a, 24); + R2(a, b, c, d, e, 25); + R2(e, a, b, c, d, 26); + R2(d, e, a, b, c, 27); + R2(c, d, e, a, b, 28); + R2(b, c, d, e, a, 29); + R2(a, b, c, d, e, 30); + R2(e, a, b, c, d, 31); + R2(d, e, a, b, c, 32); + R2(c, d, e, a, b, 33); + R2(b, c, d, e, a, 34); + R2(a, b, c, d, e, 35); + R2(e, a, b, c, d, 36); + R2(d, e, a, b, c, 37); + R2(c, d, e, a, b, 38); + R2(b, c, d, e, a, 39); + R3(a, b, c, d, e, 40); + R3(e, a, b, c, d, 41); + R3(d, e, a, b, c, 42); + R3(c, d, e, a, b, 43); + R3(b, c, d, e, a, 44); + R3(a, b, c, d, e, 45); + R3(e, a, b, c, d, 46); + R3(d, e, a, b, c, 47); + R3(c, d, e, a, b, 48); + R3(b, c, d, e, a, 49); + R3(a, b, c, d, e, 50); + R3(e, a, b, c, d, 51); + R3(d, e, a, b, c, 52); + R3(c, d, e, a, b, 53); + R3(b, c, d, e, a, 54); + R3(a, b, c, d, e, 55); + R3(e, a, b, c, d, 56); + R3(d, e, a, b, c, 57); + R3(c, d, e, a, b, 58); + R3(b, c, d, e, a, 59); + R4(a, b, c, d, e, 60); + R4(e, a, b, c, d, 61); + R4(d, e, a, b, c, 62); + R4(c, d, e, a, b, 63); + R4(b, c, d, e, a, 64); + R4(a, b, c, d, e, 65); + R4(e, a, b, c, d, 66); + R4(d, e, a, b, c, 67); + R4(c, d, e, a, b, 68); + R4(b, c, d, e, a, 69); + R4(a, b, c, d, e, 70); + R4(e, a, b, c, d, 71); + R4(d, e, a, b, c, 72); + R4(c, d, e, a, b, 73); + R4(b, c, d, e, a, 74); + R4(a, b, c, d, e, 75); + R4(e, a, b, c, d, 76); + R4(d, e, a, b, c, 77); + R4(c, d, e, a, b, 78); + R4(b, c, d, e, a, 79); + /* Add the working vars back into context.state[] */ + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + /* Wipe variables */ + a = b = c = d = e = 0; +#ifdef SHA1HANDSOFF + memset(block, '\0', sizeof(block)); +#endif +} + + +/* SHA1Init - Initialize new context */ + +void ceSHA1::SHA1Init( + SHA1_CTX * context +) +{ + /* SHA1 initialization constants */ + context->state[0] = 0x67452301; + context->state[1] = 0xEFCDAB89; + context->state[2] = 0x98BADCFE; + context->state[3] = 0x10325476; + context->state[4] = 0xC3D2E1F0; + context->count[0] = context->count[1] = 0; +} + + +/* Run your data through this. */ + +void ceSHA1::SHA1Update( + SHA1_CTX * context, + const unsigned char *data, + uint32_t len +) +{ + uint32_t i; + + uint32_t j; + + j = context->count[0]; + if ((context->count[0] += len << 3) < j) + context->count[1]++; + context->count[1] += (len >> 29); + j = (j >> 3) & 63; + if ((j + len) > 63) + { + memcpy(&context->buffer[j], data, (i = 64 - j)); + SHA1Transform(context->state, context->buffer); + for (; i + 63 < len; i += 64) + { + SHA1Transform(context->state, &data[i]); + } + j = 0; + } + else + i = 0; + memcpy(&context->buffer[j], &data[i], len - i); +} + + +/* Add padding and return the message digest. */ + +void ceSHA1::SHA1Final( + unsigned char digest[20], + SHA1_CTX * context +) +{ + unsigned i; + + unsigned char finalcount[8]; + + unsigned char c; + +#if 0 /* untested "improvement" by DHR */ + /* Convert context->count to a sequence of bytes + * in finalcount. Second element first, but + * big-endian order within element. + * But we do it all backwards. + */ + unsigned char *fcp = &finalcount[8]; + + for (i = 0; i < 2; i++) + { + uint32_t t = context->count[i]; + + int j; + + for (j = 0; j < 4; t >>= 8, j++) + *--fcp = (unsigned char) t} +#else + for (i = 0; i < 8; i++) + { + finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ + } +#endif + c = 0200; + SHA1Update(context, &c, 1); + while ((context->count[0] & 504) != 448) + { + c = 0000; + SHA1Update(context, &c, 1); + } + SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ + for (i = 0; i < 20; i++) + { + digest[i] = (unsigned char) + ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); + } + /* Wipe variables */ + memset(context, '\0', sizeof(*context)); + memset(&finalcount, '\0', sizeof(finalcount)); +} + +void ceSHA1::SHA1( + char *hash_out, + const char *str, + uint32_t len) +{ + SHA1_CTX ctx; + unsigned int ii; + + SHA1Init(&ctx); + for (ii=0; ii -#include -#include -#include -using namespace std; - - -#ifdef CE_WINDOWS - #define READ_TIMEOUT 10 // milliseconds -#else - #include - #include - #include - #include - #include -#endif - -namespace ce { - -void ceSerial::Delay(unsigned long ms){ -#ifdef CE_WINDOWS - Sleep(ms); -#else - usleep(ms*1000); -#endif -} - -ceSerial::ceSerial() : -#ifdef CE_WINDOWS - ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1) -#else - ceSerial("/dev/ttyS0", 9600, 8, 'N', 1) -#endif -{ - -} - -ceSerial::ceSerial(string Device, long BaudRate,long DataSize,char ParityType,float NStopBits):stdbaud(true) -{ -#ifdef CE_WINDOWS - hComm = INVALID_HANDLE_VALUE; -#else - fd = -1; -#endif // defined - SetBaudRate(BaudRate); - SetDataSize(DataSize); - SetParity(ParityType); - SetStopBits(NStopBits); - SetPortName(Device); -} - -ceSerial::~ceSerial() -{ - Close(); -} - -void ceSerial::SetPortName(string Device) { - port = Device; -} - -string ceSerial::GetPort() { - return port; -} - -void ceSerial::SetDataSize(long nbits) { - if ((nbits < 5) || (nbits > 8)) nbits = 8; - dsize=nbits; -} - -long ceSerial::GetDataSize() { - return dsize; -} - -void ceSerial::SetParity(char p) { - if ((p != 'N') && (p != 'E') && (p != 'O')) { -#ifdef CE_WINDOWS - if ((p != 'M') && (p != 'S')) p = 'N'; -#else - p = 'N'; -#endif - } - parity = p; -} - -char ceSerial::GetParity() { - return parity; -} - -void ceSerial::SetStopBits(float nbits) { - if (nbits >= 2) stopbits = 2; -#ifdef CE_WINDOWS - else if(nbits >= 1.5) stopbits = 1.5; -#endif - else stopbits = 1; -} - -float ceSerial::GetStopBits() { - return stopbits; -} - - -#ifdef CE_WINDOWS - -void ceSerial::SetBaudRate(long baudrate) { - stdbaud = true; - if (baudrate == 1100) baud = CBR_110; - else if (baudrate == 300) baud = CBR_300; - else if (baudrate == 600) baud = CBR_600; - else if (baudrate == 1200) baud = CBR_1200; - else if (baudrate == 2400) baud = CBR_2400; - else if (baudrate == 4800) baud = CBR_4800; - else if (baudrate == 9600) baud = CBR_9600; - else if (baudrate == 14400) baud = CBR_14400; - else if (baudrate == 19200) baud = CBR_19200; - else if (baudrate == 38400) baud = CBR_38400; - else if (baudrate == 57600) baud = CBR_57600; - else if (baudrate == 115200) baud = CBR_115200; - else if (baudrate == 128000) baud = CBR_128000; - else if (baudrate == 256000) baud = CBR_256000; - else { - baud = baudrate; - stdbaud = false; - } -} - -long ceSerial::GetBaudRate() { - return baud; -} - -long ceSerial::Open() -{ - if (IsOpened()) return 0; -#ifdef UNICODE - wstring wtext(port.begin(),port.end()); -#else - string wtext = port; -#endif - hComm = CreateFile(wtext.c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, - 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, - 0); - if (hComm == INVALID_HANDLE_VALUE) {return -1;} - - if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) {return -1;}//purge - - //get initial state - DCB dcbOri; - bool fSuccess; - fSuccess = GetCommState(hComm, &dcbOri); - if (!fSuccess) {return -1;} - - DCB dcb1 = dcbOri; - - dcb1.BaudRate = baud; - - if (parity == 'E') dcb1.Parity = EVENPARITY; - else if (parity == 'O') dcb1.Parity = ODDPARITY; - else if (parity == 'M') dcb1.Parity = MARKPARITY; - else if (parity == 'S') dcb1.Parity = SPACEPARITY; - else dcb1.Parity = NOPARITY; - - dcb1.ByteSize = (BYTE)dsize; - - if(stopbits==2) dcb1.StopBits = TWOSTOPBITS; - else if (stopbits == 1.5) dcb1.StopBits = ONE5STOPBITS; - else dcb1.StopBits = ONESTOPBIT; - - dcb1.fOutxCtsFlow = false; - dcb1.fOutxDsrFlow = false; - dcb1.fOutX = false; - dcb1.fDtrControl = DTR_CONTROL_DISABLE; - dcb1.fRtsControl = RTS_CONTROL_DISABLE; - fSuccess = SetCommState(hComm, &dcb1); - this->Delay(60); - if (!fSuccess) {return -1;} - - fSuccess = GetCommState(hComm, &dcb1); - if (!fSuccess) {return -1;} - - osReader = { 0 };// Create the overlapped event. - // Must be closed before exiting to avoid a handle leak. - osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - - if (osReader.hEvent == NULL) {return -1;}// Error creating overlapped event; abort. - fWaitingOnRead = FALSE; - - osWrite = { 0 }; - osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if (osWrite.hEvent == NULL) {return -1;} - - if (!GetCommTimeouts(hComm, &timeouts_ori)) { return -1; } // Error getting time-outs. - COMMTIMEOUTS timeouts; - timeouts.ReadIntervalTimeout = 20; - timeouts.ReadTotalTimeoutMultiplier = 15; - timeouts.ReadTotalTimeoutConstant = 100; - timeouts.WriteTotalTimeoutMultiplier = 15; - timeouts.WriteTotalTimeoutConstant = 100; - if (!SetCommTimeouts(hComm, &timeouts)) { return -1;} // Error setting time-outs. - return 0; -} - -void ceSerial::Close() -{ - if (IsOpened()) - { - SetCommTimeouts(hComm, &timeouts_ori); - CloseHandle(osReader.hEvent); - CloseHandle(osWrite.hEvent); - CloseHandle(hComm);//close comm port - hComm = INVALID_HANDLE_VALUE; - } -} - -bool ceSerial::IsOpened() -{ - if(hComm == INVALID_HANDLE_VALUE) return false; - else return true; -} - - - -bool ceSerial::Write(char *data) -{ - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - long n = strlen(data); - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { - // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -bool ceSerial::Write(char *data,long n) -{ - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { - // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -bool ceSerial::WriteChar(char ch) -{ - char s[2]; - s[0]=ch; - s[1]=0;//null terminated - return Write(s); -} - -char ceSerial::ReadChar(bool& success) -{ - success = false; - if (!IsOpened()) {return 0;} - - DWORD dwRead; - DWORD length=1; - BYTE* data = (BYTE*)(&rxchar); - //the creation of the overlapped read operation - if (!fWaitingOnRead) { - // Issue read operation. - if (!ReadFile(hComm, data, length, &dwRead, &osReader)) { - if (GetLastError() != ERROR_IO_PENDING) { /*Error*/} - else { fWaitingOnRead = TRUE; /*Waiting*/} - } - else {if(dwRead==length) success = true;}//success - } - - - //detection of the completion of an overlapped read operation - DWORD dwRes; - if (fWaitingOnRead) { - dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT); - switch (dwRes) - { - // Read completed. - case WAIT_OBJECT_0: - if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) {/*Error*/ } - else { - if (dwRead == length) success = true; - fWaitingOnRead = FALSE; - // Reset flag so that another opertion can be issued. - }// Read completed successfully. - break; - - case WAIT_TIMEOUT: - // Operation isn't complete yet. - break; - - default: - // Error in the WaitForSingleObject; - break; - } - } - return rxchar; -} - -bool ceSerial::SetRTS(bool value) -{ - bool r = false; - if (IsOpened()) { - if (value) { - if (EscapeCommFunction(hComm, SETRTS)) r = true; - } - else { - if (EscapeCommFunction(hComm, CLRRTS)) r = true; - } - } - return r; -} - -bool ceSerial::SetDTR(bool value) -{ - bool r = false; - if (IsOpened()) { - if (value) { - if (EscapeCommFunction(hComm, SETDTR)) r = true; - } - else { - if (EscapeCommFunction(hComm, CLRDTR)) r = true; - } - } - return r; -} - -bool ceSerial::GetCTS(bool& success) -{ - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)){ - r = MS_CTS_ON & dwModemStatus; - success = true; - } - } - return r; -} - -bool ceSerial::GetDSR(bool& success) -{ - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_DSR_ON & dwModemStatus; - success = true; - } - } - return r; -} - -bool ceSerial::GetRI(bool& success) -{ - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_RING_ON & dwModemStatus; - success = true; - } - } - return r; -} - -bool ceSerial::GetCD(bool& success) -{ - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_RLSD_ON & dwModemStatus; - success = true; - } - } - return r; -} - -#else //for POSIX - -long ceSerial::Open(void) { - struct serial_struct serinfo; - struct termios settings; - memset(&settings, 0, sizeof(settings)); - settings.c_iflag = 0; - settings.c_oflag = 0; - - settings.c_cflag = CREAD | CLOCAL;//see termios.h for more information - if(dsize==5) settings.c_cflag |= CS5;//no change - else if (dsize == 6) settings.c_cflag |= CS6; - else if (dsize == 7) settings.c_cflag |= CS7; - else settings.c_cflag |= CS8; - - if(stopbits==2) settings.c_cflag |= CSTOPB; - - if(parity!='N') settings.c_cflag |= PARENB; - - if (parity == 'O') settings.c_cflag |= PARODD; - - settings.c_lflag = 0; - settings.c_cc[VMIN] = 1; - settings.c_cc[VTIME] = 0; - - fd = open(port.c_str(), O_RDWR | O_NONBLOCK); - if (fd == -1) { - return -1; - } - - if (!stdbaud) { - // serial driver to interpret the value B38400 differently - serinfo.reserved_char[0] = 0; - if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1;} - serinfo.flags &= ~ASYNC_SPD_MASK; - serinfo.flags |= ASYNC_SPD_CUST; - serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud; - if (serinfo.custom_divisor < 1) serinfo.custom_divisor = 1; - if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { return -1; } - if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1; } - if (serinfo.custom_divisor * baud != serinfo.baud_base) { - /* - warnx("actual baudrate is %d / %d = %f\n", - serinfo.baud_base, serinfo.custom_divisor, - (float)serinfo.baud_base / serinfo.custom_divisor); - */ - } - cfsetospeed(&settings, B38400); - cfsetispeed(&settings, B38400); - } - else { - cfsetospeed(&settings, baud); - cfsetispeed(&settings, baud); - } - tcsetattr(fd, TCSANOW, &settings); - int flags = fcntl(fd, F_GETFL, 0); - fcntl(fd, F_SETFL, flags | O_NONBLOCK); - - if (!stdbaud) { - // driver to interpret B38400 as 38400 baud again - ioctl(fd, TIOCGSERIAL, &serinfo); - serinfo.flags &= ~ASYNC_SPD_MASK; - ioctl(fd, TIOCSSERIAL, &serinfo); - } - return 0; -} - -void ceSerial::Close() { - if(IsOpened()) close(fd); - fd=-1; -} - -bool ceSerial::IsOpened() -{ - if(fd== (-1)) return false; - else return true; -} - -void ceSerial::SetBaudRate(long baudrate) { - stdbaud = true; - if (baudrate == 0) baud = B0; - else if (baudrate == 50) baud = B50; - else if (baudrate == 75) baud = B75; - else if (baudrate == 110) baud = B110; - else if (baudrate == 134) baud = B134; - else if (baudrate == 150) baud = B150; - else if (baudrate == 200) baud = B200; - else if (baudrate == 300) baud = B300; - else if (baudrate == 600) baud = B600; - else if (baudrate == 1200) baud = B1200; - else if (baudrate == 2400) baud = B2400; - else if (baudrate == 4800) baud = B4800; - else if (baudrate == 9600) baud = B9600; - else if (baudrate == 19200) baud = B19200; - else if (baudrate == 38400) baud = B38400; - else if (baudrate == 57600) baud = B57600; - else if (baudrate == 115200) baud = B115200; - else if (baudrate == 230400) baud = B230400; - else { - baud = baudrate; - stdbaud = false; - } -} - -long ceSerial::GetBaudRate() { - return baud; -} -char ceSerial::ReadChar(bool& success) -{ - success=false; - if (!IsOpened()) {return 0; } - success=read(fd, &rxchar, 1)==1; - return rxchar; -} - -bool ceSerial::Write(char *data) -{ - if (!IsOpened()) {return false; } - long n = strlen(data); - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -bool ceSerial::Write(char *data,long n) -{ - if (!IsOpened()) {return false; } - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -bool ceSerial::WriteChar(char ch) -{ - char s[2]; - s[0]=ch; - s[1]=0;//null terminated - return Write(s); -} - -bool ceSerial::SetRTS(bool value) { - long RTS_flag = TIOCM_RTS; - bool success=true; - if (value) {//Set RTS pin - if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) success=false; - } - else {//Clear RTS pin - if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) success=false; - } - return success; -} - -bool ceSerial::SetDTR(bool value) { - long DTR_flag = TIOCM_DTR; - bool success=true; - if (value) {//Set DTR pin - if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) success=false; - } - else {//Clear DTR pin - if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) success=false; - } - return success; -} - -bool ceSerial::GetCTS(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_CTS) != 0); -} - -bool ceSerial::GetDSR(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_DSR) != 0); -} - -bool ceSerial::GetRI(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_RI) != 0); -} - -bool ceSerial::GetCD(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_CD) != 0); -} -#endif - -} // namespace ce +// File: ceSerial.cpp +// Description: ceSerial communication class implementation for Windows and Linux +// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye + +// References +// https://en.wikibooks.org/wiki/Serial_Programming/termios +// http://www.silabs.com/documents/public/application-notes/an197.pdf +// https://msdn.microsoft.com/en-us/library/ff802693.aspx +// http://www.cplusplus.com/forum/unices/10491/ + +#include "ce/ceSerial.h" +#include +#include +#include +#include +using namespace std; + + +#ifdef CE_WINDOWS + #define READ_TIMEOUT 10 // milliseconds +#else + #include + #include + #include + #include + #include +#endif + +namespace ce { + +void ceSerial::Delay(unsigned long ms){ +#ifdef CE_WINDOWS + Sleep(ms); +#else + usleep(ms*1000); +#endif +} + +ceSerial::ceSerial() : +#ifdef CE_WINDOWS + ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1) +#else + ceSerial("/dev/ttyS0", 9600, 8, 'N', 1) +#endif +{ + +} + +ceSerial::ceSerial(string Device, long BaudRate,long DataSize,char ParityType,float NStopBits):stdbaud(true) +{ +#ifdef CE_WINDOWS + hComm = INVALID_HANDLE_VALUE; +#else + fd = -1; +#endif // defined + SetBaudRate(BaudRate); + SetDataSize(DataSize); + SetParity(ParityType); + SetStopBits(NStopBits); + SetPortName(Device); +} + +ceSerial::~ceSerial() +{ + Close(); +} + +void ceSerial::SetPortName(string Device) { + port = Device; +} + +string ceSerial::GetPort() { + return port; +} + +void ceSerial::SetDataSize(long nbits) { + if ((nbits < 5) || (nbits > 8)) nbits = 8; + dsize=nbits; +} + +long ceSerial::GetDataSize() { + return dsize; +} + +void ceSerial::SetParity(char p) { + if ((p != 'N') && (p != 'E') && (p != 'O')) { +#ifdef CE_WINDOWS + if ((p != 'M') && (p != 'S')) p = 'N'; +#else + p = 'N'; +#endif + } + parity = p; +} + +char ceSerial::GetParity() { + return parity; +} + +void ceSerial::SetStopBits(float nbits) { + if (nbits >= 2) stopbits = 2; +#ifdef CE_WINDOWS + else if(nbits >= 1.5) stopbits = 1.5; +#endif + else stopbits = 1; +} + +float ceSerial::GetStopBits() { + return stopbits; +} + + +#ifdef CE_WINDOWS + +void ceSerial::SetBaudRate(long baudrate) { + stdbaud = true; + if (baudrate == 1100) baud = CBR_110; + else if (baudrate == 300) baud = CBR_300; + else if (baudrate == 600) baud = CBR_600; + else if (baudrate == 1200) baud = CBR_1200; + else if (baudrate == 2400) baud = CBR_2400; + else if (baudrate == 4800) baud = CBR_4800; + else if (baudrate == 9600) baud = CBR_9600; + else if (baudrate == 14400) baud = CBR_14400; + else if (baudrate == 19200) baud = CBR_19200; + else if (baudrate == 38400) baud = CBR_38400; + else if (baudrate == 57600) baud = CBR_57600; + else if (baudrate == 115200) baud = CBR_115200; + else if (baudrate == 128000) baud = CBR_128000; + else if (baudrate == 256000) baud = CBR_256000; + else { + baud = baudrate; + stdbaud = false; + } +} + +long ceSerial::GetBaudRate() { + return baud; +} + +long ceSerial::Open() +{ + if (IsOpened()) return 0; +#ifdef UNICODE + wstring wtext(port.begin(),port.end()); +#else + string wtext = port; +#endif + hComm = CreateFile(wtext.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + 0); + if (hComm == INVALID_HANDLE_VALUE) {return -1;} + + if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) {return -1;}//purge + + //get initial state + DCB dcbOri; + bool fSuccess; + fSuccess = GetCommState(hComm, &dcbOri); + if (!fSuccess) {return -1;} + + DCB dcb1 = dcbOri; + + dcb1.BaudRate = baud; + + if (parity == 'E') dcb1.Parity = EVENPARITY; + else if (parity == 'O') dcb1.Parity = ODDPARITY; + else if (parity == 'M') dcb1.Parity = MARKPARITY; + else if (parity == 'S') dcb1.Parity = SPACEPARITY; + else dcb1.Parity = NOPARITY; + + dcb1.ByteSize = (BYTE)dsize; + + if(stopbits==2) dcb1.StopBits = TWOSTOPBITS; + else if (stopbits == 1.5) dcb1.StopBits = ONE5STOPBITS; + else dcb1.StopBits = ONESTOPBIT; + + dcb1.fOutxCtsFlow = false; + dcb1.fOutxDsrFlow = false; + dcb1.fOutX = false; + dcb1.fDtrControl = DTR_CONTROL_DISABLE; + dcb1.fRtsControl = RTS_CONTROL_DISABLE; + fSuccess = SetCommState(hComm, &dcb1); + this->Delay(60); + if (!fSuccess) {return -1;} + + fSuccess = GetCommState(hComm, &dcb1); + if (!fSuccess) {return -1;} + + osReader = { 0 };// Create the overlapped event. + // Must be closed before exiting to avoid a handle leak. + osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + + if (osReader.hEvent == NULL) {return -1;}// Error creating overlapped event; abort. + fWaitingOnRead = FALSE; + + osWrite = { 0 }; + osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (osWrite.hEvent == NULL) {return -1;} + + if (!GetCommTimeouts(hComm, &timeouts_ori)) { return -1; } // Error getting time-outs. + COMMTIMEOUTS timeouts; + timeouts.ReadIntervalTimeout = 20; + timeouts.ReadTotalTimeoutMultiplier = 15; + timeouts.ReadTotalTimeoutConstant = 100; + timeouts.WriteTotalTimeoutMultiplier = 15; + timeouts.WriteTotalTimeoutConstant = 100; + if (!SetCommTimeouts(hComm, &timeouts)) { return -1;} // Error setting time-outs. + return 0; +} + +void ceSerial::Close() +{ + if (IsOpened()) + { + SetCommTimeouts(hComm, &timeouts_ori); + CloseHandle(osReader.hEvent); + CloseHandle(osWrite.hEvent); + CloseHandle(hComm);//close comm port + hComm = INVALID_HANDLE_VALUE; + } +} + +bool ceSerial::IsOpened() +{ + if(hComm == INVALID_HANDLE_VALUE) return false; + else return true; +} + + + +bool ceSerial::Write(char *data) +{ + if (!IsOpened()) { + return false; + } + BOOL fRes; + DWORD dwWritten; + long n = strlen(data); + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + // WriteFile failed, but it isn't delayed. Report error and abort. + if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} + else {// Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; + else fRes = TRUE;// Write operation completed successfully. + } + } + else fRes = TRUE;// WriteFile completed immediately. + return fRes; +} + +bool ceSerial::Write(char *data,long n) +{ + if (!IsOpened()) { + return false; + } + BOOL fRes; + DWORD dwWritten; + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + // WriteFile failed, but it isn't delayed. Report error and abort. + if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} + else {// Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; + else fRes = TRUE;// Write operation completed successfully. + } + } + else fRes = TRUE;// WriteFile completed immediately. + return fRes; +} + +bool ceSerial::WriteChar(char ch) +{ + char s[2]; + s[0]=ch; + s[1]=0;//null terminated + return Write(s); +} + +char ceSerial::ReadChar(bool& success) +{ + success = false; + if (!IsOpened()) {return 0;} + + DWORD dwRead; + DWORD length=1; + BYTE* data = (BYTE*)(&rxchar); + //the creation of the overlapped read operation + if (!fWaitingOnRead) { + // Issue read operation. + if (!ReadFile(hComm, data, length, &dwRead, &osReader)) { + if (GetLastError() != ERROR_IO_PENDING) { /*Error*/} + else { fWaitingOnRead = TRUE; /*Waiting*/} + } + else {if(dwRead==length) success = true;}//success + } + + + //detection of the completion of an overlapped read operation + DWORD dwRes; + if (fWaitingOnRead) { + dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT); + switch (dwRes) + { + // Read completed. + case WAIT_OBJECT_0: + if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) {/*Error*/ } + else { + if (dwRead == length) success = true; + fWaitingOnRead = FALSE; + // Reset flag so that another opertion can be issued. + }// Read completed successfully. + break; + + case WAIT_TIMEOUT: + // Operation isn't complete yet. + break; + + default: + // Error in the WaitForSingleObject; + break; + } + } + return rxchar; +} + +bool ceSerial::SetRTS(bool value) +{ + bool r = false; + if (IsOpened()) { + if (value) { + if (EscapeCommFunction(hComm, SETRTS)) r = true; + } + else { + if (EscapeCommFunction(hComm, CLRRTS)) r = true; + } + } + return r; +} + +bool ceSerial::SetDTR(bool value) +{ + bool r = false; + if (IsOpened()) { + if (value) { + if (EscapeCommFunction(hComm, SETDTR)) r = true; + } + else { + if (EscapeCommFunction(hComm, CLRDTR)) r = true; + } + } + return r; +} + +bool ceSerial::GetCTS(bool& success) +{ + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)){ + r = MS_CTS_ON & dwModemStatus; + success = true; + } + } + return r; +} + +bool ceSerial::GetDSR(bool& success) +{ + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_DSR_ON & dwModemStatus; + success = true; + } + } + return r; +} + +bool ceSerial::GetRI(bool& success) +{ + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_RING_ON & dwModemStatus; + success = true; + } + } + return r; +} + +bool ceSerial::GetCD(bool& success) +{ + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_RLSD_ON & dwModemStatus; + success = true; + } + } + return r; +} + +#else //for POSIX + +long ceSerial::Open(void) { + struct serial_struct serinfo; + struct termios settings; + memset(&settings, 0, sizeof(settings)); + settings.c_iflag = 0; + settings.c_oflag = 0; + + settings.c_cflag = CREAD | CLOCAL;//see termios.h for more information + if(dsize==5) settings.c_cflag |= CS5;//no change + else if (dsize == 6) settings.c_cflag |= CS6; + else if (dsize == 7) settings.c_cflag |= CS7; + else settings.c_cflag |= CS8; + + if(stopbits==2) settings.c_cflag |= CSTOPB; + + if(parity!='N') settings.c_cflag |= PARENB; + + if (parity == 'O') settings.c_cflag |= PARODD; + + settings.c_lflag = 0; + settings.c_cc[VMIN] = 1; + settings.c_cc[VTIME] = 0; + + fd = open(port.c_str(), O_RDWR | O_NONBLOCK); + if (fd == -1) { + return -1; + } + + if (!stdbaud) { + // serial driver to interpret the value B38400 differently + serinfo.reserved_char[0] = 0; + if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1;} + serinfo.flags &= ~ASYNC_SPD_MASK; + serinfo.flags |= ASYNC_SPD_CUST; + serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud; + if (serinfo.custom_divisor < 1) serinfo.custom_divisor = 1; + if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { return -1; } + if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1; } + if (serinfo.custom_divisor * baud != serinfo.baud_base) { + /* + warnx("actual baudrate is %d / %d = %f\n", + serinfo.baud_base, serinfo.custom_divisor, + (float)serinfo.baud_base / serinfo.custom_divisor); + */ + } + cfsetospeed(&settings, B38400); + cfsetispeed(&settings, B38400); + } + else { + cfsetospeed(&settings, baud); + cfsetispeed(&settings, baud); + } + tcsetattr(fd, TCSANOW, &settings); + int flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + + if (!stdbaud) { + // driver to interpret B38400 as 38400 baud again + ioctl(fd, TIOCGSERIAL, &serinfo); + serinfo.flags &= ~ASYNC_SPD_MASK; + ioctl(fd, TIOCSSERIAL, &serinfo); + } + return 0; +} + +void ceSerial::Close() { + if(IsOpened()) close(fd); + fd=-1; +} + +bool ceSerial::IsOpened() +{ + if(fd== (-1)) return false; + else return true; +} + +void ceSerial::SetBaudRate(long baudrate) { + stdbaud = true; + if (baudrate == 0) baud = B0; + else if (baudrate == 50) baud = B50; + else if (baudrate == 75) baud = B75; + else if (baudrate == 110) baud = B110; + else if (baudrate == 134) baud = B134; + else if (baudrate == 150) baud = B150; + else if (baudrate == 200) baud = B200; + else if (baudrate == 300) baud = B300; + else if (baudrate == 600) baud = B600; + else if (baudrate == 1200) baud = B1200; + else if (baudrate == 2400) baud = B2400; + else if (baudrate == 4800) baud = B4800; + else if (baudrate == 9600) baud = B9600; + else if (baudrate == 19200) baud = B19200; + else if (baudrate == 38400) baud = B38400; + else if (baudrate == 57600) baud = B57600; + else if (baudrate == 115200) baud = B115200; + else if (baudrate == 230400) baud = B230400; + else { + baud = baudrate; + stdbaud = false; + } +} + +long ceSerial::GetBaudRate() { + return baud; +} +char ceSerial::ReadChar(bool& success) +{ + success=false; + if (!IsOpened()) {return 0; } + success=read(fd, &rxchar, 1)==1; + return rxchar; +} + +bool ceSerial::Write(char *data) +{ + if (!IsOpened()) {return false; } + long n = strlen(data); + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + return (write(fd, data, n)==n); +} + +bool ceSerial::Write(char *data,long n) +{ + if (!IsOpened()) {return false; } + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + return (write(fd, data, n)==n); +} + +bool ceSerial::WriteChar(char ch) +{ + char s[2]; + s[0]=ch; + s[1]=0;//null terminated + return Write(s); +} + +bool ceSerial::SetRTS(bool value) { + long RTS_flag = TIOCM_RTS; + bool success=true; + if (value) {//Set RTS pin + if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) success=false; + } + else {//Clear RTS pin + if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) success=false; + } + return success; +} + +bool ceSerial::SetDTR(bool value) { + long DTR_flag = TIOCM_DTR; + bool success=true; + if (value) {//Set DTR pin + if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) success=false; + } + else {//Clear DTR pin + if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) success=false; + } + return success; +} + +bool ceSerial::GetCTS(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_CTS) != 0); +} + +bool ceSerial::GetDSR(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_DSR) != 0); +} + +bool ceSerial::GetRI(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_RI) != 0); +} + +bool ceSerial::GetCD(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_CD) != 0); +} +#endif + +} // namespace ce diff --git a/src/ceTcpServer.cpp b/src/ceTcpServer.cpp deleted file mode 100644 index 0fd5415..0000000 --- a/src/ceTcpServer.cpp +++ /dev/null @@ -1,269 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceTcpServer.cpp -// Description: TCP server module -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceTcpServer.h" -using namespace std; - -#if CE_WX==1 -namespace ce { - -void ceTcpServer::PrintLog(string str) -{ - // printf("%s \n",str.c_str()); -} - -ceTcpServer::ceTcpServer(wxEvtHandler* app, int serverid, int socketid, int port): -_app(app),_server_id(serverid),_socket_id(socketid),_port(port) -{ - Connect(serverid, wxEVT_SOCKET, wxSocketEventHandler(ceTcpServer::OnServerEvent)); - Connect(socketid, wxEVT_SOCKET, wxSocketEventHandler(ceTcpServer::OnSocketEvent)); -} - -ceTcpServer::~ceTcpServer() -{ - this->Close(); - Disconnect(_socket_id, wxEVT_SOCKET); - Disconnect(_server_id, wxEVT_SOCKET); -} - -bool ceTcpServer::Open() -{ - if(this->_listening) {return true;} // already listening - - // Create the address - defaults to localhost:0 initially - IPaddress addr; - addr.AnyAddress(); - addr.Service(this->_port); - PrintLog("Creating server at " +addr.IPAddress().ToStdString()+":"+ to_string(addr.Service())); - - // Create the socket - this->_socketServer = new wxSocketServer(addr); - - // We use IsOk() here to see if the server is really listening - if (!this->_socketServer->IsOk()){ - perror("ceTcpServer could not listen at the specified port"); - return false; - } - - IPaddress addrReal; - if (!this->_socketServer->GetLocal(addrReal)){ - perror("ceTcpServer couldn't get the address it bounds to"); - } - else{ - PrintLog("Server listening at "+addrReal.IPAddress().ToStdString()+":"+to_string(addrReal.Service())); - } - - // Setup the event handler and subscribe to connection events - this->_socketServer->SetEventHandler(*this, _server_id); - this->_socketServer->SetNotify(wxSOCKET_CONNECTION_FLAG); - this->_socketServer->Notify(true); - this->_listening = true; - this->_connected_n = 0; - return true; -} - -bool ceTcpServer::Close() -{ - if(!this->_listening) {return true;} // already closed - if(_socketBase != nullptr){ - _socketBase->Destroy(); - _socketBase = nullptr; - } - - if(_socketServer->IsClosed()) { - return true; - } - _socketServer->Discard(); - return _socketServer->Destroy(); -} - -void ceTcpServer::OnServerEvent(wxSocketEvent& event) -{ - PrintLog("OnServerEvent"); - wxSocketBase *sockBase; - IPaddress addr; - - switch (event.GetSocketEvent()) - { - case wxSOCKET_CONNECTION: - PrintLog("Connection event"); - break; - default: - perror("Unexpected event"); - return; // return if unknown - break; - } - - // Accept new connection if there is one in the pending - // connections queue, else exit. We use Accept(false) for - // non-blocking accept (although if we got here, there - // should ALWAYS be a pending connection). - - sockBase = _socketServer->Accept(false); - - if (sockBase) - { - if (!sockBase->GetPeer(addr)) - { - PrintLog("New connection from unknown client accepted"); - } - else - { - PrintLog("New client connection from "+addr.IPAddress().ToStdString()+":"+to_string(addr.Service())); - } - } - else - { - PrintLog("Couldn't accept a new connection"); - return; - } - - sockBase->SetEventHandler(*this, _socket_id); - sockBase->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG); - sockBase->Notify(true); - - _socketBase = sockBase; // point to last connected socket - this->_connected_n++; - PrintLog(to_string(this->_connected_n) + " clients connected"); - - string ip = addr.IPAddress().ToStdString(); - int port = addr.Service(); - - // 1st char: flag 1=new con, 0 = lost con, - // 2nd char: number of con - wxString ws(ip); - wxThreadEvent eventsvr(wxEVT_THREAD, _server_id); - std::vector bv{1,(char)this->_connected_n}; - eventsvr.SetPayload>(bv); - eventsvr.SetString(ws); - eventsvr.SetInt(port); - wxQueueEvent(_app, eventsvr.Clone()); -} - -void ceTcpServer::OnSocketEvent(wxSocketEvent& event) -{ - PrintLog("OnSocketEvent"); - wxSocketBase *sockBase = event.GetSocket(); - IPaddress addr; - std::vector vc; - char buf[CE_TCPSVR_RX_BUF_SIZE]; - - if (!sockBase->GetPeer(addr)) - { - PrintLog("Socket event from unknown client"); - } - else - { - PrintLog("Socket event from "+addr.IPAddress().ToStdString()+":" + to_string(addr.Service())); - } - string ip = addr.IPAddress().ToStdString(); - int port = addr.Service(); - wxString ws(ip); - - switch(event.GetSocketEvent()) - { - case wxSOCKET_INPUT: - { - PrintLog("wxSOCKET_INPUT"); - // We disable input events, so that the test doesn't trigger - // wxSocketEvent again. - sockBase->SetNotify(wxSOCKET_LOST_FLAG); - - // Receive data from socket and send it back. We will first - // get a byte with the buffer size, so we can specify the - // exact size and use the wxSOCKET_WAITALL flag. Also, we - // disabled input events so we won't have unwanted reentrance. - // This way we can avoid the infamous wxSOCKET_BLOCK flag. - // sockBase->SetFlags(wxSOCKET_WAITALL); - - // Read the message - size_t lenRd = sockBase->Read(buf, sizeof(buf)).LastCount(); - if (!lenRd) { - PrintLog("Failed to read message"); - return; - } - else { - PrintLog("Read "+to_string(lenRd)+" bytes"); - } - // Enable input events again. - sockBase->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG); - - // string str(buf,lenRd); - // PrintLog("Rx: " + str); - - vc.assign(buf,buf+lenRd); - wxThreadEvent eventskt(wxEVT_THREAD, _socket_id); - eventskt.SetPayload>(vc); - eventskt.SetString(ws); - eventskt.SetInt(port); - wxQueueEvent(_app, eventskt.Clone()); - } - break; - case wxSOCKET_LOST: - { - PrintLog("wxSOCKET_LOST"); - if(sockBase==_socketBase){ - PrintLog("Currently pointed socket lost"); - _socketBase = nullptr; - } - else { - PrintLog("Unpointed socket lost"); - } - - std::vector bv{0,(char)this->_connected_n}; - // 1st char: flag 1=new con, 0 = lost con, - // 2nd char: number of con - - wxThreadEvent eventsvr(wxEVT_THREAD, _server_id); - eventsvr.SetPayload>(bv); - eventsvr.SetString(ws); - eventsvr.SetInt(port); - wxQueueEvent(_app, eventsvr.Clone()); - // Destroy() should be used instead of delete wherever possible, - // due to the fact that wxSocket uses 'delayed events' (see the - // documentation for wxPostEvent) and we don't want an event to - // arrive to the event handler (the frame, here) after the socket - // has been deleted. Also, we might be doing some other thing with - // the socket at the same time; for example, we might be in the - // middle of a test or something. Destroy() takes care of all - // this for us. - - PrintLog("Deleting socket"); - sockBase->Destroy(); - this->_connected_n--; - PrintLog(to_string(this->_connected_n) + " clients connected"); - } - break; - default: - perror("Unexpected event"); - break; - } -} - -int ceTcpServer::Tx(std::vector bv) -{ - size_t txn = 0; - if(this->_socketBase!=nullptr){ - if(this->_socketBase->IsOk() && this->_socketBase->IsConnected()) { - // Write to pointed client - txn = bv.size(); - size_t n = _socketBase->Write(bv.data(), txn).LastCount(); - if (n != txn) { - perror("ceTcpClient write error"); - txn = n; - } - else { - PrintLog("Tx: " + ceMisc::cvec2hex(bv)); - } - } - } - return int(txn); -} - - -} // namespace ce -#endif // CE_WX \ No newline at end of file diff --git a/src/ceUDP.cpp b/src/ceUDP.cpp index e71fa2d..491624f 100644 --- a/src/ceUDP.cpp +++ b/src/ceUDP.cpp @@ -1,187 +1,187 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceUDP.cpp -// Description: UDP communication module -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -///////////////////////////////////////////////////////////////////////////// - -#include "ce/ceUDP.h" -#if CE_WX==1 -namespace ce { - -ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port) : -_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(rx_port),udp_remote_host("localhost") -{ - _ok = false; -} - -ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port) : -_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(tx_port),udp_remote_host("localhost") -{ - _ok = false; -} - -ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost) : -_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(tx_port),udp_remote_host(remotehost) -{ - _ok = false; -} - -int ceUDP::GetRxPort() -{ - return this->udp_port_rx; -} - -void ceUDP::SetRxPort(int rx_port) -{ - this->udp_port_rx = rx_port; -} - -int ceUDP::GetTxPort() -{ - return this->udp_port_tx; -} - -void ceUDP::SetTxPort(int tx_port) -{ - this->udp_port_tx = tx_port; -} - -std::string ceUDP::GetRemotehost() -{ - return this->udp_remote_host; -} - -void ceUDP::SetRemotehost(std::string remoteHost) -{ - this->udp_remote_host = remoteHost; -} - -int ceUDP::Open() -{ - // Create the address - defaults to localhost:0 initially - IPaddress addr; - addr.AnyAddress(); - if(udp_port_rx !=0) addr.Service(udp_port_rx); - std::string tmp; - // printf("UDP: creating socket at %s : %d \n",addr.IPAddress().ToStdString().c_str(),addr.Service()); - - // Create the socket - sock = new wxDatagramSocket(addr); - - // We use IsOk() here to see if the server is really listening - if (!sock->IsOk()){ - perror("ceUDP could not listen at the specified port"); - return 1; - } - - IPaddress addrReal; - if (!sock->GetLocal(addrReal)){ - perror("ceUDP couldn't get the address we bound to."); - return 1; - } - else{ - // std::string tmp = "UDP server listening at "+addrReal.IPAddress().ToStdString()+" : "+std::to_string(addrReal.Service()); - // printf("%s\n",tmp.c_str()); - } - // Setup the event handler - sock->SetEventHandler(*this,SOCKET_ID); - sock->SetNotify(wxSOCKET_INPUT_FLAG); - sock->Notify(true); - Connect(SOCKET_ID,wxEVT_SOCKET,wxSocketEventHandler(ceUDP::OnSocketEvent)); - _ok = true; - return 0; -} - -void ceUDP::Close() -{ - _ok = false; - sock->Close(); -} - -int ceUDP::Tx(std::vector bv, std::string remoteHost, int txPort) -{ - if(!_ok) return 1; - size_t txn = bv.size(); - // IPaddress addrLocal; - // addrLocal.AnyAddress(); - //addrLocal.Hostname("192.168.1.10"); - // wxDatagramSocket sock2tx(addrLocal); - // if ( !sock2tx.IsOk() ) - // { - // perror("ceUDP Tx failed to create UDP socket"); - // return; - // } - // write("UDP TX: created "+ddrLocal.IPAddress().ToStdString()+" : "+to_string(addrLocal.Service())); - - IPaddress raddr; - //raddr.Hostname("localhost"); - raddr.Hostname(remoteHost); - raddr.Service(txPort); - - if (sock->SendTo(raddr, bv.data(), txn).LastCount() != txn) - { - perror("ceUDP Tx error"); - return 1; - } - else { - // std::string tmp ="UDP TX: "+util::cvec2hex(bv); - // printf("%s\n",tmp.c_str()); - // printf("ceUDPTx n= %ld \n",txn); - // fflush(stdout); - } - return 0; -} - -int ceUDP::Tx(std::vector bv) -{ - return this->Tx(bv,udp_remote_host,udp_port_tx); -} - -void ceUDP::OnSocketEvent(wxSocketEvent& event) -{ - IPaddress addr; - addr.Service(udp_port_rx); - char buf[CE_UDP_RX_BUF_SIZE]; - size_t n; - int socketid = event.GetId(); - std::string tmp; // = ("UDP RX: id = " + to_string(socketid)); - std::vector vc; - switch(event.GetSocketEvent()) - { - case wxSOCKET_INPUT: - sock->Notify(false); - n = sock->RecvFrom(addr, buf, sizeof(buf)).LastCount(); - sock->Notify(true); - if (!n){ - perror("ceUDP Rx failed"); - return; - } - vc.assign(buf,buf+n); -// printf("Received \'%s\' from %s:%u. \n", -// util::cvec2hex(util::cptr2cvec(buf, n)).c_str(), -// addr.IPAddress().ToStdString().c_str(), -// addr.Service()); - // printf("ceUDPRx n= %ld \n",n); - // fflush(stdout); - this->Rx(socketid,vc,addr.IPAddress().ToStdString(),addr.Service()); - break; - default: - perror("ceUDP Rx unexpected event"); - break; - } -} - -void ceUDP::Rx(int socketid, std::vector bv, std::string ip, int port) -{ - // ("UDP rx" + to_string(socketid) + ": " + util::cvec2hex(bv)); - wxString ws(ip); - wxThreadEvent event(wxEVT_THREAD, socketid); - event.SetPayload>(bv); - event.SetString(ws); - event.SetInt(port); - wxQueueEvent(_app, event.Clone()); -} - -} // namespace ce -#endif // CE_WX +///////////////////////////////////////////////////////////////////////////// +// Name: ceUDP.cpp +// Description: UDP communication module +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html +///////////////////////////////////////////////////////////////////////////// + +#include "ce/ceUDP.h" +#if CE_WX==1 +namespace ce { + +ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port) : +_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(rx_port),udp_remote_host("localhost") +{ + _ok = false; +} + +ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port) : +_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(tx_port),udp_remote_host("localhost") +{ + _ok = false; +} + +ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost) : +_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(tx_port),udp_remote_host(remotehost) +{ + _ok = false; +} + +int ceUDP::GetRxPort() +{ + return this->udp_port_rx; +} + +void ceUDP::SetRxPort(int rx_port) +{ + this->udp_port_rx = rx_port; +} + +int ceUDP::GetTxPort() +{ + return this->udp_port_tx; +} + +void ceUDP::SetTxPort(int tx_port) +{ + this->udp_port_tx = tx_port; +} + +std::string ceUDP::GetRemotehost() +{ + return this->udp_remote_host; +} + +void ceUDP::SetRemotehost(std::string remoteHost) +{ + this->udp_remote_host = remoteHost; +} + +int ceUDP::Open() +{ + // Create the address - defaults to localhost:0 initially + IPaddress addr; + addr.AnyAddress(); + if(udp_port_rx !=0) addr.Service(udp_port_rx); + std::string tmp; + // printf("UDP: creating socket at %s : %d \n",addr.IPAddress().ToStdString().c_str(),addr.Service()); + + // Create the socket + sock = new wxDatagramSocket(addr); + + // We use IsOk() here to see if the server is really listening + if (!sock->IsOk()){ + perror("ceUDP could not listen at the specified port"); + return 1; + } + + IPaddress addrReal; + if (!sock->GetLocal(addrReal)){ + perror("ceUDP couldn't get the address we bound to."); + return 1; + } + else{ + // std::string tmp = "UDP server listening at "+addrReal.IPAddress().ToStdString()+" : "+std::to_string(addrReal.Service()); + // printf("%s\n",tmp.c_str()); + } + // Setup the event handler + sock->SetEventHandler(*this,SOCKET_ID); + sock->SetNotify(wxSOCKET_INPUT_FLAG); + sock->Notify(true); + Connect(SOCKET_ID,wxEVT_SOCKET,wxSocketEventHandler(ceUDP::OnSocketEvent)); + _ok = true; + return 0; +} + +void ceUDP::Close() +{ + _ok = false; + sock->Close(); +} + +int ceUDP::Tx(std::vector bv, std::string remoteHost, int txPort) +{ + if(!_ok) return 1; + size_t txn = bv.size(); + // IPaddress addrLocal; + // addrLocal.AnyAddress(); + //addrLocal.Hostname("192.168.1.10"); + // wxDatagramSocket sock2tx(addrLocal); + // if ( !sock2tx.IsOk() ) + // { + // perror("ceUDP Tx failed to create UDP socket"); + // return; + // } + // write("UDP TX: created "+ddrLocal.IPAddress().ToStdString()+" : "+to_string(addrLocal.Service())); + + IPaddress raddr; + //raddr.Hostname("localhost"); + raddr.Hostname(remoteHost); + raddr.Service(txPort); + + if (sock->SendTo(raddr, bv.data(), txn).LastCount() != txn) + { + perror("ceUDP Tx error"); + return 1; + } + else { + // std::string tmp ="UDP TX: "+util::cvec2hex(bv); + // printf("%s\n",tmp.c_str()); + // printf("ceUDPTx n= %ld \n",txn); + // fflush(stdout); + } + return 0; +} + +int ceUDP::Tx(std::vector bv) +{ + return this->Tx(bv,udp_remote_host,udp_port_tx); +} + +void ceUDP::OnSocketEvent(wxSocketEvent& event) +{ + IPaddress addr; + addr.Service(udp_port_rx); + char buf[CE_UDP_RX_BUF_SIZE]; + size_t n; + int socketid = event.GetId(); + std::string tmp; // = ("UDP RX: id = " + to_string(socketid)); + std::vector vc; + switch(event.GetSocketEvent()) + { + case wxSOCKET_INPUT: + sock->Notify(false); + n = sock->RecvFrom(addr, buf, sizeof(buf)).LastCount(); + sock->Notify(true); + if (!n){ + perror("ceUDP Rx failed"); + return; + } + vc.assign(buf,buf+n); +// printf("Received \'%s\' from %s:%u. \n", +// util::cvec2hex(util::cptr2cvec(buf, n)).c_str(), +// addr.IPAddress().ToStdString().c_str(), +// addr.Service()); + // printf("ceUDPRx n= %ld \n",n); + // fflush(stdout); + this->Rx(socketid,vc,addr.IPAddress().ToStdString(),addr.Service()); + break; + default: + perror("ceUDP Rx unexpected event"); + break; + } +} + +void ceUDP::Rx(int socketid, std::vector bv, std::string ip, int port) +{ + // ("UDP rx" + to_string(socketid) + ": " + util::cvec2hex(bv)); + wxString ws(ip); + wxThreadEvent event(wxEVT_THREAD, socketid); + event.SetPayload>(bv); + event.SetString(ws); + event.SetInt(port); + wxQueueEvent(_app, event.Clone()); +} + +} // namespace ce +#endif // CE_WX diff --git a/src/ceWxSerial.cpp b/src/ceWxSerial.cpp index 0f394bf..1ce9dea 100644 --- a/src/ceWxSerial.cpp +++ b/src/ceWxSerial.cpp @@ -1,53 +1,53 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceWxSerial.cpp -// Description: Serial module for wxWidgets -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/ceWxSerial.h" -#if CE_WX==1 - -using namespace std; - -namespace ce { - -//ctor -ceWxSerial::ceWxSerial(wxEvtHandler* app,int id, int interval, - std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits) - : _app(app), _id(id), _interval(interval), ceSerial(Device, BaudRate, DataSize, ParityType, NStopBits) -{ - this->_timer = new wxTimer(this, _id); - Connect(_id, wxEVT_TIMER, wxTimerEventHandler(ceWxSerial::OnTimer)); - this->_timer->Start(_interval - 1); -} - -ceWxSerial::~ceWxSerial() -{ - -} - -void ceWxSerial::OnTimer(wxTimerEvent& WXUNUSED(event)) -{ - vector vc = this->Chk(); - if (vc.size() > 0) { - wxThreadEvent event(wxEVT_THREAD, _id); - event.SetPayload(vc); - // send in a thread-safe way - wxQueueEvent(_app, event.Clone()); - } -} - -vector ceWxSerial::Chk() -{ - vector vc; - char ch; bool r; - do { - ch = this->ReadChar(r); - if (r) { - vc.push_back(ch); - } - } while (r); - return vc; -} - -} // namespace ce -#endif // CE_WX +///////////////////////////////////////////////////////////////////////////// +// Name: ceWxSerial.cpp +// Description: Serial module for wxWidgets +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// +#include "ce/ceWxSerial.h" +#if CE_WX==1 + +using namespace std; + +namespace ce { + +//ctor +ceWxSerial::ceWxSerial(wxEvtHandler* app,int id, int interval, + std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits) + : _app(app), _id(id), _interval(interval), ceSerial(Device, BaudRate, DataSize, ParityType, NStopBits) +{ + this->_timer = new wxTimer(this, _id); + Connect(_id, wxEVT_TIMER, wxTimerEventHandler(ceWxSerial::OnTimer)); + this->_timer->Start(_interval - 1); +} + +ceWxSerial::~ceWxSerial() +{ + +} + +void ceWxSerial::OnTimer(wxTimerEvent& WXUNUSED(event)) +{ + vector vc = this->Chk(); + if (vc.size() > 0) { + wxThreadEvent event(wxEVT_THREAD, _id); + event.SetPayload(vc); + // send in a thread-safe way + wxQueueEvent(_app, event.Clone()); + } +} + +vector ceWxSerial::Chk() +{ + vector vc; + char ch; bool r; + do { + ch = this->ReadChar(r); + if (r) { + vc.push_back(ch); + } + } while (r); + return vc; +} + +} // namespace ce +#endif // CE_WX diff --git a/src/cewxcvMisc.cpp b/src/cewxcvMisc.cpp index 5a09161..186e2d5 100644 --- a/src/cewxcvMisc.cpp +++ b/src/cewxcvMisc.cpp @@ -1,45 +1,45 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: cewxcvMisc.cpp -// Description: utility module using wxWidgets and OpenCV -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/cewxcvMisc.h" -using namespace std; -#if CE_CV==1 -using namespace cv; -#endif // CE_WX -namespace ce { - -#if CE_WX==1 - void cewxcvMisc::printTime() - { - wxDateTime* wdt; - wdt = new wxDateTime(); - wdt->SetToCurrent(); - wxString wstr = wdt->Format(wxT("%Y-%m-%d %H:%M:%S"), wxDateTime::Local); - // wxPuts(wstr); - std::string str = wstr.ToStdString(); - printf("%s\n",str.c_str()); - } -#if CE_CV==1 - wxImage cewxcvMisc::wx_from_mat(Mat &img) { - Mat im2; - if(img.channels()==1){cvtColor(img,im2,COLOR_GRAY2RGB);} - else if (img.channels() == 4) { cvtColor(img, im2, COLOR_BGRA2RGB);} - else {cvtColor(img,im2,COLOR_BGR2RGB);} - long imsize = im2.rows*im2.cols*im2.channels(); - wxImage wx(im2.cols, im2.rows,(unsigned char*)malloc(imsize), false); - unsigned char* s=im2.data; - unsigned char* d=wx.GetData(); - for (long i = 0; i < imsize; i++) { d[i] = s[i];} - return wx; - } - - Mat cewxcvMisc::mat_from_wx(wxImage &wx) { - Mat im2(Size(wx.GetWidth(),wx.GetHeight()),CV_8UC3,wx.GetData()); - cvtColor(im2,im2,COLOR_RGB2BGR); - return im2; - } -#endif // CE_CV -#endif // CE_WX +///////////////////////////////////////////////////////////////////////////// +// Name: cewxcvMisc.cpp +// Description: utility module using wxWidgets and OpenCV +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// +#include "ce/cewxcvMisc.h" +using namespace std; +#if CE_CV==1 +using namespace cv; +#endif // CE_WX +namespace ce { + +#if CE_WX==1 + void cewxcvMisc::printTime() + { + wxDateTime* wdt; + wdt = new wxDateTime(); + wdt->SetToCurrent(); + wxString wstr = wdt->Format(wxT("%Y-%m-%d %H:%M:%S"), wxDateTime::Local); + // wxPuts(wstr); + std::string str = wstr.ToStdString(); + printf("%s\n",str.c_str()); + } +#if CE_CV==1 + wxImage cewxcvMisc::wx_from_mat(Mat &img) { + Mat im2; + if(img.channels()==1){cvtColor(img,im2,COLOR_GRAY2RGB);} + else if (img.channels() == 4) { cvtColor(img, im2, COLOR_BGRA2RGB);} + else {cvtColor(img,im2,COLOR_BGR2RGB);} + long imsize = im2.rows*im2.cols*im2.channels(); + wxImage wx(im2.cols, im2.rows,(unsigned char*)malloc(imsize), false); + unsigned char* s=im2.data; + unsigned char* d=wx.GetData(); + for (long i = 0; i < imsize; i++) { d[i] = s[i];} + return wx; + } + + Mat cewxcvMisc::mat_from_wx(wxImage &wx) { + Mat im2(Size(wx.GetWidth(),wx.GetHeight()),CV_8UC3,wx.GetData()); + cvtColor(im2,im2,COLOR_RGB2BGR); + return im2; + } +#endif // CE_CV +#endif // CE_WX } // namespace ce \ No newline at end of file diff --git a/test.sh b/test.sh index 97409a5..599740f 100644 --- a/test.sh +++ b/test.sh @@ -1,12 +1,12 @@ -#!/bin/bash -cd test -if [[ ! -d "./build" ]]; then - mkdir -p build -fi -rm -r ./build/* -cmake -B ./build -S . -DCMAKE_BUILD_TYPE=Release -cmake --build ./build --config Release -cd build -ctest -N -ctest --verbose -C Release -cd .. +#!/bin/bash +cd test +if [[ ! -d "./build" ]]; then + mkdir -p build +fi +rm -r ./build/* +cmake -B ./build -S . -DCMAKE_BUILD_TYPE=Release +cmake --build ./build --config Release +cd build +ctest -N +ctest --verbose -C Release +cd .. diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 27427a6..14d9a2b 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,17 +1,17 @@ -cmake_minimum_required(VERSION 3.0.0) -project(test) - -include(CTest) -enable_testing() - -add_subdirectory(testJson) -add_test(NAME testJson COMMAND testJson) - -# add_subdirectory(testSHA1) -# add_test(NAME testSHA1 COMMAND testSHA1) - -# add_subdirectory(testDES) -# add_test(NAME testDES COMMAND testDES) - -# add_subdirectory(testRSA_OS) -# add_test(NAME testRSA_OS COMMAND testRSA_OS) +cmake_minimum_required(VERSION 3.0.0) +project(test) + +include(CTest) +enable_testing() + +add_subdirectory(testJson) +add_test(NAME testJson COMMAND testJson) + +# add_subdirectory(testSHA1) +# add_test(NAME testSHA1 COMMAND testSHA1) + +# add_subdirectory(testDES) +# add_test(NAME testDES COMMAND testDES) + +# add_subdirectory(testRSA_OS) +# add_test(NAME testRSA_OS COMMAND testRSA_OS) diff --git a/test/testDES/CMakeLists.txt b/test/testDES/CMakeLists.txt index 2dccdbc..3818abe 100644 --- a/test/testDES/CMakeLists.txt +++ b/test/testDES/CMakeLists.txt @@ -1,15 +1,15 @@ -cmake_minimum_required(VERSION 3.0.0) - -# directory name to be used as project name -project (testDES VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -#include_directories( ${PROJECT_SOURCE_DIR}/src ) -add_executable(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/main.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) - - +cmake_minimum_required(VERSION 3.0.0) + +# directory name to be used as project name +project (testDES VERSION 1.0.1) +set(ADDCV NO) +# CMakeM1 checks ADDCV variable whether to include OpenCV +# and return LIBS variable with the list of libraries to link +include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) +#include_directories( ${PROJECT_SOURCE_DIR}/src ) +add_executable(${PROJECT_NAME} +${PROJECT_SOURCE_DIR}/main.cpp +) +target_link_libraries(${PROJECT_NAME} ${LIBS}) + + diff --git a/test/testDES/main.cpp b/test/testDES/main.cpp index 89368b7..814082f 100644 --- a/test/testDES/main.cpp +++ b/test/testDES/main.cpp @@ -1,32 +1,32 @@ - -///////////////////////////////////////////////////////////////////////////// -// Project: testDES -// Description: Test program for DES -///////////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include "ce/ceDES.h" -#include "ce/ceMisc.h" -using namespace std; -using namespace ce; -int main() { - std::string message = "12345678"; - std::string keyL = "abcdefgh"; - std::string keyR = "ijklmnop"; - std::string estr = ceDES::Encrypt(message,keyL); - std::string estrh = ceMisc::ToStr16(ceMisc::str2cvec(estr),""); - cout<<"DES: "< +#include +#include +#include +#include +#include +#include "ce/ceDES.h" +#include "ce/ceMisc.h" +using namespace std; +using namespace ce; +int main() { + std::string message = "12345678"; + std::string keyL = "abcdefgh"; + std::string keyR = "ijklmnop"; + std::string estr = ceDES::Encrypt(message,keyL); + std::string estrh = ceMisc::ToStr16(ceMisc::str2cvec(estr),""); + cout<<"DES: "< -#include -#include -#include -#include -#include -#include "ce/ceConfig.h" -using namespace std; -using namespace ce; -int main() { - int i = 0; - string jstr = R"({"id":1})"; - Json::Value obj = ceConfig::GetJson(jstr); - if(!obj["id"].isNull()){ - i = obj["id"].asInt(); - cout<<"ID = "< +#include +#include +#include +#include +#include +#include "ce/ceConfig.h" +using namespace std; +using namespace ce; +int main() { + int i = 0; + string jstr = R"({"id":1})"; + Json::Value obj = ceConfig::GetJson(jstr); + if(!obj["id"].isNull()){ + i = obj["id"].asInt(); + cout<<"ID = "< -#include -#include -#include -#include -#include -#include "ce/ceRSA_OS.h" -#include "ce/ceMisc.h" -using namespace std; -using namespace ce; -// ---------------------------------------------------------------------------- -std::string str_hex2byte(std::string str) -{ - string bstr; - str.erase(remove_if(str.begin(), str.end(), [](char ch) { - return !( - (ch >= '0' && ch <= '9') || - (ch >= 'A' && ch <= 'Z') || - (ch >= 'a' && ch <= 'z')); }), str.end()); - int n = str.length(); - for (int i = 0; i < n; i += 2) - bstr += ((char)stoi(str.substr(i, 2), NULL, 16)); - return bstr; -} - -std::string str_byte2hex(std::string bstr) -{ - unsigned char u; - std::stringstream ss; - for (auto c: bstr) { - u = (unsigned char)(c); - ss << std::hex << std::setfill('0') << std::setw(2) << static_cast(u); - } - return ss.str(); -} -// ---------------------------------------------------------------------------- -int main() { - std::string mes = str_hex2byte("6a02541333ff12289999990101f001f984ab5d901597b87806063f77086ecc434a34ac1ae5fe056de000fbc6b9ff85328de9eda93654864929b938f16ac5bcc1988c21b4b024a075c1dcdce73613cd50658b5bc6ca6fd3493043185565659dbd0bb74b37dce662c17c7410b32eb8dc1da119093a0f82a0fca71765c5c16e885cb2d544432a32debf5cf6c80354bc8f71761e33e367b959cfec030c465ead85dc310b6803baca8f70db5b5cf468db1c32941a6ad3f574e6494d7e34e77ca144d3bd21f21ef495e5d24a6ac5d1440e58737e96086297aa4a20b911a8c5f81914c5eebe72c99e700bde265d274522402d467fe1c90d5fa8b5bc"); - std::string d = str_hex2byte("6e09f65f2d1ab8124c390cb04ce89ba55241c4e3695e015280fea181b3f8b71cbdfe1dfda496917e6a30ba4abf39bc2f7cab246c5bee00e1fccc4d1f08aaee65ee6103b915dd21b47c73a834a9a1c6fb1e250b33adcdc40087878ad928d7387f3531563ba9c668a57b734fb6628395e38459dde5854ac0d88177a1633a0356feca9036ed8c4799e811cb5a4a553f0b9d4b882fab9177e41a00c61a310e8cb0d059110b236b88522742fe75e7630a701d8e3cff5bf0d76a1752cc879ffdeebfa954866115d3efa082794af9118cfae460af2aa0f19a73f152239ae190fd50eed40bd9d3a32b9e287311b4de98891999d6a9427d458120b5d3"); - std::string n = str_hex2byte("a50ef18ec3a8141b72559308735ce977fb62a7551e0d01fbc17df2428df512ab1cfd2cfc76e1da3d9f4917701ed69a473b00b6a289e50152fb3273ae8d006598e5918595a0cbb28ebaad7c4efe72aa78ad3790cd84b4a600cb4b5045bd42d4becfca01597ea99cf8392cf79193c560d54686ccd847f02144c2337216724d7d347a960565c210cddffcd79a5b6e0b46de010976d5cb9263569633dfff57d73702141efc0d6549bbfcf3a9a8b122bd1db6afdd9c9206ce4cd4cc612b58d311ff499299477d6ccb8bd356b3187b4188c01527a9da08e8ec543c821a7c43c694f45f0836b89a45b1a0f6ed5f191050d9360c642fa5b514a07bdd"); - std::string e = str_hex2byte("03"); - std::cout << "RSA d (Len "<< d.length() <<"): " << str_byte2hex(d) << std::endl; - std::cout << "RSA e (Len "<< e.length() <<"): " << str_byte2hex(e) << std::endl; - std::cout << "RSA n (Len "<< n.length() <<"): " << str_byte2hex(n) << std::endl; - - string cert = ceRSA_OS::decrypt(mes, d,n,e); - cout<<"Cert: "< +#include +#include +#include +#include +#include +#include "ce/ceRSA_OS.h" +#include "ce/ceMisc.h" +using namespace std; +using namespace ce; +// ---------------------------------------------------------------------------- +std::string str_hex2byte(std::string str) +{ + string bstr; + str.erase(remove_if(str.begin(), str.end(), [](char ch) { + return !( + (ch >= '0' && ch <= '9') || + (ch >= 'A' && ch <= 'Z') || + (ch >= 'a' && ch <= 'z')); }), str.end()); + int n = str.length(); + for (int i = 0; i < n; i += 2) + bstr += ((char)stoi(str.substr(i, 2), NULL, 16)); + return bstr; +} + +std::string str_byte2hex(std::string bstr) +{ + unsigned char u; + std::stringstream ss; + for (auto c: bstr) { + u = (unsigned char)(c); + ss << std::hex << std::setfill('0') << std::setw(2) << static_cast(u); + } + return ss.str(); +} +// ---------------------------------------------------------------------------- +int main() { + std::string mes = str_hex2byte("6a02541333ff12289999990101f001f984ab5d901597b87806063f77086ecc434a34ac1ae5fe056de000fbc6b9ff85328de9eda93654864929b938f16ac5bcc1988c21b4b024a075c1dcdce73613cd50658b5bc6ca6fd3493043185565659dbd0bb74b37dce662c17c7410b32eb8dc1da119093a0f82a0fca71765c5c16e885cb2d544432a32debf5cf6c80354bc8f71761e33e367b959cfec030c465ead85dc310b6803baca8f70db5b5cf468db1c32941a6ad3f574e6494d7e34e77ca144d3bd21f21ef495e5d24a6ac5d1440e58737e96086297aa4a20b911a8c5f81914c5eebe72c99e700bde265d274522402d467fe1c90d5fa8b5bc"); + std::string d = str_hex2byte("6e09f65f2d1ab8124c390cb04ce89ba55241c4e3695e015280fea181b3f8b71cbdfe1dfda496917e6a30ba4abf39bc2f7cab246c5bee00e1fccc4d1f08aaee65ee6103b915dd21b47c73a834a9a1c6fb1e250b33adcdc40087878ad928d7387f3531563ba9c668a57b734fb6628395e38459dde5854ac0d88177a1633a0356feca9036ed8c4799e811cb5a4a553f0b9d4b882fab9177e41a00c61a310e8cb0d059110b236b88522742fe75e7630a701d8e3cff5bf0d76a1752cc879ffdeebfa954866115d3efa082794af9118cfae460af2aa0f19a73f152239ae190fd50eed40bd9d3a32b9e287311b4de98891999d6a9427d458120b5d3"); + std::string n = str_hex2byte("a50ef18ec3a8141b72559308735ce977fb62a7551e0d01fbc17df2428df512ab1cfd2cfc76e1da3d9f4917701ed69a473b00b6a289e50152fb3273ae8d006598e5918595a0cbb28ebaad7c4efe72aa78ad3790cd84b4a600cb4b5045bd42d4becfca01597ea99cf8392cf79193c560d54686ccd847f02144c2337216724d7d347a960565c210cddffcd79a5b6e0b46de010976d5cb9263569633dfff57d73702141efc0d6549bbfcf3a9a8b122bd1db6afdd9c9206ce4cd4cc612b58d311ff499299477d6ccb8bd356b3187b4188c01527a9da08e8ec543c821a7c43c694f45f0836b89a45b1a0f6ed5f191050d9360c642fa5b514a07bdd"); + std::string e = str_hex2byte("03"); + std::cout << "RSA d (Len "<< d.length() <<"): " << str_byte2hex(d) << std::endl; + std::cout << "RSA e (Len "<< e.length() <<"): " << str_byte2hex(e) << std::endl; + std::cout << "RSA n (Len "<< n.length() <<"): " << str_byte2hex(n) << std::endl; + + string cert = ceRSA_OS::decrypt(mes, d,n,e); + cout<<"Cert: "< -#include -#include -#include -#include -#include -#include "ce/ceSHA1.h" -#include "ce/ceMisc.h" -using namespace std; -using namespace ce; -int main() { - std::string message = "12345678"; - ceSHA1 mes_sha; - mes_sha.Init(); - mes_sha.Update(message); - std::string mshastr = mes_sha.Final(); - std::string mssh = ceMisc::ToStr16(ceMisc::str2cvec(mshastr),""); - cout<<"SHA1: "< +#include +#include +#include +#include +#include +#include "ce/ceSHA1.h" +#include "ce/ceMisc.h" +using namespace std; +using namespace ce; +int main() { + std::string message = "12345678"; + ceSHA1 mes_sha; + mes_sha.Init(); + mes_sha.Update(message); + std::string mshastr = mes_sha.Final(); + std::string mssh = ceMisc::ToStr16(ceMisc::str2cvec(mshastr),""); + cout<<"SHA1: "< - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 16.0 - {5397B256-872B-44E9-A100-8EE02B070E5A} - Win32Proj - ceutil - 10.0 - - - - StaticLibrary - true - v143 - Unicode - - - StaticLibrary - false - v143 - true - Unicode - - - StaticLibrary - true - v143 - Unicode - - - StaticLibrary - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - $(VCPKG_ROOT)\installed\x86-windows\lib\ - $(ProjectName)d - - - true - $(VCPKG_ROOT)\installed\x64-windows\lib - $(ProjectName)d - - - false - $(VCPKG_ROOT)\installed\x86-windows\lib\ - - - false - $(VCPKG_ROOT)\installed\x64-windows\lib\ - - - - NotUsing - Level3 - Disabled - true - NDEBUG;_LIB;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS - true - pch.h - $(SolutionDir)..\include;%(AdditionalIncludeDirectories) - - - Windows - true - - - xcopy "$(SolutionDir)..\include" "$(VCPKG_ROOT)\installed\x86-windows\include" /E /H /C /I /Y - - - - - NotUsing - Level3 - Disabled - true - NDEBUG;_LIB;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS - true - pch.h - $(SolutionDir)..\include;%(AdditionalIncludeDirectories) - - - Windows - true - - - xcopy "$(SolutionDir)..\include" "$(VCPKG_ROOT)\installed\x64-windows\include" /E /H /C /I /Y - - - - - NotUsing - Level3 - MaxSpeed - true - true - true - NDEBUG;_LIB;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS - true - pch.h - $(SolutionDir)..\include;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - - - xcopy "$(SolutionDir)..\include" "$(VCPKG_ROOT)\installed\x86-windows\include" /E /H /C /I /Y - - - - - NotUsing - Level3 - MaxSpeed - true - true - true - NDEBUG;_LIB;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS - true - pch.h - $(SolutionDir)..\include;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - - - %(AdditionalDependencies) - - - - - xcopy "$(SolutionDir)..\include" "$(VCPKG_ROOT)\installed\x64-windows\include" /E /H /C /I /Y - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 16.0 + {5397B256-872B-44E9-A100-8EE02B070E5A} + Win32Proj + ceutil + 10.0 + + + + StaticLibrary + true + v143 + Unicode + + + StaticLibrary + false + v143 + true + Unicode + + + StaticLibrary + true + v143 + Unicode + + + StaticLibrary + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(VCPKG_ROOT)\installed\x86-windows\lib\ + $(ProjectName)d + + + true + $(VCPKG_ROOT)\installed\x64-windows\lib + $(ProjectName)d + + + false + $(VCPKG_ROOT)\installed\x86-windows\lib\ + + + false + $(VCPKG_ROOT)\installed\x64-windows\lib\ + + + + NotUsing + Level3 + Disabled + true + NDEBUG;_LIB;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS + true + pch.h + $(SolutionDir)..\include;%(AdditionalIncludeDirectories) + + + Windows + true + + + xcopy "$(SolutionDir)..\include" "$(VCPKG_ROOT)\installed\x86-windows\include" /E /H /C /I /Y + + + + + NotUsing + Level3 + Disabled + true + NDEBUG;_LIB;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS + true + pch.h + $(SolutionDir)..\include;%(AdditionalIncludeDirectories) + + + Windows + true + + + xcopy "$(SolutionDir)..\include" "$(VCPKG_ROOT)\installed\x64-windows\include" /E /H /C /I /Y + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + NDEBUG;_LIB;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS + true + pch.h + $(SolutionDir)..\include;%(AdditionalIncludeDirectories) + + + Windows + true + true + true + + + xcopy "$(SolutionDir)..\include" "$(VCPKG_ROOT)\installed\x86-windows\include" /E /H /C /I /Y + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + NDEBUG;_LIB;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS + true + pch.h + $(SolutionDir)..\include;%(AdditionalIncludeDirectories) + + + Windows + true + true + true + + + %(AdditionalDependencies) + + + + + xcopy "$(SolutionDir)..\include" "$(VCPKG_ROOT)\installed\x64-windows\include" /E /H /C /I /Y + + + + + \ No newline at end of file diff --git a/vcprj/ceutil.vcxproj.filters b/vcprj/ceutil.vcxproj.filters index a12fbc9..bbb572c 100644 --- a/vcprj/ceutil.vcxproj.filters +++ b/vcprj/ceutil.vcxproj.filters @@ -1,161 +1,158 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - {c27916e6-2986-4cf4-b618-991e007063f8} - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - etc - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {c27916e6-2986-4cf4-b618-991e007063f8} + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + etc + + \ No newline at end of file From b7d3ceae8d5a13b8efaada065297a5ec876fd044 Mon Sep 17 00:00:00 2001 From: yan9a Date: Fri, 23 Aug 2024 13:32:01 +1200 Subject: [PATCH 02/10] Update date time header --- CMakeLists.txt | 3 - include/ce/ceConfig.h | 55 --- include/ce/ceDateTime.h | 226 --------- include/ce/ceMmDateTime.h | 347 -------------- include/ce/ceUtil.h | 71 --- include/ce/ceconf.h | 194 ++++++++ include/ce/cedt.h | 871 +++++++++++++++++++++++++++++++++++ include/ce/cetcpsvr.h | 510 ++++++++++++++++++++ src/ceConfig.cpp | 110 ----- src/ceMmDateTime.cpp | 870 ---------------------------------- vcprj/ceutil.vcxproj | 7 +- vcprj/ceutil.vcxproj.filters | 17 +- 12 files changed, 1581 insertions(+), 1700 deletions(-) delete mode 100644 include/ce/ceConfig.h delete mode 100644 include/ce/ceDateTime.h delete mode 100644 include/ce/ceMmDateTime.h delete mode 100644 include/ce/ceUtil.h create mode 100644 include/ce/ceconf.h create mode 100644 include/ce/cedt.h create mode 100644 include/ce/cetcpsvr.h delete mode 100644 src/ceConfig.cpp delete mode 100644 src/ceMmDateTime.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b34bbf5..ea6f310 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,8 +59,6 @@ endif() message(STATUS "List of libraries = ${LIBS}") include_directories(${PROJECT_SOURCE_DIR}/include) add_library(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/ceDateTime.cpp -${PROJECT_SOURCE_DIR}/src/ceMmDateTime.cpp ${PROJECT_SOURCE_DIR}/src/ceLog.cpp ${PROJECT_SOURCE_DIR}/src/ceSerial.cpp ${PROJECT_SOURCE_DIR}/src/ceWxTmr.cpp @@ -72,7 +70,6 @@ ${PROJECT_SOURCE_DIR}/src/ceFraChecksum.cpp ${PROJECT_SOURCE_DIR}/src/ceFraCmd.cpp ${PROJECT_SOURCE_DIR}/src/ceI2C.cpp ${PROJECT_SOURCE_DIR}/src/cePCA9535.cpp -${PROJECT_SOURCE_DIR}/src/ceConfig.cpp ${PROJECT_SOURCE_DIR}/src/ceModbus.cpp ${PROJECT_SOURCE_DIR}/src/ceWxSerial.cpp ${PROJECT_SOURCE_DIR}/src/cewxcvMisc.cpp diff --git a/include/ce/ceConfig.h b/include/ce/ceConfig.h deleted file mode 100644 index f4c414b..0000000 --- a/include/ce/ceConfig.h +++ /dev/null @@ -1,55 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceConfig.h -// Description: Configuration -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CECONFIG_H -#define CECONFIG_H - -#include "ce/ceMacros.h" // macros - -#include -#include -#include -#include -#include -#include -#if CE_JSON==1 -#include -#endif - -#define CONF_PATH "./conf.json" -namespace ce { -class ceConfig { -public: - ceConfig(); - ceConfig(std::string path); - virtual ~ceConfig(); - static std::string ReadFile(std::string path); - static int WriteFile(std::string path,std::string str); - template - static T Validate(T value,T min_val,T max_val,T default_val); // defined in header -#if CE_JSON==1 - Json::Value GetJson(); - static Json::Value GetJson(std::string jstr); - static Json::Value ReadJson(std::string path); - static int WriteJson(Json::Value obj, std::string path); - static std::string ToString(Json::Value obj); - int SaveJson(Json::Value obj); -#endif -private: - std::string m_path; -}; - -//example usage -// int i=Validate(v,1,10,5); -template -T ceConfig::Validate(T value,T min_val,T max_val,T default_val) -{ - if(valuemax_val) value=default_val; - return value; -} - -} // namespace ce -#endif // CECONFIG_H diff --git a/include/ce/ceDateTime.h b/include/ce/ceDateTime.h deleted file mode 100644 index 2937539..0000000 --- a/include/ce/ceDateTime.h +++ /dev/null @@ -1,226 +0,0 @@ -// File: ceDateTime.h -// Description: Simple C++ Date/time class -// WebSite: https://yan9a.github.io/mmcal/ -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -#ifndef CEDATETIME_H -#define CEDATETIME_H - -#include -#include "ce/ceMacros.h" // macros - -#if defined(CE_WINDOWS) - #include -#elif defined(CE_LINUX) - #include -#else - #define ceSYSTEMINDEPENDENT //the system might not even have RTC, like microcontrollers -#endif - -namespace ce { - -class ceDateTime -{ -private: - double m_tz; // time zone for this particular instance - double m_jd; // julian date in UTC - long m_ct; // calendar type [0=British (default), 1=Gregorian, 2=Julian] - long m_SG; // Beginning of Gregorian calendar in JDN [default=2361222] -public: - // Time to Fraction of day starting from 12 noon - // input: (h=hour, n=minute, s=second) output: (d: fraction of day) - static double t2d(long h,long n,double s); - - //Western date to Julian date - //Credit4 Gregorian2JD: http://www.cs.utsa.edu/~cs1063/projects/Spring2011/Project1/jdn-explanation.html - //input: (y: year, m: month, d: day, h=hour, n=minute, s=second - // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] - // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) - // Gregorian start in British calendar (1752/Sep/14 = 2361222) - //output: Julian date - static double w2j(long year, long month, long day, long hour=12, long minute=0, double second=0, long ct=0, long SG=2361222); - - //Julian date to Western date - //Credit4 Gregorian date: http://pmyers.pcug.org.au/General/JulianDates.htm - //Credit4 Julian Calendar: http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html - //input: (jd:julian date, - // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] - // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) - //output: Western date (y=year, m=month, d=day, h=hour, n=minute, s=second) - static void j2w(double jd, long& year, long& month, long& day, long& hour, long& minute, double& second, long ct=0, long SG=2361222); - - // unix time to julian date - static double u2j(time_t ut); - - // julian date to unix time - static time_t j2u(double jd); - - // Compile time string - static std::string compiletime(); - -#ifndef ceSYSTEMINDEPENDENT - // get current time in julian date - static double jdnow(); - - // get local time zone offset between local time and UTC in hours (e.g. 8 for UTC +8) - static double ltzoh(); - - // Set local date time of the system - // need super user privileges - static void SetSystemLocalTime(int year, int month, int day,int hour, int minute, int second); - - // set time to now - void Set2Now(); - - // set time zone in hours to the system's local time zone - void SetTimezone();//set to local time zone - - ceDateTime();//default constructor - -#endif //ceSYSTEMINDEPENDENT - - // jd to date time string - // input: (jd:julian date, - // fm: format [Optional argument: "%Www %y-%mm-%dd %HH:%nn:%ss %zz"] - // tz : time zone offset in hours (e.g. 8 for GMT +8) - // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] - // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) - // output: date time string according to fm where formatting strings are as follows - // %yyyy : year [0000-9999, e.g. 2018] - // %yy : year [00-99 e.g. 18] - // %y : year [0-9999, e.g. 201] - // %MMM : month [e.g. JAN] - // %Mmm : month [e.g. Jan] - // %mm : month with zero padding [01-12] - // %M : month [e.g. January] - // %m : month [1-12] - // %dd : day with zero padding [01-31] - // %d : day [1-31] - // %HH : hour [00-23] - // %hh : hour [01-12] - // %H : hour [0-23] - // %h : hour [1-12] - // %AA : AM or PM - // %aa : am or pm - // %nn : minute with zero padding [00-59] - // %n : minute [0-59] - // %ss : second [00-59] - // %s : second [0-59] - // %lll : millisecond [000-999] - // %l : millisecond [0-999] - // %WWW : Weekday [e.g. SAT] - // %Www : Weekday [e.g. Sat] - // %W : Weekday [e.g. Saturday] - // %w : Weekday number [0=sat, 1=sun, ..., 6=fri] - // %zz : time zone (e.g. +08, +06:30) - static std::string j2s(double jd, std::string fm="%Www %y-%mm-%dd %HH:%nn:%ss %zz", double tz=0, long ct=0, long SG=2361222); - - // convert date time string to jd - // inputs - // tstr : time string - // accepts following formats - // 1: yyyy-mm-dd hh:nn:ss - // 2: yyyy-mm-dd hh:nn:ss.ttt - // 3: yyyymmddhhnnss - // 4: yyyymmddhhnnssttt - // tz : time zone offset in hours - // [optional argument: 0 - UTC] - // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] - // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) - // output - // jd: julian date - // positive integer: ok - // -1 : error - static double s2j(std::string tstr, double tz=0, long ct=0, long SG=2361222); - - // set time zone in hours for this instance - void SetTimezone(double tz); - - // set time in jd - void SetJD(double jd); - - // set in unix time - void SetUnixTime(time_t ut); - - // set date time for a timezone and a calendar type - void SetDateTime(long year, long month, long day, long hour=12, long minute=0, double second=0, double tz=0, long ct=0, long SG=2361222); - - // set time using a date time string - void SetDateTimeString(std::string tstr, double tz=0, long ct=0, long SG=2361222); - - // set calendar type [0=British (default), 1=Gregorian, 2=Julian] - void SetCT(long ct); - - //------------------------------------------------------------------------- - // set Beginning of Gregorian calendar in JDN [default=2361222] - void SetSG(long sg); - - // Get Date Time string - // input: (fm: format [Optional argument: "%Www %y-%mm-%dd %HH:%nn:%ss %zz"]) - // output: date time string according to fm where formatting strings are as follows - // %yyyy : year [0000-9999, e.g. 2018] - // %yy : year [00-99 e.g. 18] - // %y : year [0-9999, e.g. 201] - // %MMM : month [e.g. JAN] - // %Mmm : month [e.g. Jan] - // %mm : month with zero padding [01-12] - // %M : month [e.g. January] - // %m : month [1-12] - // %dd : day with zero padding [01-31] - // %d : day [1-31] - // %HH : hour [00-23] - // %hh : hour [01-12] - // %H : hour [0-23] - // %h : hour [1-12] - // %AA : AM or PM - // %aa : am or pm - // %nn : minute with zero padding [00-59] - // %n : minute [0-59] - // %ss : second [00-59] - // %s : second [0-59] - // %lll : millisecond [000-999] - // %l : millisecond [0-999] - // %WWW : Weekday [e.g. SAT] - // %Www : Weekday [e.g. Sat] - // %W : Weekday [e.g. Saturday] - // %w : Weekday number [0=sat, 1=sun, ..., 6=fri] - // %zz : time zone (e.g. +08, +06:30) - std::string ToString(std::string fm = "%Www %y-%mm-%dd %HH:%nn:%ss %zz"); - - // filter input string to get digits only - static std::string GetDigits(std::string str); - - // find a string and replace all occurances - static std::string ReplaceAll(std::string str,std::string fstr,std::string rstr); - - double jd(); // julian date - double jdl(); // julian date for this time zone - long jdn(); // julian day number - long jdnl(); // julian day number for this time zone - long y(); // year - long m(); // month - long d(); // day - long h(); // hour [0-23] - long n(); // minute - long s(); // second - long l(); // millisecond - long w(); // weekday [0=sat, 1=sun, ..., 6=fri] - long ut(); // unix time - double tz(); // time zone - long ct(); // calendar type [0=British (default), 1=Gregorian, 2=Julian] - long SG(); // Beginning of Gregorian calendar in JDN [default=2361222] - long mlen(); // length of this month - //------------------------------------------------------------------------- - // find the length of western month - // input: (y=year, m=month [Jan=1, ... , Dec=12], - // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian]) - // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) - // output: (wml = length of the month) - static long wml(long y,long m,long ct=0,long SG=2361222); - //------------------------------------------------------------------------- -}; - -} // namespace ce - -#endif // CEDATETIME_H diff --git a/include/ce/ceMmDateTime.h b/include/ce/ceMmDateTime.h deleted file mode 100644 index 3dae4df..0000000 --- a/include/ce/ceMmDateTime.h +++ /dev/null @@ -1,347 +0,0 @@ -// File: ceMmDateTime.h -// Description: Modern Myanmar Calendrical Calculations -// WebSite: https://yan9a.github.io/mmcal/ -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye -// Doc: http://cool-emerald.blogspot.com/2013/06/algorithm-program-and-calculation-of.html -//------------------------------------------------------------------------- -#ifndef CEMMDATETIME_H -#define CEMMDATETIME_H - -#include"ce/ceDateTime.h" -#include -#include -namespace ce { - -class ceMmDateTime : public ceDateTime -{ -private: -public: - //------------------------------------------------------------------------- - // default constructor - ceMmDateTime(); - //------------------------------------------------------------------------- - // Get Myanmar year constants depending on era - // Thanks to Myo Zarny and Wunna Ko for earlier Myanmar years data - // input: my -myanmar year - // output: - // EI = Myanmar calendar era id [1-3] : calculations methods/constants depends on era - // WO = watat offset to compensate - // NM = number of months to find excess days - // EW = exception in watat year - static void GetMyConst(long my,double& EI,double& WO,double& NM,long& EW); - //------------------------------------------------------------------------- - // Search first dimension in a 2D array - // input: (k=key,A=array,u=size) - // output: (i=index) - static long bSearch2(long k,long (*A)[2], long u); - //----------------------------------------------------------------------------- - // Search a 1D array - // input: (k=key,A=array,u=size) - // output: (i=index) - static long bSearch1(long k,long* A, long u); - //------------------------------------------------------------------------- - // Check watat (intercalary month) - // input: (my -myanmar year) - // output: ( - // watat - intercalary month [1=watat, 0=common] - // fm - full moon day of 2nd Waso in jdn_mm (jdn+6.5 for MMT) - // [only valid when watat=1]) - // dependency: GetMyConst(my) - static void cal_watat(long my, long& watat, long& fm); //get data for respective era - //------------------------------------------------------------------------- - // Check Myanmar Year - // input: (my -myanmar year) - // output: ( myt :year type [0=common, 1=little watat, 2=big watat], - // tg1 : the 1st day of Tagu as jdn_mm (Julian Day Number for MMT) - // fm : full moon day of [2nd] Waso as Julain Day Number - // werr: watat error [0=ok, 1= error]) - // dependency: cal_watat(my) - static void cal_my(long my, long& myt, long& tg1, long& fm, long& werr); - //------------------------------------------------------------------------- - // Julian day number to Myanmar date - // input: (jdn -julian day number) - // output: ( - // myt =year type [0=common, 1=little watat, 2=big watat], - // my = year, - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md = day of the month [1 to 30]) - // dependency: cal_my(my) - static void j2m(double jd, long& myt, long& my, long& mm, long& md); - //------------------------------------------------------------------------- - // Get moon phase from day of the month, month, and year type. - // input: ( - // md= day of the month [1-30], - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // myt = year type [0=common, 1=little watat, 2=big watat]) - // output: (mp =moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon]) - static long cal_mp(long md,long mm,long myt); - //------------------------------------------------------------------------- - // Get length of month from month, and year type. - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // myt = year type [0=common, 1=little watat, 2=big watat]) - // output: (mml = length of the month [29 or 30 days]) - static long cal_mml(long mm,long myt); - //------------------------------------------------------------------------- - // Get the apparent length of the year from year type. - // input: ( myt = year type [0=common, 1=little watat, 2=big watat]) - // output: ( myl= year length [354, 384, or 385 days]) - static long cal_myl(long myt); - //------------------------------------------------------------------------- - // Get fortnight day from month day - // input: ( md= day of the month [1-30]) - // output: (mf= fortnight day [1 to 15]) - static long cal_mf(long md); - //------------------------------------------------------------------------- - // Get day of month from fortnight day, moon phase, and length of the month - // input: ( - // mf = fortnight day [1 to 15], - // mp = moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // myt = year type [0=common, 1=little watat, 2=big watat]) - // output: ( md = day of the month [1-30]) - static long cal_md(long mf,long mp,long mm,long myt); - //------------------------------------------------------------------------- - // Myanmar date to Julian day number - // input: ( - // my = year, - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12 , Late Tagu=13, Late Kason=14 ], - // md = day of the month [1-30] - // output: (jd -julian day number) - // dependency: cal_my(my) - static long m2j(long my,long mm,long md); - //------------------------------------------------------------------------- - // Checking Astrological days - // More details @ http://cool-emerald.blogspot.sg/2013/12/myanmar-astrological-calendar-days.html - //------------------------------------------------------------------------- - // Get sabbath day and sabbath eve from day of the month, month, and year type. - // input: ( - // md= day of the month [1-30], - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // myt = year type [0=common, 1=little watat, 2=big watat]) - // output: ( [1=sabbath, 2=sabbath eve, 0=else]) - static long cal_sabbath(long md, long mm, long myt); - //------------------------------------------------------------------------- - // Get yatyaza from month, and weekday - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=yatyaza, 0=else]) - static long cal_yatyaza(long mm, long wd); - //------------------------------------------------------------------------- - // Get pyathada from month, and weekday - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=pyathada, 2=afternoon pyathada, 0=else]) - static long cal_pyathada(long mm, long wd); - //------------------------------------------------------------------------- - // nagahle - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ]) - // output: ( [0=west, 1=north, 2=east, 3=south]) - static long cal_nagahle(long mm); - //------------------------------------------------------------------------- - // mahabote - // input: ( - // my = year, - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [0=Binga, 1=Atun, 2=Yaza, 3=Adipati, 4= Marana, 5=Thike, 6=Puti]) - static long cal_mahabote(long my, long wd); - //------------------------------------------------------------------------- - // nakhat - // input: ( my = year ) - // output: ( [0=orc, 1=elf, 2=human] ) - static long cal_nakhat(long my); - //------------------------------------------------------------------------- - // thamanyo - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=thamanyo, 0=else]) - static long cal_thamanyo(long mm, long wd); - //------------------------------------------------------------------------- - // Get amyeittasote - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=amyeittasote, 0=else]) - static long cal_amyeittasote(long md, long wd); - //------------------------------------------------------------------------- - // Get warameittugyi - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=warameittugyi, 0=else]) - static long cal_warameittugyi(long md, long wd); - //------------------------------------------------------------------------- - // Get warameittunge - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=warameittunge, 0=else]) - static long cal_warameittunge(long md, long wd); - //------------------------------------------------------------------------- - // Get yatpote - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=yatpote, 0=else]) - static long cal_yatpote(long md, long wd); - //------------------------------------------------------------------------- - // Get thamaphyu - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=thamaphyu, 0=else]) - static long cal_thamaphyu(long md, long wd); - //------------------------------------------------------------------------- - // Get nagapor - // input: ( - // md= day of the month [1-30], - // wd= weekday [0=sat, 1=sun, ..., 6=fri]) - // output: ( [1=nagapor, 0=else]) - static long cal_nagapor(long md, long wd); - //------------------------------------------------------------------------- - // yatyotema - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md= day of the month [1-30]) - // output: ( [1=yatyotema, 0=else]) - static long cal_yatyotema(long mm, long md); - //------------------------------------------------------------------------- - // mahayatkyan - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md= day of the month [1-30]) - // output: ( [1=mahayatkyan, 0=else]) - static long cal_mahayatkyan(long mm, long md); - //------------------------------------------------------------------------- - // shanyat - // input: ( - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md= day of the month [1-30]) - // output: ( [1=shanyat, 0=else]) - static long cal_shanyat(long mm, long md); - //------------------------------------------------------------------------- - // get astrological information - // input: (jdn: Julian Day Number) - // output: (array of strings) - static std::vector cal_astro(long jdn); - // End of checking Astrological days - //------------------------------------------------------------------------- - // Get holidays - // input: (jdn=Julian Day Number) - // output: ( array of strings) - // Thanks to Ye Lin Kyaw and Aye Nyein for the knowledge about - // the Myanmar calendar and the new year - static std::vector cal_holiday(long jdn); - //------------------------------------------------------------------------- - // DoE : Date of Easter using "Meeus/Jones/Butcher" algorithm - // Reference: Peter Duffett-Smith, Jonathan Zwart', - // "Practical Astronomy with your Calculator or Spreadsheet," - // 4th Etd, Cambridge university press, 2011. Page-4. - // input: (y=year) - // output: (j=julian day number) - // dependency: w2j() - static long DoE(long y); - //------------------------------------------------------------------------- - // Get other holidays - // input: (jdn: Julian Day Number) - // output: (array of strings) - // dependency: DoE(), j2w() - static std::vector cal_holiday2(long jdn); - //------------------------------------------------------------------------- - // jd to date string in Myanmar calendar - // input: (jd:julian date, - // fs: format string [Optional argument: "&y &M &P &ff"] - // tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) - // output: date string in Myanmar calendar according to fm - // where formatting strings are as follows - // &yyyy : Myanmar year [0000-9999, e.g. 1380] - // &YYYY : Sasana year [0000-9999, e.g. 2562] - // &y : Myanmar year [0-9999, e.g. 138] - // &mm : month with zero padding [01-14] - // &M : month [e.g. January] - // &m : month [1-14] - // &P : moon phase [e.g. waxing, waning, full moon, or new moon] - // &dd : day of the month with zero padding [01-31] - // &d : day of the month [1-31] - // &ff : fortnight day with zero padding [01-15] - // &f : fortnight day [1-15] - static std::string j2ms(double jd, std::string fs="&y &M &P &ff", double tz=0); - //------------------------------------------------------------------------- - // get properties - long myt(); // Myanmar year type - long my(); // Myanmar year - long sy(); // Sasana year - std::string my_name(); // Myanmar year name - - long mm(); // Myanmar month [1-14] - // [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ] - - long md(); // Myanmar day of the month [1-30] - long mp(); // Moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] - long mf(); // Fortnight day [1-15] - std::string sabbath(); // get sabbath string - std::string yatyaza(); // get yatyaza string - std::string pyathada(); // get pyathada string - std::string nagahle(); // get nagahle direction - std::string mahabote(); // get mahabote direction - std::vector astro(); // get the array of astrological days - std::vector holidays(); // get the array of public holidays - std::vector holidays2(); // get the array of other holidays - //------------------------------------------------------------------------- - // get Myanmar Date String - // input: ( - // fs: format string [Optional argument: "&y &M &P &ff"] - // tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) - // output: date string in Myanmar calendar according to fm - // where formatting strings are as follows - // &yyyy : Myanmar year [0000-9999, e.g. 1380] - // &YYYY : Sasana year [0000-9999, e.g. 2562] - // &y : Myanmar year [0-9999, e.g. 138] - // &mm : month with zero padding [01-14] - // &M : month [e.g. January] - // &m : month [1-14] - // &P : moon phase [e.g. waxing, waning, full moon, or new moon] - // &dd : day of the month with zero padding [01-31] - // &d : day of the month [1-31] - // &ff : fortnight day with zero padding [01-15] - // &f : fortnight day [1-15] - std::string ToMString(std::string fs="&y &M &P &ff"); - //------------------------------------------------------------------------- -}; - -} // namespace ce - -#endif // CEMMDATETIME_H \ No newline at end of file diff --git a/include/ce/ceUtil.h b/include/ce/ceUtil.h deleted file mode 100644 index bdf5576..0000000 --- a/include/ce/ceUtil.h +++ /dev/null @@ -1,71 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceUtil.h -// Description: CPP utilitiy modules -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_UTIL_H -#define CE_UTIL_H - -#include -#include "ce/ceMacros.h" // macros - -// The latest soure for ceDateTime is at -// https://github.com/yan9a/mmcal/tree/master/cpp -#include "ce/ceDateTime.h" -#include "ce/ceMmDateTime.h" - -// Log -#include "ce/ceLog.h" - -// The latest source for ceSerial is at -// https://github.com/yan9a/serial -#include "ce/ceSerial.h" - -// timer -#include "ce/ceWxTmr.h" - -// udp -// http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -#include "ce/ceUDP.h" - -// tcp -#include "ce/ceTcpServer.h" -#include "ce/ceTcpClient.h" - -// utilities -#include "ce/ceMisc.h" - -// Frame encode and decode -#include "ce/ceFrame.h" -#include "ce/ceFraCmd.h" -#include "ce/ceFraChecksum.h" - -// Modbus frame -#include "ce/ceModbus.h" - -// Frame encode and decode for command with /r/n -#include "ce/ceFraCmd.h" - -// I2C communication module -#include "ce/ceI2C.h" - -// PCA9535 -#include "ce/cePCA9535.h" - -// Config -#include "ce/ceConfig.h" - -// ceWxSerial -#include "ce/ceWxSerial.h" - -// DES -#include "ce/ceDES.h" - -// SHA1 -#include "ce/ceSHA1.h" - -// RSA OpenSSL -#include "ce/ceRSA_OS.h" - -#endif // CE_UTIL_H diff --git a/include/ce/ceconf.h b/include/ce/ceconf.h new file mode 100644 index 0000000..bdb5309 --- /dev/null +++ b/include/ce/ceconf.h @@ -0,0 +1,194 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: ceconf.h +// Description: Configuration +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// +// Requires: jsoncpp +///////////////////////////////////////////////////////////////////////////// + +#ifndef CECONFIG_H +#define CECONFIG_H + +#ifndef CE_MACROS_H + #define CE_MACROS_H + + #define CE_JSON 1 // include JSON + + #if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif + #elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif + #else + #ifndef CE_NOS + #define CE_NOS + #endif + #endif + + #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif + #elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif + #else + #ifndef CE_NARCH + #define CE_NARCH + #endif + #endif + +#endif // CE_MACROS_H + +#include +#include +#include +#include +#include +#include +#if CE_JSON==1 +#include +#endif + +#define CONF_PATH "./conf.json" +namespace ce { +class ceConfig { +public: + ceConfig(); + ceConfig(std::string path); + virtual ~ceConfig(); + static std::string ReadFile(std::string path); + static int WriteFile(std::string path,std::string str); + template + static T Validate(T value,T min_val,T max_val,T default_val); // defined in header +#if CE_JSON==1 + Json::Value GetJson(); + static Json::Value GetJson(std::string jstr); + static Json::Value ReadJson(std::string path); + static int WriteJson(Json::Value obj, std::string path); + static std::string ToString(Json::Value obj); + int SaveJson(Json::Value obj); +#endif +private: + std::string m_path; +}; + +//example usage +// int i=Validate(v,1,10,5); +template +T ceConfig::Validate(T value,T min_val,T max_val,T default_val) +{ + if(valuemax_val) value=default_val; + return value; +} + + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +inline ceConfig::ceConfig() : m_path(CONF_PATH) +{ + +} + +inline ceConfig::ceConfig(std::string path) : m_path(path) +{ + +} + +inline ceConfig::~ceConfig() +{ + +} + +inline std::string ceConfig::ReadFile(std::string path) +{ + std::string sstr = "", tstr = ""; + std::ifstream mys; + try { + mys.open(path.c_str()); + if (mys.is_open()) { + while (getline(mys, tstr)) { + sstr += tstr; + } + mys.close(); + } + } + catch (...) { + perror("Error in reading json file\n"); + } + return sstr; +} + +inline int ceConfig::WriteFile(std::string path, std::string str) +{ + std::ofstream wfile; + int r = -1; + try { + wfile.open(path.c_str()); + if (wfile.is_open()) { + wfile << str; + r = 0; + } + wfile.close(); + } + catch (...) { + perror("Error in json file writing\n"); + } + return r; +} + +#if CE_JSON==1 +inline Json::Value ceConfig::GetJson() +{ + return ReadJson(this->m_path); +} + +inline Json::Value ceConfig::ReadJson(std::string path) +{ + std::string document = ceConfig::ReadFile(path); + return ceConfig::GetJson(document); +} + +inline Json::Value ceConfig::GetJson(std::string jstr) +{ + std::stringstream ss; + Json::CharReaderBuilder reader; + Json::Value obj; + std::string errs; + ss.str(jstr); + if (Json::parseFromStream(reader, ss, &obj, &errs)) { + //printf("Parsing json string OK\n"); + } + else { + perror("Error in json parsing\n"); + } + return obj; +} + +inline int ceConfig::WriteJson(Json::Value obj, std::string path) +{ + std::string str = ceConfig::ToString(obj); + return ceConfig::WriteFile(path, str); +} + +inline std::string ceConfig::ToString(Json::Value obj) +{ + std::stringstream ss; + ss << obj; + return ss.str(); +} + +inline int ceConfig::SaveJson(Json::Value obj) +{ + return ceConfig::WriteJson(obj, this->m_path); +} +#endif // if CE_JSON +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce +#endif // CECONFIG_H diff --git a/include/ce/cedt.h b/include/ce/cedt.h new file mode 100644 index 0000000..ca0c821 --- /dev/null +++ b/include/ce/cedt.h @@ -0,0 +1,871 @@ +///////////////////////////////////////////////////////////////////////////// +// File: ceDateTime.h +// Description: Simple C++ Date/time class +// WebSite: https://yan9a.github.io/mmcal/ +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEDATETIME_H +#define CEDATETIME_H + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + +#include +#include +#include +#if defined(CE_WINDOWS) + #include + #include +#elif defined(CE_LINUX) + #include +#endif + +namespace ce { + +class ceDateTime +{ +private: + double m_tz; // time zone for this particular instance + double m_jd; // julian date in UTC + long m_ct; // calendar type [0=British (default), 1=Gregorian, 2=Julian] + long m_SG; // Beginning of Gregorian calendar in JDN [default=2361222] +public: + // Time to Fraction of day starting from 12 noon + // input: (h=hour, n=minute, s=second) output: (d: fraction of day) + static double t2d(long h,long n,double s); + + //Western date to Julian date + //Credit4 Gregorian2JD: http://www.cs.utsa.edu/~cs1063/projects/Spring2011/Project1/jdn-explanation.html + //input: (y: year, m: month, d: day, h=hour, n=minute, s=second + // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] + // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) + // Gregorian start in British calendar (1752/Sep/14 = 2361222) + //output: Julian date + static double w2j(long year, long month, long day, long hour=12, long minute=0, double second=0, long ct=0, long SG=2361222); + + //Julian date to Western date + //Credit4 Gregorian date: http://pmyers.pcug.org.au/General/JulianDates.htm + //Credit4 Julian Calendar: http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html + //input: (jd:julian date, + // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] + // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) + //output: Western date (y=year, m=month, d=day, h=hour, n=minute, s=second) + static void j2w(double jd, long& year, long& month, long& day, long& hour, long& minute, double& second, long ct=0, long SG=2361222); + + // unix time to julian date + static double u2j(time_t ut); + + // julian date to unix time + static time_t j2u(double jd); + + // Compile time string + static std::string compiletime(); + +#ifndef CE_NOS + // get current time in julian date + static double jdnow(); + + // get local time zone offset between local time and UTC in hours (e.g. 8 for UTC +8) + static double ltzoh(); + + // Set local date time of the system + // need super user privileges + static void SetSystemLocalTime(int year, int month, int day,int hour, int minute, int second); + + // set time to now + void Set2Now(); + + // set time zone in hours to the system's local time zone + void SetTimezone();//set to local time zone + + ceDateTime();//default constructor + +#endif //CE_NOS + + // jd to date time string + // input: (jd:julian date, + // fm: format [Optional argument: "%Www %y-%mm-%dd %HH:%nn:%ss %zz"] + // tz : time zone offset in hours (e.g. 8 for GMT +8) + // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] + // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) + // output: date time string according to fm where formatting strings are as follows + // %yyyy : year [0000-9999, e.g. 2018] + // %yy : year [00-99 e.g. 18] + // %y : year [0-9999, e.g. 201] + // %MMM : month [e.g. JAN] + // %Mmm : month [e.g. Jan] + // %mm : month with zero padding [01-12] + // %M : month [e.g. January] + // %m : month [1-12] + // %dd : day with zero padding [01-31] + // %d : day [1-31] + // %HH : hour [00-23] + // %hh : hour [01-12] + // %H : hour [0-23] + // %h : hour [1-12] + // %AA : AM or PM + // %aa : am or pm + // %nn : minute with zero padding [00-59] + // %n : minute [0-59] + // %ss : second [00-59] + // %s : second [0-59] + // %lll : millisecond [000-999] + // %l : millisecond [0-999] + // %WWW : Weekday [e.g. SAT] + // %Www : Weekday [e.g. Sat] + // %W : Weekday [e.g. Saturday] + // %w : Weekday number [0=sat, 1=sun, ..., 6=fri] + // %zz : time zone (e.g. +08, +06:30) + static std::string j2s(double jd, std::string fm="%Www %y-%mm-%dd %HH:%nn:%ss %zz", double tz=0, long ct=0, long SG=2361222); + + // convert date time string to jd + // inputs + // tstr : time string + // accepts following formats + // 1: yyyy-mm-dd hh:nn:ss + // 2: yyyy-mm-dd hh:nn:ss.ttt + // 3: yyyymmddhhnnss + // 4: yyyymmddhhnnssttt + // tz : time zone offset in hours + // [optional argument: 0 - UTC] + // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] + // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) + // output + // jd: julian date + // positive integer: ok + // -1 : error + static double s2j(std::string tstr, double tz=0, long ct=0, long SG=2361222); + + // set time zone in hours for this instance + void SetTimezone(double tz); + + // set time in jd + void SetJD(double jd); + + // set in unix time + void SetUnixTime(time_t ut); + + // set date time for a timezone and a calendar type + void SetDateTime(long year, long month, long day, long hour=12, long minute=0, double second=0, double tz=0, long ct=0, long SG=2361222); + + // set time using a date time string + void SetDateTimeString(std::string tstr, double tz=0, long ct=0, long SG=2361222); + + // set calendar type [0=British (default), 1=Gregorian, 2=Julian] + void SetCT(long ct); + + //------------------------------------------------------------------------- + // set Beginning of Gregorian calendar in JDN [default=2361222] + void SetSG(long sg); + + // Get Date Time string + // input: (fm: format [Optional argument: "%Www %y-%mm-%dd %HH:%nn:%ss %zz"]) + // output: date time string according to fm where formatting strings are as follows + // %yyyy : year [0000-9999, e.g. 2018] + // %yy : year [00-99 e.g. 18] + // %y : year [0-9999, e.g. 201] + // %MMM : month [e.g. JAN] + // %Mmm : month [e.g. Jan] + // %mm : month with zero padding [01-12] + // %M : month [e.g. January] + // %m : month [1-12] + // %dd : day with zero padding [01-31] + // %d : day [1-31] + // %HH : hour [00-23] + // %hh : hour [01-12] + // %H : hour [0-23] + // %h : hour [1-12] + // %AA : AM or PM + // %aa : am or pm + // %nn : minute with zero padding [00-59] + // %n : minute [0-59] + // %ss : second [00-59] + // %s : second [0-59] + // %lll : millisecond [000-999] + // %l : millisecond [0-999] + // %WWW : Weekday [e.g. SAT] + // %Www : Weekday [e.g. Sat] + // %W : Weekday [e.g. Saturday] + // %w : Weekday number [0=sat, 1=sun, ..., 6=fri] + // %zz : time zone (e.g. +08, +06:30) + std::string ToString(std::string fm = "%Www %y-%mm-%dd %HH:%nn:%ss %zz"); + + // filter input string to get digits only + static std::string GetDigits(std::string str); + + // find a string and replace all occurances + static std::string ReplaceAll(std::string str,std::string fstr,std::string rstr); + + double jd(); // julian date + double jdl(); // julian date for this time zone + long jdn(); // julian day number + long jdnl(); // julian day number for this time zone + long y(); // year + long m(); // month + long d(); // day + long h(); // hour [0-23] + long n(); // minute + long s(); // second + long l(); // millisecond + long w(); // weekday [0=sat, 1=sun, ..., 6=fri] + long ut(); // unix time + double tz(); // time zone + long ct(); // calendar type [0=British (default), 1=Gregorian, 2=Julian] + long SG(); // Beginning of Gregorian calendar in JDN [default=2361222] + long mlen(); // length of this month + //------------------------------------------------------------------------- + // find the length of western month + // input: (y=year, m=month [Jan=1, ... , Dec=12], + // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian]) + // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) + // output: (wml = length of the month) + static long wml(long y,long m,long ct=0,long SG=2361222); + //------------------------------------------------------------------------- +}; + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +//------------------------------------------------------------------------- +// Time to Fraction of day starting from 12 noon +// input: (h=hour, n=minute, s=second) output: (d: fraction of day) +inline double ceDateTime::t2d(long h,long n,double s) +{ + return ((double(h)-12)/24.0+double(n)/1440.0+s/86400.0); +} +//------------------------------------------------------------------------- +//Western date to Julian date +//Credit4 Gregorian2JD: http://www.cs.utsa.edu/~cs1063/projects/Spring2011/Project1/jdn-explanation.html +//input: (y: year, m: month, d: day, h=hour, n=minute, s=second + // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] + // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) + // Gregorian start in British calendar (1752/Sep/14 = 2361222) +//output: Julian date +inline double ceDateTime::w2j(long y, long m, long d, long h, long n, double s, long ct, long SG) +{ + long a = long(floor((14 - m) / 12)); y = y + 4800 - a; m = m + (12 * a) - 3; + long jd =long( d + floor((153 * m + 2) / 5) + (365 * y) + floor(y / 4)); + if (ct == 1) jd = long( jd - floor(y / 100) + floor(y / 400) - 32045); + else if (ct == 2) jd = jd - 32083; + else { + jd = long( jd - floor(y / 100) + floor(y / 400) - 32045); + if (jdSG) jd = SG; + } + } + return double(jd)+t2d(h,n,s); +} +//------------------------------------------------------------------------- +//Julian date to Western date +//Credit4 Gregorian date: http://pmyers.pcug.org.au/General/JulianDates.htm +//Credit4 Julian Calendar: http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html +//input: (jd:julian date, + // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] + // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) +//output: Western date (y=year, m=month, d=day, h=hour, n=minute, s=second) +inline void ceDateTime::j2w(double jd,long& year, long& month, long& day, long& hour, long& minute, double& second, long ct, long SG) +{ + long j,y,m,d,h,n; + double jf,s; + if (ct==2 || (ct==0 && (jd13)?(e-13):(e-1); + d=b-f- long(floor(30.6001*double(e))); y=m<3?(c-4715):(c-4716); + } + else{ + j= long(floor(jd+0.5)); jf=jd+0.5-j; j-=1721119; + y=(long)(((double)(4*j-1))/146097); + j=4*j-1-146097*y; + d=(long)(((double)(j))/4); + j=(long)((4*(double)d+3)/1461); + d=4*d+3-1461*j; + d=(long)(((double)d+4)/4); m=(long)((5*(double)d-3)/153); d=5*d-3-153*m; + d=(long)(((double)d+5)/5); y=100*y+j; + if(m<10) {m+=3;} + else {m-=9; y=y+1;} + } + jf*=24; h=(long)(jf); jf=(jf-h)*60; n=(long)(jf); s=((jf-n)*60); + year=y; month=m; day=d; hour=h; minute=n; second=s; +} +//------------------------------------------------------------------------- +// convert unix timestamp to jd +inline double ceDateTime::u2j(time_t ut) +{ + //number of seconds from 1970 Jan 1 00:00:00 (UTC) + return (2440587.5+double(ut)/86400.0);//converte to day(/24h/60min/60sec) and to JD +} +//------------------------------------------------------------------------- +// julian date to unix time +inline time_t ceDateTime::j2u(double jd) +{ + return long(floor((jd-2440587.5)*86400.0+0.5)); +} +//------------------------------------------------------------------------- +// Compile time string +inline std::string ceDateTime::compiletime() +{ + std::string s=__DATE__; + s+=" "; + s+=__TIME__; + //s+=" "; + //s+=__cplusplus; + return s; +} +//------------------------------------------------------------------------- +#ifndef CE_NOS +// get current time in julian date +inline double ceDateTime::jdnow() +{ + //number of seconds from 1970 Jan 1 00:00:00 (UTC) + time_t ut = time(0);//now + double jd=ceDateTime::u2j(ut); + double ms=0;//milliseconds +#ifdef CE_WINDOWS + SYSTEMTIME wt; + GetSystemTime(&wt); + ms=double(wt.wMilliseconds); +#elif defined(CE_LINUX) + timeval time; + gettimeofday(&time,NULL); + ms=double(time.tv_usec)/1000.0; +#endif + jd+=ms/86400000.0; + return jd; +} +//------------------------------------------------------------------------- +// get local time zone offset between local time and UTC in hours (e.g. 8 for GMT +8) +inline double ceDateTime::ltzoh() +{ + double jdu= ceDateTime::jdnow();//utc + //http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html + time_t ut = time(0);//number of seconds from 1970 Jan 1 00:00:00 (UTC) + struct tm * ts=localtime(&ut); + double jdl= ceDateTime::w2j(ts->tm_year+1900,ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); + double stz=jdl-jdu;// local and utc day difference + //round to 1 min quantization + stz=double(floor(stz*1440.0+0.5))/60.0; + return stz; +} +//------------------------------------------------------------------------- +// Set local date time of the system +// need super user privileges +// https://www.linuxquestions.org/questions/programming-9/c-code-to-change-date-time-on-linux-707384/ +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724936(v=vs.85).aspx +inline void ceDateTime::SetSystemLocalTime(int year, int month, int day,int hour, int minute, int second) +{ +#ifdef CE_WINDOWS + //For Windows + SYSTEMTIME lt; + GetLocalTime(<); + lt.wYear=year; + lt.wMonth=month; + lt.wDay=day; + lt.wHour=hour; + lt.wMinute=minute; + lt.wSecond=second; + SetLocalTime(<); +#elif defined(CE_LINUX) + //For POSX + time_t mytime = time(0); + struct tm* tm_ptr = localtime(&mytime); + + if (tm_ptr) + { + tm_ptr->tm_mon = month - 1; + tm_ptr->tm_mday = day; + tm_ptr->tm_year = year - 1900; + + tm_ptr->tm_hour = hour; + tm_ptr->tm_min = minute; + tm_ptr->tm_sec = second; + + const struct timeval tv = {mktime(tm_ptr), 0}; + settimeofday(&tv, 0);//need super user privileges + } +#endif +} + +//------------------------------------------------------------------------- +// set local time zone +inline void ceDateTime::SetTimezone() +{ + this->m_tz = ceDateTime::ltzoh(); +} +//------------------------------------------------------------------------- +// set time to now +inline void ceDateTime::Set2Now() +{ + this->m_jd = ceDateTime::jdnow(); +} +//------------------------------------------------------------------------- +#endif // CE_NOS +inline ceDateTime::ceDateTime() +{ +#ifndef CE_NOS + this->SetTimezone(); + this->Set2Now(); +#else + this->SetTimezone(0); + this->SetUnixTime(0); +#endif // CE_NOS + this->m_ct=0; + this->m_SG=2361222; +} +//------------------------------------------------------------------------- +// jd to date time string +// input: (jd:julian date, +// fm: format [Optional argument: "%Www %y-%mm-%dd %HH:%nn:%ss %zz"] +// tz : time zone offset in hours (e.g. 8 for GMT +8) +// ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] +// SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) +// output: date time string according to fm where formatting strings are as follows +// %yyyy : year [0000-9999, e.g. 2018] +// %yy : year [00-99 e.g. 18] +// %y : year [0-9999, e.g. 201] +// %MMM : month [e.g. JAN] +// %Mmm : month [e.g. Jan] +// %mm : month with zero padding [01-12] +// %M : month [e.g. January] +// %m : month [1-12] +// %dd : day with zero padding [01-31] +// %d : day [1-31] +// %HH : hour [00-23] +// %hh : hour [01-12] +// %H : hour [0-23] +// %h : hour [1-12] +// %AA : AM or PM +// %aa : am or pm +// %nn : minute with zero padding [00-59] +// %n : minute [0-59] +// %ss : second [00-59] +// %s : second [0-59] +// %lll : millisecond [000-999] +// %l : millisecond [0-999] +// %WWW : Weekday [e.g. SAT] +// %Www : Weekday [e.g. Sat] +// %W : Weekday [e.g. Saturday] +// %w : Weekday number [0=sat, 1=sun, ..., 6=fri] +// %zz : time zone (e.g. +08, +06:30) +inline std::string ceDateTime::j2s(double jd, std::string fm, double tz, long ct, long SG) +{ + long year,month,day,hour,minute; + double second; + jd+=tz/24.0; + ceDateTime::j2w(jd,year,month,day,hour,minute,second,ct,SG); + long s= long(floor(second));//shold not take round to make sure s<60 + long l= long(floor((second-double(s))*1000)); // not rounding + long jdn= long(floor(jd+0.5)); + long wd=(jdn+2)%7;//week day [0=sat, 1=sun, ..., 6=fri] + long h = hour % 12; + if (h == 0) h = 12; + std::string W[]={"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"}; + std::string M[] = {"January","February","March","April","May","June","July","August","September","October","November","December"}; + + // replace format string with values + std::string fstr,rstr; + //-------------------------------------------------------- + fstr = "%yyyy"; + rstr = std::string(4, '0') + std::to_string(year); + rstr = rstr.substr(rstr.length() - 4); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%yy"; + long y = year % 100; + rstr = std::string(2, '0') + std::to_string(y); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%y"; + rstr = std::to_string(year); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%MMM"; + rstr = M[month-1]; + std::transform(rstr.begin(), rstr.end(), rstr.begin(), ::toupper); + rstr = rstr.substr(0,3); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%Mmm"; + rstr = M[month - 1]; + rstr = rstr.substr(0, 3); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%mm"; + rstr = std::string(2, '0') + std::to_string(month); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%M"; + rstr = M[month - 1]; + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%m"; + rstr = std::to_string(month); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%dd"; + rstr = std::string(2, '0') + std::to_string(day); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%d"; + rstr = std::to_string(day); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%HH"; + rstr = std::string(2, '0') + std::to_string(hour); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%hh"; + rstr = std::string(2, '0') + std::to_string(h); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%H"; + rstr = std::to_string(hour); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%h"; + rstr = std::to_string(h); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%AA"; + rstr = hour<12?"AM":"PM"; + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%aa"; + rstr = hour<12 ? "am" : "pm"; + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%nn"; + rstr = std::string(2, '0') + std::to_string(minute); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%n"; + rstr = std::to_string(minute); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%ss"; + rstr = std::string(2, '0') + std::to_string(s); + rstr = rstr.substr(rstr.length() - 2); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%s"; + rstr = std::to_string(s); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%lll"; + rstr = std::string(3, '0') + std::to_string(l); + rstr = rstr.substr(rstr.length() - 3); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%l"; + rstr = std::to_string(l); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%WWW"; + rstr = W[wd]; + std::transform(rstr.begin(), rstr.end(), rstr.begin(), ::toupper); + rstr = rstr.substr(0, 3); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%Www"; + rstr = W[wd]; + rstr = rstr.substr(0, 3); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%W"; + rstr = W[wd]; + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%w"; + rstr = std::to_string(wd); + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + fstr = "%zz"; + std::string tzs = tz < 0 ? "-" : "+"; + std::string tzh = std::string(2, '0') + std::to_string(long(floor(tz))); + tzh = tzh.substr(tzh.length() - 2); + rstr = tzs+tzh; + double tzf = tz - floor(tz); + if (tzf > 0) { + tzh = std::string(2, '0') + std::to_string(long(floor(tzf*60.0+0.5))); + tzh = tzh.substr(tzh.length() - 2); + rstr += ":"+tzh; + } + fm = ceDateTime::ReplaceAll(fm, fstr, rstr); + //-------------------------------------------------------- + return fm; +} +//------------------------------------------------------------------------- +// convert date time string to jd +// inputs +// tstr : time string +// accepts following formats +// 1: yyyy-mm-dd hh:nn:ss +// 2: yyyy-mm-dd hh:nn:ss.ttt +// 3: yyyymmddhhnnss +// 4: yyyymmddhhnnssttt +// 5: yyyy-mm-dd (default time is 12:00:00) +// 6: yyyymmdd (default time is 12:00:00) +// tz : time zone offset in hours +// [optional argument: 0 - UTC] +// ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] +// SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) +// output +// jd: julian date +// positive integer: ok +// -1 : error +inline double ceDateTime::s2j(std::string tstr, double tz, long ct, long SG) +{ + std::string str,pstr; + long y=0,m=0,d=0,h=12,n=0; + double jd=-1; + double s=0,ls=0; + str= ceDateTime::GetDigits(tstr); + if(str.length() == 8 || str.length()==14 || str.length()==17){ + pstr=str.substr(0,4); y=stol(pstr); //get year + pstr=str.substr(4,2); m=stol(pstr); //get month + pstr=str.substr(6,2); d=stol(pstr); //get day + if (str.length() == 14 || str.length() == 17) { + pstr = str.substr(8, 2); h = stol(pstr); //get hour + pstr = str.substr(10, 2); n = stol(pstr); //get minute + pstr = str.substr(12, 2); s = double(stol(pstr)); //get second + if (str.length() == 17) { + pstr = str.substr(14, 3); ls = double(stol(pstr)); //get millisecond + s += ls / 1000.0; + } + } + jd= ceDateTime::w2j(y,m,d,h,n,s,ct,SG)-tz/24.0; // convert to UTC + } + return jd; +} +//------------------------------------------------------------------------- +// set time zone in hours for this instance +inline void ceDateTime::SetTimezone(double tz)//set time zone +{ + if(tz<=14 || tz>=(-12)){ this->m_tz=tz; } +} +//------------------------------------------------------------------------- +// set time in jd +inline void ceDateTime::SetJD(double jd) +{ + this->m_jd=jd; +} +//------------------------------------------------------------------------- +// set in unix time +inline void ceDateTime::SetUnixTime(time_t ut) +{ + this->m_jd= ceDateTime::u2j(ut); +} +//------------------------------------------------------------------------- +// set date time for a timezone and a calendar type +inline void ceDateTime::SetDateTime(long year, long month, long day, long hour, long minute, double second, double tz, long ct, long SG) +{ + this->m_jd= ceDateTime::w2j(year,month,day,hour,minute,second,ct,SG)-tz/24.0; +} +//------------------------------------------------------------------------- +// set calendar type [0=British (default), 1=Gregorian, 2=Julian] +inline void ceDateTime::SetCT(long ct) +{ + this->m_ct=ct%3; +} +//------------------------------------------------------------------------- +// set Beginning of Gregorian calendar in JDN [default=2361222] +inline void ceDateTime::SetSG(long sg) +{ + this->m_SG=sg; +} +//------------------------------------------------------------------------- +// set time using a date time string +// inputs +// tstr : time string +// accepts following formats +// 1: yyyy-mm-dd hh:nn:ss +// 2: yyyy-mm-dd hh:nn:ss.ttt +// 3: yyyymmddhhnnss +// 4: yyyymmddhhnnssttt +// tz : time zone offset in hours +// [optional argument: 0 - UTC] +// ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] +// SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) +inline void ceDateTime::SetDateTimeString(std::string tstr, double tz, long ct, long SG) +{ + double jd= ceDateTime::s2j(tstr, tz, ct, SG); + if (jd >= 0) this->m_jd = jd; +} +//------------------------------------------------------------------------- +// Get Date Time string +// input: (fm: format [Optional argument: "%Www %y-%mm-%dd %HH:%nn:%ss %zz"]) +// output: date time string according to fm where formatting strings are as follows +// %yyyy : year [0000-9999, e.g. 2018] +// %yy : year [00-99 e.g. 18] +// %y : year [0-9999, e.g. 201] +// %MMM : month [e.g. JAN] +// %Mmm : month [e.g. Jan] +// %mm : month with zero padding [01-12] +// %M : month [e.g. January] +// %m : month [1-12] +// %dd : day with zero padding [01-31] +// %d : day [1-31] +// %HH : hour [00-23] +// %hh : hour [01-12] +// %H : hour [0-23] +// %h : hour [1-12] +// %AA : AM or PM +// %aa : am or pm +// %nn : minute with zero padding [00-59] +// %n : minute [0-59] +// %ss : second [00-59] +// %s : second [0-59] +// %lll : millisecond [000-999] +// %l : millisecond [0-999] +// %WWW : Weekday [e.g. SAT] +// %Www : Weekday [e.g. Sat] +// %W : Weekday [e.g. Saturday] +// %w : Weekday number [0=sat, 1=sun, ..., 6=fri] +// %zz : time zone (e.g. +08, +06:30) +inline std::string ceDateTime::ToString(std::string fm) +{ + return ceDateTime::j2s(this->m_jd, fm, this->m_tz,this->m_ct,this->m_SG); +} +//------------------------------------------------------------------------- +// filter input string to get digits only +inline std::string ceDateTime::GetDigits(std::string str) +{ + std::string ostr = ""; + size_t len = str.length(); + if (len>0) { + for (size_t i = 0; i= '0' && str[i] <= '9') ostr += str[i]; + } + return ostr; +} +//------------------------------------------------------------------------- +// find a string and replace all occurances +inline std::string ceDateTime::ReplaceAll(std::string str, std::string fstr, std::string rstr) +{ + size_t i = 0; + while (true) { + i = str.find(fstr, i); + if (i == std::string::npos) break; + str.replace(i, fstr.length(), rstr); + i += rstr.length(); + } + return str; +} +//------------------------------------------------------------------------- +inline double ceDateTime::jd() { return this->m_jd; } +inline double ceDateTime::jdl() { return (this->m_jd+this->m_tz/24.0); } // jd for this time zone +inline long ceDateTime::jdn() { return long(round(this->m_jd)); } +inline long ceDateTime::jdnl() { return (long)round(this->m_jd+this->m_tz/24.0); } // jdn for this time zone +inline long ceDateTime::y() { + long y,m,d,h,n; double s; + ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); + return y; +} // year + +inline long ceDateTime::m() { + long y,m,d,h,n; double s; + ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); + return m; +} // month + +inline long ceDateTime::d() { + long y,m,d,h,n; double s; + ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); + return d; +} // day +inline long ceDateTime::h() { + long y,m,d,h,n; double s; + ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); + return h; +} // hour [0-23] + +inline long ceDateTime::n() { + long y,m,d,h,n; double s; + ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); + return n; +} // minute + +inline long ceDateTime::s() { + long y,m,d,h,n; double s; + ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); + long si=(long)floor(s); //shold not take round to make sure s<60 + return si; +} // second + +inline long ceDateTime::l() { + long y,m,d,h,n; double s; + ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); + long si=(long)floor(s); //shold not take round to make sure s<60 + long l= long(floor((s-double(si))*1000)); // not rounding + return l; +} // millisecond + +inline long ceDateTime::w() { return (this->jdnl()+2)%7;} // weekday [0=sat, 1=sun, ..., 6=fri] + +inline long ceDateTime::ut() { return ceDateTime::j2u(this->m_jd);} // unix time +inline double ceDateTime::tz() { return this->m_tz; } // time zone in hour +inline long ceDateTime::ct(){ return this->m_ct; } // calendar type [0=British (default), 1=Gregorian, 2=Julian] +inline long ceDateTime::SG(){ return this->m_SG; } // Beginning of Gregorian calendar in JDN [default=2361222] +inline long ceDateTime::mlen() // length of this month + { return ceDateTime::wml(this->y(),this->m(),m_ct,m_SG); } +//------------------------------------------------------------------------- +// find the length of western month +// input: (y=year, m=month [Jan=1, ... , Dec=12], +// ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian]) +// SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) +// output: (wml = length of the month) +inline long ceDateTime::wml(long y,long m,long ct,long SG) { + long j1,j2; long m2=m+1; long y2=y; + if(m2>12){y2++; m2%=12;} + j1=long(ceDateTime::w2j(y,m,1,12,0,0,ct,SG)); + j2=long(ceDateTime::w2j(y2,m2,1,12,0,0,ct,SG)); + return (j2-j1); +} +//------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce + +#endif // CEDATETIME_H diff --git a/include/ce/cetcpsvr.h b/include/ce/cetcpsvr.h new file mode 100644 index 0000000..50438d8 --- /dev/null +++ b/include/ce/cetcpsvr.h @@ -0,0 +1,510 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: cetcpsvr.h +// Description: TCP server module +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html +///////////////////////////////////////////////////////////////////////////// +// Requires: wxWidgets +///////////////////////////////////////////////////////////////////////////// + +#ifndef CETCPSVR_H +#define CETCPSVR_H + #ifndef CE_MACROS_H + #define CE_MACROS_H + #define CE_WX 1 // include WX + #define CE_DBG_PRINT 0 // print dbg mes + + #if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif + #elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif + #else + #ifndef CE_NOS + #define CE_NOS + #endif + #endif + + #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif + #elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif + #else + #ifndef CE_NARCH + #define CE_NARCH + #endif + #endif + + #endif // CE_MACROS_H + + +#if CE_WX==1 +#include +#include +#include +#include +#include +#include +#include +#include "wx/wx.h" +#include "wx/socket.h" +// this example is currently written to use only IP or only IPv4 sockets, it +// should be extended to allow using either in the future +//#if wxUSE_IPV6 +//typedef wxIPV6address IPaddress; +//#else +typedef wxIPV4address IPaddress; +//#endif +#define CE_DEFAULE_TCPSVR_RX_BUF_SIZE 32768 + +namespace ce { +class ceTcpServer : public wxEvtHandler { +public: + // port = listening port number, max number of sockets + // event will raise with id range = socketid - (socketid+ns-1) + ceTcpServer(wxEvtHandler* eh, int serverid, int socketid, int port, int ns); + + ~ceTcpServer(); + + bool Open(); // return true = success, false = error + bool Close(); + + // Transmit (write) + // to all connected sockets + int Tx(std::vector bv); // return 0 = success, 1 = error + + // to the socket with id + int Tx(int id, std::vector bv); // return 0 = success, 1 = error + + // to all except the socket with id + int TxExcept(int id, std::vector bv); // return 0 = success, 1 = error + + // Receive (read) will raise receive event + + void SetBufSize(int n); + int GetBufSize(); + +private: + void OnServerEvent(wxSocketEvent& event); + void OnSocketEvent(wxSocketEvent& event); + wxEvtHandler* _eh; + int _socket_id; + int _server_id; + int _port; + bool _listening{false}; + int _ns{ 0 }; + wxSocketServer* _socketServer{}; + std::deque> _socketBaseQ; + void PrintLog(std::string str); + int _bufSize{ CE_DEFAULE_TCPSVR_RX_BUF_SIZE }; + int GetFreeSocketId(); +}; + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +inline void ceTcpServer::PrintLog(std::string str) +{ +#if CE_DBG_PRINT==1 + std::cout << str << std::endl; +#endif +} + +// port = listening port number, max number of sockets +// event will raise with id range = socketid - (socketid+ns-1) +inline ceTcpServer::ceTcpServer(wxEvtHandler* eh, int serverid, int socketid, int port, int ns) : + _eh(eh), _server_id(serverid), _socket_id(socketid), _port(port), _ns(ns) +{ + Connect(serverid, wxEVT_SOCKET, wxSocketEventHandler(ceTcpServer::OnServerEvent)); + for (int i = 0; i < ns; i++) { + Connect(socketid + i, wxEVT_SOCKET, wxSocketEventHandler(ceTcpServer::OnSocketEvent)); + } +} + +inline ceTcpServer::~ceTcpServer() +{ + this->Close(); + for (int i = 0; i < _ns; i++) { + Disconnect(_socket_id + i, wxEVT_SOCKET); + } + Disconnect(_server_id, wxEVT_SOCKET); +} + +inline bool ceTcpServer::Open() +{ + if (this->_listening) { return true; } // already listening + + // Create the address - defaults to localhost:0 initially + IPaddress addr; + addr.AnyAddress(); + addr.Service(this->_port); + PrintLog("Creating server at " + addr.IPAddress().ToStdString() + ":" + std::to_string(addr.Service())); + + // Create the socket + this->_socketServer = new wxSocketServer(addr); + + // We use IsOk() here to see if the server is really listening + if (!this->_socketServer->IsOk()) { + perror("ceTcpServer could not listen at the specified port"); + return false; + } + + IPaddress addrReal; + if (!this->_socketServer->GetLocal(addrReal)) { + perror("ceTcpServer couldn't get the address it bounds to"); + } + else { + PrintLog("Server listening at " + addrReal.IPAddress().ToStdString() + ":" + std::to_string(addrReal.Service())); + } + + // Setup the event handler and subscribe to connection events + this->_socketServer->SetEventHandler(*this, _server_id); + this->_socketServer->SetNotify(wxSOCKET_CONNECTION_FLAG); + this->_socketServer->Notify(true); + this->_listening = true; + return true; +} + +inline bool ceTcpServer::Close() +{ + if (!this->_listening) { return true; } // already closed + for (auto& a : _socketBaseQ) { + if (a.second != nullptr) { + a.second->Destroy(); + a.second = nullptr; + } + } + _socketBaseQ.clear(); + + if (_socketServer->IsClosed()) { + return true; + } + _socketServer->Discard(); + return _socketServer->Destroy(); +} + +inline int ceTcpServer::GetFreeSocketId() +{ + int id = _socket_id; + for (int i = 0; i < _ns; i++) { + bool f = true; + for (const auto& a : _socketBaseQ) { + if (a.first == (id+i)) { + f = false; + break; + } + } + if (f) { + id += i; + break; + } + } + // will happen to give base id, if all are used + PrintLog("Found free socket id: " + std::to_string(id)); + return id; +} + +inline void ceTcpServer::OnServerEvent(wxSocketEvent& event) +{ + PrintLog("OnServerEvent"); + wxSocketBase* sockBase; + IPaddress addr; + + switch (event.GetSocketEvent()) + { + case wxSOCKET_CONNECTION: + PrintLog("Connection event"); + break; + default: + perror("Unexpected event"); + return; // return if unknown + break; + } + + // Accept new connection if there is one in the pending + // connections queue, else exit. We use Accept(false) for + // non-blocking accept (although if we got here, there + // should ALWAYS be a pending connection). + + sockBase = _socketServer->Accept(false); + + if (sockBase) + { + if (!sockBase->GetPeer(addr)) + { + PrintLog("New connection from unknown client accepted"); + } + else + { + PrintLog("New client connection from " + addr.IPAddress().ToStdString() + ":" + std::to_string(addr.Service())); + } + } + else + { + PrintLog("Couldn't accept a new connection"); + return; + } + + if (this->_socketBaseQ.size() >= _ns) { + // first in first out + auto a = this->_socketBaseQ.front(); + wxSocketBase* sockBase = a.second; + if (sockBase != nullptr) { + sockBase->Destroy(); + } + PrintLog("Deleting front socket id: " + std::to_string(a.first)); + this->_socketBaseQ.pop_front(); + } + + int id = this->GetFreeSocketId(); + sockBase->SetEventHandler(*this, id); + sockBase->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG); + sockBase->Notify(true); + this->_socketBaseQ.push_back(std::make_pair(id,sockBase)); + PrintLog(std::to_string(_socketBaseQ.size()) + " clients connected"); + + std::string ip = addr.IPAddress().ToStdString(); + int port = addr.Service(); + + // 1st char: flag 1=new con, 0 = lost con, + // 2nd char: number of con + // 3rd char: relative socket id + wxString ws(ip); + wxThreadEvent eventsvr(wxEVT_THREAD, _server_id); + std::vector bv{ 1,(char)_socketBaseQ.size(), (char)(id-_socket_id)}; + eventsvr.SetPayload>(bv); + eventsvr.SetString(ws); + eventsvr.SetInt(port); + wxQueueEvent(_eh, eventsvr.Clone()); +} + +inline void ceTcpServer::OnSocketEvent(wxSocketEvent& event) +{ + char* buf = new char[_bufSize];// dynamically allocate buf + + int id = event.GetId(); + PrintLog("OnSocketEvent id: "+std::to_string(id)); + wxSocketBase* sockBase = event.GetSocket(); + IPaddress addr; + std::vector vc; + + + if (!sockBase->GetPeer(addr)) + { + PrintLog("Socket event from unknown client"); + } + else + { + PrintLog("Socket event from " + addr.IPAddress().ToStdString() + ":" + std::to_string(addr.Service())); + } + std::string ip = addr.IPAddress().ToStdString(); + int port = addr.Service(); + wxString ws(ip); + + switch (event.GetSocketEvent()) + { + case wxSOCKET_INPUT: + { + PrintLog("wxSOCKET_INPUT"); + // We disable input events, so that the test doesn't trigger + // wxSocketEvent again. + sockBase->SetNotify(wxSOCKET_LOST_FLAG); + + // Receive data from socket and send it back. We will first + // get a byte with the buffer size, so we can specify the + // exact size and use the wxSOCKET_WAITALL flag. Also, we + // disabled input events so we won't have unwanted reentrance. + // This way we can avoid the infamous wxSOCKET_BLOCK flag. + // sockBase->SetFlags(wxSOCKET_WAITALL); + + // Read the message + size_t lenRd = sockBase->Read(buf, _bufSize).LastCount(); + if (!lenRd) { + PrintLog("Failed to read message"); + return; + } + else { + PrintLog("Read " + std::to_string(lenRd) + " bytes"); + } + // Enable input events again. + sockBase->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG); + + // string str(buf,lenRd); + // PrintLog("Rx: " + str); + + vc.assign(buf, buf + lenRd); + wxThreadEvent eventskt(wxEVT_THREAD, id); + eventskt.SetPayload>(vc); + eventskt.SetString(ws); + eventskt.SetInt(port); + wxQueueEvent(_eh, eventskt.Clone()); + } + break; + case wxSOCKET_LOST: + { + PrintLog("Lost socket id: " + std::to_string(id)); + auto it = std::find_if(_socketBaseQ.begin(), _socketBaseQ.end(), + [id](const std::pair& element) { + return element.first == id; + }); + + // Check if the element was found + if (it != _socketBaseQ.end()) { + PrintLog("Socket id removing from the list"); + // destroy at the end of method + _socketBaseQ.erase(it); + } + else { + PrintLog("Socket id not found in the list"); + } + + std::vector bv{ 0,(char)this->_socketBaseQ.size(), char(id - _socket_id)}; + // 1st char: flag 1=new con, 0 = lost con, + // 2nd char: number of con + // 3rd char: relative socket id + + wxThreadEvent eventsvr(wxEVT_THREAD, _server_id); + eventsvr.SetPayload>(bv); + eventsvr.SetString(ws); + eventsvr.SetInt(port); + wxQueueEvent(_eh, eventsvr.Clone()); + // Destroy() should be used instead of delete wherever possible, + // due to the fact that wxSocket uses 'delayed events' (see the + // documentation for wxPostEvent) and we don't want an event to + // arrive to the event handler (the frame, here) after the socket + // has been deleted. Also, we might be doing some other thing with + // the socket at the same time; for example, we might be in the + // middle of a test or something. Destroy() takes care of all + // this for us. + + PrintLog("Deleting socket"); + sockBase->Destroy(); + PrintLog("Remaining clients: " + std::to_string(this->_socketBaseQ.size())); + } + break; + default: + perror("Unexpected event"); + break; + } + delete[] buf; // destroy buf +} + +inline int ceTcpServer::Tx(std::vector bv) +{ + int r = 0; + size_t txn = 0; + wxSocketBase* socketBase; + for (auto& a : _socketBaseQ) + { + socketBase = a.second; + if (socketBase != nullptr) { + if (socketBase->IsOk() && socketBase->IsConnected()) { + // Write to pointed client + txn = bv.size(); + size_t n = socketBase->Write(bv.data(), txn).LastCount(); + if (n != txn) { + perror("ceTcpClient write error"); + r = 1; + } + else { + // PrintLog("Tx: " + ceMisc::cvec2hex(bv)); + } + } + else { + r = 1; + } + } + } + return r; +} + +inline int ceTcpServer::Tx(int id, std::vector bv) +{ + int r = 0; + size_t txn = 0; + wxSocketBase* socketBase; + auto it = std::find_if(_socketBaseQ.begin(), _socketBaseQ.end(), + [id](const std::pair& element) { + return element.first == id; + }); + + // Check if the element was found + if (it != _socketBaseQ.end()) { + socketBase = it->second; + if (socketBase != nullptr) { + if (socketBase->IsOk() && socketBase->IsConnected()) { + // Write to pointed client + txn = bv.size(); + size_t n = socketBase->Write(bv.data(), txn).LastCount(); + if (n != txn) { + perror("ceTcpClient write error"); + r = 1; + } + else { + // PrintLog("Tx: " + ceMisc::cvec2hex(bv)); + } + } + else { + r = 1; + } + } + } + else { + PrintLog("Socket id not found in the list"); + } + return r; +} + +inline int ceTcpServer::TxExcept(int id, std::vector bv) +{ + int r = 0; + size_t txn = 0; + wxSocketBase* socketBase; + for (auto& a : _socketBaseQ) + { + if (a.first != id) { + socketBase = a.second; + if (socketBase != nullptr) { + if (socketBase->IsOk() && socketBase->IsConnected()) { + // Write to pointed client + txn = bv.size(); + size_t n = socketBase->Write(bv.data(), txn).LastCount(); + if (n != txn) { + perror("ceTcpClient write error"); + r = 1; + } + else { + // PrintLog("Tx: " + ceMisc::cvec2hex(bv)); + } + } + else { + r = 1; + } + } + } + } + return r; +} + +inline void ceTcpServer::SetBufSize(int n) +{ + this->_bufSize = n; +} + +inline int ceTcpServer::GetBufSize() +{ + return _bufSize; +} + +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce +#endif // CE_WX +#endif // CETCPSVR_H diff --git a/src/ceConfig.cpp b/src/ceConfig.cpp deleted file mode 100644 index 38d11ba..0000000 --- a/src/ceConfig.cpp +++ /dev/null @@ -1,110 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceConfig.cpp -// Description: Configuration module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#include "ce/ceConfig.h" -using namespace std; - -namespace ce { -ceConfig::ceConfig() : m_path(CONF_PATH) -{ - -} - -ceConfig::ceConfig(string path) : m_path(path) -{ - -} - -ceConfig::~ceConfig() -{ - -} - -string ceConfig::ReadFile(string path) -{ - string sstr = "", tstr = ""; - ifstream mys; - try { - mys.open(path.c_str()); - if (mys.is_open()) { - while (getline(mys, tstr)) { - sstr += tstr; - } - mys.close(); - } - } - catch (...) { - perror("Error in reading json file\n"); - } - return sstr; -} - -int ceConfig::WriteFile(string path, string str) -{ - ofstream wfile; - int r = -1; - try { - wfile.open(path.c_str()); - if (wfile.is_open()) { - wfile << str; - r = 0; - } - wfile.close(); - } - catch (...) { - perror("Error in json file writing\n"); - } - return r; -} - -#if CE_JSON==1 -Json::Value ceConfig::GetJson() -{ - return ReadJson(this->m_path); -} - -Json::Value ceConfig::ReadJson(std::string path) -{ - string document = ceConfig::ReadFile(path); - return ceConfig::GetJson(document); -} - -Json::Value ceConfig::GetJson(std::string jstr) -{ - stringstream ss; - Json::CharReaderBuilder reader; - Json::Value obj; - string errs; - ss.str(jstr); - if (Json::parseFromStream(reader, ss, &obj, &errs)) { - //printf("Parsing json string OK\n"); - } - else { - perror("Error in json parsing\n"); - } - return obj; -} - -int ceConfig::WriteJson(Json::Value obj, std::string path) -{ - string str = ceConfig::ToString(obj); - return ceConfig::WriteFile(path,str); -} - -std::string ceConfig::ToString(Json::Value obj) -{ - stringstream ss; - ss << obj; - return ss.str(); -} - -int ceConfig::SaveJson(Json::Value obj) -{ - return ceConfig::WriteJson(obj, this->m_path); -} -#endif -} // namespace ce - diff --git a/src/ceMmDateTime.cpp b/src/ceMmDateTime.cpp deleted file mode 100644 index ad7fd85..0000000 --- a/src/ceMmDateTime.cpp +++ /dev/null @@ -1,870 +0,0 @@ -// File: ceMmDateTime.cpp -// Description: Modern Myanmar Calendrical Calculations -// WebSite: https://yan9a.github.io/mcal/ -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye -// Doc: http://cool-emerald.blogspot.com/2013/06/algorithm-program-and-calculation-of.html -//------------------------------------------------------------------------- -#include"ce/ceMmDateTime.h" -#include - -using namespace std; - -namespace ce { -//------------------------------------------------------------------------- -// default constructor -ceMmDateTime::ceMmDateTime():ceDateTime() -{ - -} -//------------------------------------------------------------------------- -// Get Myanmar year constants depending on era -// Thanks to Myo Zarny and Wunna Ko for earlier Myanmar years data -// input: my -myanmar year -// output: -// EI = Myanmar calendar era id [1-3] : calculations methods/constants depends on era -// WO = watat offset to compensate -// NM = number of months to find excess days -// EW = exception in watat year -void ceMmDateTime::GetMyConst(long my, double& EI, double& WO, double& NM, long& EW) -{ - EW = 0; long (*fme)[2]; long* wte; long i=-1,uf,uw; - // The third era (the era after Independence 1312 ME and after) - if (my >= 1312) { - EI = 3; WO = -0.5; NM = 8; - long fme3[][2] = { {1377, 1} }; - long wte3[] = { 1344, 1345 }; - fme = fme3; wte = wte3; - uf=long(sizeof(fme3)/sizeof(fme3[0])); - uw=long(sizeof(wte3)/sizeof(wte3[0])); - } - // The second era (the era under British colony: 1217 ME - 1311 ME) - else if (my >= 1217) { - EI = 2; WO = -1; NM = 4; - long fme2[][2] = { {1234, 1},{1261, -1} }; - long wte2[] = { 1263, 1264 }; - fme = fme2; wte = wte2; - uf=long(sizeof(fme2)/sizeof(fme2[0])); - uw=long(sizeof(wte2)/sizeof(wte2[0])); - } - // The first era (the era of Myanmar kings: ME1216 and before) - // Thandeikta (ME 1100 - 1216) - else if (my >= 1100) { - EI = 1.3; WO = -0.85; NM = -1; - long fme13[][2] = {{1120, 1}, {1126, -1}, {1150, 1}, {1172, -1}, {1207, 1}}; - long wte13[] = {1201, 1202}; - fme = fme13; wte = wte13; - uf=long(sizeof(fme13)/sizeof(fme13[0])); - uw=long(sizeof(wte13)/sizeof(wte13[0])); - } - // Makaranta system 2 (ME 798 - 1099) - else if (my >= 798) { - EI = 1.2; WO = -1.1; NM = -1; - long fme12[][2] = {{813, -1}, {849, -1}, {851, -1}, {854, -1}, {927, -1}, - {933, -1}, {936, -1}, {938, -1}, {949, -1}, {952, -1}, {963, -1}, {968, -1}, {1039, -1}}; - long wte12[] = {-9999}; - fme = fme12; wte = wte12; - uf=long(sizeof(fme12)/sizeof(fme12[0])); - uw=long(sizeof(wte12)/sizeof(wte12[0])); - } - // Makaranta system 1 (ME 0 - 797) - else { - EI = 1.1; WO = -1.1; NM = -1; - long fme11[][2] = {{205, 1}, {246, 1}, {471, 1}, {572, -1}, {651, 1}, - {653, 2}, {656, 1}, {672, 1}, {729, 1}, {767, -1}}; - long wte11[] = {-9999}; - fme = fme11; wte = wte11; - uf=long(sizeof(fme11)/sizeof(fme11[0])); - uw=long(sizeof(wte11)/sizeof(wte11[0])); - } - i = ceMmDateTime::bSearch2(my, fme,uf); if (i >= 0) WO += fme[i][1]; // full moon day offset exceptions - i = ceMmDateTime::bSearch1(my, wte,uw); if (i >= 0) EW = 1; //correct watat exceptions -} -//---------------------------------------------------------------------------- -// Search first dimension in a 2D array -// input: (k=key,A=array,u=size) -// output: (i=index) -long ceMmDateTime::bSearch2(long k,long (*A)[2], long u) { - long i = 0; long l = 0; u--; - while(u>=l) { - i=long(floor((l+u)/2)); - if (A[i][0]>k) u=i-1; - else if (A[i][0]=l) { - i=long(floor((l+u)/2)); - if (A[i]>k) u=i-1; - else if (A[i]= 2) {//if 2nd era or later find watat based on excess days - TW=LM-(SY/12-LM)*NM; - if(ed >= TW) watat=1; - } - else {//if 1st era,find watat by 19 years metonic cycle - //Myanmar year is divided by 19 and there is intercalary month - //if the remainder is 2,5,7,10,13,15,18 - //https://github.com/kanasimi/CeJS/blob/master/data/date/calendar.js#L2330 - watat=(my*7+2)%19; if (watat < 0) watat+=19; - watat=long(floor(watat/12)); - } - watat^=EW;//correct watat exceptions -} -//------------------------------------------------------------------------- -// Check Myanmar Year -// input: (my -myanmar year) -// output: ( myt :year type [0=common, 1=little watat, 2=big watat], -// tg1 : the 1st day of Tagu as jdn_mm (Julian Day Number for MMT) -// fm : full moon day of [2nd] Waso as Julain Day Number -// werr: watat error [0=ok, 1= error]) -// dependency: cal_watat(my) -void ceMmDateTime::cal_my(long my, long& myt, long& tg1, long& fm, long& werr) { - long yd = 0, nd = 0, y1watat, y1fm, y2watat, y2fm; werr = 0; - ceMmDateTime::cal_watat(my,y2watat,y2fm); myt = y2watat; - do { yd++; ceMmDateTime::cal_watat(my - yd,y1watat,y1fm); } while (y1watat == 0 && yd < 3); - if (myt) { - nd = (y2fm - y1fm) % 354; myt = long(floor(nd / 31)+ 1); - fm = y2fm; if (nd != 30 && nd != 31) { werr = 1; } - } - else fm = y1fm + 354 * yd; - tg1 = y1fm + 354 * yd - 102; -} -//------------------------------------------------------------------------- -// Julian day number to Myanmar date -// input: (jdn -julian day number) -// output: ( - // myt =year type [0=common, 1=little watat, 2=big watat], - // my = year, - // mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, - // Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, - // Tabaung=12, Late Tagu=13, Late Kason=14 ], - // md = day of the month [1 to 30]) -// dependency: cal_my(my) -void ceMmDateTime::j2m(double jd, long& myt, long& my, long& mm, long& md) { - long jdn=long(round(jd));//convert jdn to integer - double SY=1577917828.0/4320000.0; //solar year (365.2587565) - double MO=1954168.050623; //beginning of 0 ME - long dd,myl,mmt,a,b,c,e,f; - long tg1,fm,werr; - my=long(floor((jdn-0.5-MO)/SY));//Myanmar year - ceMmDateTime::cal_my(my,myt,tg1,fm,werr);//check year - dd=jdn-tg1+1;//day count - b=long(floor(myt/2)); c=long(floor(1/(myt+1))); //big wa and common yr - myl=354+(1-c)*30+b;//year length - mmt=long(floor((dd-1)/myl));//month type: late =1 or early = 0 - dd-=mmt*myl; a=long(floor((dd+423)/512)); //adjust day count and threshold - mm=long(floor((dd-b*a+c*a*30+29.26)/29.544));//month - e=long(floor((mm+12)/16)); f=long(floor((mm+11)/16)); - md=dd-long(floor(29.544*mm-29.26))-b*e+c*f*30;//day - mm+=f*3-e*4+12*mmt; // adjust month numbers for late months -} -//------------------------------------------------------------------------- -// Get moon phase from day of the month, month, and year type. -// input: ( -// md= day of the month [1-30], -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// myt = year type [0=common, 1=little watat, 2=big watat]) -// output: (mp =moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon]) -long ceMmDateTime::cal_mp(long md,long mm,long myt) { - long mml=ceMmDateTime::cal_mml(mm,myt); - return long(floor((md+1)/16)+floor(md/16)+floor(md/mml)); -} -//------------------------------------------------------------------------- -// Get length of month from month, and year type. -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// myt = year type [0=common, 1=little watat, 2=big watat]) -// output: (mml = length of the month [29 or 30 days]) -long ceMmDateTime::cal_mml(long mm,long myt) { - long mml=30-mm%2;//month length - if(mm==3) mml+=long(floor(myt/2));//adjust if Nayon in big watat - return mml; -} -//------------------------------------------------------------------------- -// Get the apparent length of the year from year type. -// input: ( myt = year type [0=common, 1=little watat, 2=big watat]) -// output: ( myl= year length [354, 384, or 385 days]) -long ceMmDateTime::cal_myl(long myt) { - return (354+(1-long(floor(1/(myt+1))))*30+long(floor(myt/2))); -} -//------------------------------------------------------------------------- -// Get fortnight day from month day -// input: ( md= day of the month [1-30]) -// output: (mf= fortnight day [1 to 15]) -long ceMmDateTime::cal_mf(long md) { - return (md-15*long(floor(md/16))); -} -//------------------------------------------------------------------------- -// Get day of month from fortnight day, moon phase, and length of the month -// input: ( -// mf = fortnight day [1 to 15], -// mp = moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// myt = year type [0=common, 1=little watat, 2=big watat]) -// output: ( md = day of the month [1-30]) -long ceMmDateTime::cal_md(long mf,long mp,long mm,long myt) { - long mml=ceMmDateTime::cal_mml(mm,myt); - long m1=mp%2; long m2=long(floor(mp/2)); - return (m1*(15+m2*(mml-15))+(1-m1)*(mf+15*m2)); -} -//------------------------------------------------------------------------- -// Myanmar date to Julian day number -// input: ( -// my = year, -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12 , Late Tagu=13, Late Kason=14 ], -// md = day of the month [1-30] -// output: (jd -julian day number) -// dependency: cal_my(my) -long ceMmDateTime::m2j(long my,long mm,long md) { - long b,c,dd,myl,mmt; - long myt,tg1,fm,werr; - ceMmDateTime::cal_my(my,myt,tg1,fm,werr);//check year - mmt=long(floor(mm/13)); mm=mm%13+mmt; // to 1-12 with month type - b=long(floor(myt/2)); c=1-long(floor((myt+1)/2)); //if big watat and common year - mm+=4-long(floor((mm+15)/16))*4+long(floor((mm+12)/16));//adjust month - dd=md+long(floor(29.544*mm-29.26))-c*long(floor((mm+11)/16))*30 - +b*long(floor((mm+12)/16)); - myl=354+(1-c)*30+b; dd+=mmt*myl;//adjust day count with year length - return (dd+tg1-1); -} -//------------------------------------------------------------------------- -//Checking Astrological days -// More details @ http://cool-emerald.blogspot.sg/2013/12/myanmar-astrological-calendar-days.html -//------------------------------------------------------------------------- -// Get sabbath day and sabbath eve from day of the month, month, and year type. -// input: ( -// md= day of the month [1-30], -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// myt = year type [0=common, 1=little watat, 2=big watat]) -// output: ( [1=sabbath, 2=sabbath eve, 0=else]) -long ceMmDateTime::cal_sabbath(long md, long mm, long myt) { - long mml = ceMmDateTime::cal_mml(mm, myt); - long s = 0; if ((md == 8) || (md == 15) || (md == 23) || (md == mml)) s = 1; - if ((md == 7) || (md == 14) || (md == 22) || (md == (mml - 1))) s = 2; - return s; -} -//------------------------------------------------------------------------- -// Get yatyaza from month, and weekday -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=yatyaza, 0=else]) -long ceMmDateTime::cal_yatyaza(long mm, long wd) { - //first waso is considered waso - long m1 = mm % 4; long yatyaza = 0; long wd1 = long(floor(m1 / 2)) + 4; - long wd2 = ((1 - long(floor(m1 / 2))) + m1 % 2)*(1 + 2 * (m1 % 2)); - if ((wd == wd1) || (wd == wd2)) yatyaza = 1; - return yatyaza; -} -//------------------------------------------------------------------------- -// Get pyathada from month, and weekday -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=pyathada, 2=afternoon pyathada, 0=else]) -long ceMmDateTime::cal_pyathada(long mm, long wd) { - //first waso is considered waso - long m1 = mm % 4; long pyathada = 0; long wda[] = { 1, 3, 3, 0, 2, 1, 2 }; - if ((m1 == 0) && (wd == 4)) pyathada = 2;//afternoon pyathada - if (m1 == wda[wd]) pyathada = 1; - return pyathada; -} -//------------------------------------------------------------------------- -// nagahle -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ]) -// output: ( [0=west, 1=north, 2=east, 3=south]) -long ceMmDateTime::cal_nagahle(long mm) { - if (mm <= 0) mm = 4;//first waso is considered waso - return long(floor((mm % 12) / 3)); -} -//------------------------------------------------------------------------- -// mahabote -// input: ( -// my = year, -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [0=Binga, 1=Atun, 2=Yaza, 3=Adipati, 4= Marana, 5=Thike, 6=Puti]) -long ceMmDateTime::cal_mahabote(long my, long wd) { return ((my - wd) % 7); } -//------------------------------------------------------------------------- -// nakhat -// input: ( my = year ) -// output: ( [0=orc, 1=elf, 2=human] ) -long ceMmDateTime::cal_nakhat(long my) { return (my % 3); } -//------------------------------------------------------------------------- -// thamanyo -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=thamanyo, 0=else]) -long ceMmDateTime::cal_thamanyo(long mm, long wd) { - long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type - if (mm <= 0) mm = 4;//first waso is considered waso (looks no need here) - long thamanyo = 0; - long m1 = mm - 1 - (long)floor(mm / 9); - long wd1 = (m1 * 2 - (long)floor(m1 / 8)) % 7; - long wd2 = (wd + 7 - wd1) % 7; - if (wd2 <= 1) thamanyo = 1; - return thamanyo; -} -//------------------------------------------------------------------------- -// Get amyeittasote -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=amyeittasote, 0=else]) -long ceMmDateTime::cal_amyeittasote(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long amyeittasote = 0; long wda[] = { 5, 8, 3, 7, 2, 4, 1 }; - if (mf == wda[wd]) amyeittasote = 1; - return amyeittasote; -} -//------------------------------------------------------------------------- -// Get warameittugyi -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=warameittugyi, 0=else]) -long ceMmDateTime::cal_warameittugyi(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long warameittugyi = 0; long wda[] = { 7, 1, 4, 8, 9, 6, 3 }; - if (mf == wda[wd]) warameittugyi = 1; - return warameittugyi; -} -//------------------------------------------------------------------------- -// Get warameittunge -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=warameittunge, 0=else]) -long ceMmDateTime::cal_warameittunge(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long warameittunge = 0; long wn = (wd + 6) % 7; - if ((12 - mf) == wn) warameittunge = 1; - return warameittunge; -} -//------------------------------------------------------------------------- -// Get yatpote -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=yatpote, 0=else]) -long ceMmDateTime::cal_yatpote(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long yatpote = 0; long wda[] = { 8, 1, 4, 6, 9, 8, 7 }; - if (mf == wda[wd]) yatpote = 1; - return yatpote; -} -//------------------------------------------------------------------------- -// Get thamaphyu -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=thamaphyu, 0=else]) -long ceMmDateTime::cal_thamaphyu(long md, long wd) { - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long thamaphyu = 0; long wda[] = { 1, 2, 6, 6, 5, 6, 7 }; - if (mf == wda[wd]) thamaphyu = 1; - long wdb[] = { 0, 1, 0, 0, 0, 3, 3 }; if (mf == wdb[wd]) thamaphyu = 1; - if ((mf == 4) && (wd == 5)) thamaphyu = 1; - return thamaphyu; -} -//------------------------------------------------------------------------- -// Get nagapor -// input: ( -// md= day of the month [1-30], -// wd= weekday [0=sat, 1=sun, ..., 6=fri]) -// output: ( [1=nagapor, 0=else]) -long ceMmDateTime::cal_nagapor(long md, long wd) { - long nagapor = 0; long wda[] = { 26, 21, 2, 10, 18, 2, 21 }; - if (md == wda[wd]) nagapor = 1; - long wdb[] = { 17, 19, 1, 0, 9, 0, 0 }; if (md == wdb[wd]) nagapor = 1; - if (((md == 2) && (wd == 1)) || (((md == 12) || (md == 4) || (md == 18)) && (wd == 2))) nagapor = 1; - return nagapor; -} -//------------------------------------------------------------------------- -// yatyotema -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// md= day of the month [1-30]) -// output: ( [1=yatyotema, 0=else]) -long ceMmDateTime::cal_yatyotema(long mm, long md) { - long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type - if (mm <= 0) mm = 4;//first waso is considered waso - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long yatyotema = 0; long m1 = (mm % 2) ? mm : ((mm + 9) % 12); - m1 = (m1 + 4) % 12 + 1; if (mf == m1) yatyotema = 1; - return yatyotema; -} -//------------------------------------------------------------------------- -// mahayatkyan -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// md= day of the month [1-30]) -// output: ( [1=mahayatkyan, 0=else]) -long ceMmDateTime::cal_mahayatkyan(long mm, long md) { - if (mm <= 0) mm = 4;//first waso is considered waso - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long mahayatkyan = 0; long m1 = ((long)floor((mm % 12) / 2) + 4) % 6 + 1; - if (mf == m1) mahayatkyan = 1; - return mahayatkyan; -} -//------------------------------------------------------------------------- -// shanyat -// input: ( -// mm = month [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ], -// md= day of the month [1-30]) -// output: ( [1=shanyat, 0=else]) -long ceMmDateTime::cal_shanyat(long mm, long md) { - long mmt = long(floor(mm / 13)); mm = mm % 13 + mmt; // to 1-12 with month type - if (mm <= 0) mm = 4;//first waso is considered waso - long mf = md - 15 * (long)floor(md / 16);//get fortnight day [0-15] - long shanyat = 0; long sya[] = { 8, 8, 2, 2, 9, 3, 3, 5, 1, 4, 7, 4 }; - if (mf == sya[mm - 1]) shanyat = 1; - return shanyat; -} -//------------------------------------------------------------------------- -// get astrological information -// input: (jdn: Julian Day Number) -// output: (array of strings) -std::vector ceMmDateTime::cal_astro(long jdn) { - // jdn=(long)round(jdn); - long myt,my,mm,md; vector hs; - ceMmDateTime::j2m(jdn,myt,my,mm,md); - long wd=(jdn+2)%7;//week day [0=sat, 1=sun, ..., 6=fri] - if(ceMmDateTime::cal_thamanyo(mm,wd)) {hs.push_back("thamanyo");} - if(ceMmDateTime::cal_amyeittasote(md,wd)) {hs.push_back("amyeittasote");} - if(ceMmDateTime::cal_warameittugyi(md,wd)) {hs.push_back("warameittugyi");} - if(ceMmDateTime::cal_warameittunge(md,wd)) {hs.push_back("warameittunge");} - if(ceMmDateTime::cal_yatpote(md,wd)) {hs.push_back("yatpote");} - if(ceMmDateTime::cal_thamaphyu(md,wd)) {hs.push_back("thamaphyu");} - if(ceMmDateTime::cal_nagapor(md,wd)) {hs.push_back("nagapor");} - if(ceMmDateTime::cal_yatyotema(mm,md)) {hs.push_back("yatyotema");} - if(ceMmDateTime::cal_mahayatkyan(mm,md)) {hs.push_back("mahayatkyan");} - if(ceMmDateTime::cal_shanyat(mm,md)) {hs.push_back("shanyat");} - return hs; -} -//End of core functions ############################################################### - -//Start of checking holidays ################################################## -// Get holidays -// input: (jdn=Julian Day Number) -// output: ( array of strings) -// Thanks to Ye Lin Kyaw and Aye Nyein for the knowledge about -// the Myanmar calendar and the new year -std::vector ceMmDateTime::cal_holiday(long jdn) { - // jdn=(long)round(jdn); - long myt,my,mm,md,mp,mmt,gy,gm,gd,gh,gn; double gs; - ceMmDateTime::j2m(jdn,myt,my,mm,md); - mp=ceMmDateTime::cal_mp(md,mm,myt); - mmt=(long)floor(mm/13); vector hs; - ceDateTime::j2w(jdn,gy,gm,gd,gh,gn,gs); - //--------------------------------- - // Thingyan - double SY=1577917828.0/4320000.0; //solar year (365.2587565) - double MO=1954168.050623; //beginning of 0 ME - long BGNTG=1100, SE3=1312;//start of Thingyan and third era - long akn,atn; double ja,jk; - ja=SY*(my+mmt)+MO; // atat time - if (my >= SE3) jk=ja-2.169918982; // akya time - else jk=ja-2.1675; - akn=(long)round(jk); atn=(long)round(ja); - if(jdn==(atn+1)) {hs.push_back("Myanmar New Year Day");} - if ((my+mmt)>=BGNTG) { - if(jdn==atn) {hs.push_back("Thingyan Atat");} - else if((jdn>akn)&&(jdn=1369)&&((my+mmt)<1379)&&((jdn==(akn-2))|| - ((jdn>=(atn+2))&&(jdn<=(akn+7))))) {hs.push_back("Holiday");} - } - //--------------------------------- - // holidays on gregorian calendar - if((gy>=2018) && (gm==1) && (gd==1)) {hs.push_back("New Year Day");} - else if((gy>=1948) && (gm==1) && (gd==4)) {hs.push_back("Independence Day");} - else if((gy>=1947) && (gm==2) && (gd==12)) {hs.push_back("Union Day");} - else if((gy>=1958) && (gm==3) && (gd==2)) {hs.push_back("Peasants Day");} - else if((gy>=1945) && (gm==3) && (gd==27)) {hs.push_back("Resistance Day");} - else if((gy>=1923) && (gm==5) && (gd==1)) {hs.push_back("Labour Day");} - else if((gy>=1947) && (gm==7) && (gd==19)) {hs.push_back("Martyrs Day");} - else if((gy>=1752) && (gm==12) && (gd==25)) {hs.push_back("Christmas Day");} - else if((gy==2017) && (gm==12) && (gd==30)) {hs.push_back("Holiday");} - else if((gy>=2017) && (gm==12) && (gd==31)) {hs.push_back("Holiday");} - //--------------------------------- - // holidays on myanmar calendar - if((mm==2) && (mp==1)) {hs.push_back("Buddha Day");}//Vesak day - else if((mm==4)&& (mp==1)) {hs.push_back("Start of Buddhist Lent");}//Warso day - else if((mm==7) && (mp==1)) {hs.push_back("End of Buddhist Lent");} - else if((my>=1379) && (mm==7) && (md==14||md==16)) {hs.push_back("Holiday");} - else if((mm==8) && (mp==1)) {hs.push_back("Tazaungdaing");} - else if((my>=1379) && (mm==8) && (md==14)) {hs.push_back("Holiday");} - else if((my>=1282) && (mm==8) && (md==25)) {hs.push_back("National Day");} - else if((mm==10) && (md==1)) {hs.push_back("Karen New Year Day");} - else if((mm==12) && (mp==1)) {hs.push_back("Tabaung Pwe");} - //--------------------------------- - // //other holidays - // long ghEid[]={2456513,2456867,2457221,2457576,2457930,2458285,2458640}; - // if(ceMmDateTime::bSearch1(jdn,ghEid,long(sizeof(ghEid)/sizeof(ghEid[0])))>=0) - // {hs.push_back("Eid");} - - // // long ghDiwali[]={2456599,2456953,2457337,2457691,2458045,2458430,2458784}; - // // if(ceMmDateTime::bSearch1(jdn,ghDiwali,long(sizeof(ghDiwali)/sizeof(ghDiwali[0])))>=0) - // // {hs.push_back("Diwali");} - // if((mm==7) && (mp==3)) {hs.push_back("~Diwali");} - //--------------------------------- - return hs; -} -//------------------------------------------------------------------------- -// DoE : Date of Easter using "Meeus/Jones/Butcher" algorithm -// Reference: Peter Duffett-Smith, Jonathan Zwart', -// "Practical Astronomy with your Calculator or Spreadsheet," -// 4th Etd, Cambridge university press, 2011. Page-4. -// input: (y=year) -// output: (j=julian day number) -// dependency: w2j() -long ceMmDateTime::DoE(long y) { - long a,b,c,d,e,f,g,h,i,k,l,m,p,q,n; - a=y%19; - b=(long)floor(y/100); c=y%100; - d=(long)floor(b/4); e=b%4; - f=(long)floor((b+8)/25); - g=(long)floor((b-f+1)/3); - h=(19*a+b-d-g+15)%30; - i=(long)floor(c/4); k=c%4; - l=(32+2*e+2*i-h-k)%7; - m=(long)floor((a+11*h+22*l)/451); - q=h+l-7*m+114; p=(q%31)+1; n=(long)floor(q/31); - return (long)round(ceDateTime::w2j(y,n,p,12,0,0,1));// this is for Gregorian -} -//------------------------------------------------------------------------- -// Get other holidays -// input: (jdn: Julian Day Number) -// output: (array of strings) -// dependency: DoE(), j2w() -std::vector ceMmDateTime::cal_holiday2(long jdn) { - // jdn=(long)round(jdn); - long myt,my,mm,md,mp,mmt,gy,gm,gd,gh,gn; double gs; - ceMmDateTime::j2m(jdn,myt,my,mm,md); - mp=ceMmDateTime::cal_mp(md,mm,myt); - mmt=(long)floor(mm/13); vector hs; - ceDateTime::j2w(jdn,gy,gm,gd,gh,gn,gs); - //--------------------------------- - // holidays on gregorian calendar - long doe=ceMmDateTime::DoE(gy); - if((gy<=2017) && (gm==1) && (gd==1)) {hs.push_back("New Year Day");} - else if((gy>=1915) && (gm==2) && (gd==13)) {hs.push_back("G. Aung San BD");} - else if((gy>=1969) && (gm==2) && (gd==14)) {hs.push_back("Valentines Day");} - else if((gy>=1970) && (gm==4) && (gd==22)) {hs.push_back("Earth Day");} - else if((gy>=1392) && (gm==4) && (gd==1)) {hs.push_back("April Fools Day");} - else if((gy>=1948) && (gm==5) && (gd==8)) {hs.push_back("Red Cross Day");} - else if((gy>=1994) && (gm==10) && (gd==5)) {hs.push_back("World Teachers Day");} - else if((gy>=1947) && (gm==10) && (gd==24)) {hs.push_back("United Nations Day");} - else if((gy>=1753) && (gm==10) && (gd==31)) {hs.push_back("Halloween");} - if((gy>=1876) && (jdn==doe)) {hs.push_back("Easter");} - else if((gy>=1876) && (jdn==(doe-2))) {hs.push_back("Good Friday");} - //--------------------------------- - // holidays on myanmar calendar - if((my>=1309) && (mm==11) && (md==16)) - {hs.push_back("Mon National Day");}//the ancient founding of Hanthawady - else if((mm==9) && (md==1)) { - hs.push_back("Shan New Year Day"); - if(my>=1306) {hs.push_back("Authors Day");} - }//Nadaw waxing moon 1 - else if((mm==3) && (mp==1)) {hs.push_back("Mahathamaya Day");}//Nayon full moon - else if((mm==6)&&(mp==1)){hs.push_back("Garudhamma Day");}//Tawthalin full moon - else if((my>=1356) && (mm==10) && (mp==1)) - {hs.push_back("Mothers Day");}//Pyatho full moon - else if((my>=1370) && (mm==12) && (mp==1)) - {hs.push_back("Fathers Day");}//Tabaung full moon - else if((mm==5) && (mp==1)) {hs.push_back("Metta Day");}//Waguang full moon - else if((mm==5) && (md==10)) {hs.push_back("Taungpyone Pwe");}//Taung Pyone Pwe - else if((mm==5) && (md==23)) {hs.push_back("Yadanagu Pwe");}//Yadanagu Pwe - //---------------------------------------------------------------------------- - // //other holidays - // long ghEid2[]={2456936,2457290,2457644,2457998,2458353,2458707}; - // long ghCNY[]={2456689,2456690,2457073,2457074,2457427,2457428,2457782, - // 2457783,2458166,2458167,2458520,2458521}; - // if(ceMmDateTime::bSearch1(jdn,ghEid2,long(sizeof(ghEid2)/sizeof(ghEid2[0])))>=0) - // {hs.push_back("Eid");} - // if(ceMmDateTime::bSearch1(jdn,ghCNY,long(sizeof(ghCNY)/sizeof(ghCNY[0])))>=0) - // {hs.push_back("Chinese New Year");} - //---------------------------------------------------------------------------- - return hs; -} - -//----------------------------------------------------------------------------- -//End of checking holidays #################################################### -//------------------------------------------------------------------------- -// jd to date string in Myanmar calendar -// input: (jd:julian date, -// fs: format string [Optional argument: "&y &M &P &ff"] -// tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) -// output: date string in Myanmar calendar according to fm -// where formatting strings are as follows -// &yyyy : Myanmar year [0000-9999, e.g. 1380] -// &YYYY : Sasana year [0000-9999, e.g. 2562] -// &y : Myanmar year [0-9999, e.g. 138] -// &mm : month with zero padding [01-14] -// &M : month [e.g. January] -// &m : month [1-14] -// &P : moon phase [e.g. waxing, waning, full moon, or new moon] -// &dd : day of the month with zero padding [01-31] -// &d : day of the month [1-31] -// &ff : fortnight day with zero padding [01-15] -// &f : fortnight day [1-15] -std::string ceMmDateTime::j2ms(double jd, std::string fs, double tz) { - jd+=tz/24.0; - long jdn=(long)round(jd); - long myt,my,mm,md,mp,mf; - ceMmDateTime::j2m(jdn,myt,my,mm,md); - mp=ceMmDateTime::cal_mp(md,mm,myt); - mf=ceMmDateTime::cal_mf(md); - string mma[]={"First Waso","Tagu","Kason","Nayon","Waso","Wagaung","Tawthalin", - "Thadingyut","Tazaungmon","Nadaw","Pyatho","Tabodwe","Tabaung","Late Tagu","Late Kason"}; - string mpa[]={"Waxing","Full Moon","Waning","New Moon"}; - // replace format string with values - string fm=fs; string fstr,rstr; - //-------------------------------------------------------- - fstr = "&yyyy"; - rstr = string(4, '0') + to_string(my); - rstr = rstr.substr(rstr.length() - 4); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - long sy=my+1182; //Sasana year - fstr = "&YYYY"; - rstr = string(4, '0') + to_string(my); - rstr = rstr.substr(rstr.length() - 4); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&y"; - rstr = to_string(my); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&mm"; - rstr = string(2, '0') + to_string(mm); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&M"; - rstr = mma[mm]; if(mm==4 && myt>0){rstr="Second "+rstr;} - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&m"; - rstr = to_string(mm); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&P"; - rstr = mpa[mp]; - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&dd"; - rstr = string(2, '0') + to_string(md); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&d"; - rstr = to_string(md); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&ff"; - rstr = string(2, '0') + to_string(mf); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "&f"; - rstr = to_string(mf); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - return fm; -} -//------------------------------------------------------------------------- -// get properties - -// Myanmar year type -long ceMmDateTime::myt(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return myt; -} - -// Myanmar year -long ceMmDateTime::my(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return my; -} - -// Sasana year -long ceMmDateTime::sy(){ - long sy=this->my()+1182; - return sy; -} - -// Myanmar year name -string ceMmDateTime::my_name(){ - // "ပုဿနှစ်","မာခနှစ်","ဖ္လကိုန်နှစ်","စယ်နှစ်", - // "ပိသျက်နှစ်","စိဿနှစ်","အာသတ်နှစ်","သရဝန်နှစ်", - // "ဘဒြနှစ်","အာသိန်နှစ်","ကြတိုက်နှစ်","မြိက္ကသိုဝ်နှစ်" - string yna[]={"Hpusha","Magha","Phalguni","Chitra", - "Visakha","Jyeshtha","Ashadha","Sravana", - "Bhadrapaha","Asvini","Krittika","Mrigasiras"}; - return yna[this->my()%12]; -} - -// Myanmar month [1-14] -// [Tagu=1, Kason=2, Nayon=3, 1st Waso=0, (2nd) Waso=4, Wagaung=5, -// Tawthalin=6, Thadingyut=7, Tazaungmon=8, Nadaw=9, Pyatho=10, Tabodwe=11, -// Tabaung=12, Late Tagu=13, Late Kason=14 ] -long ceMmDateTime::mm(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return mm; -} - -// Myanmar day of the month [1-30] -long ceMmDateTime::md(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return md; -} - -// Moon phase [0=waxing, 1=full moon, 2=waning, 3=new moon] -long ceMmDateTime::mp(){ - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - return ceMmDateTime::cal_mp(md,mm,myt); -} - -// Fortnight day [1-15] -long ceMmDateTime::mf() { - return ceMmDateTime::cal_mf(this->md()); -} - -// get sabbath string -string ceMmDateTime::sabbath() { - long myt,my,mm,md; - ceMmDateTime::j2m(this->jdnl(),myt,my,mm,md); - long sb=ceMmDateTime::cal_sabbath(md,mm,myt); - string str=""; - if(sb==1) str="Sabbath"; - else if(sb==2) str="Sabbath Eve"; - return str; -} - -// get yatyaza string -string ceMmDateTime::yatyaza() { - long v=ceMmDateTime::cal_yatyaza(this->mm(),this->w()); - return (v?"Yatyaza":""); -} - -// get pyathada string -string ceMmDateTime::pyathada() { - long v=ceMmDateTime::cal_pyathada(this->mm(),this->w()); - string pa[]={"","Pyathada","Afternoon Pyathada"}; - return pa[v%3]; -} - -// get nagahle direction -string ceMmDateTime::nagahle() { - long v=ceMmDateTime::cal_nagahle(this->mm()); - string pa[]={"West","North","East","South"}; - return pa[v%4]; -} - -// get mahabote direction -string ceMmDateTime::mahabote() { - long v=ceMmDateTime::cal_mahabote(this->my(),this->w()); - string pa[]={"Binga","Atun","Yaza","Adipati","Marana","Thike","Puti"}; - return pa[v%7]; -} - -// get the array of astrological days -vector ceMmDateTime::astro() { - return ceMmDateTime::cal_astro(this->jdnl()); -} - -// get the array of public holidays -vector ceMmDateTime::holidays() { - return ceMmDateTime::cal_holiday(this->jdnl()); -} - -// get the array of other holidays -vector ceMmDateTime::holidays2() { - return ceMmDateTime::cal_holiday2(this->jdnl()); -} - -//------------------------------------------------------------------------- -// get Myanmar Date String -// input: ( -// fs: format string [Optional argument: "&y &M &P &ff"] -// tz : time zone offset in hours (Optional, e.g. 8 for GMT +8)) -// output: date string in Myanmar calendar according to fm -// where formatting strings are as follows -// &yyyy : Myanmar year [0000-9999, e.g. 1380] -// &YYYY : Sasana year [0000-9999, e.g. 2562] -// &y : Myanmar year [0-9999, e.g. 138] -// &mm : month with zero padding [01-14] -// &M : month [e.g. January] -// &m : month [1-14] -// &P : moon phase [e.g. waxing, waning, full moon, or new moon] -// &dd : day of the month with zero padding [01-31] -// &d : day of the month [1-31] -// &ff : fortnight day with zero padding [01-15] -// &f : fortnight day [1-15] -string ceMmDateTime::ToMString(string fs) { - return ceMmDateTime::j2ms(this->jd(),fs,this->tz()); -} -//------------------------------------------------------------------------- - -} //namespace ce \ No newline at end of file diff --git a/vcprj/ceutil.vcxproj b/vcprj/ceutil.vcxproj index 44fa389..273bef6 100644 --- a/vcprj/ceutil.vcxproj +++ b/vcprj/ceutil.vcxproj @@ -19,9 +19,9 @@ - - + + @@ -29,7 +29,6 @@ - @@ -38,13 +37,11 @@ - - diff --git a/vcprj/ceutil.vcxproj.filters b/vcprj/ceutil.vcxproj.filters index bbb572c..b705fe2 100644 --- a/vcprj/ceutil.vcxproj.filters +++ b/vcprj/ceutil.vcxproj.filters @@ -18,10 +18,7 @@ - - Header Files - - + Header Files @@ -36,9 +33,6 @@ Header Files - - Header Files - Header Files @@ -48,9 +42,6 @@ Header Files - - Header Files - Header Files @@ -87,11 +78,11 @@ Header Files + + Header Files + - - Source Files - Source Files From 72acd003b566fbbd3db9d056226d78e359627870 Mon Sep 17 00:00:00 2001 From: yan9a Date: Sat, 24 Aug 2024 15:36:00 +1200 Subject: [PATCH 03/10] Update more as single header files --- CMakeLists.txt | 25 +- Dockerfile | 47 -- ceutil.sh | 107 --- ceutilw.bat | 13 - examples/Timer/CMakeLists.txt | 11 - examples/Timer/Timer.sh | 60 -- examples/Timer/Timer/Timer.sln | 31 - examples/Timer/Timer/Timer.vcxproj | 162 ----- examples/Timer/Timer/Timer.vcxproj.filters | 22 - examples/Timer/src/Timer.cpp | 32 - examples/Timer/timerw.bat | 11 - examples/WxSerial/CMakeLists.txt | 12 - examples/WxSerial/WxSerial.sh | 60 -- examples/WxSerial/src/WxSerial.cpp | 31 - examples/WxSerial/wxserialw.bat | 11 - examples/interface/CMakeLists.txt | 11 - examples/interface/interface.bat | 11 - examples/interface/interface.sh | 60 -- examples/interface/src/main.cpp | 29 - examples/interface/vsprj/interface.sln | 31 - examples/interface/vsprj/interface.vcxproj | 162 ----- .../interface/vsprj/interface.vcxproj.filters | 22 - include/ce/ceDES.h | 517 +++++++++++++-- include/ce/ceFraChecksum.h | 49 -- include/ce/ceFraCmd.h | 43 +- include/ce/ceFrame.h | 119 +++- include/ce/ceI2C.h | 127 +++- include/ce/ceInterface.h | 36 - include/ce/ceLog.h | 263 +++++++- include/ce/ceMisc.h | 252 ++++++- include/ce/ceModbus.h | 201 +++++- include/ce/cePCA9535.h | 87 ++- include/ce/ceSerial.h | 600 ++++++++++++++++- include/ce/ceWxSerial.h | 32 - include/ce/ceWxTmr.h | 28 - src/ceFraChecksum.cpp => include/ce/cefracs.h | 253 ++++--- include/ce/{ceRSA_OS.h => cersaos.h} | 127 ++-- src/ceDES.cpp | 493 -------------- src/ceDateTime.cpp | 622 ------------------ src/ceFraCmd.cpp | 47 -- src/ceFrame.cpp | 123 ---- src/ceI2C.cpp | 88 --- src/ceInterface.cpp | 25 - src/ceLog.cpp | 224 ------- src/ceMisc.cpp | 219 ------ src/ceModbus.cpp | 207 ------ src/cePCA9535.cpp | 89 --- src/ceSerial.cpp | 617 ----------------- src/ceWxSerial.cpp | 53 -- src/ceWxTmr.cpp | 35 - vcprj/ceutil.vcxproj | 39 +- vcprj/ceutil.vcxproj.filters | 93 +-- 52 files changed, 2377 insertions(+), 4292 deletions(-) delete mode 100644 Dockerfile delete mode 100644 ceutil.sh delete mode 100644 ceutilw.bat delete mode 100644 examples/Timer/CMakeLists.txt delete mode 100644 examples/Timer/Timer.sh delete mode 100644 examples/Timer/Timer/Timer.sln delete mode 100644 examples/Timer/Timer/Timer.vcxproj delete mode 100644 examples/Timer/Timer/Timer.vcxproj.filters delete mode 100644 examples/Timer/src/Timer.cpp delete mode 100644 examples/Timer/timerw.bat delete mode 100644 examples/WxSerial/CMakeLists.txt delete mode 100644 examples/WxSerial/WxSerial.sh delete mode 100644 examples/WxSerial/src/WxSerial.cpp delete mode 100644 examples/WxSerial/wxserialw.bat delete mode 100644 examples/interface/CMakeLists.txt delete mode 100644 examples/interface/interface.bat delete mode 100644 examples/interface/interface.sh delete mode 100644 examples/interface/src/main.cpp delete mode 100644 examples/interface/vsprj/interface.sln delete mode 100644 examples/interface/vsprj/interface.vcxproj delete mode 100644 examples/interface/vsprj/interface.vcxproj.filters delete mode 100644 include/ce/ceFraChecksum.h delete mode 100644 include/ce/ceInterface.h delete mode 100644 include/ce/ceWxSerial.h delete mode 100644 include/ce/ceWxTmr.h rename src/ceFraChecksum.cpp => include/ce/cefracs.h (60%) rename include/ce/{ceRSA_OS.h => cersaos.h} (89%) delete mode 100644 src/ceDES.cpp delete mode 100644 src/ceDateTime.cpp delete mode 100644 src/ceFraCmd.cpp delete mode 100644 src/ceFrame.cpp delete mode 100644 src/ceI2C.cpp delete mode 100644 src/ceInterface.cpp delete mode 100644 src/ceLog.cpp delete mode 100644 src/ceMisc.cpp delete mode 100644 src/ceModbus.cpp delete mode 100644 src/cePCA9535.cpp delete mode 100644 src/ceSerial.cpp delete mode 100644 src/ceWxSerial.cpp delete mode 100644 src/ceWxTmr.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ea6f310..af00bf6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,8 +1,7 @@ cmake_minimum_required(VERSION 3.0.0) -project (ceutil VERSION 2.1.0) -# version 1.1.0 Added DES, SHA, RSA -# version 2.1.0 Replace wxAppConsole with wxEvtHandler, add TCP server - +project (ceutil VERSION 2.1.3) +# version 1.0.0 Added DES, SHA, RSA +# version 2.0.0 Replace wxAppConsole with wxEvtHandler, add TCP server, header only set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -59,23 +58,7 @@ endif() message(STATUS "List of libraries = ${LIBS}") include_directories(${PROJECT_SOURCE_DIR}/include) add_library(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/ceLog.cpp -${PROJECT_SOURCE_DIR}/src/ceSerial.cpp -${PROJECT_SOURCE_DIR}/src/ceWxTmr.cpp -${PROJECT_SOURCE_DIR}/src/ceUDP.cpp -${PROJECT_SOURCE_DIR}/src/ceTcpClient.cpp -${PROJECT_SOURCE_DIR}/src/ceMisc.cpp -${PROJECT_SOURCE_DIR}/src/ceFrame.cpp -${PROJECT_SOURCE_DIR}/src/ceFraChecksum.cpp -${PROJECT_SOURCE_DIR}/src/ceFraCmd.cpp -${PROJECT_SOURCE_DIR}/src/ceI2C.cpp -${PROJECT_SOURCE_DIR}/src/cePCA9535.cpp -${PROJECT_SOURCE_DIR}/src/ceModbus.cpp -${PROJECT_SOURCE_DIR}/src/ceWxSerial.cpp -${PROJECT_SOURCE_DIR}/src/cewxcvMisc.cpp -${PROJECT_SOURCE_DIR}/src/ceDES.cpp -${PROJECT_SOURCE_DIR}/src/ceSHA1.cpp -${PROJECT_SOURCE_DIR}/src/ceRSA_OS.cpp + ) target_link_libraries(${PROJECT_NAME} ${LIBS}) install(TARGETS ${PROJECT_NAME} DESTINATION lib) diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 4a42e47..0000000 --- a/Dockerfile +++ /dev/null @@ -1,47 +0,0 @@ -FROM debian:bookworm - -# required libs -RUN apt update \ - && apt install --no-install-recommends --no-install-suggests -y build-essential cmake \ - libgtk-3-dev checkinstall libwxgtk3.0-gtk3-dev \ - git pkg-config libavcodec-dev libavformat-dev libswscale-dev libopencv-dev \ - libjsoncpp-dev apt-transport-https ca-certificates \ - autoconf automake libtool - -RUN apt update \ - && apt install --no-install-recommends --no-install-suggests -y curl gdb cmake-extras \ - bc bison flex libssl-dev make \ - libboost-atomic-dev libboost-thread-dev libboost-system-dev libboost-date-time-dev libboost-regex-dev \ - libboost-filesystem-dev libboost-random-dev libboost-chrono-dev libboost-serialization-dev libwebsocketpp-dev \ - openssl ninja-build g++ \ - libcpprest-dev gpiod libgpiod-dev rsync sshpass\ - libpng-dev texlive doxygen - -RUN apt update \ - && apt-cache pkgnames | grep -i crypto++ \ - && apt install --no-install-recommends --no-install-suggests -y libcrypto++8 libcrypto++-utils libcrypto++-dev - -# ceutil lib -RUN git clone --depth 1 https://github.com/yan9a/ceutil.git \ - && cd ceutil && mkdir -p build && cd build \ - && cmake -D CMAKE_BUILD_TYPE=Release -D BUILD_SHARED_LIBS=ON -D CMAKE_INSTALL_PREFIX=/usr/local .. \ - && make && make install \ - && sh -c "echo /usr/local/lib > /etc/ld.so.conf.d/ceutil.conf" \ - && ldconfig && cd ../.. - -# nfc lib -RUN git clone --depth 1 https://github.com/NXPNFCLinux/linux_libnfc-nci.git \ - && cd linux_libnfc-nci && ./bootstrap \ - && ./configure --enable-alt && make && make install \ - && sh -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/nfc-nci.conf" \ - && ldconfig && cd .. - -# zint lib -RUN git clone https://github.com/woo-j/zint.git \ - && cd zint && mkdir -p build && cd build \ - && cmake .. && make && make install \ - && sh -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/zint.conf" \ - && ldconfig && cd ../.. - -EXPOSE 80 443 - diff --git a/ceutil.sh b/ceutil.sh deleted file mode 100644 index 7436883..0000000 --- a/ceutil.sh +++ /dev/null @@ -1,107 +0,0 @@ -#!/bin/bash - -# fix script -# sed -i -e 's/\r$//' ceutil.sh -# chmod +x ceutil.sh - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -opt_sh="build" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'install' : to install prerequisite packages, generate cmake files, build and install the lib" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - - -if [[ "$opt_sh" == "install" ]]; then - # add the user to groups - opt_au="y" - read -p "Do you want to add current user to netdev and dialout groups [y/N]?: " opt_au - if [ $opt_au == "y" ] || [ $opt_au == "Y" ]; then - echo "Adding $USER to groups" - sudo usermod -a -G netdev $USER - sudo usermod -a -G dialout $USER - fi - opt_reqlib="y" - read -p "Do you want to install required libraries [y/N]?: " opt_reqlib - if [ $opt_reqlib == "y" ] || [ $opt_reqlib == "Y" ]; then - # install required lib - echo "Installing required lib ..." - sudo apt update \ - && sudo apt install --no-install-recommends --no-install-suggests -y build-essential cmake cmake-extras gdb\ - libgtk-3-dev checkinstall libwxgtk3.0-gtk3-dev \ - git pkg-config libavcodec-dev libavformat-dev libswscale-dev libopencv-dev \ - libjsoncpp-dev apt-transport-https ca-certificates \ - autoconf automake libtool gdb cmake-extras \ - libssl-dev openssl - fi - echo " ." - echo " ." - echo " ." -fi # lib - -cd $SCRIPTDIR -if [[ "$opt_sh" == "install" ]] || [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D BUILD_SHARED_LIBS=ON \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "install" ]] || [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd build && make && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - ls -l *ceutil.so - ldd *ceutil.so - # ls -l *$ceutil.a - # ar -t *$ceutil.a - else - echo "Error in compiling" - fi -else - echo "Invalid option for $PRJNAME ..." -fi - -if [[ "$opt_sh" == "install" ]]; then - echo "Configuring lib path ..." - sudo sh -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/ceutil.conf" - sudo ldconfig - echo " ." - echo " ." - echo " ." -fi # config - - - diff --git a/ceutilw.bat b/ceutilw.bat deleted file mode 100644 index a789019..0000000 --- a/ceutilw.bat +++ /dev/null @@ -1,13 +0,0 @@ -@REM To run the script set VCPKG_ROOT environmental variable for vcpkg root folder -if exist buildw ( -echo deleting -rmdir /s /q buildw -) -cmake -G "Visual Studio 17 2022" -A x64 -B ./buildw -S ./ -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake" -DCMAKE_INSTALL_PREFIX="%VCPKG_ROOT%/installed/x64-windows/" -DCMAKE_DEBUG_POSTFIX=d -cd buildw -cmake --build . --config Release -cmake --install . --config Release -cmake --build . --config Debug -cmake --install . --config Debug - -cd .. diff --git a/examples/Timer/CMakeLists.txt b/examples/Timer/CMakeLists.txt deleted file mode 100644 index b38146d..0000000 --- a/examples/Timer/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -cmake_minimum_required(VERSION 3.0.0) -project(Timer VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/Timer/Timer.sh b/examples/Timer/Timer.sh deleted file mode 100644 index 84086f0..0000000 --- a/examples/Timer/Timer.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - diff --git a/examples/Timer/Timer/Timer.sln b/examples/Timer/Timer/Timer.sln deleted file mode 100644 index 10d800e..0000000 --- a/examples/Timer/Timer/Timer.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Timer", "Timer.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} - EndGlobalSection -EndGlobal diff --git a/examples/Timer/Timer/Timer.vcxproj b/examples/Timer/Timer/Timer.vcxproj deleted file mode 100644 index 3ba5c6e..0000000 --- a/examples/Timer/Timer/Timer.vcxproj +++ /dev/null @@ -1,162 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} - Win32Proj - Timer - 10.0 - - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include - - - Windows - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release - ceUtil.lib;%(AdditionalDependencies) - - - - - - \ No newline at end of file diff --git a/examples/Timer/Timer/Timer.vcxproj.filters b/examples/Timer/Timer/Timer.vcxproj.filters deleted file mode 100644 index ff3b72e..0000000 --- a/examples/Timer/Timer/Timer.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - - \ No newline at end of file diff --git a/examples/Timer/src/Timer.cpp b/examples/Timer/src/Timer.cpp deleted file mode 100644 index 5f958a5..0000000 --- a/examples/Timer/src/Timer.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include -#include "ce/ceUtil.h" -#include -using namespace ce; -#define TMR_ID1 201 -class MyApp : public wxAppConsole -{ - public: - virtual bool OnInit(); - void OnTmrEvent(wxThreadEvent& event); - ceLog* _log; -}; -IMPLEMENT_APP(MyApp) -bool MyApp::OnInit() -{ - this->_log = new ceLog("./", 1); - this->_log->SetEnPrintf(true); - ceWxTmr* t = new ceWxTmr(this,TMR_ID1,2000);// 2 seconds - t->Start(); - Connect(TMR_ID1, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnTmrEvent)); - return true; -} - -void MyApp::OnTmrEvent(wxThreadEvent& event) -{ - static int c = 0; - std::vector v = event.GetPayload>(); - this->_log->Print("Ev = "+ std::to_string(int(v[0]))); - if(++c >= 3){ - Exit(); - } -} \ No newline at end of file diff --git a/examples/Timer/timerw.bat b/examples/Timer/timerw.bat deleted file mode 100644 index 736e72e..0000000 --- a/examples/Timer/timerw.bat +++ /dev/null @@ -1,11 +0,0 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -Timer.exe -@REM cpack --verbose -cd ../.. diff --git a/examples/WxSerial/CMakeLists.txt b/examples/WxSerial/CMakeLists.txt deleted file mode 100644 index 00596a4..0000000 --- a/examples/WxSerial/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(WxSerial VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/WxSerial/WxSerial.sh b/examples/WxSerial/WxSerial.sh deleted file mode 100644 index 84086f0..0000000 --- a/examples/WxSerial/WxSerial.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - diff --git a/examples/WxSerial/src/WxSerial.cpp b/examples/WxSerial/src/WxSerial.cpp deleted file mode 100644 index cbe7103..0000000 --- a/examples/WxSerial/src/WxSerial.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include -#include "ce/ceUtil.h" -#include -using namespace ce; -#define WXSERIAL_ID1 201 -class MyApp : public wxAppConsole -{ - public: - virtual bool OnInit(); - void OnSerialEvent(wxThreadEvent& event); - ceLog* _log; -}; -IMPLEMENT_APP(MyApp) -bool MyApp::OnInit() -{ - this->_log = new ceLog("./", 1); - this->_log->SetEnPrintf(true); - ceWxSerial* com = new ceWxSerial(this,WXSERIAL_ID1,100,"/dev/ttyS6",9600,8,'N',1); - com->Open(); - Connect(WXSERIAL_ID1, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); - char tx[] = "Hello"; - com->Write(tx); - return true; -} - -void MyApp::OnSerialEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - this->_log->Print("Ev = "+ ceMisc::cvec2str(v)); - Exit(); -} \ No newline at end of file diff --git a/examples/WxSerial/wxserialw.bat b/examples/WxSerial/wxserialw.bat deleted file mode 100644 index 75d5922..0000000 --- a/examples/WxSerial/wxserialw.bat +++ /dev/null @@ -1,11 +0,0 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -WxSerial.exe -@REM cpack --verbose -cd ../.. diff --git a/examples/interface/CMakeLists.txt b/examples/interface/CMakeLists.txt deleted file mode 100644 index 25c02c2..0000000 --- a/examples/interface/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -cmake_minimum_required(VERSION 3.0.0) -project(interface VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} -${PROJECT_SOURCE_DIR}/src/main.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/interface/interface.bat b/examples/interface/interface.bat deleted file mode 100644 index 3c521a3..0000000 --- a/examples/interface/interface.bat +++ /dev/null @@ -1,11 +0,0 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -interface.exe -@REM cpack --verbose -cd ../.. diff --git a/examples/interface/interface.sh b/examples/interface/interface.sh deleted file mode 100644 index 84086f0..0000000 --- a/examples/interface/interface.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - diff --git a/examples/interface/src/main.cpp b/examples/interface/src/main.cpp deleted file mode 100644 index 56cff89..0000000 --- a/examples/interface/src/main.cpp +++ /dev/null @@ -1,29 +0,0 @@ - #include -#include "ce/ceMacros.h" -#include "ce/ceMisc.h" -#include -using namespace std; -using namespace ce; - -#define TMR_ID1 201 -class MyApp : public wxAppConsole -{ - public: - virtual bool OnInit(); - void OnTmrEvent(wxTimerEvent& WXUNUSED(event)); -}; -IMPLEMENT_APP(MyApp) -bool MyApp::OnInit() -{ - wxTimer* t = new wxTimer(this,TMR_ID1); - t->Start(1000); - Connect(TMR_ID1, wxEVT_TIMER, wxTimerEventHandler(MyApp::OnTmrEvent)); - return true; -} - -void MyApp::OnTmrEvent(wxTimerEvent& WXUNUSED(event)) -{ - std::cout << "tmr ev" << std::endl; - -} - diff --git a/examples/interface/vsprj/interface.sln b/examples/interface/vsprj/interface.sln deleted file mode 100644 index 8e00a41..0000000 --- a/examples/interface/vsprj/interface.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "interface", "interface.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} - EndGlobalSection -EndGlobal diff --git a/examples/interface/vsprj/interface.vcxproj b/examples/interface/vsprj/interface.vcxproj deleted file mode 100644 index 0b9725f..0000000 --- a/examples/interface/vsprj/interface.vcxproj +++ /dev/null @@ -1,162 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} - Win32Proj - interface - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(VCPKG_ROOT)\installed\include - - - Windows - true - true - true - $(VCPKG_ROOT)\installed\Release - ceUtil.lib;%(AdditionalDependencies) - - - - - - \ No newline at end of file diff --git a/examples/interface/vsprj/interface.vcxproj.filters b/examples/interface/vsprj/interface.vcxproj.filters deleted file mode 100644 index bf96c1c..0000000 --- a/examples/interface/vsprj/interface.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - - \ No newline at end of file diff --git a/include/ce/ceDES.h b/include/ce/ceDES.h index 798348f..5f5404b 100644 --- a/include/ce/ceDES.h +++ b/include/ce/ceDES.h @@ -1,71 +1,474 @@ -// Description: Simple functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) -// Class implementation of the following repository: https://github.com/yan9a/ceDES +///////////////////////////////////////////////////////////////////////////// +// File: cedes.h +// Description: Simple C functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) +// Repository: https://github.com/yan9a/cedes // WebSite: http://cool-emerald.blogspot.com // MIT License (https://opensource.org/licenses/MIT) // Copyright (c) 2023 Yan Naing Aye - +///////////////////////////////////////////////////////////////////////////// // Related links // https://www.rapidtables.com/convert/number/ascii-to-hex.html // https://emvlab.org/descalc/ // https://paymentcardtools.com/crypto-calculators/des-calculator // https://github.com/yan9a/cecpp/blob/master/des_cryptopp/main.cpp +///////////////////////////////////////////////////////////////////////////// #ifndef CEDES_H #define CEDES_H -#include +#if defined(__cplusplus) +extern "C" { +#endif + +// Functions +// void ceDES_Encrypt(unsigned char *dMes,unsigned char *dKey); +// void ceDES_Decrypt(unsigned char *dMes,unsigned char *dKey); +// void ceTDES_Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR); +// void ceTDES_Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR); + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +//----------------------------------------------------------------------------- +// Init permutation table +// 64 bit data -> 64 bit data +const unsigned char IP_table[64] = { + 58, 50, 42, 34, 26, 18, 10, 2, + 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, + 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, + 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, + 63, 55, 47, 39, 31, 23, 15, 7 }; +//----------------------------------------------------------------------------- +//Permuted Choice 1 +// Key permutation table +// 64 bit key data -> 56 bit key data +const unsigned char PC1_table[56] = { + 57, 49, 41, 33, 25, 17, 9, + 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, + 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, + 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, + 21, 13, 5, 28, 20, 12, 4 }; +//----------------------------------------------------------------------------- +// Key shift table +const unsigned char LeftShift_table[16] = { + 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; +//----------------------------------------------------------------------------- +// Key Compression permutation table +// 56 bit key data -> 48 bit +const unsigned char PC2_table[48] = { + 14, 17, 11, 24, 1, 5, 3, 28, + 15, 6, 21, 10, 23, 19, 12, 4, + 26, 8, 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, 30, 40, + 51, 45, 33, 48, 44, 49, 39, 56, + 34, 53, 46, 42, 50, 36, 29, 32 }; +//----------------------------------------------------------------------------- +// Expansion permutation table +// 32 bit data -> 48 bit data +const unsigned char E_table[48] = { + 32, 1, 2, 3, 4, 5, + 4, 5, 6, 7, 8, 9, + 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, + 16, 17, 18, 19, 20, 21, + 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, + 28, 29, 30, 31, 32, 1 }; +//----------------------------------------------------------------------------- +const unsigned char S[8][4][16] = { + { + {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, + {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, + {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, + {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} + }, + { + {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, + {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, + {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, + {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} + }, + { + {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, + {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, + {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, + {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} + }, + { + {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, + {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, + {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, + {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} + }, + { + {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, + {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, + {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, + {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} + }, + { + {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, + {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, + {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, + {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} + }, + { + {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, + {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, + {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, + {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} + }, + { + {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, + {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, + {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, + {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} + } + }; +//----------------------------------------------------------------------------- +// Strait permutation table +// 32 bit data -> 32 bit data +const unsigned char P_table[32] = { + 16, 7, 20, 21, 29, 12, 28, 17, + 1, 15, 23, 26, 5, 18, 31, 10, + 2, 8, 24, 14, 32, 27, 3, 9, + 19, 13, 30, 6, 22, 11, 4, 25 }; +//----------------------------------------------------------------------------- +// Inverse permutation table +// 64 bit data -> 64 bit data +const unsigned char InverseIP_table[64] = { + 40, 8, 48, 16, 56, 24, 64, 32, + 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, + 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, + 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, + 33, 1, 41, 9, 49, 17, 57, 25 }; +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//pData =input to permutate +//ni =number of input bytes +//pTable =permutation table +//no =number of output bytes +void ceDES_Permutate(unsigned char *pData,unsigned char ni, + unsigned char *pTable,unsigned char no) +{ + unsigned char temp[8]; + unsigned char i,j,x; + unsigned char ByteI,BitIndex; + + for(i=0;i>3];//divided by 8 + BitIndex =7-(BitIndex & 7);//mod 8 + x|=((ByteI>>BitIndex) & 0x01); + } + *pData=x; + } + +}; +//----------------------------------------------------------------------------- +//nKey -Key to shift +//b -number of bits +//priority to speed rather than code size +void ceDES_LeftShift(unsigned char *nKey,unsigned char b) +{ + unsigned char x,y,c; + c=8-b; + + //avoid loop to get linear code + x=nKey[6]; + nKey[6]=x<>c; + + x=nKey[5]; + nKey[5]=(x<>c; + + x=nKey[4]; + nKey[4]=(x<>c; + + x=nKey[3]; + nKey[3]=(x<>c; + + x<<=4; + nKey[6]|=x>>c; + + x=nKey[2]; + nKey[2]=(x<>c; + + x=nKey[1]; + nKey[1]=(x<>c; + + x=nKey[0]; + nKey[0]=(x<>c; + + x=(b==1)?0xEF:0xCF; + x &=nKey[3]; + nKey[3]=x|(y<<4); +}; +//----------------------------------------------------------------------------- +//nKey -Key to shift +//b -number of bits +//written for speed +void ceDES_RightShift(unsigned char *nKey,unsigned char b) +{ + unsigned char x,y,c; + c=8-b; + + //avoid loop to get linear code + x=nKey[0]; + nKey[0]=x>>b; + y=x<>b)|y; + y=x<>b)|y; + y=x<>b)|y; + y=x<>=4; + nKey[0]|=x<>b)|y; + y=x<>b)|y; + y=x<>b)|y; + y=x<>4); +}; +//----------------------------------------------------------------------------- +//written for speed +void ceDES_Expand(unsigned char *R) +{ + unsigned char a,b,c,d,x; + a=R[0]; + b=R[1]; + c=R[2]; + d=R[3]; + + x=(d<<7) & 0x80;//bit 32 to 1 + x|=((a>>1) & 0x7C); + x|=((a>>3) & 0x03); + R[0]=x; + + x=(a<<5) & 0xE0; + x|=(b>>3) & 0x10; + x|=(a<<3) & 0x08; + x|=(b>>5) & 0x07; + R[1]=x; + + x=(b<<3) & 0xC0; + x|=((b<<1) & 0x3E); + x|=((c>>7) & 0x01); + R[2]=x; + + x=(b<<7) & 0x80; + x|=((c>>1) & 0x7C); + x|=((c>>3) & 0x03); + R[3]=x; + + x=(c<<5) & 0xE0; + x|=(d>>3) & 0x10; + x|=(c<<3) & 0x08; + x|=(d>>5) & 0x07; + R[4]=x; + + x=(d<<3) & 0xC0; + x|=((d<<1) & 0x3E); + x|=((a>>7) & 0x01); + R[5]=x; +}; +//----------------------------------------------------------------------------- +//written for speed +void ceDES_F(unsigned char *R,unsigned char *K) +{ + unsigned char i,r,c; + + //special function for expansion to improve speed + ceDES_Expand(R); + + for(i=0;i<6;i++) K[i]^=R[i]; + + //R[0]=S0 S1 + c=(K[0]>>3) & 0x0F; + r=(K[0]>>2) & 1; + r|=(K[0]>>6) & 2; + R[0]=(S[0][r][c])<<4; + + c=(K[0]<<3) & 0x08; + c |=(K[1]>>5) & 0x07; + r=(K[1]>>4) & 1; + r|=(K[0] & 2); + R[0]|=(S[1][r][c]); + + //R[1]=S2 S3 + c=(K[1]<<1) & 0x0E; + c|=(K[2]>>7) & 1; + r=(K[2]>>6) & 1; + r|=(K[1]>>2) & 2; + R[1]=(S[2][r][c])<<4; + + c=(K[2]>>1) & 0x0F; + r=K[2] & 1; + r|=(K[2]>>4) & 2; + R[1]|=(S[3][r][c]); + + //R[2]=S4 S5 + c=(K[3]>>3) & 0x0F; + r=(K[3]>>2) & 1; + r|=(K[3]>>6) & 2; + R[2]=(S[4][r][c])<<4; + + c=(K[3]<<3) & 0x08; + c |=(K[4]>>5) & 0x07; + r=(K[4]>>4) & 1; + r|=(K[3] & 2); + R[2]|=(S[5][r][c]); + + //R[3]=S6 S7 + c=(K[4]<<1) & 0x0E; + c|=(K[5]>>7) & 1; + r=(K[5]>>6) & 1; + r|=(K[4]>>2) & 2; + R[3]=(S[6][r][c])<<4; + + c=(K[5]>>1) & 0x0F; + r=K[5] & 1; + r|=(K[5]>>4) & 2; + R[3]|=(S[7][r][c]); + + //Permutate the S box output + ceDES_Permutate(R,4,(unsigned char *)P_table,4);//32 bit output +}; +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//dMes=Message to encrypt +//dKey=Key +void ceDES_Encrypt(unsigned char *dMes,unsigned char *dKey) +{ + unsigned char Kn[7]; + unsigned char Rn_1[6]; + unsigned char n,i; + unsigned char dKeyC[8]; + for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key + + ceDES_Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output + ceDES_Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output + for(n=0;n<16;n++) + { + ceDES_LeftShift(dKeyC,LeftShift_table[n]); + for(i=0;i<7;i++) Kn[i]=dKeyC[i]; + ceDES_Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output + for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; + ceDES_F(Rn_1,Kn); + + if(n>=15) + { + for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; + break; + } + for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; + for(i=0;i<4;i++) dMes[i]=dMes[i+4]; + for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; + } + ceDES_Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output +}; +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//dMes=Message to decrypt +//dKey=Key +void ceDES_Decrypt(unsigned char *dMes,unsigned char *dKey) +{ + unsigned char Kn[7]; + unsigned char Rn_1[6]; + unsigned char n,i; + unsigned char dKeyC[8]; + for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key + + ceDES_Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output + ceDES_Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output + + for(n=0;n<16;n++) + { + for(i=0;i<7;i++) Kn[i]=dKeyC[i]; + ceDES_Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output + for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; + ceDES_F(Rn_1,Kn); + + if(n>=15) + { + for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; + break; + } + for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; + for(i=0;i<4;i++) dMes[i]=dMes[i+4]; + for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; + ceDES_RightShift(dKeyC,LeftShift_table[15-n]); + } + ceDES_Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output +}; +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//dMes=Message to encrypt +//dKeyL=KeyLeft +//dKeyR=KeyRight +void ceTDES_Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) +{ + ceDES_Encrypt(dMes,dKeyL); + ceDES_Decrypt(dMes,dKeyR); + ceDES_Encrypt(dMes,dKeyL); +}; +//----------------------------------------------------------------------------- +//dMes=Message to decrypt +//dKeyL=KeyLeft +//dKeyR=KeyRight +void ceTDES_Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) +{ + ceDES_Decrypt(dMes,dKeyL); + ceDES_Encrypt(dMes,dKeyR); + ceDES_Decrypt(dMes,dKeyL); +}; +//----------------------------------------------------------------------------- + +///////////////////////////////////////////////////////////////////////////// + +#if defined(__cplusplus) +} +#endif -namespace ce { - class ceDES { - private: - //----------------------------------------------------------------------------- - // Init permutation table - // 64 bit data -> 64 bit data - static const unsigned char IP_table[64]; - //----------------------------------------------------------------------------- - //Permuted Choice 1 - // Key permutation table - // 64 bit key data -> 56 bit key data - static const unsigned char PC1_table[56]; - //----------------------------------------------------------------------------- - // Key shift table - static const unsigned char LeftShift_table[16]; - //----------------------------------------------------------------------------- - // Key Compression permutation table - // 56 bit key data -> 48 bit - static const unsigned char PC2_table[48]; - //----------------------------------------------------------------------------- - // Expansion permutation table - // 32 bit data -> 48 bit data - static const unsigned char E_table[48]; - //----------------------------------------------------------------------------- - static const unsigned char S[8][4][16]; - //----------------------------------------------------------------------------- - // Strait permutation table - // 32 bit data -> 32 bit data - static const unsigned char P_table[32]; - //----------------------------------------------------------------------------- - // Inverse permutation table - // 64 bit data -> 64 bit data - static const unsigned char InverseIP_table[64]; - //----------------------------------------------------------------------------- - static unsigned char Kn[7]; - static unsigned char Rn_1[6]; - //----------------------------------------------------------------------------- - static void Permutate(unsigned char* pData, unsigned char ni, - unsigned char* pTable, unsigned char no); - static void LeftShift(unsigned char* nKey, unsigned char b); - static void RightShift(unsigned char* nKey, unsigned char b); - static void Expand(unsigned char* R); - static void F(unsigned char* R, unsigned char* K); - //----------------------------------------------------------------------------- - static void Encrypt(unsigned char* dMes, unsigned char* dKey); // DES encryption - static void Decrypt(unsigned char* dMes, unsigned char* dKey); // DES decryption - static void Encrypt(unsigned char* dMes, unsigned char* dKeyL, unsigned char* dKeyR);// TDES encryption - static void Decrypt(unsigned char* dMes, unsigned char* dKeyL, unsigned char* dKeyR);// TDES decryption - public: - static std::string Encrypt(std::string dMes, std::string dKey); // DES encryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes - static std::string Decrypt(std::string dMes, std::string dKey); // DES decryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes - }; -} // namespace ce #endif // CEDES_H \ No newline at end of file diff --git a/include/ce/ceFraChecksum.h b/include/ce/ceFraChecksum.h deleted file mode 100644 index 30389b2..0000000 --- a/include/ce/ceFraChecksum.h +++ /dev/null @@ -1,49 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceFraChecksum.h -// Description: Byte stuffing- sending and receiving frames with checksum -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_FRACHECKSUM_H -#define CE_FRACHECKSUM_H - -#include - -#define STX 0x02 -#define ETX 0x03 -#define DLE 0x10 - -#define CE_FRAME_TX_BUF_SIZE 1024 -#define CE_FRAME_RX_BUF_SIZE 1024 - -// frame state definition -#define CE_FRAME_IGNORE 0 -#define CE_FRAME_RECEIVING 1 -#define CE_FRAME_ESCAPE 2 -#define CE_FRAME_CHKSUM 3 - -namespace ce { - -//----------------------------------------------------------------------------- -class ceFraChecksum { - int rState; -protected: - size_t TxN;//number of transmitting bytes - size_t RxN;//number of receiving bytes - char tb[CE_FRAME_TX_BUF_SIZE];//transmit buffer - char rb[CE_FRAME_RX_BUF_SIZE];//receiving data -public: - ceFraChecksum(); - size_t GetTxN(); - size_t GetRxN(); - char* GetTxBuf(); - char* GetRxBuf(); - virtual size_t SetTxFrame(char* d, size_t n); - virtual uint8_t Checksum(char* s, size_t len); - virtual size_t ReceiveRxFrame(char c);//get receiving frame from received char -}; -//----------------------------------------------------------------------------- -} // namespace ce - -#endif // CE_FRACHECKSUM_H \ No newline at end of file diff --git a/include/ce/ceFraCmd.h b/include/ce/ceFraCmd.h index a2c36e1..0957b26 100644 --- a/include/ce/ceFraCmd.h +++ b/include/ce/ceFraCmd.h @@ -1,5 +1,5 @@ ///////////////////////////////////////////////////////////////////////////// -// Name: ceFraCmd.h +// Name: cefracmd.h // Description: Byte stuffing- sending and receiving commands as frames // Author: Yan Naing Aye // Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html @@ -7,7 +7,7 @@ #ifndef CE_FRACMD_H #define CE_FRACMD_H -#include "ce/ceFrame.h" +#include "ce/ceframe.h" namespace ce { //----------------------------------------------------------------------------- class ceFraCmd : public ceFrame { @@ -17,6 +17,45 @@ class ceFraCmd : public ceFrame { size_t ReceiveRxFrame(char ch) override;//get receiving frame from received char }; //----------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +inline ceFraCmd::ceFraCmd() :ceFrame() { + +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +inline size_t ceFraCmd::SetTxFrame(char* d, size_t n) +{ + int i = 0; + if (n >= CE_FRAME_TX_BUF_SIZE) n = CE_FRAME_TX_BUF_SIZE - 1; //discard policy + for (int j = 0; j < n; j++) { + tb[i++] = d[j]; + } + tb[i++] = 0x0D;//end of frame + TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +inline size_t ceFraCmd::ReceiveRxFrame(char ch) +{ + static int n = 0; + if (ch >= 32 && ch <= 126) { + this->rb[n++] = ch; + this->RxN = 0; + } + + if (ch == 0x0D || n >= (CE_FRAME_RX_BUF_SIZE - 1)) { + this->RxN = n; + this->rb[n] = 0;//null termination + n = 0; + return this->RxN; + } + return 0; +} + +///////////////////////////////////////////////////////////////////////////// } // namespace ce #endif // CE_FRACMD_H \ No newline at end of file diff --git a/include/ce/ceFrame.h b/include/ce/ceFrame.h index d3dd6d3..e0f5cfa 100644 --- a/include/ce/ceFrame.h +++ b/include/ce/ceFrame.h @@ -1,5 +1,5 @@ ///////////////////////////////////////////////////////////////////////////// -// Name: ceFrame.h +// Name: ceframe.h // Description: Byte stuffing- sending and receiving frames // Author: Yan Naing Aye // Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html @@ -9,6 +9,7 @@ #define CE_FRAME_H #include +#include #define STX 0x02 #define ETX 0x03 @@ -45,6 +46,122 @@ class ceFrame { virtual size_t ReceiveRxFrame(char c);//get receiving frame from received char }; //----------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +inline ceFrame::ceFrame() :TxN(0), RxN(0), rState(CE_FRAME_IGNORE) { + rb[0] = 0; + tb[0] = 0; +} +//----------------------------------------------------------------------------- +inline char* ceFrame::GetTxBuf() { + return tb; +} +//----------------------------------------------------------------------------- +inline char* ceFrame::GetRxBuf() { + return rb; +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +inline size_t ceFrame::SetTxFrame(char* d, size_t n) +{ + unsigned int txcrc = 0xFFFF;//initialize crc + char c; + int i = 0, j = 0; + tb[i++] = STX;//start of frame + for (j = 0; j < n; j++) { + c = d[j]; + if ((c == STX) || (c == ETX) || (c == DLE)) tb[i++] = (DLE); + tb[i++] = c; + } + tb[i++] = (ETX);//end of frame + + txcrc = CRC16(d, n, txcrc);//calculate crc + tb[i++] = txcrc & 0xFF; + tb[i++] = (txcrc >> 8) & 0xFF; + TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +//Inputs +//s : pointer to input char string +//len: string len (maximum 255) +//crc: initial CRC value + +//Output +//Returns calculated CRC +inline uint16_t ceFrame::CRC16(char* s, size_t len, uint16_t crc) +{ + //CRC Order: 16 + //CCITT(recommendation) : F(x)= x16 + x12 + x5 + 1 + //CRC Poly: 0x1021 + //Operational initial value: 0xFFFF + //Final xor value: 0 + size_t i, j; + for (i = 0; i < len; i++, s++) { + crc ^= ((unsigned int)(*s) & 0xFF) << 8; + for (j = 0; j < 8; j++) { + if (crc & 0x8000) crc = (crc << 1) ^ 0x1021; + else crc <<= 1; + } + } + return (crc & 0xFFFF);//truncate last 16 bit +} +//----------------------------------------------------------------------------- +//get number of transmitting bytes +inline size_t ceFrame::GetTxN() +{ + return TxN; +} +//----------------------------------------------------------------------------- +//get number of receiving bytes +inline size_t ceFrame::GetRxN() +{ + return RxN; +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +inline size_t ceFrame::ReceiveRxFrame(char c) +{ + static char b; + unsigned int crc; + unsigned int rxcrc = 0xFFFF;//initialize CRC + switch (rState) { + case CE_FRAME_RECEIVING: + if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } + else if (c == ETX) { rState = CE_FRAME_RXCRC1; } + else if (c == DLE) { rState = CE_FRAME_ESCAPE; } + else { rb[RxN++] = c; } + break; + case CE_FRAME_ESCAPE: + rb[RxN++] = c; rState = CE_FRAME_RECEIVING; + break; + case CE_FRAME_RXCRC1: + b = c; rState = CE_FRAME_RXCRC2; + break; + case CE_FRAME_RXCRC2: + rState = CE_FRAME_IGNORE; + crc = ((int)c << 8 | ((int)b & 0xFF)) & 0xFFFF;//get received crc + rxcrc = CRC16(rb, RxN, rxcrc);//calculate crc + //printf("crc: %x rxcrc:%x \n",crc,rxcrc); + if (rxcrc == crc) { return RxN; }//if crc is correct + else { RxN = 0; }//discard the frame + break; + default: //case CE_FRAME_IGNORE: + if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } + break; + } + + if (RxN >= CE_FRAME_RX_BUF_SIZE) { + RxN = 0; + rState = CE_FRAME_IGNORE; + } + + return 0; +} + +///////////////////////////////////////////////////////////////////////////// } // namespace ce #endif // CE_FRAME_H \ No newline at end of file diff --git a/include/ce/ceI2C.h b/include/ce/ceI2C.h index 8b02027..d2bac36 100644 --- a/include/ce/ceI2C.h +++ b/include/ce/ceI2C.h @@ -1,16 +1,51 @@ -// File: ceI2C.h +///////////////////////////////////////////////////////////////////////////// +// File: cei2c.h // Description: ceI2C class to use i2c communication // WebSite: http://cool-emerald.blogspot.com // MIT License (https://opensource.org/licenses/MIT) // Copyright (c) 2018 Yan Naing Aye // Reference : http://elinux.org/Interfacing_with_I2C_Devices +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H #ifndef CEI2C_H #define CEI2C_H -#include "ce/ceMacros.h" // macros - #ifdef CE_LINUX #include #include @@ -19,8 +54,8 @@ #endif #include -#include -#include +#include +#include #include namespace ce { @@ -40,5 +75,87 @@ class ceI2C int fd; }; +///////////////////////////////////////////////////////////////////////////// +// Implementation + +template +std::string ceI2C::ToString(T a) +{ + std::ostringstream ss; + ss << a; + return ss.str(); +} + +inline ceI2C::ceI2C() +{ + //ctor +} + +inline ceI2C::ceI2C(int bus_id, int slave_address) +{ + Begin(bus_id, slave_address); +} + +inline ceI2C::~ceI2C() +{ + //dtor +#ifdef CE_LINUX + close(fd); +#else +#endif +} + +inline bool ceI2C::Begin(int bus_id, int slave_address) +{ + std::string filename = "/dev/i2c-"; + filename += ToString(bus_id); +#ifdef CE_LINUX + if ((fd = open(filename.c_str(), O_RDWR)) < 0) { + perror("Failed to open the i2c bus\n"); + return false; + } + if (ioctl(fd, I2C_SLAVE, slave_address) < 0) { + perror("Failed to acquire bus access and/or talk to slave.\n"); + return false; + } +#else +#endif + return true; +} + +inline bool ceI2C::Write(char* buf, int n) +{ +#ifdef CE_LINUX + if (write(fd, buf, n) != n) { + perror("Failed to write to the i2c bus.\n"); + return false; + } +#else +#endif + return true; +} + +inline bool ceI2C::Read(char* buf, int n) +{ +#ifdef CE_LINUX + if (read(fd, buf, n) != n) { + perror("Failed to read from the i2c bus.\n"); + return false; + } +#else +#endif + return true; +} + +inline void ceI2C::Close() +{ +#ifdef CE_LINUX + close(fd); +#else +#endif +} + +///////////////////////////////////////////////////////////////////////////// + } // namespace ce #endif // CEI2C_H diff --git a/include/ce/ceInterface.h b/include/ce/ceInterface.h deleted file mode 100644 index 5c551ce..0000000 --- a/include/ce/ceInterface.h +++ /dev/null @@ -1,36 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceInterface.h -// Description: Interface to communitcate modules -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_INTERFACE_H -#define CE_INTERFACE_H - -#include -#include -#include -#include -#include -#include -#include - -namespace ce { -class ceInterface { -public: - ceInterface(); - ceInterface(ceInterface* if, std::function,std::string,int>)> cbf); - virtual ~ceInterface(); - void check(); // to regularly check message queue (e.g. 10 ms) to trigger callback function - int send(std::tuple,std::string,int>); - void setRxCallback(std::function,std::string,int>)> cbf); - void setIf2Connect(ceInterface* if); -private: - std::queue,std::string,int>> _mes; - std::function,std::string,int>)> _cbf; - ceInterface* _if = nullptr; -}; - - -} // namespace ce -#endif // CE_INTERFACE_H diff --git a/include/ce/ceLog.h b/include/ce/ceLog.h index 4f16bb5..9afac48 100644 --- a/include/ce/ceLog.h +++ b/include/ce/ceLog.h @@ -1,5 +1,5 @@ ///////////////////////////////////////////////////////////////////////////// -// Name: ceLog.h +// Name: celog.h // Description: logging module // Author: Yan Naing Aye ///////////////////////////////////////////////////////////////////////////// @@ -7,14 +7,49 @@ #ifndef ceLog_H #define ceLog_H -#include +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + +#include #include #include #include #include #include -#include "ce/ceDateTime.h" -#include "ce/ceMacros.h" // macros +#include "ce/cedt.h" + #if defined(CE_WINDOWS) #include #define stat _stat @@ -58,6 +93,226 @@ class ceLog{ bool GetEnPrintf(); void SetEnPrintf(bool en); }; + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +inline ceLog::ceLog() +{ + SetPath(LOG_PATH); + SetExpiry(30); + SetExtension(".log"); + SetEnPrintf(false); +} + +inline ceLog::ceLog(std::string path, double expdays) +{ + SetPath(path); + SetExpiry(expdays); + SetExtension(".log"); + SetEnPrintf(true); +} + +inline void ceLog::SetPath(std::string path) +{ + this->m_path = path; +} + +inline std::string ceLog::GetPath() +{ + return this->m_path; +} + +inline void ceLog::SetExtension(std::string ext) +{ + this->m_extension = ext; +} + +inline std::string ceLog::GetExtension() +{ + return this->m_extension; +} + +inline ceLog::~ceLog() +{ + +} + +inline bool ceLog::GetEnPrintf() +{ + return this->m_enPrintf; +} + +inline void ceLog::SetEnPrintf(bool en) +{ + this->m_enPrintf = en; +} + +inline double ceLog::GetExpiry() +{ + return this->m_expiry_days; +} + +inline void ceLog::SetExpiry(double days) +{ + this->m_expiry_days = days; +} + +inline void ceLog::SetTimezone(double a)//set time zone +{ + this->m_dt.SetTimezone(a); +} + +inline void ceLog::SetTimezone()//set local time zone +{ + this->m_dt.SetTimezone(); +} + +inline double ceLog::GetTimezone()//get time zone +{ + return this->m_dt.tz(); +} + +inline int ceLog::Write(std::string mes) +{ + std::ofstream wfile; + int r = -1; + this->m_dt.Set2Now(); + std::string logpath = this->m_path + "L" + this->m_dt.ToString("%yyyy-%mm-%dd") + ".log"; + try { + wfile.open(logpath.c_str(), std::fstream::out | std::fstream::app); + if (wfile.is_open()) { + wfile << this->m_dt.ToString("%HH:%nn:%ss.%lll") << " " << mes << std::endl; + r = 0; + } + wfile.close(); + } + catch (...) { + perror("ceLog error in writing"); + } + return r; +} + +inline int ceLog::Print(std::string mes) +{ + if (this->m_enPrintf) { + // printf("%s\n",mes.c_str()); + std::cout << mes << std::endl; + } + return Write(mes); +} + +inline void ceLog::Clean(std::string path, std::string extension, double expiry_seconds) +{ + std::vector filenames; + std::string fn = ""; + std::string fpath = ""; + double fileage = 0; + int pos = 0; + + try { + ReadDir(path, filenames); + int nfiles = (int)filenames.size(); +#if ceLog_PRINT == 1 + printf("Number of items: %d \n", nfiles); +#endif + + if (nfiles <= 2) { //if only . and .. + return; + } + this->m_dt.Set2Now(); + + for (int i = 0; i < nfiles; i++) { + fn = filenames.at(i); +#if ceLog_PRINT == 1 + printf("File name: %s \n", fn.c_str()); +#endif + pos = (int)fn.find(extension); + if (pos >= 0) { + fpath = path + fn; + this->m_ft.SetJD(LastModified(fpath)); +#if ceLog_PRINT ==1 + printf("Modified time: %s \n", m_ft.DateTimeString().c_str()); +#endif + fileage = (this->m_dt.jd() - this->m_ft.jd()) * 86400.0; + if (fileage > expiry_seconds) { + remove(fpath.c_str()); +#if ceLog_PRINT == 1 + printf("%s has been deleted \n", fpath.c_str()); + //this->Write("Deleted "+fp); +#endif + } + } + } + } + catch (...) { + perror("ceLog error in cleaning\n"); + } +} +inline void ceLog::Clean() //clean old log files +{ + this->Clean(this->m_path, this->m_extension, this->m_expiry_days * 86400); +} + +//http://www.martinbroadhurst.com/list-the-files-in-a-directory-in-c.html +#ifdef CE_WINDOWS +inline void ceLog::ReadDir(const std::string& name, std::vector& v) +{ + std::string pattern(name); + pattern.append("\\*"); + //WIN32_FIND_DATA data; + WIN32_FIND_DATAA data; + HANDLE hFind; + + WCHAR wstr[256]; + //http://msdn.microsoft.com/en-us/library/cc500362.aspx + MultiByteToWideChar(0, 0, pattern.c_str(), (int)pattern.length(), wstr, 256); + // LPCSTR lstr = wstr; + LPBOOL useddefault = FALSE; + // char fn[256]; + + if ((hFind = FindFirstFileA(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE) { + //if ((hFind = FindFirstFile(wstr, &data)) != INVALID_HANDLE_VALUE) { + do { + //WideCharToMultiByte(0, 0, data.cFileName, -1, fn, 256, NULL, useddefault); + //v.push_back(string(fn)); + v.push_back(data.cFileName); + } while (FindNextFileA(hFind, &data) != 0); + FindClose(hFind); + } +} +#else +inline void ceLog::ReadDir(const string& name, vector& v) +{ + DIR* dirp = opendir(name.c_str()); + struct dirent* dp; + while ((dp = readdir(dirp)) != NULL) { + v.push_back(dp->d_name); + } + closedir(dirp); +} +#endif + +inline double ceLog::LastModified(const std::string& name) +{ + struct stat attrib; + struct tm* fmt; + ceDateTime dt; + if (stat(name.c_str(), &attrib) == 0) + { + fmt = localtime(&(attrib.st_mtime)); + dt.SetDateTime(fmt->tm_year + 1900, fmt->tm_mon + 1, fmt->tm_mday, + fmt->tm_hour, fmt->tm_min, fmt->tm_sec); + // printf("Modified time: %s \n",dt.DateTimeString().c_str()); + } + else { + // printf("Error in using stat.\n"); + } + return dt.jd(); +} + +///////////////////////////////////////////////////////////////////////////// + } // namespace ce diff --git a/include/ce/ceMisc.h b/include/ce/ceMisc.h index 83ad009..96ca496 100644 --- a/include/ce/ceMisc.h +++ b/include/ce/ceMisc.h @@ -1,5 +1,5 @@ ///////////////////////////////////////////////////////////////////////////// -// Name: ceMisc.h +// Name: cemisc.h // Description: utility module // Author: Yan Naing Aye ///////////////////////////////////////////////////////////////////////////// @@ -7,13 +7,47 @@ #ifndef CEMISC_H #define CEMISC_H +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + #include #include #include #include #include #include -#include "ce/ceMacros.h" // macros #if defined(CE_WINDOWS) #include @@ -57,5 +91,219 @@ class ceMisc { static char get_ch(); // get char }; +///////////////////////////////////////////////////////////////////////////// +// Implementation + +// filter the string for alphanumeric characters only +inline std::string ceMisc::alnum(std::string str) +{ + str.erase(remove_if(str.begin(), str.end(), [](char ch) { + return !( + (ch >= '0' && ch <= '9') || + (ch >= 'A' && ch <= 'Z') || + (ch >= 'a' && ch <= 'z')); }), str.end()); + return str; +} + +// convert hex string to char vector +inline std::vector ceMisc::hex2cvec(std::string str) +{ + std::vector v; + str = ceMisc::alnum(str);// filter for alphanumeric characters + int n = (int)str.length(); + for (int i = 0; i < n; i += 2) + v.push_back((char)stoi(str.substr(i, 2), NULL, 16)); + return v; +} + +// convert hex string to byte string +inline std::string ceMisc::hex2str(std::string str) +{ + return ceMisc::cvec2str(ceMisc::hex2cvec(str)); +} + +// convert to hexadecimal string +inline std::string ceMisc::ToStr16(unsigned int u) +{ + std::ostringstream ss; + ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u; + return ss.str(); +} + +inline std::string ceMisc::ToStr16(int i) +{ + return ceMisc::ToStr16((unsigned int)i); +} + +inline std::string ceMisc::ToStr16(unsigned char c) +{ + return ceMisc::ToStr16((unsigned int)c); +} + +inline std::string ceMisc::ToStr16(char c) +{ + return ceMisc::ToStr16((unsigned char)c); +} + +// convert vector to hexadecimal string +inline std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { + std::vector uv(bv.begin(), bv.end()); + return ceMisc::ToStr16(uv, separator, prefix, postfix); +} + +// convert vector to hexadecimal string +inline std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { + std::ostringstream ss; + unsigned int u; + for (auto& c : bv) { + u = (unsigned char)c; + ss << prefix; + ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u << postfix; + if (&c != &bv.back()) ss << separator; + } + return ss.str(); +} + +// to hexadecimal string +inline std::string ceMisc::ToStr16(std::string str, std::string separator, std::string prefix, std::string postfix) +{ + return ceMisc::ToStr16(ceMisc::str2cvec(str), separator, prefix, postfix); +} + +// convert char vector to hex string +inline std::string ceMisc::cvec2hex(std::vector bv) { + std::ostringstream ss; + unsigned int u; + for (char& c : bv) { + u = (unsigned char)c; + ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u << " "; + } + return ss.str(); +} + +// convert char vector to string +inline std::string ceMisc::cvec2str(std::vector bv) { + std::ostringstream ss; + for (char& c : bv) { + ss << c; + } + return ss.str(); +} + + +// character vector to char* +inline void ceMisc::cvec2cptr(std::vector& v, char*& cstr, int& n) { + n = (int)v.size(); + cstr = v.data(); // reinterpret_cast(v.data()); +} + +// char* to char vector +inline std::vector ceMisc::cptr2cvec(char* cstr, int n) { + std::vector v(cstr, cstr + n); + return v; +} + +// convert char* to string +inline std::string ceMisc::cptr2str(char* cstr, int n) { + std::ostringstream ss; + for (int i = 0; i < n; i++) { + ss << cstr[i]; + } + return ss.str(); +} + +// string to char vector +inline std::vector ceMisc::str2cvec(std::string str) { + std::vector v(str.begin(), str.end()); + return v; +} + +inline std::string ceMisc::f2s(float f, int n) { + std::stringstream ss; + ss << std::fixed << std::setprecision(n) << f; + return ss.str(); +} + +inline std::vector ceMisc::splitStr(std::string str, std::string delimiter) +{ + size_t pos = 0; + std::vector tokens; + while ((pos = str.find(delimiter)) != std::string::npos) { + tokens.push_back(str.substr(0, pos)); + str.erase(0, pos + delimiter.length()); + } + tokens.push_back(str); + return tokens; +} + +inline std::string ceMisc::exepath() +{ +#ifdef CE_WINDOWS + char result[MAX_PATH]; + return std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); +#else + char result[PATH_MAX]; + ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); + return std::string(result, (count > 0) ? count : 0); +#endif +} + +inline std::string ceMisc::exedir() +{ + std::string str = exepath(); + std::size_t found = str.find_last_of("/\\"); + return str.substr(0, found + 1); +} + +inline bool ceMisc::kb_hit() // check keyboard hit +{ +#if defined(CE_WINDOWS) + return _kbhit(); +#else + // https://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux + termios term; + tcgetattr(0, &term); + + termios term2 = term; + term2.c_lflag &= ~ICANON; + tcsetattr(0, TCSANOW, &term2); + + int byteswaiting; + ioctl(0, FIONREAD, &byteswaiting); + + tcsetattr(0, TCSANOW, &term); + + return byteswaiting > 0; +#endif +} + +inline char ceMisc::get_ch() // get char +{ +#if defined(CE_WINDOWS) + return _getch(); +#else + //https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed + char buf = 0; + struct termios old = { 0 }; + if (tcgetattr(0, &old) < 0) + perror("tcsetattr()"); + old.c_lflag &= ~ICANON; + old.c_lflag &= ~ECHO; + old.c_cc[VMIN] = 1; + old.c_cc[VTIME] = 0; + if (tcsetattr(0, TCSANOW, &old) < 0) + perror("tcsetattr ICANON"); + if (read(0, &buf, 1) < 0) + perror("read()"); + old.c_lflag |= ICANON; + old.c_lflag |= ECHO; + if (tcsetattr(0, TCSADRAIN, &old) < 0) + perror("tcsetattr ~ICANON"); + return (buf); +#endif +} + +///////////////////////////////////////////////////////////////////////////// + } // namespace ce #endif // CEMISC_H diff --git a/include/ce/ceModbus.h b/include/ce/ceModbus.h index 6915cf1..2bd04a2 100644 --- a/include/ce/ceModbus.h +++ b/include/ce/ceModbus.h @@ -8,7 +8,7 @@ #ifndef CE_MODBUS_H #define CE_MODBUS_H -#include "ce/ceFrame.h" +#include "ce/ceframe.h" #define CR 0x0D #define LF 0x0A #define CE_NUMBER_OF_TICKS_TO_RESET 10 @@ -40,6 +40,205 @@ class ceModbus : public ceFrame { int GetResetTickCount(); }; //----------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +inline ceModbus::ceModbus() :ceFrame(), _count(0), _frameSize(8), _tick_n(0), _reset_tick(CE_NUMBER_OF_TICKS_TO_RESET) { +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +inline size_t ceModbus::SetTxFrame(char* d, size_t n) +{ + if (n > (CE_FRAME_TX_BUF_SIZE - 2)) return 0;// size error + uint16_t txcrc = 0xFFFF;//initialize crc + char c; + size_t i = 0, j = 0; + for (j = 0; j < n; j++) { + c = d[j]; + // no need to check c in building Modbus frame + this->tb[i++] = c; + } + txcrc = this->CRC16((char*)d, n, txcrc);//calculate crc + this->tb[i++] = txcrc & 0xFF; + this->tb[i++] = (txcrc >> 8) & 0xFF; + this->TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +//Inputs +//s : pointer to input char string +//len: string len (maximum 255) +//crc: initial CRC value + +//Output +//Returns calculated CRC + +// Ref: http://cool-emerald.blogspot.com/2009/09/crc-calculation-in-vb-and-c.html +inline uint16_t ceModbus::CRC16(char* s, size_t len, uint16_t crc) +{ + //CRC Order: 16 + //CRC Poly: 0x8005 <=> A001 + //Operational initial value: 0xFFFF + //Final xor value: 0 + size_t i, j; + for (i = 0; i < len; i++, s++) { + crc ^= ((unsigned int)(*s)) & 0xFF; + for (j = 0; j < 8; j++) { + if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; + else crc >>= 1; + } + } + return (crc & 0xFFFF);//truncate last 16 bit +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +// CRC16 is also included +inline size_t ceModbus::ReceiveRxFrame(char c) +{ + // accept any value even 0x0D to get 8 bytes + // (not using start and end 28 bit length mark condition) + this->_tick_n = 0; // reset for every rx ch + this->RxN = 0; + this->rb[this->_count++] = c; + + if (this->_count == 3) { + // check function + if (this->rb[1] == 0x06) { + this->_frameSize = 8; // reply for control cmd + } + else if (this->rb[1] == 0x03) { + uint8_t len = (uint8_t)this->rb[2]; + this->_frameSize = 5 + len; // reply for read cmd + } + } + + // instead use frame size for particular frame + if (this->_count >= this->_frameSize) { + this->rb[this->_count] = 0;//null termination + this->RxN = this->_count; + this->_count = 0; + this->_frameSize = 8;// default + this->_tick_n = 0; // will clear RxN when time out + // for (int i = 0; i < this->RxN; i++) printf("%02X ", (unsigned int)this->rb[i] & 0xFF); + // uint16_t rxcrc = ((uint16_t)this->rb[this->RxN-1] << 8 | ((uint16_t)this->rb[this->RxN - 2] & 0xFF)) & 0xFFFF;//get received crc + uint16_t computed_crc = 0xFFFF;//initialize CRC + computed_crc = this->CRC16(rb, RxN, computed_crc);//calculate crc + // printf("\nComputed crc: %02X \n",computed_crc); + if (computed_crc == 0) { + //this->RxN -= 2; + return (this->RxN); //if crc is correct return bytes including crc + } + else { this->RxN = 0; }//discard the frame + } + return 0; +} + +// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx +// return = 0 : if no reset, 1 : if reset +inline int ceModbus::Tick() +{ + if (this->_tick_n <= this->_reset_tick) { + this->_tick_n++; + } + else { + this->_count = 0; + this->_frameSize = 8;// default + this->RxN = 0; + } + return this->_tick_n; +} + +// command vector without CRC16 +// CRC16 will be calculated and appended +inline void ceModbus::SetCmd(std::vector v) +{ + this->SetTxFrame((char*)v.data(), v.size()); +} + +inline void ceModbus::SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data) +{ + uint8_t ah = uint8_t((addr >> 8) & 0xFF); + uint8_t al = uint8_t(addr & 0xFF); + std::vector v = { slaveid,func,ah,al }; + v.insert(v.end(), data.begin(), data.end()); + this->SetCmd(v); +} + +inline void ceModbus::SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay) +{ + uint8_t ah = uint8_t((addr >> 8) & 0xFF); + uint8_t al = uint8_t(addr & 0xFF); + std::vector v = { slaveid,0x06,ah,al,command,delay }; + this->SetCmd(v); +} + +inline void ceModbus::SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len) +{ + uint8_t ah = uint8_t((startAddr >> 8) & 0xFF); + uint8_t al = uint8_t(startAddr & 0xFF); + uint8_t lh = uint8_t((len >> 8) & 0xFF); + uint8_t ll = uint8_t(len & 0xFF); + std::vector v = { slaveid,0x03,ah,al,lh,ll }; + this->SetCmd(v); +} + +// extract vector of status from received byte array +// crc16 bytes will be neglected if included +inline std::vector ceModbus::GetStatus(char* d, size_t n) +{ + std::vector v; + if (n < 3) { + // perror("Modbus frame error in getting status"); + return v; + } + + if (d[1] != 0x03) { + // perror("Frame must be Modbus read status return to get status"); + return v; + } + + uint8_t len = (uint8_t)d[2]; // get len + if (n < ((size_t)len + 3)) { + // perror("Modbus frame length error in getting status"); + return v; + } + + uint16_t s; + uint8_t count = len >> 1;// 2 bytes each + for (uint8_t i = 0; i < count; i++) { + // for big endian + s = (uint8_t)d[3 + ((uint64_t)i << 1)]; + s <<= 8; + s |= (uint8_t)d[4 + ((uint64_t)i << 1)]; + v.push_back(s); + } + return v; +} + +inline std::vector ceModbus::GetTxVec() +{ + std::vector v((char*)tb, (char*)tb + this->TxN); + return v; +} + +inline std::vector ceModbus::GetRxVec() +{ + std::vector v((char*)rb, (char*)rb + this->RxN); + return v; +} + +inline void ceModbus::SetResetTickCount(int n) +{ + this->_reset_tick = n; +} + +inline int ceModbus::GetResetTickCount() +{ + return this->_reset_tick; +} + +///////////////////////////////////////////////////////////////////////////// } // namespace ce #endif // CE_MODBUS_H \ No newline at end of file diff --git a/include/ce/cePCA9535.h b/include/ce/cePCA9535.h index ec390f1..1c97ff6 100644 --- a/include/ce/cePCA9535.h +++ b/include/ce/cePCA9535.h @@ -1,10 +1,10 @@ ///////////////////////////////////////////////////////////////////////////// -// Name: cePCA9535.h +// Name: cepca9535.h // Description: cePCA9535 - Digital IO chip // Author: Yan Naing Aye ///////////////////////////////////////////////////////////////////////////// #include -#include "ce/ceI2C.h" +#include "ce/cei2c.h" #ifndef cePCA9535_H #define cePCA9535_H #ifndef PCA9535_REGISTERS @@ -42,5 +42,88 @@ class cePCA9535 { unsigned char conf0,unsigned char conf1, int i2cBus); }; +///////////////////////////////////////////////////////////////////////////// + +inline cePCA9535::cePCA9535(uint8_t i2cBusNo, uint8_t Addr) : _bus(i2cBusNo), _addr(Addr) +{ + +} + +inline cePCA9535::~cePCA9535() +{ + +} + +inline bool cePCA9535::SetReg(uint8_t rVal, uint8_t rAddr) +{ + return this->SetReg(_addr, rVal, rAddr, _bus); +} + +inline bool cePCA9535::GetReg(uint8_t& rVal, uint8_t rAddr) +{ + return this->GetReg(_addr, rVal, rAddr, _bus); +} + +inline bool cePCA9535::Init(unsigned char outp0, unsigned char outp1, + unsigned char polarity0, unsigned char polarity1, + unsigned char conf0, unsigned char conf1) +{ + return this->Init(_addr, + outp0, outp1, + polarity0, polarity1, + conf0, conf1, _bus); +} + +inline bool cePCA9535::SetReg(uint8_t chipAddr, uint8_t rVal, uint8_t rAddr, uint8_t i2cBus) +{ + char d[] = { 0,0 }; + ce::ceI2C chip1(i2cBus, chipAddr); + d[0] = rAddr; + d[1] = rVal; + bool r = chip1.Write(d, 2); // send new register data + chip1.Close(); + if (r == false) { + printf("cePCA9535 I2C error at bus = %d, addr = 0x%X\n", i2cBus, chipAddr); + // perror("cePCA9535 I2C error"); + } + return r; +} + +inline bool cePCA9535::GetReg(uint8_t chipAddr, uint8_t& rVal, uint8_t rAddr, uint8_t i2cBus) +{ + char d[] = { 0,0 }; + ce::ceI2C chip1(i2cBus, chipAddr); + d[0] = rAddr; + bool r = chip1.Write(d, 1); // send new register data + r = r && chip1.Read(d, 1); + chip1.Close(); + if (r) { + rVal = d[0]; + } + else { + printf("cePCA9535 I2C error at bus = %d, addr = 0x%X\n", i2cBus, chipAddr); + // perror("cePCA9535 I2C error"); + } + return r; +} + +// initialize PCA9535 +inline bool cePCA9535::Init(unsigned char chipAddr, + unsigned char outp0, unsigned char outp1, + unsigned char polarity0, unsigned char polarity1, + unsigned char conf0, unsigned char conf1, int i2cbus) +{ + bool r = true; + r = r && this->SetReg(chipAddr, polarity0, PCA9535_POLARITY_P0_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, polarity1, PCA9535_POLARITY_P1_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, conf0, PCA9535_CONF_P0_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, conf1, PCA9535_CONF_P1_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, outp0, PCA9535_OUTPUT_P0_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, outp1, PCA9535_OUTPUT_P1_ADDR, i2cbus); + return r; +} + +///////////////////////////////////////////////////////////////////////////// + } // namespace ce #endif // cePCA9535_H diff --git a/include/ce/ceSerial.h b/include/ce/ceSerial.h index 32c67ae..dd2d2e2 100644 --- a/include/ce/ceSerial.h +++ b/include/ce/ceSerial.h @@ -13,14 +13,28 @@ #ifndef CESERIAL_H #define CESERIAL_H #include -#include "ce/ceMacros.h" // macros +#include +#include +#include + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif #ifdef CE_WINDOWS #include #endif -namespace ce { - class ceSerial { private: char rxchar; @@ -47,9 +61,9 @@ class ceSerial { long Open(void);//return 0 if success void Close(); char ReadChar(bool& success);//return read char if success - bool WriteChar(char ch);////return success flag - bool Write(char *data);//write null terminated string and return success flag - bool Write(char *data,long n); + bool WriteChar(const char ch);////return success flag + bool Write(const char *data);//write null terminated string and return success flag + bool Write(const char *data,long n); bool SetRTS(bool value);//return success flag bool SetDTR(bool value);//return success flag bool GetCTS(bool& success); @@ -69,6 +83,578 @@ class ceSerial { float GetStopBits(); }; -} // namespace ce +//----------------------------------------------------------------------------- +#ifdef CE_WINDOWS + #define READ_TIMEOUT 10 // milliseconds +#else + #include + #include + #include + #include + #include +#endif + +inline void ceSerial::Delay(unsigned long ms) { +#ifdef CE_WINDOWS + Sleep(ms); +#else + usleep(ms*1000); +#endif +} + +inline ceSerial::ceSerial() : +#ifdef CE_WINDOWS + ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1) +#else + ceSerial("/dev/ttyS0", 9600, 8, 'N', 1) +#endif +{ + +} + +inline ceSerial::ceSerial(std::string Device, long BaudRate,long DataSize,char ParityType,float NStopBits):stdbaud(true) { +#ifdef CE_WINDOWS + hComm = INVALID_HANDLE_VALUE; +#else + fd = -1; +#endif // defined + SetBaudRate(BaudRate); + SetDataSize(DataSize); + SetParity(ParityType); + SetStopBits(NStopBits); + SetPortName(Device); +} + +inline ceSerial::~ceSerial() { + Close(); +} + +inline void ceSerial::SetPortName(std::string Device) { + port = Device; +} + +inline std::string ceSerial::GetPort() { + return port; +} + +inline void ceSerial::SetDataSize(long nbits) { + if ((nbits < 5) || (nbits > 8)) nbits = 8; + dsize=nbits; +} + +inline long ceSerial::GetDataSize() { + return dsize; +} + +inline void ceSerial::SetParity(char p) { + if ((p != 'N') && (p != 'E') && (p != 'O')) { +#ifdef CE_WINDOWS + if ((p != 'M') && (p != 'S')) p = 'N'; +#else + p = 'N'; +#endif + } + parity = p; +} + +inline char ceSerial::GetParity() { + return parity; +} + +inline void ceSerial::SetStopBits(float nbits) { + if (nbits >= 2) stopbits = 2; +#ifdef CE_WINDOWS + else if(nbits >= 1.5) stopbits = 1.5; +#endif + else stopbits = 1; +} + +inline float ceSerial::GetStopBits() { + return stopbits; +} + + +#ifdef CE_WINDOWS + +inline void ceSerial::SetBaudRate(long baudrate) { + stdbaud = true; + if (baudrate == 110) baud = CBR_110; + else if (baudrate == 300) baud = CBR_300; + else if (baudrate == 600) baud = CBR_600; + else if (baudrate == 1200) baud = CBR_1200; + else if (baudrate == 2400) baud = CBR_2400; + else if (baudrate == 4800) baud = CBR_4800; + else if (baudrate == 9600) baud = CBR_9600; + else if (baudrate == 14400) baud = CBR_14400; + else if (baudrate == 19200) baud = CBR_19200; + else if (baudrate == 38400) baud = CBR_38400; + else if (baudrate == 57600) baud = CBR_57600; + else if (baudrate == 115200) baud = CBR_115200; + else if (baudrate == 128000) baud = CBR_128000; + else if (baudrate == 256000) baud = CBR_256000; + else { + baud = baudrate; + stdbaud = false; + } +} + +inline long ceSerial::GetBaudRate() { + return baud; +} + +inline long ceSerial::Open() { + if (IsOpened()) return 0; +#ifdef UNICODE + std::wstring wtext(port.begin(),port.end()); +#else + std::string wtext = port; +#endif + hComm = CreateFile(wtext.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + 0); + if (hComm == INVALID_HANDLE_VALUE) {return -1;} + + if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) {return -1;}//purge + + //get initial state + DCB dcbOri; + bool fSuccess; + fSuccess = GetCommState(hComm, &dcbOri); + if (!fSuccess) {return -1;} + + DCB dcb1 = dcbOri; + + dcb1.BaudRate = baud; + + if (parity == 'E') dcb1.Parity = EVENPARITY; + else if (parity == 'O') dcb1.Parity = ODDPARITY; + else if (parity == 'M') dcb1.Parity = MARKPARITY; + else if (parity == 'S') dcb1.Parity = SPACEPARITY; + else dcb1.Parity = NOPARITY; + + dcb1.ByteSize = (BYTE)dsize; + + if(stopbits==2) dcb1.StopBits = TWOSTOPBITS; + else if (stopbits == 1.5) dcb1.StopBits = ONE5STOPBITS; + else dcb1.StopBits = ONESTOPBIT; + + dcb1.fOutxCtsFlow = false; + dcb1.fOutxDsrFlow = false; + dcb1.fOutX = false; + dcb1.fDtrControl = DTR_CONTROL_DISABLE; + dcb1.fRtsControl = RTS_CONTROL_DISABLE; + fSuccess = SetCommState(hComm, &dcb1); + this->Delay(60); + if (!fSuccess) {return -1;} + + fSuccess = GetCommState(hComm, &dcb1); + if (!fSuccess) {return -1;} + + osReader = { 0 };// Create the overlapped event. + // Must be closed before exiting to avoid a handle leak. + osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + + if (osReader.hEvent == NULL) {return -1;}// Error creating overlapped event; abort. + fWaitingOnRead = FALSE; + + osWrite = { 0 }; + osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (osWrite.hEvent == NULL) {return -1;} + + if (!GetCommTimeouts(hComm, &timeouts_ori)) { return -1; } // Error getting time-outs. + COMMTIMEOUTS timeouts; + timeouts.ReadIntervalTimeout = 20; + timeouts.ReadTotalTimeoutMultiplier = 15; + timeouts.ReadTotalTimeoutConstant = 100; + timeouts.WriteTotalTimeoutMultiplier = 15; + timeouts.WriteTotalTimeoutConstant = 100; + if (!SetCommTimeouts(hComm, &timeouts)) { return -1;} // Error setting time-outs. + return 0; +} + +inline void ceSerial::Close() { + if (IsOpened()) + { + SetCommTimeouts(hComm, &timeouts_ori); + CloseHandle(osReader.hEvent); + CloseHandle(osWrite.hEvent); + CloseHandle(hComm);//close comm port + hComm = INVALID_HANDLE_VALUE; + } +} + +inline bool ceSerial::IsOpened() { + if(hComm == INVALID_HANDLE_VALUE) return false; + else return true; +} + +inline bool ceSerial::Write(const char *data) { + if (!IsOpened()) { + return false; + } + BOOL fRes; + DWORD dwWritten; + long n = strlen(data); + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + // WriteFile failed, but it isn't delayed. Report error and abort. + if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} + else {// Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; + else fRes = TRUE;// Write operation completed successfully. + } + } + else fRes = TRUE;// WriteFile completed immediately. + return fRes; +} + +inline bool ceSerial::Write(const char *data,long n) { + if (!IsOpened()) { + return false; + } + BOOL fRes; + DWORD dwWritten; + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + // WriteFile failed, but it isn't delayed. Report error and abort. + if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} + else {// Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; + else fRes = TRUE;// Write operation completed successfully. + } + } + else fRes = TRUE;// WriteFile completed immediately. + return fRes; +} + +inline bool ceSerial::WriteChar(const char ch) { + char s[2]; + s[0]=ch; + s[1]=0;//null terminated + return Write(s); +} + +inline char ceSerial::ReadChar(bool& success) { + success = false; + if (!IsOpened()) {return 0;} + + DWORD dwRead; + DWORD length=1; + BYTE* data = (BYTE*)(&rxchar); + //the creation of the overlapped read operation + if (!fWaitingOnRead) { + // Issue read operation. + if (!ReadFile(hComm, data, length, &dwRead, &osReader)) { + if (GetLastError() != ERROR_IO_PENDING) { /*Error*/} + else { fWaitingOnRead = TRUE; /*Waiting*/} + } + else {if(dwRead==length) success = true;}//success + } + + + //detection of the completion of an overlapped read operation + DWORD dwRes; + if (fWaitingOnRead) { + dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT); + switch (dwRes) + { + // Read completed. + case WAIT_OBJECT_0: + if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) {/*Error*/ } + else { + if (dwRead == length) success = true; + fWaitingOnRead = FALSE; + // Reset flag so that another opertion can be issued. + }// Read completed successfully. + break; + + case WAIT_TIMEOUT: + // Operation isn't complete yet. + break; + + default: + // Error in the WaitForSingleObject; + break; + } + } + return rxchar; +} + +inline bool ceSerial::SetRTS(bool value) { + bool r = false; + if (IsOpened()) { + if (value) { + if (EscapeCommFunction(hComm, SETRTS)) r = true; + } + else { + if (EscapeCommFunction(hComm, CLRRTS)) r = true; + } + } + return r; +} + +inline bool ceSerial::SetDTR(bool value) { + bool r = false; + if (IsOpened()) { + if (value) { + if (EscapeCommFunction(hComm, SETDTR)) r = true; + } + else { + if (EscapeCommFunction(hComm, CLRDTR)) r = true; + } + } + return r; +} + +inline bool ceSerial::GetCTS(bool& success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)){ + r = MS_CTS_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetDSR(bool& success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_DSR_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetRI(bool& success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_RING_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetCD(bool& success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_RLSD_ON & dwModemStatus; + success = true; + } + } + return r; +} + +#else //for POSIX + +inline long ceSerial::Open(void) { + struct serial_struct serinfo; + struct termios settings; + memset(&settings, 0, sizeof(settings)); + settings.c_iflag = 0; + settings.c_oflag = 0; + + settings.c_cflag = CREAD | CLOCAL;//see termios.h for more information + if(dsize==5) settings.c_cflag |= CS5;//no change + else if (dsize == 6) settings.c_cflag |= CS6; + else if (dsize == 7) settings.c_cflag |= CS7; + else settings.c_cflag |= CS8; + + if(stopbits==2) settings.c_cflag |= CSTOPB; + + if(parity!='N') settings.c_cflag |= PARENB; + + if (parity == 'O') settings.c_cflag |= PARODD; + + settings.c_lflag = 0; + settings.c_cc[VMIN] = 1; + settings.c_cc[VTIME] = 0; + + fd = open(port.c_str(), O_RDWR | O_NONBLOCK); + if (fd == -1) { + return -1; + } + + if (!stdbaud) { + // serial driver to interpret the value B38400 differently + serinfo.reserved_char[0] = 0; + if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1;} + serinfo.flags &= ~ASYNC_SPD_MASK; + serinfo.flags |= ASYNC_SPD_CUST; + serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud; + if (serinfo.custom_divisor < 1) serinfo.custom_divisor = 1; + if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { return -1; } + if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1; } + if (serinfo.custom_divisor * baud != serinfo.baud_base) { + /* + warnx("actual baudrate is %d / %d = %f\n", + serinfo.baud_base, serinfo.custom_divisor, + (float)serinfo.baud_base / serinfo.custom_divisor); + */ + } + cfsetospeed(&settings, B38400); + cfsetispeed(&settings, B38400); + } + else { + cfsetospeed(&settings, baud); + cfsetispeed(&settings, baud); + } + tcsetattr(fd, TCSANOW, &settings); + int flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + + if (!stdbaud) { + // driver to interpret B38400 as 38400 baud again + ioctl(fd, TIOCGSERIAL, &serinfo); + serinfo.flags &= ~ASYNC_SPD_MASK; + ioctl(fd, TIOCSSERIAL, &serinfo); + } + return 0; +} + +inline void ceSerial::Close() { + if(IsOpened()) close(fd); + fd=-1; +} + +inline bool ceSerial::IsOpened() { + if(fd== (-1)) return false; + else return true; +} + +inline void ceSerial::SetBaudRate(long baudrate) { + stdbaud = true; + if (baudrate == 0) baud = B0; + else if (baudrate == 50) baud = B50; + else if (baudrate == 75) baud = B75; + else if (baudrate == 110) baud = B110; + else if (baudrate == 134) baud = B134; + else if (baudrate == 150) baud = B150; + else if (baudrate == 200) baud = B200; + else if (baudrate == 300) baud = B300; + else if (baudrate == 600) baud = B600; + else if (baudrate == 1200) baud = B1200; + else if (baudrate == 2400) baud = B2400; + else if (baudrate == 4800) baud = B4800; + else if (baudrate == 9600) baud = B9600; + else if (baudrate == 19200) baud = B19200; + else if (baudrate == 38400) baud = B38400; + else if (baudrate == 57600) baud = B57600; + else if (baudrate == 115200) baud = B115200; + else if (baudrate == 230400) baud = B230400; + else { + baud = baudrate; + stdbaud = false; + } +} + +inline long ceSerial::GetBaudRate() { + return baud; +} + +inline char ceSerial::ReadChar(bool& success) { + success=false; + if (!IsOpened()) {return 0; } + success=read(fd, &rxchar, 1)==1; + return rxchar; +} + +inline bool ceSerial::Write(const char *data) { + if (!IsOpened()) {return false; } + long n = strlen(data); + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + return (write(fd, data, n)==n); +} + +inline bool ceSerial::Write(const char *data,long n) { + if (!IsOpened()) {return false; } + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + return (write(fd, data, n)==n); +} + +inline bool ceSerial::WriteChar(const char ch) { + char s[2]; + s[0]=ch; + s[1]=0;//null terminated + return Write(s); +} + +inline bool ceSerial::SetRTS(bool value) { + long RTS_flag = TIOCM_RTS; + bool success=true; + if (value) {//Set RTS pin + if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) success=false; + } + else {//Clear RTS pin + if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) success=false; + } + return success; +} + +inline bool ceSerial::SetDTR(bool value) { + long DTR_flag = TIOCM_DTR; + bool success=true; + if (value) {//Set DTR pin + if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) success=false; + } + else {//Clear DTR pin + if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) success=false; + } + return success; +} + +inline bool ceSerial::GetCTS(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_CTS) != 0); +} + +inline bool ceSerial::GetDSR(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_DSR) != 0); +} + +inline bool ceSerial::GetRI(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_RI) != 0); +} + +inline bool ceSerial::GetCD(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_CD) != 0); +} +#endif #endif // CESERIAL_H diff --git a/include/ce/ceWxSerial.h b/include/ce/ceWxSerial.h deleted file mode 100644 index 8b850d2..0000000 --- a/include/ce/ceWxSerial.h +++ /dev/null @@ -1,32 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceWxSerial.h -// Description: Serial module for wxWidgets -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEWXSERIAL_H -#define CEWXSERIAL_H -#include "ce/ceMacros.h" // macros -#if CE_WX==1 -#include "wx/wx.h" -#include -#include "ce/ceSerial.h" -namespace ce { - -class ceWxSerial : public wxEvtHandler, public ce::ceSerial { -public: - ceWxSerial(wxEvtHandler* app,int id, int interval, - std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits); - ~ceWxSerial(); - void OnTimer(wxTimerEvent& event); - std::vector Chk(); -private: - wxTimer* _timer; - wxEvtHandler* _app; - int _id; - int _interval; -}; - -} // namespace ce -#endif // CE_WX -#endif // CEWXSERIAL_H diff --git a/include/ce/ceWxTmr.h b/include/ce/ceWxTmr.h deleted file mode 100644 index 76c799a..0000000 --- a/include/ce/ceWxTmr.h +++ /dev/null @@ -1,28 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceWxTmr.h -// Description: Timer module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEWXTMR_H -#define CEWXTMR_H -#include "ce/ceMacros.h" // macros -#if CE_WX==1 -#include "wx/wx.h" -namespace ce { - -class ceWxTmr : public wxEvtHandler { -public: - ceWxTmr(wxEvtHandler* app,int id, int interval); - void OnTimer(wxTimerEvent& event); - void Start(); -private: - wxTimer* _timer; - wxEvtHandler* _app; - int _id; - int _interval; -}; - -} // namespace ce -#endif // CE_WX -#endif // CEWXTMR_H diff --git a/src/ceFraChecksum.cpp b/include/ce/cefracs.h similarity index 60% rename from src/ceFraChecksum.cpp rename to include/ce/cefracs.h index 2a9815f..d9eb1b8 100644 --- a/src/ceFraChecksum.cpp +++ b/include/ce/cefracs.h @@ -1,105 +1,148 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceFraChecksum.cpp -// Description: Byte stuffing- sending and receiving frames with checksum -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceFraChecksum.h" -namespace ce { -//----------------------------------------------------------------------------- -ceFraChecksum::ceFraChecksum() :TxN(0), RxN(0), rState(CE_FRAME_IGNORE) { - rb[0] = 0; - tb[0] = 0; -} -//----------------------------------------------------------------------------- -char* ceFraChecksum::GetTxBuf() { - return tb; -} -//----------------------------------------------------------------------------- -char* ceFraChecksum::GetRxBuf() { - return rb; -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -size_t ceFraChecksum::SetTxFrame(char* d, size_t n) -{ - char c; - int i = 0, j = 0; - tb[i++] = STX;//start of frame - for (j = 0; j < n; j++) { - c = d[j]; - if ((c == STX) || (c == ETX) || (c == DLE)) tb[i++] = (DLE); - tb[i++] = c; - } - tb[i++] = (ETX);//end of frame - tb[i++] = Checksum(d, n);//calculate CS - TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -//Inputs -//s : pointer to input char string -//len: string len - -//Output -//Returns calculated Checksum -uint8_t ceFraChecksum::Checksum(char* s, size_t len) -{ - uint8_t cs = 0; // check sum - for (size_t i = 0; i < len; i++, s++) { - cs ^= (uint8_t)(*s); - } - return cs; -} -//----------------------------------------------------------------------------- -//get number of transmitting bytes -size_t ceFraChecksum::GetTxN() -{ - return TxN; -} -//----------------------------------------------------------------------------- -//get number of receiving bytes -size_t ceFraChecksum::GetRxN() -{ - return RxN; -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -size_t ceFraChecksum::ReceiveRxFrame(char c) -{ - uint8_t cs; - uint8_t rxcs; - switch (rState) { - case CE_FRAME_RECEIVING: - if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } - else if (c == ETX) { rState = CE_FRAME_CHKSUM; } - else if (c == DLE) { rState = CE_FRAME_ESCAPE; } - else { rb[RxN++] = c; } - break; - case CE_FRAME_ESCAPE: - rb[RxN++] = c; rState = CE_FRAME_RECEIVING; - break; - case CE_FRAME_CHKSUM: - rxcs = c; - rState = CE_FRAME_IGNORE; - cs = Checksum(rb, RxN);//calculate crc - //printf("cs: %x rxcs: %x \n",cs,rxcs); - if (rxcs == cs) { return RxN; }//if cs is correct - else { RxN = 0; }//discard the frame - break; - default: //case CE_FRAME_IGNORE: - if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } - break; - } - - if (RxN >= CE_FRAME_RX_BUF_SIZE) { - RxN = 0; - rState = CE_FRAME_IGNORE; - } - - return 0; -} - -} // namespace ce \ No newline at end of file +///////////////////////////////////////////////////////////////////////////// +// Name: cefracs.h +// Description: Byte stuffing- sending and receiving frames with checksum +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_FRACHECKSUM_H +#define CE_FRACHECKSUM_H + +#include +#include + +#define STX 0x02 +#define ETX 0x03 +#define DLE 0x10 + +#define CE_FRAME_TX_BUF_SIZE 1024 +#define CE_FRAME_RX_BUF_SIZE 1024 + +// frame state definition +#define CE_FRAME_IGNORE 0 +#define CE_FRAME_RECEIVING 1 +#define CE_FRAME_ESCAPE 2 +#define CE_FRAME_CHKSUM 3 + +namespace ce { + +//----------------------------------------------------------------------------- +class ceFraChecksum { + int rState; +protected: + size_t TxN;//number of transmitting bytes + size_t RxN;//number of receiving bytes + char tb[CE_FRAME_TX_BUF_SIZE];//transmit buffer + char rb[CE_FRAME_RX_BUF_SIZE];//receiving data +public: + ceFraChecksum(); + size_t GetTxN(); + size_t GetRxN(); + char* GetTxBuf(); + char* GetRxBuf(); + virtual size_t SetTxFrame(char* d, size_t n); + virtual uint8_t Checksum(char* s, size_t len); + virtual size_t ReceiveRxFrame(char c);//get receiving frame from received char +}; +//----------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +inline ceFraChecksum::ceFraChecksum() :TxN(0), RxN(0), rState(CE_FRAME_IGNORE) { + rb[0] = 0; + tb[0] = 0; +} +//----------------------------------------------------------------------------- +inline char* ceFraChecksum::GetTxBuf() { + return tb; +} +//----------------------------------------------------------------------------- +inline char* ceFraChecksum::GetRxBuf() { + return rb; +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +inline size_t ceFraChecksum::SetTxFrame(char* d, size_t n) +{ + char c; + int i = 0, j = 0; + tb[i++] = STX;//start of frame + for (j = 0; j < n; j++) { + c = d[j]; + if ((c == STX) || (c == ETX) || (c == DLE)) tb[i++] = (DLE); + tb[i++] = c; + } + tb[i++] = (ETX);//end of frame + tb[i++] = Checksum(d, n);//calculate CS + TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +//Inputs +//s : pointer to input char string +//len: string len + +//Output +//Returns calculated Checksum +inline uint8_t ceFraChecksum::Checksum(char* s, size_t len) +{ + uint8_t cs = 0; // check sum + for (size_t i = 0; i < len; i++, s++) { + cs ^= (uint8_t)(*s); + } + return cs; +} +//----------------------------------------------------------------------------- +//get number of transmitting bytes +inline size_t ceFraChecksum::GetTxN() +{ + return TxN; +} +//----------------------------------------------------------------------------- +//get number of receiving bytes +inline size_t ceFraChecksum::GetRxN() +{ + return RxN; +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +inline size_t ceFraChecksum::ReceiveRxFrame(char c) +{ + uint8_t cs; + uint8_t rxcs; + switch (rState) { + case CE_FRAME_RECEIVING: + if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } + else if (c == ETX) { rState = CE_FRAME_CHKSUM; } + else if (c == DLE) { rState = CE_FRAME_ESCAPE; } + else { rb[RxN++] = c; } + break; + case CE_FRAME_ESCAPE: + rb[RxN++] = c; rState = CE_FRAME_RECEIVING; + break; + case CE_FRAME_CHKSUM: + rxcs = c; + rState = CE_FRAME_IGNORE; + cs = Checksum(rb, RxN);//calculate crc + //printf("cs: %x rxcs: %x \n",cs,rxcs); + if (rxcs == cs) { return RxN; }//if cs is correct + else { RxN = 0; }//discard the frame + break; + default: //case CE_FRAME_IGNORE: + if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } + break; + } + + if (RxN >= CE_FRAME_RX_BUF_SIZE) { + RxN = 0; + rState = CE_FRAME_IGNORE; + } + + return 0; +} + +///////////////////////////////////////////////////////////////////////////// +} // namespace ce + +#endif // CE_FRACHECKSUM_H \ No newline at end of file diff --git a/include/ce/ceRSA_OS.h b/include/ce/cersaos.h similarity index 89% rename from include/ce/ceRSA_OS.h rename to include/ce/cersaos.h index 44e0451..a146f40 100644 --- a/include/ce/ceRSA_OS.h +++ b/include/ce/cersaos.h @@ -1,62 +1,65 @@ -#ifndef CERSA_OS_H -#define CERSA_OS_H - - // Description: Functions to calculate RSA using OpenSSL crypto lib - // Class implementation of the following example: https://github.com/yan9a/cecpp/blob/master/rsa_openssl/main.cpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -namespace ce { - class ceRSA_OS { - public: - // ---------------------------------------------------------------------------- - static std::string bn2str(BIGNUM* bigN); - - // Load public key from file - static RSA* loadPublicKey(std::string publicKeyFile); - - // Load private key from file - static RSA* loadPrivateKey(std::string privateKeyFile); - - // Encrypt data using public key - static std::string encrypt(const std::string& message, RSA* rsa_key); - - // Decrypt data using private key - static std::string decrypt(const std::string& ciphertext, RSA* rsa_key); - - // Generate a public-private key pair and save to files - static RSA* generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t bit_len = 2048, uint32_t exp = 3); - - // Generate a public-private key pair and returns RSA - static RSA* generateKeyPair(uint32_t bit_len = 2048, uint32_t exp = 3); - - // Encrypt data using public key - static std::string encrypt(const std::string& message, std::string publicKeyFile); - - // Decrypt data using private key - static std::string decrypt(const std::string& ciphertext, std::string privateKeyFile); - - // Encrypt data using modulus n and exponent e - static std::string encrypt(const std::string& message, std::string n, std::string e); - - // Decrypt data using secret number d, modulus n and exponent e - static std::string decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e); - - // Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key - static void getBN(RSA* key, std::string& d, std::string& n, std::string& e); - }; -} // namespace ce - -#endif // CERSA_OS_H +///////////////////////////////////////////////////////////////////////////// +// Name: cersaos.h +// Description: Functions to calculate RSA using OpenSSL crypto lib +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + // Class implementation of the following example: https://github.com/yan9a/cecpp/blob/master/rsa_openssl/main.cpp +#ifndef CERSA_OS_H +#define CERSA_OS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace ce { + class ceRSA_OS { + public: + // ---------------------------------------------------------------------------- + static std::string bn2str(BIGNUM* bigN); + + // Load public key from file + static RSA* loadPublicKey(std::string publicKeyFile); + + // Load private key from file + static RSA* loadPrivateKey(std::string privateKeyFile); + + // Encrypt data using public key + static std::string encrypt(const std::string& message, RSA* rsa_key); + + // Decrypt data using private key + static std::string decrypt(const std::string& ciphertext, RSA* rsa_key); + + // Generate a public-private key pair and save to files + static RSA* generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t bit_len = 2048, uint32_t exp = 3); + + // Generate a public-private key pair and returns RSA + static RSA* generateKeyPair(uint32_t bit_len = 2048, uint32_t exp = 3); + + // Encrypt data using public key + static std::string encrypt(const std::string& message, std::string publicKeyFile); + + // Decrypt data using private key + static std::string decrypt(const std::string& ciphertext, std::string privateKeyFile); + + // Encrypt data using modulus n and exponent e + static std::string encrypt(const std::string& message, std::string n, std::string e); + + // Decrypt data using secret number d, modulus n and exponent e + static std::string decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e); + + // Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key + static void getBN(RSA* key, std::string& d, std::string& n, std::string& e); + }; +} // namespace ce + +#endif // CERSA_OS_H diff --git a/src/ceDES.cpp b/src/ceDES.cpp deleted file mode 100644 index 96735ba..0000000 --- a/src/ceDES.cpp +++ /dev/null @@ -1,493 +0,0 @@ -// Description: Simple functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) -// Class implementation of the following repository: https://github.com/yan9a/ceDES -// WebSite: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2023 Yan Naing Aye - -// Related links -// https://www.rapidtables.com/convert/number/ascii-to-hex.html -// https://emvlab.org/descalc/ -// https://paymentcardtools.com/crypto-calculators/des-calculator -// https://github.com/yan9a/cecpp/blob/master/des_cryptopp/main.cpp - -#include -#include "ce/ceDES.h" -namespace ce { - //----------------------------------------------------------------------------- - // Init permutation table - // 64 bit data -> 64 bit data - const unsigned char ceDES::IP_table[64] = { - 58, 50, 42, 34, 26, 18, 10, 2, - 60, 52, 44, 36, 28, 20, 12, 4, - 62, 54, 46, 38, 30, 22, 14, 6, - 64, 56, 48, 40, 32, 24, 16, 8, - 57, 49, 41, 33, 25, 17, 9, 1, - 59, 51, 43, 35, 27, 19, 11, 3, - 61, 53, 45, 37, 29, 21, 13, 5, - 63, 55, 47, 39, 31, 23, 15, 7 }; - //----------------------------------------------------------------------------- - //Permuted Choice 1 - // Key permutation table - // 64 bit key data -> 56 bit key data - const unsigned char ceDES::PC1_table[56] = { - 57, 49, 41, 33, 25, 17, 9, - 1, 58, 50, 42, 34, 26, 18, - 10, 2, 59, 51, 43, 35, 27, - 19, 11, 3, 60, 52, 44, 36, - 63, 55, 47, 39, 31, 23, 15, - 7, 62, 54, 46, 38, 30, 22, - 14, 6, 61, 53, 45, 37, 29, - 21, 13, 5, 28, 20, 12, 4 }; - //----------------------------------------------------------------------------- - // Key shift table - const unsigned char ceDES::LeftShift_table[16] = { - 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; - //----------------------------------------------------------------------------- - // Key Compression permutation table - // 56 bit key data -> 48 bit - const unsigned char ceDES::PC2_table[48] = { - 14, 17, 11, 24, 1, 5, 3, 28, - 15, 6, 21, 10, 23, 19, 12, 4, - 26, 8, 16, 7, 27, 20, 13, 2, - 41, 52, 31, 37, 47, 55, 30, 40, - 51, 45, 33, 48, 44, 49, 39, 56, - 34, 53, 46, 42, 50, 36, 29, 32 }; - //----------------------------------------------------------------------------- - // Expansion permutation table - // 32 bit data -> 48 bit data - const unsigned char ceDES::E_table[48] = { - 32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9, 10, 11, 12, 13, - 12, 13, 14, 15, 16, 17, - 16, 17, 18, 19, 20, 21, - 20, 21, 22, 23, 24, 25, - 24, 25, 26, 27, 28, 29, - 28, 29, 30, 31, 32, 1 }; - //----------------------------------------------------------------------------- - const unsigned char ceDES::S[8][4][16] = { - { - {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, - {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, - {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, - {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} - }, - { - {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, - {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, - {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, - {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} - }, - { - {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, - {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, - {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, - {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} - }, - { - {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, - {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, - {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, - {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} - }, - { - {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, - {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, - {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, - {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} - }, - { - {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, - {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, - {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, - {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} - }, - { - {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, - {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, - {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, - {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} - }, - { - {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, - {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, - {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, - {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} - } - }; - //----------------------------------------------------------------------------- - // Strait permutation table - // 32 bit data -> 32 bit data - const unsigned char ceDES::P_table[32] = { - 16, 7, 20, 21, 29, 12, 28, 17, - 1, 15, 23, 26, 5, 18, 31, 10, - 2, 8, 24, 14, 32, 27, 3, 9, - 19, 13, 30, 6, 22, 11, 4, 25 }; - //----------------------------------------------------------------------------- - // Inverse permutation table - // 64 bit data -> 64 bit data - const unsigned char ceDES::InverseIP_table[64] = { - 40, 8, 48, 16, 56, 24, 64, 32, - 39, 7, 47, 15, 55, 23, 63, 31, - 38, 6, 46, 14, 54, 22, 62, 30, - 37, 5, 45, 13, 53, 21, 61, 29, - 36, 4, 44, 12, 52, 20, 60, 28, - 35, 3, 43, 11, 51, 19, 59, 27, - 34, 2, 42, 10, 50, 18, 58, 26, - 33, 1, 41, 9, 49, 17, 57, 25 }; - //----------------------------------------------------------------------------- - unsigned char ceDES::Kn[7]; - unsigned char ceDES::Rn_1[6]; -//----------------------------------------------------------------------------- -//dMes=Message to encrypt -//dKey=Key -void ceDES::Encrypt(unsigned char *dMes,unsigned char *dKey) -{ - unsigned char n,i; - unsigned char dKeyC[8]; - for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key - - Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output - Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output - for(n=0;n<16;n++) - { - LeftShift(dKeyC,LeftShift_table[n]); - for(i=0;i<7;i++) Kn[i]=dKeyC[i]; - Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output - for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; - F(Rn_1,Kn); - - if(n>=15) - { - for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; - break; - } - for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; - for(i=0;i<4;i++) dMes[i]=dMes[i+4]; - for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; - } - Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output -} -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//dMes=Message to decrypt -//dKey=Key -void ceDES::Decrypt(unsigned char *dMes,unsigned char *dKey) -{ - unsigned char n,i; - unsigned char dKeyC[8]; - for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key - - Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output - Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output - - for(n=0;n<16;n++) - { - for(i=0;i<7;i++) Kn[i]=dKeyC[i]; - Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output - for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; - F(Rn_1,Kn); - - if(n>=15) - { - for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; - break; - } - for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; - for(i=0;i<4;i++) dMes[i]=dMes[i+4]; - for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; - RightShift(dKeyC,LeftShift_table[15-n]); - } - Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output -} -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//pData =input to permutate -//ni =number of input bytes -//pTable =permutation table -//no =number of output bytes -void ceDES::Permutate(unsigned char *pData,unsigned char ni, - unsigned char *pTable,unsigned char no) -{ - unsigned char temp[8]; - unsigned char i,j,x; - unsigned char ByteI,BitIndex; - - for(i=0;i>3];//divided by 8 - BitIndex =7-(BitIndex & 7);//mod 8 - x|=((ByteI>>BitIndex) & 0x01); - } - *pData=x; - } - -} -//----------------------------------------------------------------------------- -//nKey -Key to shift -//b -number of bits -//priority to speed rather than code size -void ceDES::LeftShift(unsigned char *nKey,unsigned char b) -{ - unsigned char x,y,c; - c=8-b; - - //avoid loop to get linear code - x=nKey[6]; - nKey[6]=x<>c; - - x=nKey[5]; - nKey[5]=(x<>c; - - x=nKey[4]; - nKey[4]=(x<>c; - - x=nKey[3]; - nKey[3]=(x<>c; - - x<<=4; - nKey[6]|=x>>c; - - x=nKey[2]; - nKey[2]=(x<>c; - - x=nKey[1]; - nKey[1]=(x<>c; - - x=nKey[0]; - nKey[0]=(x<>c; - - x=(b==1)?0xEF:0xCF; - x &=nKey[3]; - nKey[3]=x|(y<<4); -} -//----------------------------------------------------------------------------- -//nKey -Key to shift -//b -number of bits -//written for speed -void ceDES::RightShift(unsigned char *nKey,unsigned char b) -{ - unsigned char x,y,c; - c=8-b; - - //avoid loop to get linear code - x=nKey[0]; - nKey[0]=x>>b; - y=x<>b)|y; - y=x<>b)|y; - y=x<>b)|y; - y=x<>=4; - nKey[0]|=x<>b)|y; - y=x<>b)|y; - y=x<>b)|y; - y=x<>4); -} -//----------------------------------------------------------------------------- -//written for speed -void ceDES::Expand(unsigned char *R) -{ - unsigned char a,b,c,d,x; - a=R[0]; - b=R[1]; - c=R[2]; - d=R[3]; - - x=(d<<7) & 0x80;//bit 32 to 1 - x|=((a>>1) & 0x7C); - x|=((a>>3) & 0x03); - R[0]=x; - - x=(a<<5) & 0xE0; - x|=(b>>3) & 0x10; - x|=(a<<3) & 0x08; - x|=(b>>5) & 0x07; - R[1]=x; - - x=(b<<3) & 0xC0; - x|=((b<<1) & 0x3E); - x|=((c>>7) & 0x01); - R[2]=x; - - x=(b<<7) & 0x80; - x|=((c>>1) & 0x7C); - x|=((c>>3) & 0x03); - R[3]=x; - - x=(c<<5) & 0xE0; - x|=(d>>3) & 0x10; - x|=(c<<3) & 0x08; - x|=(d>>5) & 0x07; - R[4]=x; - - x=(d<<3) & 0xC0; - x|=((d<<1) & 0x3E); - x|=((a>>7) & 0x01); - R[5]=x; -} -//----------------------------------------------------------------------------- -//written for speed -void ceDES::F(unsigned char *R,unsigned char *K) -{ - unsigned char i,r,c; - - //special function for expansion to improve speed - Expand(R); - - for(i=0;i<6;i++) K[i]^=R[i]; - - //R[0]=S0 S1 - c=(K[0]>>3) & 0x0F; - r=(K[0]>>2) & 1; - r|=(K[0]>>6) & 2; - R[0]=(S[0][r][c])<<4; - - c=(K[0]<<3) & 0x08; - c |=(K[1]>>5) & 0x07; - r=(K[1]>>4) & 1; - r|=(K[0] & 2); - R[0]|=(S[1][r][c]); - - //R[1]=S2 S3 - c=(K[1]<<1) & 0x0E; - c|=(K[2]>>7) & 1; - r=(K[2]>>6) & 1; - r|=(K[1]>>2) & 2; - R[1]=(S[2][r][c])<<4; - - c=(K[2]>>1) & 0x0F; - r=K[2] & 1; - r|=(K[2]>>4) & 2; - R[1]|=(S[3][r][c]); - - //R[2]=S4 S5 - c=(K[3]>>3) & 0x0F; - r=(K[3]>>2) & 1; - r|=(K[3]>>6) & 2; - R[2]=(S[4][r][c])<<4; - - c=(K[3]<<3) & 0x08; - c |=(K[4]>>5) & 0x07; - r=(K[4]>>4) & 1; - r|=(K[3] & 2); - R[2]|=(S[5][r][c]); - - //R[3]=S6 S7 - c=(K[4]<<1) & 0x0E; - c|=(K[5]>>7) & 1; - r=(K[5]>>6) & 1; - r|=(K[4]>>2) & 2; - R[3]=(S[6][r][c])<<4; - - c=(K[5]>>1) & 0x0F; - r=K[5] & 1; - r|=(K[5]>>4) & 2; - R[3]|=(S[7][r][c]); - - //Permutate the S box output - Permutate(R,4,(unsigned char *)P_table,4);//32 bit output -} -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//dMes=Message to encrypt -//dKeyL=KeyLeft -//dKeyR=KeyRight -void ceDES::Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) -{ - Encrypt(dMes,dKeyL); - Decrypt(dMes,dKeyR); - Encrypt(dMes,dKeyL); -} -//----------------------------------------------------------------------------- -//dMes=Message to decrypt -//dKeyL=KeyLeft -//dKeyR=KeyRight -void ceDES::Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) -{ - Decrypt(dMes,dKeyL); - Encrypt(dMes,dKeyR); - Decrypt(dMes,dKeyL); -} -//----------------------------------------------------------------------------- -// DES encryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes -std::string ceDES::Encrypt(std::string dMes, std::string dKey) -{ - unsigned char buf[8]; - dMes.resize(8,'\0'); - memcpy(buf, dMes.c_str(), 8); - - dKey.resize(std::max(dKey.length(), 8), '\0'); - - // check if TDES to use - if (dKey.length() > 8) { - dKey.resize(std::max(dKey.length(), 16), '\0'); - Encrypt(buf, (unsigned char*)(dKey.c_str()), (unsigned char*)(dKey.c_str() + 8)); - } - // for DES - else { - Encrypt(buf, (unsigned char*)(dKey.c_str())); - } - std::string r((char*)buf, 8); - return r; -} -//----------------------------------------------------------------------------- -// DES decryption, DES if dKey is 8 bytes, and TDES if it is 16 bytes -std::string ceDES::Decrypt(std::string dMes, std::string dKey) -{ - unsigned char buf[8]; - dMes.resize(8, '\0'); - memcpy(buf, dMes.c_str(), 8); - - dKey.resize(std::max(dKey.length(), 8), '\0'); - - // check if TDES to use - if (dKey.length() > 8) { - dKey.resize(std::max(dKey.length(), 16), '\0'); - Decrypt(buf, (unsigned char*)(dKey.c_str()), (unsigned char*)(dKey.c_str() + 8)); - } - // for DES - else { - Decrypt(buf, (unsigned char*)(dKey.c_str())); - } - std::string r((char*)buf, 8); - return r; -} -//----------------------------------------------------------------------------- -} // namespace ce \ No newline at end of file diff --git a/src/ceDateTime.cpp b/src/ceDateTime.cpp deleted file mode 100644 index d49ad7d..0000000 --- a/src/ceDateTime.cpp +++ /dev/null @@ -1,622 +0,0 @@ -// File: ceDateTime.cpp -// Description: Simple C++ Date/time class -// WebSite: https://yan9a.github.io/mcal/ -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -#include "ce/ceDateTime.h" -#include -#include -#ifdef CE_WINDOWS - #include -#elif defined(CE_LINUX) - #include -#endif -using namespace std; - -namespace ce { -//------------------------------------------------------------------------- -// Time to Fraction of day starting from 12 noon -// input: (h=hour, n=minute, s=second) output: (d: fraction of day) -double ceDateTime::t2d(long h,long n,double s) -{ - return ((double(h)-12)/24.0+double(n)/1440.0+s/86400.0); -} -//------------------------------------------------------------------------- -//Western date to Julian date -//Credit4 Gregorian2JD: http://www.cs.utsa.edu/~cs1063/projects/Spring2011/Project1/jdn-explanation.html -//input: (y: year, m: month, d: day, h=hour, n=minute, s=second - // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] - // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) - // Gregorian start in British calendar (1752/Sep/14 = 2361222) -//output: Julian date -double ceDateTime::w2j(long y, long m, long d, long h, long n, double s, long ct, long SG) -{ - long a = long(floor((14 - m) / 12)); y = y + 4800 - a; m = m + (12 * a) - 3; - long jd =long( d + floor((153 * m + 2) / 5) + (365 * y) + floor(y / 4)); - if (ct == 1) jd = long( jd - floor(y / 100) + floor(y / 400) - 32045); - else if (ct == 2) jd = jd - 32083; - else { - jd = long( jd - floor(y / 100) + floor(y / 400) - 32045); - if (jdSG) jd = SG; - } - } - return double(jd)+t2d(h,n,s); -} -//------------------------------------------------------------------------- -//Julian date to Western date -//Credit4 Gregorian date: http://pmyers.pcug.org.au/General/JulianDates.htm -//Credit4 Julian Calendar: http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html -//input: (jd:julian date, - // ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] - // SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) -//output: Western date (y=year, m=month, d=day, h=hour, n=minute, s=second) -void ceDateTime::j2w(double jd,long& year, long& month, long& day, long& hour, long& minute, double& second, long ct, long SG) -{ - long j,y,m,d,h,n; - double jf,s; - if (ct==2 || (ct==0 && (jd13)?(e-13):(e-1); - d=b-f- long(floor(30.6001*double(e))); y=m<3?(c-4715):(c-4716); - } - else{ - j= long(floor(jd+0.5)); jf=jd+0.5-j; j-=1721119; - y=(long)(((double)(4*j-1))/146097); - j=4*j-1-146097*y; - d=(long)(((double)(j))/4); - j=(long)((4*(double)d+3)/1461); - d=4*d+3-1461*j; - d=(long)(((double)d+4)/4); m=(long)((5*(double)d-3)/153); d=5*d-3-153*m; - d=(long)(((double)d+5)/5); y=100*y+j; - if(m<10) {m+=3;} - else {m-=9; y=y+1;} - } - jf*=24; h=(long)(jf); jf=(jf-h)*60; n=(long)(jf); s=((jf-n)*60); - year=y; month=m; day=d; hour=h; minute=n; second=s; -} -//------------------------------------------------------------------------- -// convert unix timestamp to jd -double ceDateTime::u2j(time_t ut) -{ - //number of seconds from 1970 Jan 1 00:00:00 (UTC) - return (2440587.5+double(ut)/86400.0);//converte to day(/24h/60min/60sec) and to JD -} -//------------------------------------------------------------------------- -// julian date to unix time -time_t ceDateTime::j2u(double jd) -{ - return long(floor((jd-2440587.5)*86400.0+0.5)); -} -//------------------------------------------------------------------------- -// Compile time string -string ceDateTime::compiletime() -{ - string s=__DATE__; - s+=" "; - s+=__TIME__; - //s+=" "; - //s+=__cplusplus; - return s; -} -//------------------------------------------------------------------------- -#ifndef ceSYSTEMINDEPENDENT -// get current time in julian date -double ceDateTime::jdnow() -{ - //number of seconds from 1970 Jan 1 00:00:00 (UTC) - time_t ut = time(0);//now - double jd=ceDateTime::u2j(ut); - double ms=0;//milliseconds -#ifdef CE_WINDOWS - SYSTEMTIME wt; - GetSystemTime(&wt); - ms=double(wt.wMilliseconds); -#elif defined(CE_LINUX) - timeval time; - gettimeofday(&time,NULL); - ms=double(time.tv_usec)/1000.0; -#endif - jd+=ms/86400000.0; - return jd; -} -//------------------------------------------------------------------------- -// get local time zone offset between local time and UTC in hours (e.g. 8 for GMT +8) -double ceDateTime::ltzoh() -{ - double jdu= ceDateTime::jdnow();//utc - //http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html - time_t ut = time(0);//number of seconds from 1970 Jan 1 00:00:00 (UTC) - struct tm * ts=localtime(&ut); - double jdl= ceDateTime::w2j(ts->tm_year+1900,ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); - double stz=jdl-jdu;// local and utc day difference - //round to 1 min quantization - stz=double(floor(stz*1440.0+0.5))/60.0; - return stz; -} -//------------------------------------------------------------------------- -// Set local date time of the system -// need super user privileges -// https://www.linuxquestions.org/questions/programming-9/c-code-to-change-date-time-on-linux-707384/ -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724936(v=vs.85).aspx -void ceDateTime::SetSystemLocalTime(int year, int month, int day,int hour, int minute, int second) -{ -#ifdef CE_WINDOWS - //For Windows - SYSTEMTIME lt; - GetLocalTime(<); - lt.wYear=year; - lt.wMonth=month; - lt.wDay=day; - lt.wHour=hour; - lt.wMinute=minute; - lt.wSecond=second; - SetLocalTime(<); -#elif defined(CE_LINUX) - //For POSX - time_t mytime = time(0); - struct tm* tm_ptr = localtime(&mytime); - - if (tm_ptr) - { - tm_ptr->tm_mon = month - 1; - tm_ptr->tm_mday = day; - tm_ptr->tm_year = year - 1900; - - tm_ptr->tm_hour = hour; - tm_ptr->tm_min = minute; - tm_ptr->tm_sec = second; - - const struct timeval tv = {mktime(tm_ptr), 0}; - settimeofday(&tv, 0);//need super user privileges - } -#endif -} - -//------------------------------------------------------------------------- -// set local time zone -void ceDateTime::SetTimezone() -{ - this->m_tz = ceDateTime::ltzoh(); -} -//------------------------------------------------------------------------- -// set time to now -void ceDateTime::Set2Now() -{ - this->m_jd = ceDateTime::jdnow(); -} -//------------------------------------------------------------------------- -#endif // ceSYSTEMINDEPENDENT -ceDateTime::ceDateTime() -{ -#ifndef ceSYSTEMINDEPENDENT - this->SetTimezone(); - this->Set2Now(); -#else - this->SetTimezone(0); - this->SetUnixTime(0); -#endif // ceSYSTEMINDEPENDENT - this->m_ct=0; - this->m_SG=2361222; -} -//------------------------------------------------------------------------- -// jd to date time string -// input: (jd:julian date, -// fm: format [Optional argument: "%Www %y-%mm-%dd %HH:%nn:%ss %zz"] -// tz : time zone offset in hours (e.g. 8 for GMT +8) -// ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] -// SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) -// output: date time string according to fm where formatting strings are as follows -// %yyyy : year [0000-9999, e.g. 2018] -// %yy : year [00-99 e.g. 18] -// %y : year [0-9999, e.g. 201] -// %MMM : month [e.g. JAN] -// %Mmm : month [e.g. Jan] -// %mm : month with zero padding [01-12] -// %M : month [e.g. January] -// %m : month [1-12] -// %dd : day with zero padding [01-31] -// %d : day [1-31] -// %HH : hour [00-23] -// %hh : hour [01-12] -// %H : hour [0-23] -// %h : hour [1-12] -// %AA : AM or PM -// %aa : am or pm -// %nn : minute with zero padding [00-59] -// %n : minute [0-59] -// %ss : second [00-59] -// %s : second [0-59] -// %lll : millisecond [000-999] -// %l : millisecond [0-999] -// %WWW : Weekday [e.g. SAT] -// %Www : Weekday [e.g. Sat] -// %W : Weekday [e.g. Saturday] -// %w : Weekday number [0=sat, 1=sun, ..., 6=fri] -// %zz : time zone (e.g. +08, +06:30) -string ceDateTime::j2s(double jd, string fm, double tz, long ct, long SG) -{ - long year,month,day,hour,minute; - double second; - jd+=tz/24.0; - ceDateTime::j2w(jd,year,month,day,hour,minute,second,ct,SG); - long s= long(floor(second));//shold not take round to make sure s<60 - long l= long(floor((second-double(s))*1000)); // not rounding - long jdn= long(floor(jd+0.5)); - long wd=(jdn+2)%7;//week day [0=sat, 1=sun, ..., 6=fri] - long h = hour % 12; - if (h == 0) h = 12; - string W[]={"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"}; - string M[] = {"January","February","March","April","May","June","July","August","September","October","November","December"}; - - // replace format string with values - string fstr,rstr; - //-------------------------------------------------------- - fstr = "%yyyy"; - rstr = string(4, '0') + to_string(year); - rstr = rstr.substr(rstr.length() - 4); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%yy"; - long y = year % 100; - rstr = string(2, '0') + to_string(y); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%y"; - rstr = to_string(year); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%MMM"; - rstr = M[month-1]; - std::transform(rstr.begin(), rstr.end(), rstr.begin(), ::toupper); - rstr = rstr.substr(0,3); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%Mmm"; - rstr = M[month - 1]; - rstr = rstr.substr(0, 3); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%mm"; - rstr = string(2, '0') + to_string(month); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%M"; - rstr = M[month - 1]; - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%m"; - rstr = to_string(month); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%dd"; - rstr = string(2, '0') + to_string(day); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%d"; - rstr = to_string(day); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%HH"; - rstr = string(2, '0') + to_string(hour); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%hh"; - rstr = string(2, '0') + to_string(h); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%H"; - rstr = to_string(hour); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%h"; - rstr = to_string(h); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%AA"; - rstr = hour<12?"AM":"PM"; - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%aa"; - rstr = hour<12 ? "am" : "pm"; - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%nn"; - rstr = string(2, '0') + to_string(minute); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%n"; - rstr = to_string(minute); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%ss"; - rstr = string(2, '0') + to_string(s); - rstr = rstr.substr(rstr.length() - 2); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%s"; - rstr = to_string(s); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%lll"; - rstr = string(3, '0') + to_string(l); - rstr = rstr.substr(rstr.length() - 3); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%l"; - rstr = to_string(l); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%WWW"; - rstr = W[wd]; - std::transform(rstr.begin(), rstr.end(), rstr.begin(), ::toupper); - rstr = rstr.substr(0, 3); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%Www"; - rstr = W[wd]; - rstr = rstr.substr(0, 3); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%W"; - rstr = W[wd]; - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%w"; - rstr = to_string(wd); - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - fstr = "%zz"; - string tzs = tz < 0 ? "-" : "+"; - string tzh = string(2, '0') + to_string(long(floor(tz))); - tzh = tzh.substr(tzh.length() - 2); - rstr = tzs+tzh; - double tzf = tz - floor(tz); - if (tzf > 0) { - tzh = string(2, '0') + to_string(long(floor(tzf*60.0+0.5))); - tzh = tzh.substr(tzh.length() - 2); - rstr += ":"+tzh; - } - fm = ceDateTime::ReplaceAll(fm, fstr, rstr); - //-------------------------------------------------------- - return fm; -} -//------------------------------------------------------------------------- -// convert date time string to jd -// inputs -// tstr : time string -// accepts following formats -// 1: yyyy-mm-dd hh:nn:ss -// 2: yyyy-mm-dd hh:nn:ss.ttt -// 3: yyyymmddhhnnss -// 4: yyyymmddhhnnssttt -// 5: yyyy-mm-dd (default time is 12:00:00) -// 6: yyyymmdd (default time is 12:00:00) -// tz : time zone offset in hours -// [optional argument: 0 - UTC] -// ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] -// SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) -// output -// jd: julian date -// positive integer: ok -// -1 : error -double ceDateTime::s2j(string tstr, double tz, long ct, long SG) -{ - string str,pstr; - long y=0,m=0,d=0,h=12,n=0; - double jd=-1; - double s=0,ls=0; - str= ceDateTime::GetDigits(tstr); - if(str.length() == 8 || str.length()==14 || str.length()==17){ - pstr=str.substr(0,4); y=stol(pstr); //get year - pstr=str.substr(4,2); m=stol(pstr); //get month - pstr=str.substr(6,2); d=stol(pstr); //get day - if (str.length() == 14 || str.length() == 17) { - pstr = str.substr(8, 2); h = stol(pstr); //get hour - pstr = str.substr(10, 2); n = stol(pstr); //get minute - pstr = str.substr(12, 2); s = double(stol(pstr)); //get second - if (str.length() == 17) { - pstr = str.substr(14, 3); ls = double(stol(pstr)); //get millisecond - s += ls / 1000.0; - } - } - jd= ceDateTime::w2j(y,m,d,h,n,s,ct,SG)-tz/24.0; // convert to UTC - } - return jd; -} -//------------------------------------------------------------------------- -// set time zone in hours for this instance -void ceDateTime::SetTimezone(double tz)//set time zone -{ - if(tz<=14 || tz>=(-12)){ this->m_tz=tz; } -} -//------------------------------------------------------------------------- -// set time in jd -void ceDateTime::SetJD(double jd) -{ - this->m_jd=jd; -} -//------------------------------------------------------------------------- -// set in unix time -void ceDateTime::SetUnixTime(time_t ut) -{ - this->m_jd= ceDateTime::u2j(ut); -} -//------------------------------------------------------------------------- -// set date time for a timezone and a calendar type -void ceDateTime::SetDateTime(long year, long month, long day, long hour, long minute, double second, double tz, long ct, long SG) -{ - this->m_jd= ceDateTime::w2j(year,month,day,hour,minute,second,ct,SG)-tz/24.0; -} -//------------------------------------------------------------------------- -// set calendar type [0=British (default), 1=Gregorian, 2=Julian] -void ceDateTime::SetCT(long ct) -{ - this->m_ct=ct%3; -} -//------------------------------------------------------------------------- -// set Beginning of Gregorian calendar in JDN [default=2361222] -void ceDateTime::SetSG(long sg) -{ - this->m_SG=sg; -} -//------------------------------------------------------------------------- -// set time using a date time string -// inputs -// tstr : time string -// accepts following formats -// 1: yyyy-mm-dd hh:nn:ss -// 2: yyyy-mm-dd hh:nn:ss.ttt -// 3: yyyymmddhhnnss -// 4: yyyymmddhhnnssttt -// tz : time zone offset in hours -// [optional argument: 0 - UTC] -// ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian] -// SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) -void ceDateTime::SetDateTimeString(std::string tstr, double tz, long ct, long SG) -{ - double jd= ceDateTime::s2j(tstr, tz, ct, SG); - if (jd >= 0) this->m_jd = jd; -} -//------------------------------------------------------------------------- -// Get Date Time string -// input: (fm: format [Optional argument: "%Www %y-%mm-%dd %HH:%nn:%ss %zz"]) -// output: date time string according to fm where formatting strings are as follows -// %yyyy : year [0000-9999, e.g. 2018] -// %yy : year [00-99 e.g. 18] -// %y : year [0-9999, e.g. 201] -// %MMM : month [e.g. JAN] -// %Mmm : month [e.g. Jan] -// %mm : month with zero padding [01-12] -// %M : month [e.g. January] -// %m : month [1-12] -// %dd : day with zero padding [01-31] -// %d : day [1-31] -// %HH : hour [00-23] -// %hh : hour [01-12] -// %H : hour [0-23] -// %h : hour [1-12] -// %AA : AM or PM -// %aa : am or pm -// %nn : minute with zero padding [00-59] -// %n : minute [0-59] -// %ss : second [00-59] -// %s : second [0-59] -// %lll : millisecond [000-999] -// %l : millisecond [0-999] -// %WWW : Weekday [e.g. SAT] -// %Www : Weekday [e.g. Sat] -// %W : Weekday [e.g. Saturday] -// %w : Weekday number [0=sat, 1=sun, ..., 6=fri] -// %zz : time zone (e.g. +08, +06:30) -string ceDateTime::ToString(string fm) -{ - return ceDateTime::j2s(this->m_jd, fm, this->m_tz,this->m_ct,this->m_SG); -} -//------------------------------------------------------------------------- -// filter input string to get digits only -string ceDateTime::GetDigits(string str) -{ - string ostr = ""; - size_t len = str.length(); - if (len>0) { - for (size_t i = 0; i= '0' && str[i] <= '9') ostr += str[i]; - } - return ostr; -} -//------------------------------------------------------------------------- -// find a string and replace all occurances -std::string ceDateTime::ReplaceAll(std::string str, std::string fstr, std::string rstr) -{ - size_t i = 0; - while (true) { - i = str.find(fstr, i); - if (i == string::npos) break; - str.replace(i, fstr.length(), rstr); - i += rstr.length(); - } - return str; -} -//------------------------------------------------------------------------- -double ceDateTime::jd() { return this->m_jd; } -double ceDateTime::jdl() { return (this->m_jd+this->m_tz/24.0); } // jd for this time zone -long ceDateTime::jdn() { return long(round(this->m_jd)); } -long ceDateTime::jdnl() { return (long)round(this->m_jd+this->m_tz/24.0); } // jdn for this time zone -long ceDateTime::y() { - long y,m,d,h,n; double s; - ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); - return y; -} // year - -long ceDateTime::m() { - long y,m,d,h,n; double s; - ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); - return m; -} // month - -long ceDateTime::d() { - long y,m,d,h,n; double s; - ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); - return d; -} // day -long ceDateTime::h() { - long y,m,d,h,n; double s; - ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); - return h; -} // hour [0-23] - -long ceDateTime::n() { - long y,m,d,h,n; double s; - ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); - return n; -} // minute - -long ceDateTime::s() { - long y,m,d,h,n; double s; - ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); - long si=(long)floor(s); //shold not take round to make sure s<60 - return si; -} // second - -long ceDateTime::l() { - long y,m,d,h,n; double s; - ceDateTime::j2w(this->jdl(),y,m,d,h,n,s,this->m_ct,this->m_SG); - long si=(long)floor(s); //shold not take round to make sure s<60 - long l= long(floor((s-double(si))*1000)); // not rounding - return l; -} // millisecond - -long ceDateTime::w() { return (this->jdnl()+2)%7;} // weekday [0=sat, 1=sun, ..., 6=fri] - -long ceDateTime::ut() { return ceDateTime::j2u(this->m_jd);} // unix time -double ceDateTime::tz() { return this->m_tz; } // time zone in hour -long ceDateTime::ct(){ return this->m_ct; } // calendar type [0=British (default), 1=Gregorian, 2=Julian] -long ceDateTime::SG(){ return this->m_SG; } // Beginning of Gregorian calendar in JDN [default=2361222] -long ceDateTime::mlen() // length of this month - { return ceDateTime::wml(this->y(),this->m(),m_ct,m_SG); } -//------------------------------------------------------------------------- -// find the length of western month -// input: (y=year, m=month [Jan=1, ... , Dec=12], -// ct:calendar type [Optional argument: 0=British (default), 1=Gregorian, 2=Julian]) -// SG: Beginning of Gregorian calendar in JDN [Optional argument: (default=2361222)]) -// output: (wml = length of the month) -long ceDateTime::wml(long y,long m,long ct,long SG) { - long j1,j2; long m2=m+1; long y2=y; - if(m2>12){y2++; m2%=12;} - j1=long(ceDateTime::w2j(y,m,1,12,0,0,ct,SG)); - j2=long(ceDateTime::w2j(y2,m2,1,12,0,0,ct,SG)); - return (j2-j1); -} -//------------------------------------------------------------------------- -} //namespace ce \ No newline at end of file diff --git a/src/ceFraCmd.cpp b/src/ceFraCmd.cpp deleted file mode 100644 index 502d4be..0000000 --- a/src/ceFraCmd.cpp +++ /dev/null @@ -1,47 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceFraCmd.cpp -// Description: Byte stuffing- sending and receiving commands as frames -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceFraCmd.h" -namespace ce { -//----------------------------------------------------------------------------- -ceFraCmd::ceFraCmd():ceFrame(){ - -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -size_t ceFraCmd::SetTxFrame(char* d, size_t n) -{ - int i = 0; - if (n >= CE_FRAME_TX_BUF_SIZE) n = CE_FRAME_TX_BUF_SIZE - 1; //discard policy - for (int j = 0; j < n; j++) { - tb[i++] = d[j]; - } - tb[i++] = 0x0D;//end of frame - TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -size_t ceFraCmd::ReceiveRxFrame(char ch) -{ - static int n = 0; - if (ch >= 32 && ch <= 126) { - this->rb[n++] = ch; - this->RxN = 0; - } - - if (ch == 0x0D || n >= (CE_FRAME_RX_BUF_SIZE -1)) { - this->RxN = n; - this->rb[n] = 0;//null termination - n = 0; - return this->RxN; - } - return 0; -} - -} // namespace ce \ No newline at end of file diff --git a/src/ceFrame.cpp b/src/ceFrame.cpp deleted file mode 100644 index 3529b87..0000000 --- a/src/ceFrame.cpp +++ /dev/null @@ -1,123 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceFrame.cpp -// Description: Byte stuffing- sending and receiving frames -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceFrame.h" -namespace ce { -//----------------------------------------------------------------------------- -ceFrame::ceFrame() :TxN(0), RxN(0), rState(CE_FRAME_IGNORE) { - rb[0] = 0; - tb[0] = 0; -} -//----------------------------------------------------------------------------- -char* ceFrame::GetTxBuf() { - return tb; -} -//----------------------------------------------------------------------------- -char* ceFrame::GetRxBuf() { - return rb; -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -size_t ceFrame::SetTxFrame(char* d, size_t n) -{ - unsigned int txcrc = 0xFFFF;//initialize crc - char c; - int i = 0, j = 0; - tb[i++] = STX;//start of frame - for (j = 0; j < n; j++) { - c = d[j]; - if ((c == STX) || (c == ETX) || (c == DLE)) tb[i++] = (DLE); - tb[i++] = c; - } - tb[i++] = (ETX);//end of frame - - txcrc = CRC16(d, n, txcrc);//calculate crc - tb[i++] = txcrc & 0xFF; - tb[i++] = (txcrc >> 8) & 0xFF; - TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -//Inputs -//s : pointer to input char string -//len: string len (maximum 255) -//crc: initial CRC value - -//Output -//Returns calculated CRC -uint16_t ceFrame::CRC16(char* s, size_t len, uint16_t crc) -{ - //CRC Order: 16 - //CCITT(recommendation) : F(x)= x16 + x12 + x5 + 1 - //CRC Poly: 0x1021 - //Operational initial value: 0xFFFF - //Final xor value: 0 - size_t i, j; - for (i = 0; i < len; i++, s++) { - crc ^= ((unsigned int)(*s) & 0xFF) << 8; - for (j = 0; j < 8; j++) { - if (crc & 0x8000) crc = (crc << 1) ^ 0x1021; - else crc <<= 1; - } - } - return (crc & 0xFFFF);//truncate last 16 bit -} -//----------------------------------------------------------------------------- -//get number of transmitting bytes -size_t ceFrame::GetTxN() -{ - return TxN; -} -//----------------------------------------------------------------------------- -//get number of receiving bytes -size_t ceFrame::GetRxN() -{ - return RxN; -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -size_t ceFrame::ReceiveRxFrame(char c) -{ - static char b; - unsigned int crc; - unsigned int rxcrc = 0xFFFF;//initialize CRC - switch (rState) { - case CE_FRAME_RECEIVING: - if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } - else if (c == ETX) { rState = CE_FRAME_RXCRC1; } - else if (c == DLE) { rState = CE_FRAME_ESCAPE; } - else { rb[RxN++] = c; } - break; - case CE_FRAME_ESCAPE: - rb[RxN++] = c; rState = CE_FRAME_RECEIVING; - break; - case CE_FRAME_RXCRC1: - b = c; rState = CE_FRAME_RXCRC2; - break; - case CE_FRAME_RXCRC2: - rState = CE_FRAME_IGNORE; - crc = ((int)c << 8 | ((int)b & 0xFF)) & 0xFFFF;//get received crc - rxcrc = CRC16(rb, RxN, rxcrc);//calculate crc - //printf("crc: %x rxcrc:%x \n",crc,rxcrc); - if (rxcrc == crc) { return RxN; }//if crc is correct - else { RxN = 0; }//discard the frame - break; - default: //case CE_FRAME_IGNORE: - if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } - break; - } - - if (RxN >= CE_FRAME_RX_BUF_SIZE) { - RxN = 0; - rState = CE_FRAME_IGNORE; - } - - return 0; -} - -} // namespace ce \ No newline at end of file diff --git a/src/ceI2C.cpp b/src/ceI2C.cpp deleted file mode 100644 index 6f5a904..0000000 --- a/src/ceI2C.cpp +++ /dev/null @@ -1,88 +0,0 @@ -// File: ceI2C.h -// Description: ceI2C class to use i2c communication -// WebSite: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -#include "ce/ceI2C.h" -using namespace std; - -namespace ce { -template -string ceI2C::ToString(T a) -{ - ostringstream ss; - ss << a; - return ss.str(); -} - -ceI2C::ceI2C() -{ - //ctor -} - -ceI2C::ceI2C(int bus_id, int slave_address) -{ - Begin(bus_id, slave_address); -} - -ceI2C::~ceI2C() -{ - //dtor -#ifdef CE_LINUX - close(fd); -#else -#endif -} - -bool ceI2C::Begin(int bus_id, int slave_address) -{ - string filename = "/dev/i2c-"; - filename += ToString(bus_id); -#ifdef CE_LINUX - if ((fd = open(filename.c_str(), O_RDWR)) < 0) { - perror("Failed to open the i2c bus\n"); - return false; - } - if (ioctl(fd, I2C_SLAVE, slave_address) < 0) { - perror("Failed to acquire bus access and/or talk to slave.\n"); - return false; - } -#else -#endif - return true; -} - -bool ceI2C::Write(char* buf, int n) -{ -#ifdef CE_LINUX - if (write(fd, buf, n) != n) { - perror("Failed to write to the i2c bus.\n"); - return false; - } -#else -#endif - return true; -} - -bool ceI2C::Read(char* buf, int n) -{ -#ifdef CE_LINUX - if (read(fd, buf, n) != n) { - perror("Failed to read from the i2c bus.\n"); - return false; - } -#else -#endif - return true; -} - -void ceI2C::Close() -{ -#ifdef CE_LINUX - close(fd); -#else -#endif -} - -} // namespace ce \ No newline at end of file diff --git a/src/ceInterface.cpp b/src/ceInterface.cpp deleted file mode 100644 index 3da89ce..0000000 --- a/src/ceInterface.cpp +++ /dev/null @@ -1,25 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceInterface.h -// Description: Interface to communitcate modules -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/ceInterface.h" -namespace ce { -//----------------------------------------------------------------------------- -ceInterface::ceInterface() { - -} -//----------------------------------------------------------------------------- -ceInterface::ceInterface(std::function,std::string,int>)> cbf): _cbf(cbf) { - -} -//----------------------------------------------------------------------------- -void ceInterface::setRxCallback(std::function,std::string,int>)> cbf) { - _cbf = cbf; -} -//----------------------------------------------------------------------------- -void ceInterface::check(){ - -} -//----------------------------------------------------------------------------- -} // namespace ce \ No newline at end of file diff --git a/src/ceLog.cpp b/src/ceLog.cpp deleted file mode 100644 index a24350e..0000000 --- a/src/ceLog.cpp +++ /dev/null @@ -1,224 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceLog.cpp -// Description: logging module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#include "ce/ceLog.h" -using namespace std; - -namespace ce { -ceLog::ceLog() -{ - SetPath(LOG_PATH); - SetExpiry(30); - SetExtension(".log"); - SetEnPrintf(false); -} - -ceLog::ceLog(string path,double expdays) -{ - SetPath(path); - SetExpiry(expdays); - SetExtension(".log"); - SetEnPrintf(true); -} - -void ceLog::SetPath(string path) -{ - this->m_path=path; -} - -string ceLog::GetPath() -{ - return this->m_path; -} - -void ceLog::SetExtension(string ext) -{ - this->m_extension=ext; -} - -string ceLog::GetExtension() -{ - return this->m_extension; -} - -ceLog::~ceLog() -{ - -} - -bool ceLog::GetEnPrintf() -{ - return this->m_enPrintf; -} - -void ceLog::SetEnPrintf(bool en) -{ - this->m_enPrintf = en; -} - -double ceLog::GetExpiry() -{ - return this->m_expiry_days; -} - -void ceLog::SetExpiry(double days) -{ - this->m_expiry_days=days; -} - -void ceLog::SetTimezone(double a)//set time zone -{ - this->m_dt.SetTimezone(a); -} - -void ceLog::SetTimezone()//set local time zone -{ - this->m_dt.SetTimezone(); -} - -double ceLog::GetTimezone()//get time zone -{ - return this->m_dt.tz(); -} - -int ceLog::Write(string mes) -{ - ofstream wfile; - int r=-1; - this->m_dt.Set2Now(); - string logpath=this->m_path+"L"+this->m_dt.ToString("%yyyy-%mm-%dd")+".log"; - try{ - wfile.open(logpath.c_str(),std::fstream::out | std::fstream::app); - if (wfile.is_open()) { - wfile << this->m_dt.ToString("%HH:%nn:%ss.%lll") << " " << mes << endl; - r=0; - } - wfile.close(); - } - catch(...){ - perror("ceLog error in writing"); - } - return r; -} - -int ceLog::Print(string mes) -{ - if(this->m_enPrintf){ - // printf("%s\n",mes.c_str()); - cout << mes << endl; - } - return Write(mes); -} - -void ceLog::Clean(string path,string extension,double expiry_seconds) -{ - vector filenames; - string fn=""; - string fpath=""; - double fileage=0; - int pos=0; - - try{ - ReadDir(path,filenames); - int nfiles=(int)filenames.size(); - #if ceLog_PRINT == 1 - printf("Number of items: %d \n",nfiles); - #endif - - if(nfiles<=2){ //if only . and .. - return; - } - this->m_dt.Set2Now(); - - for(int i=0;i=0){ - fpath=path+fn; - this->m_ft.SetJD(LastModified(fpath)); - #if ceLog_PRINT ==1 - printf("Modified time: %s \n",m_ft.DateTimeString().c_str()); - #endif - fileage=(this->m_dt.jd()-this->m_ft.jd())*86400.0; - if(fileage>expiry_seconds){ - remove(fpath.c_str()); - #if ceLog_PRINT == 1 - printf("%s has been deleted \n", fpath.c_str()); - //this->Write("Deleted "+fp); - #endif - } - } - } - } - catch(...){ - perror("ceLog error in cleaning\n"); - } -} -void ceLog::Clean() //clean old log files -{ - this->Clean(this->m_path,this->m_extension,this->m_expiry_days*86400); -} - -//http://www.martinbroadhurst.com/list-the-files-in-a-directory-in-c.html -#ifdef CE_WINDOWS - void ceLog::ReadDir(const string& name, vector& v) - { - string pattern(name); - pattern.append("\\*"); - //WIN32_FIND_DATA data; - WIN32_FIND_DATAA data; - HANDLE hFind; - - WCHAR wstr[256]; - //http://msdn.microsoft.com/en-us/library/cc500362.aspx - MultiByteToWideChar(0, 0, pattern.c_str(), (int)pattern.length(), wstr, 256); - // LPCSTR lstr = wstr; - LPBOOL useddefault = FALSE; - // char fn[256]; - - if ((hFind = FindFirstFileA(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE) { - //if ((hFind = FindFirstFile(wstr, &data)) != INVALID_HANDLE_VALUE) { - do { - //WideCharToMultiByte(0, 0, data.cFileName, -1, fn, 256, NULL, useddefault); - //v.push_back(string(fn)); - v.push_back(data.cFileName); - } while (FindNextFileA(hFind, &data) != 0); - FindClose(hFind); - } - } -#else - void ceLog::ReadDir(const string& name, vector& v) - { - DIR* dirp = opendir(name.c_str()); - struct dirent * dp; - while ((dp = readdir(dirp)) != NULL) { - v.push_back(dp->d_name); - } - closedir(dirp); - } -#endif - -double ceLog::LastModified(const string& name) -{ - struct stat attrib; - struct tm *fmt; - ceDateTime dt; - if(stat(name.c_str(), &attrib)==0) - { - fmt = localtime(&(attrib.st_mtime)); - dt.SetDateTime(fmt->tm_year+1900,fmt->tm_mon+1,fmt->tm_mday, - fmt->tm_hour,fmt->tm_min,fmt->tm_sec); - // printf("Modified time: %s \n",dt.DateTimeString().c_str()); - } - else{ - // printf("Error in using stat.\n"); - } - return dt.jd(); -} -} // namespace ce diff --git a/src/ceMisc.cpp b/src/ceMisc.cpp deleted file mode 100644 index 50d8de6..0000000 --- a/src/ceMisc.cpp +++ /dev/null @@ -1,219 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceMisc.cpp -// Description: utility module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/ceMisc.h" -using namespace std; -namespace ce { - -// filter the string for alphanumeric characters only -string ceMisc::alnum(string str) -{ - str.erase(remove_if(str.begin(), str.end(), [](char ch) { - return !( - (ch >= '0' && ch <= '9') || - (ch >= 'A' && ch <= 'Z') || - (ch >= 'a' && ch <= 'z')); }), str.end()); - return str; -} - -// convert hex string to char vector -vector ceMisc::hex2cvec(string str) -{ - vector v; - str = ceMisc::alnum(str);// filter for alphanumeric characters - int n = (int)str.length(); - for (int i = 0; i < n; i += 2) - v.push_back((char)stoi(str.substr(i, 2), NULL, 16)); - return v; -} - -// convert hex string to byte string -std::string ceMisc::hex2str(std::string str) -{ - return ceMisc::cvec2str(ceMisc::hex2cvec(str)); -} - -// convert to hexadecimal string -std::string ceMisc::ToStr16(unsigned int u) -{ - ostringstream ss; - ss << setfill('0') << setw(2) << uppercase << hex << u; - return ss.str(); -} - -std::string ceMisc::ToStr16(int i) -{ - return ceMisc::ToStr16((unsigned int)i); -} - -std::string ceMisc::ToStr16(unsigned char c) -{ - return ceMisc::ToStr16((unsigned int)c); -} - -std::string ceMisc::ToStr16(char c) -{ - return ceMisc::ToStr16((unsigned char)c); -} - -// convert vector to hexadecimal string -std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { - std::vector uv(bv.begin(), bv.end()); - return ceMisc::ToStr16(uv,separator,prefix,postfix); -} - -// convert vector to hexadecimal string -std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { - ostringstream ss; - unsigned int u; - for (auto& c : bv) { - u = (unsigned char)c; - ss << prefix; - ss << setfill('0') << setw(2) << uppercase << hex << u << postfix; - if (&c != &bv.back()) ss << separator; - } - return ss.str(); -} - -// to hexadecimal string -std::string ceMisc::ToStr16(std::string str, std::string separator, std::string prefix, std::string postfix) -{ - return ceMisc::ToStr16(ceMisc::str2cvec(str), separator, prefix, postfix); -} - -// convert char vector to hex string -string ceMisc::cvec2hex(vector bv) { - ostringstream ss; - unsigned int u; - for (char& c : bv) { - u = (unsigned char)c; - ss << setfill('0') << setw(2) << uppercase << hex << u << " "; - } - return ss.str(); -} - -// convert char vector to string -string ceMisc::cvec2str(vector bv) { - ostringstream ss; - for (char& c : bv) { - ss << c; - } - return ss.str(); -} - - -// character vector to char* -void ceMisc::cvec2cptr(vector& v, char*& cstr, int& n) { - n = (int)v.size(); - cstr = v.data(); // reinterpret_cast(v.data()); -} - -// char* to char vector -vector ceMisc::cptr2cvec(char* cstr,int n) { - vector v(cstr, cstr + n); - return v; -} - -// convert char* to string -string ceMisc::cptr2str(char* cstr, int n) { - ostringstream ss; - for (int i = 0; i < n;i++) { - ss << cstr[i]; - } - return ss.str(); -} - -// string to char vector -vector ceMisc::str2cvec(string str) { - vector v(str.begin(), str.end()); - return v; -} - -string ceMisc::f2s(float f, int n) { - stringstream ss; - ss< ceMisc::splitStr(string str, string delimiter) -{ - size_t pos = 0; - vector tokens; - while ((pos = str.find(delimiter)) != string::npos) { - tokens.push_back(str.substr(0, pos)); - str.erase(0, pos + delimiter.length()); - } - tokens.push_back(str); - return tokens; -} - -std::string ceMisc::exepath() -{ -#ifdef CE_WINDOWS - char result[MAX_PATH]; - return std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); -#else - char result[PATH_MAX]; - ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); - return std::string(result, (count > 0) ? count : 0); -#endif -} - -std::string ceMisc::exedir() -{ - std::string str = exepath(); - std::size_t found = str.find_last_of("/\\"); - return str.substr(0, found + 1); -} - -bool ceMisc::kb_hit() // check keyboard hit -{ -#if defined(CE_WINDOWS) - return _kbhit(); -#else - // https://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux - termios term; - tcgetattr(0, &term); - - termios term2 = term; - term2.c_lflag &= ~ICANON; - tcsetattr(0, TCSANOW, &term2); - - int byteswaiting; - ioctl(0, FIONREAD, &byteswaiting); - - tcsetattr(0, TCSANOW, &term); - - return byteswaiting > 0; -#endif -} - -char ceMisc::get_ch() // get char -{ -#if defined(CE_WINDOWS) - return _getch(); -#else - //https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed - char buf = 0; - struct termios old = { 0 }; - if (tcgetattr(0, &old) < 0) - perror("tcsetattr()"); - old.c_lflag &= ~ICANON; - old.c_lflag &= ~ECHO; - old.c_cc[VMIN] = 1; - old.c_cc[VTIME] = 0; - if (tcsetattr(0, TCSANOW, &old) < 0) - perror("tcsetattr ICANON"); - if (read(0, &buf, 1) < 0) - perror("read()"); - old.c_lflag |= ICANON; - old.c_lflag |= ECHO; - if (tcsetattr(0, TCSADRAIN, &old) < 0) - perror("tcsetattr ~ICANON"); - return (buf); -#endif -} - -} // namespace ce \ No newline at end of file diff --git a/src/ceModbus.cpp b/src/ceModbus.cpp deleted file mode 100644 index 1917c2a..0000000 --- a/src/ceModbus.cpp +++ /dev/null @@ -1,207 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceModbus.cpp -// Description: Byte stuffing- sending and receiving frames -// Modbus RTU frame format (primarily used on asynchronous serial data lines like RS-485/EIA-485) -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceModbus.h" -namespace ce { -//----------------------------------------------------------------------------- -ceModbus::ceModbus():ceFrame(),_count(0), _frameSize(8), _tick_n(0), _reset_tick(CE_NUMBER_OF_TICKS_TO_RESET) { -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -size_t ceModbus::SetTxFrame(char* d, size_t n) -{ - if (n > (CE_FRAME_TX_BUF_SIZE - 2)) return 0;// size error - uint16_t txcrc = 0xFFFF;//initialize crc - char c; - size_t i = 0, j = 0; - for (j = 0; j < n; j++) { - c = d[j]; - // no need to check c in building Modbus frame - this->tb[i++] = c; - } - txcrc = this->CRC16((char*)d, n, txcrc);//calculate crc - this->tb[i++] = txcrc & 0xFF; - this->tb[i++] = (txcrc >> 8) & 0xFF; - this->TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -//Inputs -//s : pointer to input char string -//len: string len (maximum 255) -//crc: initial CRC value - -//Output -//Returns calculated CRC - -// Ref: http://cool-emerald.blogspot.com/2009/09/crc-calculation-in-vb-and-c.html -uint16_t ceModbus::CRC16(char* s, size_t len, uint16_t crc) -{ - //CRC Order: 16 - //CRC Poly: 0x8005 <=> A001 - //Operational initial value: 0xFFFF - //Final xor value: 0 - size_t i, j; - for (i = 0; i < len; i++, s++) { - crc ^= ((unsigned int)(*s)) & 0xFF; - for (j = 0; j < 8; j++) { - if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; - else crc >>= 1; - } - } - return (crc & 0xFFFF);//truncate last 16 bit -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -// CRC16 is also included -size_t ceModbus::ReceiveRxFrame(char c) -{ - // accept any value even 0x0D to get 8 bytes - // (not using start and end 28 bit length mark condition) - this->_tick_n = 0; // reset for every rx ch - this->RxN = 0; - this->rb[this->_count++] = c; - - if (this->_count == 3) { - // check function - if (this->rb[1] == 0x06) { - this->_frameSize = 8; // reply for control cmd - } - else if (this->rb[1] == 0x03) { - uint8_t len = (uint8_t)this->rb[2]; - this->_frameSize = 5 + len; // reply for read cmd - } - } - - // instead use frame size for particular frame - if (this->_count >= this->_frameSize) { - this->rb[this->_count] = 0;//null termination - this->RxN = this->_count; - this->_count = 0; - this->_frameSize = 8;// default - this->_tick_n = 0; // will clear RxN when time out - // for (int i = 0; i < this->RxN; i++) printf("%02X ", (unsigned int)this->rb[i] & 0xFF); - // uint16_t rxcrc = ((uint16_t)this->rb[this->RxN-1] << 8 | ((uint16_t)this->rb[this->RxN - 2] & 0xFF)) & 0xFFFF;//get received crc - uint16_t computed_crc = 0xFFFF;//initialize CRC - computed_crc = this->CRC16(rb, RxN, computed_crc);//calculate crc - // printf("\nComputed crc: %02X \n",computed_crc); - if (computed_crc == 0) { - //this->RxN -= 2; - return (this->RxN); //if crc is correct return bytes including crc - } - else { this->RxN = 0; }//discard the frame - } - return 0; -} - -// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx -// return = 0 : if no reset, 1 : if reset -int ceModbus::Tick() -{ - if (this->_tick_n <= this->_reset_tick) { - this->_tick_n++; - } - else { - this->_count = 0; - this->_frameSize = 8;// default - this->RxN = 0; - } - return this->_tick_n; -} - -// command vector without CRC16 -// CRC16 will be calculated and appended -void ceModbus::SetCmd(std::vector v) -{ - this->SetTxFrame((char*)v.data(), v.size()); -} - -void ceModbus::SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data) -{ - uint8_t ah = uint8_t((addr >> 8) & 0xFF); - uint8_t al = uint8_t(addr & 0xFF); - std::vector v = {slaveid,func,ah,al}; - v.insert(v.end(), data.begin(), data.end()); - this->SetCmd(v); -} - -void ceModbus::SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay) -{ - uint8_t ah = uint8_t((addr >> 8) & 0xFF); - uint8_t al = uint8_t(addr & 0xFF); - std::vector v = { slaveid,0x06,ah,al,command,delay }; - this->SetCmd(v); -} - -void ceModbus::SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len) -{ - uint8_t ah = uint8_t((startAddr >> 8) & 0xFF); - uint8_t al = uint8_t(startAddr & 0xFF); - uint8_t lh = uint8_t((len >> 8) & 0xFF); - uint8_t ll = uint8_t(len & 0xFF); - std::vector v = { slaveid,0x03,ah,al,lh,ll }; - this->SetCmd(v); -} - -// extract vector of status from received byte array -// crc16 bytes will be neglected if included -std::vector ceModbus::GetStatus(char* d, size_t n) -{ - std::vector v; - if (n < 3) { - // perror("Modbus frame error in getting status"); - return v; - } - - if (d[1] != 0x03) { - // perror("Frame must be Modbus read status return to get status"); - return v; - } - - uint8_t len = (uint8_t)d[2]; // get len - if (n < ((size_t)len+3)) { - // perror("Modbus frame length error in getting status"); - return v; - } - - uint16_t s; - uint8_t count = len >> 1;// 2 bytes each - for (uint8_t i = 0; i < count; i++) { - // for big endian - s = (uint8_t)d[3 + ((uint64_t)i<<1)]; - s <<= 8; - s |= (uint8_t)d[4 + ((uint64_t)i << 1)]; - v.push_back(s); - } - return v; -} - -std::vector ceModbus::GetTxVec() -{ - std::vector v((char*)tb, (char*)tb + this->TxN); - return v; -} - -std::vector ceModbus::GetRxVec() -{ - std::vector v((char*)rb, (char*)rb + this->RxN); - return v; -} - -void ceModbus::SetResetTickCount(int n) -{ - this->_reset_tick = n; -} - -int ceModbus::GetResetTickCount() -{ - return this->_reset_tick; -} - -} // namespace ce \ No newline at end of file diff --git a/src/cePCA9535.cpp b/src/cePCA9535.cpp deleted file mode 100644 index b5f82ba..0000000 --- a/src/cePCA9535.cpp +++ /dev/null @@ -1,89 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: cePCA9535.cpp -// Description: cePCA9535 - Digital IO chip -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/cePCA9535.h" - -namespace ce { - -cePCA9535::cePCA9535(uint8_t i2cBusNo, uint8_t Addr) : _bus(i2cBusNo),_addr(Addr) -{ - -} - -cePCA9535::~cePCA9535() -{ - -} - -bool cePCA9535::SetReg(uint8_t rVal, uint8_t rAddr) -{ - return this->SetReg(_addr,rVal,rAddr,_bus); -} - -bool cePCA9535::GetReg(uint8_t& rVal, uint8_t rAddr) -{ - return this->GetReg(_addr,rVal,rAddr,_bus); -} - -bool cePCA9535::Init(unsigned char outp0,unsigned char outp1, - unsigned char polarity0,unsigned char polarity1, - unsigned char conf0,unsigned char conf1) -{ - return this->Init(_addr, - outp0, outp1, - polarity0, polarity1, - conf0, conf1, _bus); -} - -bool cePCA9535::SetReg(uint8_t chipAddr, uint8_t rVal, uint8_t rAddr, uint8_t i2cBus) -{ - char d[] = { 0,0 }; - ce::ceI2C chip1(i2cBus, chipAddr); - d[0] = rAddr; - d[1] = rVal; - bool r = chip1.Write(d, 2); // send new register data - chip1.Close(); - if (r == false) { - printf("cePCA9535 I2C error at bus = %d, addr = 0x%X\n",i2cBus,chipAddr); - // perror("cePCA9535 I2C error"); - } - return r; -} - -bool cePCA9535::GetReg(uint8_t chipAddr, uint8_t& rVal, uint8_t rAddr, uint8_t i2cBus) -{ - char d[] = { 0,0 }; - ce::ceI2C chip1(i2cBus, chipAddr); - d[0] = rAddr; - bool r = chip1.Write(d, 1); // send new register data - r = r && chip1.Read(d, 1); - chip1.Close(); - if (r) { - rVal = d[0]; - } - else { - printf("cePCA9535 I2C error at bus = %d, addr = 0x%X\n",i2cBus,chipAddr); - // perror("cePCA9535 I2C error"); - } - return r; -} - -// initialize PCA9535 -bool cePCA9535::Init(unsigned char chipAddr, - unsigned char outp0, unsigned char outp1, - unsigned char polarity0, unsigned char polarity1, - unsigned char conf0, unsigned char conf1, int i2cbus) -{ - bool r = true; - r = r && this->SetReg(chipAddr, polarity0, PCA9535_POLARITY_P0_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, polarity1, PCA9535_POLARITY_P1_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, conf0, PCA9535_CONF_P0_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, conf1, PCA9535_CONF_P1_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, outp0, PCA9535_OUTPUT_P0_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, outp1, PCA9535_OUTPUT_P1_ADDR, i2cbus); - return r; -} - -} // namespace ce \ No newline at end of file diff --git a/src/ceSerial.cpp b/src/ceSerial.cpp deleted file mode 100644 index 2680f4c..0000000 --- a/src/ceSerial.cpp +++ /dev/null @@ -1,617 +0,0 @@ -// File: ceSerial.cpp -// Description: ceSerial communication class implementation for Windows and Linux -// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -// References -// https://en.wikibooks.org/wiki/Serial_Programming/termios -// http://www.silabs.com/documents/public/application-notes/an197.pdf -// https://msdn.microsoft.com/en-us/library/ff802693.aspx -// http://www.cplusplus.com/forum/unices/10491/ - -#include "ce/ceSerial.h" -#include -#include -#include -#include -using namespace std; - - -#ifdef CE_WINDOWS - #define READ_TIMEOUT 10 // milliseconds -#else - #include - #include - #include - #include - #include -#endif - -namespace ce { - -void ceSerial::Delay(unsigned long ms){ -#ifdef CE_WINDOWS - Sleep(ms); -#else - usleep(ms*1000); -#endif -} - -ceSerial::ceSerial() : -#ifdef CE_WINDOWS - ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1) -#else - ceSerial("/dev/ttyS0", 9600, 8, 'N', 1) -#endif -{ - -} - -ceSerial::ceSerial(string Device, long BaudRate,long DataSize,char ParityType,float NStopBits):stdbaud(true) -{ -#ifdef CE_WINDOWS - hComm = INVALID_HANDLE_VALUE; -#else - fd = -1; -#endif // defined - SetBaudRate(BaudRate); - SetDataSize(DataSize); - SetParity(ParityType); - SetStopBits(NStopBits); - SetPortName(Device); -} - -ceSerial::~ceSerial() -{ - Close(); -} - -void ceSerial::SetPortName(string Device) { - port = Device; -} - -string ceSerial::GetPort() { - return port; -} - -void ceSerial::SetDataSize(long nbits) { - if ((nbits < 5) || (nbits > 8)) nbits = 8; - dsize=nbits; -} - -long ceSerial::GetDataSize() { - return dsize; -} - -void ceSerial::SetParity(char p) { - if ((p != 'N') && (p != 'E') && (p != 'O')) { -#ifdef CE_WINDOWS - if ((p != 'M') && (p != 'S')) p = 'N'; -#else - p = 'N'; -#endif - } - parity = p; -} - -char ceSerial::GetParity() { - return parity; -} - -void ceSerial::SetStopBits(float nbits) { - if (nbits >= 2) stopbits = 2; -#ifdef CE_WINDOWS - else if(nbits >= 1.5) stopbits = 1.5; -#endif - else stopbits = 1; -} - -float ceSerial::GetStopBits() { - return stopbits; -} - - -#ifdef CE_WINDOWS - -void ceSerial::SetBaudRate(long baudrate) { - stdbaud = true; - if (baudrate == 1100) baud = CBR_110; - else if (baudrate == 300) baud = CBR_300; - else if (baudrate == 600) baud = CBR_600; - else if (baudrate == 1200) baud = CBR_1200; - else if (baudrate == 2400) baud = CBR_2400; - else if (baudrate == 4800) baud = CBR_4800; - else if (baudrate == 9600) baud = CBR_9600; - else if (baudrate == 14400) baud = CBR_14400; - else if (baudrate == 19200) baud = CBR_19200; - else if (baudrate == 38400) baud = CBR_38400; - else if (baudrate == 57600) baud = CBR_57600; - else if (baudrate == 115200) baud = CBR_115200; - else if (baudrate == 128000) baud = CBR_128000; - else if (baudrate == 256000) baud = CBR_256000; - else { - baud = baudrate; - stdbaud = false; - } -} - -long ceSerial::GetBaudRate() { - return baud; -} - -long ceSerial::Open() -{ - if (IsOpened()) return 0; -#ifdef UNICODE - wstring wtext(port.begin(),port.end()); -#else - string wtext = port; -#endif - hComm = CreateFile(wtext.c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, - 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, - 0); - if (hComm == INVALID_HANDLE_VALUE) {return -1;} - - if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) {return -1;}//purge - - //get initial state - DCB dcbOri; - bool fSuccess; - fSuccess = GetCommState(hComm, &dcbOri); - if (!fSuccess) {return -1;} - - DCB dcb1 = dcbOri; - - dcb1.BaudRate = baud; - - if (parity == 'E') dcb1.Parity = EVENPARITY; - else if (parity == 'O') dcb1.Parity = ODDPARITY; - else if (parity == 'M') dcb1.Parity = MARKPARITY; - else if (parity == 'S') dcb1.Parity = SPACEPARITY; - else dcb1.Parity = NOPARITY; - - dcb1.ByteSize = (BYTE)dsize; - - if(stopbits==2) dcb1.StopBits = TWOSTOPBITS; - else if (stopbits == 1.5) dcb1.StopBits = ONE5STOPBITS; - else dcb1.StopBits = ONESTOPBIT; - - dcb1.fOutxCtsFlow = false; - dcb1.fOutxDsrFlow = false; - dcb1.fOutX = false; - dcb1.fDtrControl = DTR_CONTROL_DISABLE; - dcb1.fRtsControl = RTS_CONTROL_DISABLE; - fSuccess = SetCommState(hComm, &dcb1); - this->Delay(60); - if (!fSuccess) {return -1;} - - fSuccess = GetCommState(hComm, &dcb1); - if (!fSuccess) {return -1;} - - osReader = { 0 };// Create the overlapped event. - // Must be closed before exiting to avoid a handle leak. - osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - - if (osReader.hEvent == NULL) {return -1;}// Error creating overlapped event; abort. - fWaitingOnRead = FALSE; - - osWrite = { 0 }; - osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if (osWrite.hEvent == NULL) {return -1;} - - if (!GetCommTimeouts(hComm, &timeouts_ori)) { return -1; } // Error getting time-outs. - COMMTIMEOUTS timeouts; - timeouts.ReadIntervalTimeout = 20; - timeouts.ReadTotalTimeoutMultiplier = 15; - timeouts.ReadTotalTimeoutConstant = 100; - timeouts.WriteTotalTimeoutMultiplier = 15; - timeouts.WriteTotalTimeoutConstant = 100; - if (!SetCommTimeouts(hComm, &timeouts)) { return -1;} // Error setting time-outs. - return 0; -} - -void ceSerial::Close() -{ - if (IsOpened()) - { - SetCommTimeouts(hComm, &timeouts_ori); - CloseHandle(osReader.hEvent); - CloseHandle(osWrite.hEvent); - CloseHandle(hComm);//close comm port - hComm = INVALID_HANDLE_VALUE; - } -} - -bool ceSerial::IsOpened() -{ - if(hComm == INVALID_HANDLE_VALUE) return false; - else return true; -} - - - -bool ceSerial::Write(char *data) -{ - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - long n = strlen(data); - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { - // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -bool ceSerial::Write(char *data,long n) -{ - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { - // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -bool ceSerial::WriteChar(char ch) -{ - char s[2]; - s[0]=ch; - s[1]=0;//null terminated - return Write(s); -} - -char ceSerial::ReadChar(bool& success) -{ - success = false; - if (!IsOpened()) {return 0;} - - DWORD dwRead; - DWORD length=1; - BYTE* data = (BYTE*)(&rxchar); - //the creation of the overlapped read operation - if (!fWaitingOnRead) { - // Issue read operation. - if (!ReadFile(hComm, data, length, &dwRead, &osReader)) { - if (GetLastError() != ERROR_IO_PENDING) { /*Error*/} - else { fWaitingOnRead = TRUE; /*Waiting*/} - } - else {if(dwRead==length) success = true;}//success - } - - - //detection of the completion of an overlapped read operation - DWORD dwRes; - if (fWaitingOnRead) { - dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT); - switch (dwRes) - { - // Read completed. - case WAIT_OBJECT_0: - if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) {/*Error*/ } - else { - if (dwRead == length) success = true; - fWaitingOnRead = FALSE; - // Reset flag so that another opertion can be issued. - }// Read completed successfully. - break; - - case WAIT_TIMEOUT: - // Operation isn't complete yet. - break; - - default: - // Error in the WaitForSingleObject; - break; - } - } - return rxchar; -} - -bool ceSerial::SetRTS(bool value) -{ - bool r = false; - if (IsOpened()) { - if (value) { - if (EscapeCommFunction(hComm, SETRTS)) r = true; - } - else { - if (EscapeCommFunction(hComm, CLRRTS)) r = true; - } - } - return r; -} - -bool ceSerial::SetDTR(bool value) -{ - bool r = false; - if (IsOpened()) { - if (value) { - if (EscapeCommFunction(hComm, SETDTR)) r = true; - } - else { - if (EscapeCommFunction(hComm, CLRDTR)) r = true; - } - } - return r; -} - -bool ceSerial::GetCTS(bool& success) -{ - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)){ - r = MS_CTS_ON & dwModemStatus; - success = true; - } - } - return r; -} - -bool ceSerial::GetDSR(bool& success) -{ - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_DSR_ON & dwModemStatus; - success = true; - } - } - return r; -} - -bool ceSerial::GetRI(bool& success) -{ - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_RING_ON & dwModemStatus; - success = true; - } - } - return r; -} - -bool ceSerial::GetCD(bool& success) -{ - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_RLSD_ON & dwModemStatus; - success = true; - } - } - return r; -} - -#else //for POSIX - -long ceSerial::Open(void) { - struct serial_struct serinfo; - struct termios settings; - memset(&settings, 0, sizeof(settings)); - settings.c_iflag = 0; - settings.c_oflag = 0; - - settings.c_cflag = CREAD | CLOCAL;//see termios.h for more information - if(dsize==5) settings.c_cflag |= CS5;//no change - else if (dsize == 6) settings.c_cflag |= CS6; - else if (dsize == 7) settings.c_cflag |= CS7; - else settings.c_cflag |= CS8; - - if(stopbits==2) settings.c_cflag |= CSTOPB; - - if(parity!='N') settings.c_cflag |= PARENB; - - if (parity == 'O') settings.c_cflag |= PARODD; - - settings.c_lflag = 0; - settings.c_cc[VMIN] = 1; - settings.c_cc[VTIME] = 0; - - fd = open(port.c_str(), O_RDWR | O_NONBLOCK); - if (fd == -1) { - return -1; - } - - if (!stdbaud) { - // serial driver to interpret the value B38400 differently - serinfo.reserved_char[0] = 0; - if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1;} - serinfo.flags &= ~ASYNC_SPD_MASK; - serinfo.flags |= ASYNC_SPD_CUST; - serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud; - if (serinfo.custom_divisor < 1) serinfo.custom_divisor = 1; - if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { return -1; } - if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1; } - if (serinfo.custom_divisor * baud != serinfo.baud_base) { - /* - warnx("actual baudrate is %d / %d = %f\n", - serinfo.baud_base, serinfo.custom_divisor, - (float)serinfo.baud_base / serinfo.custom_divisor); - */ - } - cfsetospeed(&settings, B38400); - cfsetispeed(&settings, B38400); - } - else { - cfsetospeed(&settings, baud); - cfsetispeed(&settings, baud); - } - tcsetattr(fd, TCSANOW, &settings); - int flags = fcntl(fd, F_GETFL, 0); - fcntl(fd, F_SETFL, flags | O_NONBLOCK); - - if (!stdbaud) { - // driver to interpret B38400 as 38400 baud again - ioctl(fd, TIOCGSERIAL, &serinfo); - serinfo.flags &= ~ASYNC_SPD_MASK; - ioctl(fd, TIOCSSERIAL, &serinfo); - } - return 0; -} - -void ceSerial::Close() { - if(IsOpened()) close(fd); - fd=-1; -} - -bool ceSerial::IsOpened() -{ - if(fd== (-1)) return false; - else return true; -} - -void ceSerial::SetBaudRate(long baudrate) { - stdbaud = true; - if (baudrate == 0) baud = B0; - else if (baudrate == 50) baud = B50; - else if (baudrate == 75) baud = B75; - else if (baudrate == 110) baud = B110; - else if (baudrate == 134) baud = B134; - else if (baudrate == 150) baud = B150; - else if (baudrate == 200) baud = B200; - else if (baudrate == 300) baud = B300; - else if (baudrate == 600) baud = B600; - else if (baudrate == 1200) baud = B1200; - else if (baudrate == 2400) baud = B2400; - else if (baudrate == 4800) baud = B4800; - else if (baudrate == 9600) baud = B9600; - else if (baudrate == 19200) baud = B19200; - else if (baudrate == 38400) baud = B38400; - else if (baudrate == 57600) baud = B57600; - else if (baudrate == 115200) baud = B115200; - else if (baudrate == 230400) baud = B230400; - else { - baud = baudrate; - stdbaud = false; - } -} - -long ceSerial::GetBaudRate() { - return baud; -} -char ceSerial::ReadChar(bool& success) -{ - success=false; - if (!IsOpened()) {return 0; } - success=read(fd, &rxchar, 1)==1; - return rxchar; -} - -bool ceSerial::Write(char *data) -{ - if (!IsOpened()) {return false; } - long n = strlen(data); - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -bool ceSerial::Write(char *data,long n) -{ - if (!IsOpened()) {return false; } - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -bool ceSerial::WriteChar(char ch) -{ - char s[2]; - s[0]=ch; - s[1]=0;//null terminated - return Write(s); -} - -bool ceSerial::SetRTS(bool value) { - long RTS_flag = TIOCM_RTS; - bool success=true; - if (value) {//Set RTS pin - if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) success=false; - } - else {//Clear RTS pin - if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) success=false; - } - return success; -} - -bool ceSerial::SetDTR(bool value) { - long DTR_flag = TIOCM_DTR; - bool success=true; - if (value) {//Set DTR pin - if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) success=false; - } - else {//Clear DTR pin - if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) success=false; - } - return success; -} - -bool ceSerial::GetCTS(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_CTS) != 0); -} - -bool ceSerial::GetDSR(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_DSR) != 0); -} - -bool ceSerial::GetRI(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_RI) != 0); -} - -bool ceSerial::GetCD(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_CD) != 0); -} -#endif - -} // namespace ce diff --git a/src/ceWxSerial.cpp b/src/ceWxSerial.cpp deleted file mode 100644 index 1ce9dea..0000000 --- a/src/ceWxSerial.cpp +++ /dev/null @@ -1,53 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceWxSerial.cpp -// Description: Serial module for wxWidgets -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/ceWxSerial.h" -#if CE_WX==1 - -using namespace std; - -namespace ce { - -//ctor -ceWxSerial::ceWxSerial(wxEvtHandler* app,int id, int interval, - std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits) - : _app(app), _id(id), _interval(interval), ceSerial(Device, BaudRate, DataSize, ParityType, NStopBits) -{ - this->_timer = new wxTimer(this, _id); - Connect(_id, wxEVT_TIMER, wxTimerEventHandler(ceWxSerial::OnTimer)); - this->_timer->Start(_interval - 1); -} - -ceWxSerial::~ceWxSerial() -{ - -} - -void ceWxSerial::OnTimer(wxTimerEvent& WXUNUSED(event)) -{ - vector vc = this->Chk(); - if (vc.size() > 0) { - wxThreadEvent event(wxEVT_THREAD, _id); - event.SetPayload(vc); - // send in a thread-safe way - wxQueueEvent(_app, event.Clone()); - } -} - -vector ceWxSerial::Chk() -{ - vector vc; - char ch; bool r; - do { - ch = this->ReadChar(r); - if (r) { - vc.push_back(ch); - } - } while (r); - return vc; -} - -} // namespace ce -#endif // CE_WX diff --git a/src/ceWxTmr.cpp b/src/ceWxTmr.cpp deleted file mode 100644 index d99bb61..0000000 --- a/src/ceWxTmr.cpp +++ /dev/null @@ -1,35 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceWxTmr.cpp -// Description: Timer module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#include "ce/ceWxTmr.h" -#if CE_WX==1 -#include -using namespace std; -namespace ce { -//ctor -ceWxTmr::ceWxTmr(wxEvtHandler* app,int id, int interval) : _app(app), _id(id), _interval(interval) -{ - this->_timer = new wxTimer(this, _id); - Connect(_id, wxEVT_TIMER, wxTimerEventHandler(ceWxTmr::OnTimer)); -} - -void ceWxTmr::OnTimer(wxTimerEvent& WXUNUSED(event)) -{ - printf("ceWxTmr event...\n"); - vector vc = {64,65}; - wxThreadEvent event( wxEVT_THREAD, _id ); - event.SetPayload(vc); - // send in a thread-safe way - wxQueueEvent( _app, event.Clone() ); -} - -void ceWxTmr::Start() -{ - this->_timer->Start(_interval-1); -} - -} // namespace ce -#endif // CE_WX \ No newline at end of file diff --git a/vcprj/ceutil.vcxproj b/vcprj/ceutil.vcxproj index 273bef6..9f2d81f 100644 --- a/vcprj/ceutil.vcxproj +++ b/vcprj/ceutil.vcxproj @@ -20,50 +20,33 @@ - + - - - - - + + + + + - - - - - - + + + - - - - - - - - - - - - - - - - + + 16.0 diff --git a/vcprj/ceutil.vcxproj.filters b/vcprj/ceutil.vcxproj.filters index b705fe2..c328023 100644 --- a/vcprj/ceutil.vcxproj.filters +++ b/vcprj/ceutil.vcxproj.filters @@ -21,116 +21,59 @@ Header Files - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - Source Files - - Source Files - Source Files - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - Source Files @@ -145,5 +88,11 @@ etc + + etc + + + etc + \ No newline at end of file From 8c88fdba60eb464eb7af3eec3d51fbd5f4ca1ea2 Mon Sep 17 00:00:00 2001 From: yan9a Date: Sat, 24 Aug 2024 16:02:41 +1200 Subject: [PATCH 04/10] Update names --- include/ce/ceMacros.h | 43 - include/ce/ceSHA1.h | 57 - include/ce/{ceDES.h => cedesx.h} | 946 ++++++++-------- include/ce/{ceFraCmd.h => cefracmdx.h} | 120 +- include/ce/{ceFrame.h => ceframex.h} | 332 +++--- include/ce/{ceI2C.h => cei2cx.h} | 322 +++--- include/ce/{ceLog.h => celogx.h} | 638 +++++------ include/ce/{ceMisc.h => cemiscx.h} | 618 +++++----- include/ce/{ceModbus.h => cemodbusx.h} | 486 ++++---- include/ce/{cePCA9535.h => cepca9535x.h} | 258 ++--- include/ce/{ceSerial.h => ceserialx.h} | 1320 +++++++++++----------- src/ceSHA1.cpp => include/ce/cesha1x.h | 681 +++++------ include/ce/{ceTcpClient.h => cetcpcli.h} | 38 +- include/ce/{ceUDP.h => ceudpx.h} | 151 ++- include/ce/cewxcvMisc.h | 38 +- vcprj/ceutil.vcxproj | 8 +- vcprj/ceutil.vcxproj.filters | 24 +- 17 files changed, 3071 insertions(+), 3009 deletions(-) delete mode 100644 include/ce/ceMacros.h delete mode 100644 include/ce/ceSHA1.h rename include/ce/{ceDES.h => cedesx.h} (96%) rename include/ce/{ceFraCmd.h => cefracmdx.h} (96%) rename include/ce/{ceFrame.h => ceframex.h} (96%) rename include/ce/{ceI2C.h => cei2cx.h} (95%) rename include/ce/{ceLog.h => celogx.h} (95%) rename include/ce/{ceMisc.h => cemiscx.h} (96%) rename include/ce/{ceModbus.h => cemodbusx.h} (96%) rename include/ce/{cePCA9535.h => cepca9535x.h} (96%) rename include/ce/{ceSerial.h => ceserialx.h} (96%) rename src/ceSHA1.cpp => include/ce/cesha1x.h (74%) rename include/ce/{ceTcpClient.h => cetcpcli.h} (67%) rename include/ce/{ceUDP.h => ceudpx.h} (69%) diff --git a/include/ce/ceMacros.h b/include/ce/ceMacros.h deleted file mode 100644 index 2299f55..0000000 --- a/include/ce/ceMacros.h +++ /dev/null @@ -1,43 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceMacros.h -// Description: Predefined macros for ceUtil -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_MACROS_H -#define CE_MACROS_H - -#define CE_JSON 1 // include JSON -#define CE_WX 1 // include WX -#define CE_CV 1 // include CV -#define CE_DBG_PRINT 0 // print dbg mes - -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif -#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif -#else - #ifndef CE_NOS - #define CE_NOS - #endif -#endif - -#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) - #ifndef CE_x86_64 - #define CE_x86_64 - #endif -#elif defined(__arm__) || defined(_M_ARM) - #ifndef CE_ARM - #define CE_ARM - #endif -#else - #ifndef CE_NARCH - #define CE_NARCH - #endif -#endif - -#endif // CE_MACROS_H \ No newline at end of file diff --git a/include/ce/ceSHA1.h b/include/ce/ceSHA1.h deleted file mode 100644 index 7a0c4fe..0000000 --- a/include/ce/ceSHA1.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef SHA1_H -#define SHA1_H - -/* - SHA-1 in C - By Steve Reid - 100% Public Domain - */ - // Description: Functions to calculate SHA1 - // Class implementation of the following repository: https://github.com/clibs/sha1 - -#include "stdint.h" -#include - - namespace ce { - typedef struct - { - uint32_t state[5]; - uint32_t count[2]; - unsigned char buffer[64]; - } SHA1_CTX; - - class ceSHA1 { - private: - SHA1_CTX sha; - //----------------------------------------------------------------------------- - void SHA1Transform( - uint32_t state[5], - const unsigned char buffer[64] - ); - - void SHA1Init( - SHA1_CTX* context - ); - - void SHA1Update( - SHA1_CTX* context, - const unsigned char* data, - uint32_t len - ); - - void SHA1Final( - unsigned char digest[20], - SHA1_CTX* context - ); - void SHA1( - char* hash_out, - const char* str, - uint32_t len); - public: - void Init(); - void Update(std::string str); - std::string Final(); - }; - } // namespace ce - -#endif /* SHA1_H */ diff --git a/include/ce/ceDES.h b/include/ce/cedesx.h similarity index 96% rename from include/ce/ceDES.h rename to include/ce/cedesx.h index 5f5404b..2e295ec 100644 --- a/include/ce/ceDES.h +++ b/include/ce/cedesx.h @@ -1,474 +1,474 @@ -///////////////////////////////////////////////////////////////////////////// -// File: cedes.h -// Description: Simple C functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) -// Repository: https://github.com/yan9a/cedes -// WebSite: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2023 Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -// Related links -// https://www.rapidtables.com/convert/number/ascii-to-hex.html -// https://emvlab.org/descalc/ -// https://paymentcardtools.com/crypto-calculators/des-calculator -// https://github.com/yan9a/cecpp/blob/master/des_cryptopp/main.cpp -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEDES_H -#define CEDES_H - -#if defined(__cplusplus) -extern "C" { -#endif - -// Functions -// void ceDES_Encrypt(unsigned char *dMes,unsigned char *dKey); -// void ceDES_Decrypt(unsigned char *dMes,unsigned char *dKey); -// void ceTDES_Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR); -// void ceTDES_Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR); - -///////////////////////////////////////////////////////////////////////////// -// Implementation - -//----------------------------------------------------------------------------- -// Init permutation table -// 64 bit data -> 64 bit data -const unsigned char IP_table[64] = { - 58, 50, 42, 34, 26, 18, 10, 2, - 60, 52, 44, 36, 28, 20, 12, 4, - 62, 54, 46, 38, 30, 22, 14, 6, - 64, 56, 48, 40, 32, 24, 16, 8, - 57, 49, 41, 33, 25, 17, 9, 1, - 59, 51, 43, 35, 27, 19, 11, 3, - 61, 53, 45, 37, 29, 21, 13, 5, - 63, 55, 47, 39, 31, 23, 15, 7 }; -//----------------------------------------------------------------------------- -//Permuted Choice 1 -// Key permutation table -// 64 bit key data -> 56 bit key data -const unsigned char PC1_table[56] = { - 57, 49, 41, 33, 25, 17, 9, - 1, 58, 50, 42, 34, 26, 18, - 10, 2, 59, 51, 43, 35, 27, - 19, 11, 3, 60, 52, 44, 36, - 63, 55, 47, 39, 31, 23, 15, - 7, 62, 54, 46, 38, 30, 22, - 14, 6, 61, 53, 45, 37, 29, - 21, 13, 5, 28, 20, 12, 4 }; -//----------------------------------------------------------------------------- -// Key shift table -const unsigned char LeftShift_table[16] = { - 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; -//----------------------------------------------------------------------------- -// Key Compression permutation table -// 56 bit key data -> 48 bit -const unsigned char PC2_table[48] = { - 14, 17, 11, 24, 1, 5, 3, 28, - 15, 6, 21, 10, 23, 19, 12, 4, - 26, 8, 16, 7, 27, 20, 13, 2, - 41, 52, 31, 37, 47, 55, 30, 40, - 51, 45, 33, 48, 44, 49, 39, 56, - 34, 53, 46, 42, 50, 36, 29, 32 }; -//----------------------------------------------------------------------------- -// Expansion permutation table -// 32 bit data -> 48 bit data -const unsigned char E_table[48] = { - 32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9, 10, 11, 12, 13, - 12, 13, 14, 15, 16, 17, - 16, 17, 18, 19, 20, 21, - 20, 21, 22, 23, 24, 25, - 24, 25, 26, 27, 28, 29, - 28, 29, 30, 31, 32, 1 }; -//----------------------------------------------------------------------------- -const unsigned char S[8][4][16] = { - { - {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, - {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, - {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, - {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} - }, - { - {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, - {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, - {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, - {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} - }, - { - {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, - {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, - {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, - {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} - }, - { - {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, - {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, - {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, - {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} - }, - { - {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, - {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, - {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, - {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} - }, - { - {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, - {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, - {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, - {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} - }, - { - {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, - {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, - {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, - {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} - }, - { - {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, - {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, - {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, - {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} - } - }; -//----------------------------------------------------------------------------- -// Strait permutation table -// 32 bit data -> 32 bit data -const unsigned char P_table[32] = { - 16, 7, 20, 21, 29, 12, 28, 17, - 1, 15, 23, 26, 5, 18, 31, 10, - 2, 8, 24, 14, 32, 27, 3, 9, - 19, 13, 30, 6, 22, 11, 4, 25 }; -//----------------------------------------------------------------------------- -// Inverse permutation table -// 64 bit data -> 64 bit data -const unsigned char InverseIP_table[64] = { - 40, 8, 48, 16, 56, 24, 64, 32, - 39, 7, 47, 15, 55, 23, 63, 31, - 38, 6, 46, 14, 54, 22, 62, 30, - 37, 5, 45, 13, 53, 21, 61, 29, - 36, 4, 44, 12, 52, 20, 60, 28, - 35, 3, 43, 11, 51, 19, 59, 27, - 34, 2, 42, 10, 50, 18, 58, 26, - 33, 1, 41, 9, 49, 17, 57, 25 }; -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//pData =input to permutate -//ni =number of input bytes -//pTable =permutation table -//no =number of output bytes -void ceDES_Permutate(unsigned char *pData,unsigned char ni, - unsigned char *pTable,unsigned char no) -{ - unsigned char temp[8]; - unsigned char i,j,x; - unsigned char ByteI,BitIndex; - - for(i=0;i>3];//divided by 8 - BitIndex =7-(BitIndex & 7);//mod 8 - x|=((ByteI>>BitIndex) & 0x01); - } - *pData=x; - } - -}; -//----------------------------------------------------------------------------- -//nKey -Key to shift -//b -number of bits -//priority to speed rather than code size -void ceDES_LeftShift(unsigned char *nKey,unsigned char b) -{ - unsigned char x,y,c; - c=8-b; - - //avoid loop to get linear code - x=nKey[6]; - nKey[6]=x<>c; - - x=nKey[5]; - nKey[5]=(x<>c; - - x=nKey[4]; - nKey[4]=(x<>c; - - x=nKey[3]; - nKey[3]=(x<>c; - - x<<=4; - nKey[6]|=x>>c; - - x=nKey[2]; - nKey[2]=(x<>c; - - x=nKey[1]; - nKey[1]=(x<>c; - - x=nKey[0]; - nKey[0]=(x<>c; - - x=(b==1)?0xEF:0xCF; - x &=nKey[3]; - nKey[3]=x|(y<<4); -}; -//----------------------------------------------------------------------------- -//nKey -Key to shift -//b -number of bits -//written for speed -void ceDES_RightShift(unsigned char *nKey,unsigned char b) -{ - unsigned char x,y,c; - c=8-b; - - //avoid loop to get linear code - x=nKey[0]; - nKey[0]=x>>b; - y=x<>b)|y; - y=x<>b)|y; - y=x<>b)|y; - y=x<>=4; - nKey[0]|=x<>b)|y; - y=x<>b)|y; - y=x<>b)|y; - y=x<>4); -}; -//----------------------------------------------------------------------------- -//written for speed -void ceDES_Expand(unsigned char *R) -{ - unsigned char a,b,c,d,x; - a=R[0]; - b=R[1]; - c=R[2]; - d=R[3]; - - x=(d<<7) & 0x80;//bit 32 to 1 - x|=((a>>1) & 0x7C); - x|=((a>>3) & 0x03); - R[0]=x; - - x=(a<<5) & 0xE0; - x|=(b>>3) & 0x10; - x|=(a<<3) & 0x08; - x|=(b>>5) & 0x07; - R[1]=x; - - x=(b<<3) & 0xC0; - x|=((b<<1) & 0x3E); - x|=((c>>7) & 0x01); - R[2]=x; - - x=(b<<7) & 0x80; - x|=((c>>1) & 0x7C); - x|=((c>>3) & 0x03); - R[3]=x; - - x=(c<<5) & 0xE0; - x|=(d>>3) & 0x10; - x|=(c<<3) & 0x08; - x|=(d>>5) & 0x07; - R[4]=x; - - x=(d<<3) & 0xC0; - x|=((d<<1) & 0x3E); - x|=((a>>7) & 0x01); - R[5]=x; -}; -//----------------------------------------------------------------------------- -//written for speed -void ceDES_F(unsigned char *R,unsigned char *K) -{ - unsigned char i,r,c; - - //special function for expansion to improve speed - ceDES_Expand(R); - - for(i=0;i<6;i++) K[i]^=R[i]; - - //R[0]=S0 S1 - c=(K[0]>>3) & 0x0F; - r=(K[0]>>2) & 1; - r|=(K[0]>>6) & 2; - R[0]=(S[0][r][c])<<4; - - c=(K[0]<<3) & 0x08; - c |=(K[1]>>5) & 0x07; - r=(K[1]>>4) & 1; - r|=(K[0] & 2); - R[0]|=(S[1][r][c]); - - //R[1]=S2 S3 - c=(K[1]<<1) & 0x0E; - c|=(K[2]>>7) & 1; - r=(K[2]>>6) & 1; - r|=(K[1]>>2) & 2; - R[1]=(S[2][r][c])<<4; - - c=(K[2]>>1) & 0x0F; - r=K[2] & 1; - r|=(K[2]>>4) & 2; - R[1]|=(S[3][r][c]); - - //R[2]=S4 S5 - c=(K[3]>>3) & 0x0F; - r=(K[3]>>2) & 1; - r|=(K[3]>>6) & 2; - R[2]=(S[4][r][c])<<4; - - c=(K[3]<<3) & 0x08; - c |=(K[4]>>5) & 0x07; - r=(K[4]>>4) & 1; - r|=(K[3] & 2); - R[2]|=(S[5][r][c]); - - //R[3]=S6 S7 - c=(K[4]<<1) & 0x0E; - c|=(K[5]>>7) & 1; - r=(K[5]>>6) & 1; - r|=(K[4]>>2) & 2; - R[3]=(S[6][r][c])<<4; - - c=(K[5]>>1) & 0x0F; - r=K[5] & 1; - r|=(K[5]>>4) & 2; - R[3]|=(S[7][r][c]); - - //Permutate the S box output - ceDES_Permutate(R,4,(unsigned char *)P_table,4);//32 bit output -}; -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//dMes=Message to encrypt -//dKey=Key -void ceDES_Encrypt(unsigned char *dMes,unsigned char *dKey) -{ - unsigned char Kn[7]; - unsigned char Rn_1[6]; - unsigned char n,i; - unsigned char dKeyC[8]; - for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key - - ceDES_Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output - ceDES_Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output - for(n=0;n<16;n++) - { - ceDES_LeftShift(dKeyC,LeftShift_table[n]); - for(i=0;i<7;i++) Kn[i]=dKeyC[i]; - ceDES_Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output - for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; - ceDES_F(Rn_1,Kn); - - if(n>=15) - { - for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; - break; - } - for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; - for(i=0;i<4;i++) dMes[i]=dMes[i+4]; - for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; - } - ceDES_Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output -}; -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//dMes=Message to decrypt -//dKey=Key -void ceDES_Decrypt(unsigned char *dMes,unsigned char *dKey) -{ - unsigned char Kn[7]; - unsigned char Rn_1[6]; - unsigned char n,i; - unsigned char dKeyC[8]; - for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key - - ceDES_Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output - ceDES_Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output - - for(n=0;n<16;n++) - { - for(i=0;i<7;i++) Kn[i]=dKeyC[i]; - ceDES_Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output - for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; - ceDES_F(Rn_1,Kn); - - if(n>=15) - { - for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; - break; - } - for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; - for(i=0;i<4;i++) dMes[i]=dMes[i+4]; - for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; - ceDES_RightShift(dKeyC,LeftShift_table[15-n]); - } - ceDES_Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output -}; -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//dMes=Message to encrypt -//dKeyL=KeyLeft -//dKeyR=KeyRight -void ceTDES_Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) -{ - ceDES_Encrypt(dMes,dKeyL); - ceDES_Decrypt(dMes,dKeyR); - ceDES_Encrypt(dMes,dKeyL); -}; -//----------------------------------------------------------------------------- -//dMes=Message to decrypt -//dKeyL=KeyLeft -//dKeyR=KeyRight -void ceTDES_Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) -{ - ceDES_Decrypt(dMes,dKeyL); - ceDES_Encrypt(dMes,dKeyR); - ceDES_Decrypt(dMes,dKeyL); -}; -//----------------------------------------------------------------------------- - -///////////////////////////////////////////////////////////////////////////// - -#if defined(__cplusplus) -} -#endif - +///////////////////////////////////////////////////////////////////////////// +// File: cedes.h +// Description: Simple C functions to calculate DES (Data Encryption Standard) and 3DES (Triple DES) +// Repository: https://github.com/yan9a/cedes +// WebSite: http://cool-emerald.blogspot.com +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2023 Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// +// Related links +// https://www.rapidtables.com/convert/number/ascii-to-hex.html +// https://emvlab.org/descalc/ +// https://paymentcardtools.com/crypto-calculators/des-calculator +// https://github.com/yan9a/cecpp/blob/master/des_cryptopp/main.cpp +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEDES_H +#define CEDES_H + +#if defined(__cplusplus) +extern "C" { +#endif + +// Functions +// void ceDES_Encrypt(unsigned char *dMes,unsigned char *dKey); +// void ceDES_Decrypt(unsigned char *dMes,unsigned char *dKey); +// void ceTDES_Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR); +// void ceTDES_Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR); + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +//----------------------------------------------------------------------------- +// Init permutation table +// 64 bit data -> 64 bit data +const unsigned char IP_table[64] = { + 58, 50, 42, 34, 26, 18, 10, 2, + 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, + 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, + 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, + 63, 55, 47, 39, 31, 23, 15, 7 }; +//----------------------------------------------------------------------------- +//Permuted Choice 1 +// Key permutation table +// 64 bit key data -> 56 bit key data +const unsigned char PC1_table[56] = { + 57, 49, 41, 33, 25, 17, 9, + 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, + 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, + 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, + 21, 13, 5, 28, 20, 12, 4 }; +//----------------------------------------------------------------------------- +// Key shift table +const unsigned char LeftShift_table[16] = { + 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; +//----------------------------------------------------------------------------- +// Key Compression permutation table +// 56 bit key data -> 48 bit +const unsigned char PC2_table[48] = { + 14, 17, 11, 24, 1, 5, 3, 28, + 15, 6, 21, 10, 23, 19, 12, 4, + 26, 8, 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, 30, 40, + 51, 45, 33, 48, 44, 49, 39, 56, + 34, 53, 46, 42, 50, 36, 29, 32 }; +//----------------------------------------------------------------------------- +// Expansion permutation table +// 32 bit data -> 48 bit data +const unsigned char E_table[48] = { + 32, 1, 2, 3, 4, 5, + 4, 5, 6, 7, 8, 9, + 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, + 16, 17, 18, 19, 20, 21, + 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, + 28, 29, 30, 31, 32, 1 }; +//----------------------------------------------------------------------------- +const unsigned char S[8][4][16] = { + { + {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, + {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, + {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, + {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} + }, + { + {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, + {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, + {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, + {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} + }, + { + {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, + {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, + {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, + {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} + }, + { + {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, + {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, + {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, + {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} + }, + { + {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, + {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, + {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, + {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} + }, + { + {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, + {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, + {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, + {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} + }, + { + {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, + {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, + {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, + {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} + }, + { + {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, + {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, + {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, + {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} + } + }; +//----------------------------------------------------------------------------- +// Strait permutation table +// 32 bit data -> 32 bit data +const unsigned char P_table[32] = { + 16, 7, 20, 21, 29, 12, 28, 17, + 1, 15, 23, 26, 5, 18, 31, 10, + 2, 8, 24, 14, 32, 27, 3, 9, + 19, 13, 30, 6, 22, 11, 4, 25 }; +//----------------------------------------------------------------------------- +// Inverse permutation table +// 64 bit data -> 64 bit data +const unsigned char InverseIP_table[64] = { + 40, 8, 48, 16, 56, 24, 64, 32, + 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, + 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, + 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, + 33, 1, 41, 9, 49, 17, 57, 25 }; +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//pData =input to permutate +//ni =number of input bytes +//pTable =permutation table +//no =number of output bytes +void ceDES_Permutate(unsigned char *pData,unsigned char ni, + unsigned char *pTable,unsigned char no) +{ + unsigned char temp[8]; + unsigned char i,j,x; + unsigned char ByteI,BitIndex; + + for(i=0;i>3];//divided by 8 + BitIndex =7-(BitIndex & 7);//mod 8 + x|=((ByteI>>BitIndex) & 0x01); + } + *pData=x; + } + +}; +//----------------------------------------------------------------------------- +//nKey -Key to shift +//b -number of bits +//priority to speed rather than code size +void ceDES_LeftShift(unsigned char *nKey,unsigned char b) +{ + unsigned char x,y,c; + c=8-b; + + //avoid loop to get linear code + x=nKey[6]; + nKey[6]=x<>c; + + x=nKey[5]; + nKey[5]=(x<>c; + + x=nKey[4]; + nKey[4]=(x<>c; + + x=nKey[3]; + nKey[3]=(x<>c; + + x<<=4; + nKey[6]|=x>>c; + + x=nKey[2]; + nKey[2]=(x<>c; + + x=nKey[1]; + nKey[1]=(x<>c; + + x=nKey[0]; + nKey[0]=(x<>c; + + x=(b==1)?0xEF:0xCF; + x &=nKey[3]; + nKey[3]=x|(y<<4); +}; +//----------------------------------------------------------------------------- +//nKey -Key to shift +//b -number of bits +//written for speed +void ceDES_RightShift(unsigned char *nKey,unsigned char b) +{ + unsigned char x,y,c; + c=8-b; + + //avoid loop to get linear code + x=nKey[0]; + nKey[0]=x>>b; + y=x<>b)|y; + y=x<>b)|y; + y=x<>b)|y; + y=x<>=4; + nKey[0]|=x<>b)|y; + y=x<>b)|y; + y=x<>b)|y; + y=x<>4); +}; +//----------------------------------------------------------------------------- +//written for speed +void ceDES_Expand(unsigned char *R) +{ + unsigned char a,b,c,d,x; + a=R[0]; + b=R[1]; + c=R[2]; + d=R[3]; + + x=(d<<7) & 0x80;//bit 32 to 1 + x|=((a>>1) & 0x7C); + x|=((a>>3) & 0x03); + R[0]=x; + + x=(a<<5) & 0xE0; + x|=(b>>3) & 0x10; + x|=(a<<3) & 0x08; + x|=(b>>5) & 0x07; + R[1]=x; + + x=(b<<3) & 0xC0; + x|=((b<<1) & 0x3E); + x|=((c>>7) & 0x01); + R[2]=x; + + x=(b<<7) & 0x80; + x|=((c>>1) & 0x7C); + x|=((c>>3) & 0x03); + R[3]=x; + + x=(c<<5) & 0xE0; + x|=(d>>3) & 0x10; + x|=(c<<3) & 0x08; + x|=(d>>5) & 0x07; + R[4]=x; + + x=(d<<3) & 0xC0; + x|=((d<<1) & 0x3E); + x|=((a>>7) & 0x01); + R[5]=x; +}; +//----------------------------------------------------------------------------- +//written for speed +void ceDES_F(unsigned char *R,unsigned char *K) +{ + unsigned char i,r,c; + + //special function for expansion to improve speed + ceDES_Expand(R); + + for(i=0;i<6;i++) K[i]^=R[i]; + + //R[0]=S0 S1 + c=(K[0]>>3) & 0x0F; + r=(K[0]>>2) & 1; + r|=(K[0]>>6) & 2; + R[0]=(S[0][r][c])<<4; + + c=(K[0]<<3) & 0x08; + c |=(K[1]>>5) & 0x07; + r=(K[1]>>4) & 1; + r|=(K[0] & 2); + R[0]|=(S[1][r][c]); + + //R[1]=S2 S3 + c=(K[1]<<1) & 0x0E; + c|=(K[2]>>7) & 1; + r=(K[2]>>6) & 1; + r|=(K[1]>>2) & 2; + R[1]=(S[2][r][c])<<4; + + c=(K[2]>>1) & 0x0F; + r=K[2] & 1; + r|=(K[2]>>4) & 2; + R[1]|=(S[3][r][c]); + + //R[2]=S4 S5 + c=(K[3]>>3) & 0x0F; + r=(K[3]>>2) & 1; + r|=(K[3]>>6) & 2; + R[2]=(S[4][r][c])<<4; + + c=(K[3]<<3) & 0x08; + c |=(K[4]>>5) & 0x07; + r=(K[4]>>4) & 1; + r|=(K[3] & 2); + R[2]|=(S[5][r][c]); + + //R[3]=S6 S7 + c=(K[4]<<1) & 0x0E; + c|=(K[5]>>7) & 1; + r=(K[5]>>6) & 1; + r|=(K[4]>>2) & 2; + R[3]=(S[6][r][c])<<4; + + c=(K[5]>>1) & 0x0F; + r=K[5] & 1; + r|=(K[5]>>4) & 2; + R[3]|=(S[7][r][c]); + + //Permutate the S box output + ceDES_Permutate(R,4,(unsigned char *)P_table,4);//32 bit output +}; +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//dMes=Message to encrypt +//dKey=Key +void ceDES_Encrypt(unsigned char *dMes,unsigned char *dKey) +{ + unsigned char Kn[7]; + unsigned char Rn_1[6]; + unsigned char n,i; + unsigned char dKeyC[8]; + for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key + + ceDES_Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output + ceDES_Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output + for(n=0;n<16;n++) + { + ceDES_LeftShift(dKeyC,LeftShift_table[n]); + for(i=0;i<7;i++) Kn[i]=dKeyC[i]; + ceDES_Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output + for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; + ceDES_F(Rn_1,Kn); + + if(n>=15) + { + for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; + break; + } + for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; + for(i=0;i<4;i++) dMes[i]=dMes[i+4]; + for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; + } + ceDES_Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output +}; +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//dMes=Message to decrypt +//dKey=Key +void ceDES_Decrypt(unsigned char *dMes,unsigned char *dKey) +{ + unsigned char Kn[7]; + unsigned char Rn_1[6]; + unsigned char n,i; + unsigned char dKeyC[8]; + for(i=0;i<8;i++) dKeyC[i]=dKey[i];//copy key + + ceDES_Permutate(dMes,8,(unsigned char *)IP_table,8);//64 bit output + ceDES_Permutate(dKeyC,8,(unsigned char *)PC1_table,7);//56 bit output + + for(n=0;n<16;n++) + { + for(i=0;i<7;i++) Kn[i]=dKeyC[i]; + ceDES_Permutate(Kn,7,(unsigned char *)PC2_table,6);//48 bit output + for(i=0;i<4;i++) Rn_1[i]=dMes[i+4]; + ceDES_F(Rn_1,Kn); + + if(n>=15) + { + for(i=0;i<4;i++) dMes[i]^=Rn_1[i]; + break; + } + for(i=0;i<4;i++) Rn_1[i]^=dMes[i]; + for(i=0;i<4;i++) dMes[i]=dMes[i+4]; + for(i=0;i<4;i++) dMes[i+4]=Rn_1[i]; + ceDES_RightShift(dKeyC,LeftShift_table[15-n]); + } + ceDES_Permutate(dMes,8,(unsigned char *)InverseIP_table,8);//64 bit output +}; +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +//dMes=Message to encrypt +//dKeyL=KeyLeft +//dKeyR=KeyRight +void ceTDES_Encrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) +{ + ceDES_Encrypt(dMes,dKeyL); + ceDES_Decrypt(dMes,dKeyR); + ceDES_Encrypt(dMes,dKeyL); +}; +//----------------------------------------------------------------------------- +//dMes=Message to decrypt +//dKeyL=KeyLeft +//dKeyR=KeyRight +void ceTDES_Decrypt(unsigned char *dMes,unsigned char *dKeyL,unsigned char *dKeyR) +{ + ceDES_Decrypt(dMes,dKeyL); + ceDES_Encrypt(dMes,dKeyR); + ceDES_Decrypt(dMes,dKeyL); +}; +//----------------------------------------------------------------------------- + +///////////////////////////////////////////////////////////////////////////// + +#if defined(__cplusplus) +} +#endif + #endif // CEDES_H \ No newline at end of file diff --git a/include/ce/ceFraCmd.h b/include/ce/cefracmdx.h similarity index 96% rename from include/ce/ceFraCmd.h rename to include/ce/cefracmdx.h index 0957b26..2682a8e 100644 --- a/include/ce/ceFraCmd.h +++ b/include/ce/cefracmdx.h @@ -1,61 +1,61 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: cefracmd.h -// Description: Byte stuffing- sending and receiving commands as frames -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_FRACMD_H -#define CE_FRACMD_H -#include "ce/ceframe.h" -namespace ce { -//----------------------------------------------------------------------------- -class ceFraCmd : public ceFrame { -public: - ceFraCmd(); - size_t SetTxFrame(char* d, size_t n) override; - size_t ReceiveRxFrame(char ch) override;//get receiving frame from received char -}; -//----------------------------------------------------------------------------- -///////////////////////////////////////////////////////////////////////////// - -inline ceFraCmd::ceFraCmd() :ceFrame() { - -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -inline size_t ceFraCmd::SetTxFrame(char* d, size_t n) -{ - int i = 0; - if (n >= CE_FRAME_TX_BUF_SIZE) n = CE_FRAME_TX_BUF_SIZE - 1; //discard policy - for (int j = 0; j < n; j++) { - tb[i++] = d[j]; - } - tb[i++] = 0x0D;//end of frame - TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -inline size_t ceFraCmd::ReceiveRxFrame(char ch) -{ - static int n = 0; - if (ch >= 32 && ch <= 126) { - this->rb[n++] = ch; - this->RxN = 0; - } - - if (ch == 0x0D || n >= (CE_FRAME_RX_BUF_SIZE - 1)) { - this->RxN = n; - this->rb[n] = 0;//null termination - n = 0; - return this->RxN; - } - return 0; -} - -///////////////////////////////////////////////////////////////////////////// -} // namespace ce - +///////////////////////////////////////////////////////////////////////////// +// Name: cefracmd.h +// Description: Byte stuffing- sending and receiving commands as frames +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_FRACMD_H +#define CE_FRACMD_H +#include "ce/ceframe.h" +namespace ce { +//----------------------------------------------------------------------------- +class ceFraCmd : public ceFrame { +public: + ceFraCmd(); + size_t SetTxFrame(char* d, size_t n) override; + size_t ReceiveRxFrame(char ch) override;//get receiving frame from received char +}; +//----------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +inline ceFraCmd::ceFraCmd() :ceFrame() { + +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +inline size_t ceFraCmd::SetTxFrame(char* d, size_t n) +{ + int i = 0; + if (n >= CE_FRAME_TX_BUF_SIZE) n = CE_FRAME_TX_BUF_SIZE - 1; //discard policy + for (int j = 0; j < n; j++) { + tb[i++] = d[j]; + } + tb[i++] = 0x0D;//end of frame + TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +inline size_t ceFraCmd::ReceiveRxFrame(char ch) +{ + static int n = 0; + if (ch >= 32 && ch <= 126) { + this->rb[n++] = ch; + this->RxN = 0; + } + + if (ch == 0x0D || n >= (CE_FRAME_RX_BUF_SIZE - 1)) { + this->RxN = n; + this->rb[n] = 0;//null termination + n = 0; + return this->RxN; + } + return 0; +} + +///////////////////////////////////////////////////////////////////////////// +} // namespace ce + #endif // CE_FRACMD_H \ No newline at end of file diff --git a/include/ce/ceFrame.h b/include/ce/ceframex.h similarity index 96% rename from include/ce/ceFrame.h rename to include/ce/ceframex.h index e0f5cfa..bfb1033 100644 --- a/include/ce/ceFrame.h +++ b/include/ce/ceframex.h @@ -1,167 +1,167 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceframe.h -// Description: Byte stuffing- sending and receiving frames -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_FRAME_H -#define CE_FRAME_H - -#include -#include - -#define STX 0x02 -#define ETX 0x03 -#define DLE 0x10 - -#define CE_FRAME_TX_BUF_SIZE 1024 -#define CE_FRAME_RX_BUF_SIZE 1024 - -// frame state definition -#define CE_FRAME_IGNORE 0 -#define CE_FRAME_RECEIVING 1 -#define CE_FRAME_ESCAPE 2 -#define CE_FRAME_RXCRC1 3 -#define CE_FRAME_RXCRC2 4 - -namespace ce { - -//----------------------------------------------------------------------------- -class ceFrame { - int rState; -protected: - size_t TxN;//number of transmitting bytes - size_t RxN;//number of receiving bytes - char tb[CE_FRAME_TX_BUF_SIZE];//transmit buffer - char rb[CE_FRAME_RX_BUF_SIZE];//receiving data -public: - ceFrame(); - size_t GetTxN(); - size_t GetRxN(); - char* GetTxBuf(); - char* GetRxBuf(); - virtual size_t SetTxFrame(char* d, size_t n); - virtual uint16_t CRC16(char* s, size_t len, uint16_t crc); - virtual size_t ReceiveRxFrame(char c);//get receiving frame from received char -}; -//----------------------------------------------------------------------------- -///////////////////////////////////////////////////////////////////////////// - -//----------------------------------------------------------------------------- -inline ceFrame::ceFrame() :TxN(0), RxN(0), rState(CE_FRAME_IGNORE) { - rb[0] = 0; - tb[0] = 0; -} -//----------------------------------------------------------------------------- -inline char* ceFrame::GetTxBuf() { - return tb; -} -//----------------------------------------------------------------------------- -inline char* ceFrame::GetRxBuf() { - return rb; -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -inline size_t ceFrame::SetTxFrame(char* d, size_t n) -{ - unsigned int txcrc = 0xFFFF;//initialize crc - char c; - int i = 0, j = 0; - tb[i++] = STX;//start of frame - for (j = 0; j < n; j++) { - c = d[j]; - if ((c == STX) || (c == ETX) || (c == DLE)) tb[i++] = (DLE); - tb[i++] = c; - } - tb[i++] = (ETX);//end of frame - - txcrc = CRC16(d, n, txcrc);//calculate crc - tb[i++] = txcrc & 0xFF; - tb[i++] = (txcrc >> 8) & 0xFF; - TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -//Inputs -//s : pointer to input char string -//len: string len (maximum 255) -//crc: initial CRC value - -//Output -//Returns calculated CRC -inline uint16_t ceFrame::CRC16(char* s, size_t len, uint16_t crc) -{ - //CRC Order: 16 - //CCITT(recommendation) : F(x)= x16 + x12 + x5 + 1 - //CRC Poly: 0x1021 - //Operational initial value: 0xFFFF - //Final xor value: 0 - size_t i, j; - for (i = 0; i < len; i++, s++) { - crc ^= ((unsigned int)(*s) & 0xFF) << 8; - for (j = 0; j < 8; j++) { - if (crc & 0x8000) crc = (crc << 1) ^ 0x1021; - else crc <<= 1; - } - } - return (crc & 0xFFFF);//truncate last 16 bit -} -//----------------------------------------------------------------------------- -//get number of transmitting bytes -inline size_t ceFrame::GetTxN() -{ - return TxN; -} -//----------------------------------------------------------------------------- -//get number of receiving bytes -inline size_t ceFrame::GetRxN() -{ - return RxN; -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -inline size_t ceFrame::ReceiveRxFrame(char c) -{ - static char b; - unsigned int crc; - unsigned int rxcrc = 0xFFFF;//initialize CRC - switch (rState) { - case CE_FRAME_RECEIVING: - if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } - else if (c == ETX) { rState = CE_FRAME_RXCRC1; } - else if (c == DLE) { rState = CE_FRAME_ESCAPE; } - else { rb[RxN++] = c; } - break; - case CE_FRAME_ESCAPE: - rb[RxN++] = c; rState = CE_FRAME_RECEIVING; - break; - case CE_FRAME_RXCRC1: - b = c; rState = CE_FRAME_RXCRC2; - break; - case CE_FRAME_RXCRC2: - rState = CE_FRAME_IGNORE; - crc = ((int)c << 8 | ((int)b & 0xFF)) & 0xFFFF;//get received crc - rxcrc = CRC16(rb, RxN, rxcrc);//calculate crc - //printf("crc: %x rxcrc:%x \n",crc,rxcrc); - if (rxcrc == crc) { return RxN; }//if crc is correct - else { RxN = 0; }//discard the frame - break; - default: //case CE_FRAME_IGNORE: - if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } - break; - } - - if (RxN >= CE_FRAME_RX_BUF_SIZE) { - RxN = 0; - rState = CE_FRAME_IGNORE; - } - - return 0; -} - -///////////////////////////////////////////////////////////////////////////// -} // namespace ce - +///////////////////////////////////////////////////////////////////////////// +// Name: ceframe.h +// Description: Byte stuffing- sending and receiving frames +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2011/05/byte-stuffing.html +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_FRAME_H +#define CE_FRAME_H + +#include +#include + +#define STX 0x02 +#define ETX 0x03 +#define DLE 0x10 + +#define CE_FRAME_TX_BUF_SIZE 1024 +#define CE_FRAME_RX_BUF_SIZE 1024 + +// frame state definition +#define CE_FRAME_IGNORE 0 +#define CE_FRAME_RECEIVING 1 +#define CE_FRAME_ESCAPE 2 +#define CE_FRAME_RXCRC1 3 +#define CE_FRAME_RXCRC2 4 + +namespace ce { + +//----------------------------------------------------------------------------- +class ceFrame { + int rState; +protected: + size_t TxN;//number of transmitting bytes + size_t RxN;//number of receiving bytes + char tb[CE_FRAME_TX_BUF_SIZE];//transmit buffer + char rb[CE_FRAME_RX_BUF_SIZE];//receiving data +public: + ceFrame(); + size_t GetTxN(); + size_t GetRxN(); + char* GetTxBuf(); + char* GetRxBuf(); + virtual size_t SetTxFrame(char* d, size_t n); + virtual uint16_t CRC16(char* s, size_t len, uint16_t crc); + virtual size_t ReceiveRxFrame(char c);//get receiving frame from received char +}; +//----------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +inline ceFrame::ceFrame() :TxN(0), RxN(0), rState(CE_FRAME_IGNORE) { + rb[0] = 0; + tb[0] = 0; +} +//----------------------------------------------------------------------------- +inline char* ceFrame::GetTxBuf() { + return tb; +} +//----------------------------------------------------------------------------- +inline char* ceFrame::GetRxBuf() { + return rb; +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +inline size_t ceFrame::SetTxFrame(char* d, size_t n) +{ + unsigned int txcrc = 0xFFFF;//initialize crc + char c; + int i = 0, j = 0; + tb[i++] = STX;//start of frame + for (j = 0; j < n; j++) { + c = d[j]; + if ((c == STX) || (c == ETX) || (c == DLE)) tb[i++] = (DLE); + tb[i++] = c; + } + tb[i++] = (ETX);//end of frame + + txcrc = CRC16(d, n, txcrc);//calculate crc + tb[i++] = txcrc & 0xFF; + tb[i++] = (txcrc >> 8) & 0xFF; + TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +//Inputs +//s : pointer to input char string +//len: string len (maximum 255) +//crc: initial CRC value + +//Output +//Returns calculated CRC +inline uint16_t ceFrame::CRC16(char* s, size_t len, uint16_t crc) +{ + //CRC Order: 16 + //CCITT(recommendation) : F(x)= x16 + x12 + x5 + 1 + //CRC Poly: 0x1021 + //Operational initial value: 0xFFFF + //Final xor value: 0 + size_t i, j; + for (i = 0; i < len; i++, s++) { + crc ^= ((unsigned int)(*s) & 0xFF) << 8; + for (j = 0; j < 8; j++) { + if (crc & 0x8000) crc = (crc << 1) ^ 0x1021; + else crc <<= 1; + } + } + return (crc & 0xFFFF);//truncate last 16 bit +} +//----------------------------------------------------------------------------- +//get number of transmitting bytes +inline size_t ceFrame::GetTxN() +{ + return TxN; +} +//----------------------------------------------------------------------------- +//get number of receiving bytes +inline size_t ceFrame::GetRxN() +{ + return RxN; +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +inline size_t ceFrame::ReceiveRxFrame(char c) +{ + static char b; + unsigned int crc; + unsigned int rxcrc = 0xFFFF;//initialize CRC + switch (rState) { + case CE_FRAME_RECEIVING: + if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } + else if (c == ETX) { rState = CE_FRAME_RXCRC1; } + else if (c == DLE) { rState = CE_FRAME_ESCAPE; } + else { rb[RxN++] = c; } + break; + case CE_FRAME_ESCAPE: + rb[RxN++] = c; rState = CE_FRAME_RECEIVING; + break; + case CE_FRAME_RXCRC1: + b = c; rState = CE_FRAME_RXCRC2; + break; + case CE_FRAME_RXCRC2: + rState = CE_FRAME_IGNORE; + crc = ((int)c << 8 | ((int)b & 0xFF)) & 0xFFFF;//get received crc + rxcrc = CRC16(rb, RxN, rxcrc);//calculate crc + //printf("crc: %x rxcrc:%x \n",crc,rxcrc); + if (rxcrc == crc) { return RxN; }//if crc is correct + else { RxN = 0; }//discard the frame + break; + default: //case CE_FRAME_IGNORE: + if (c == STX) { rState = CE_FRAME_RECEIVING; RxN = 0; } + break; + } + + if (RxN >= CE_FRAME_RX_BUF_SIZE) { + RxN = 0; + rState = CE_FRAME_IGNORE; + } + + return 0; +} + +///////////////////////////////////////////////////////////////////////////// +} // namespace ce + #endif // CE_FRAME_H \ No newline at end of file diff --git a/include/ce/ceI2C.h b/include/ce/cei2cx.h similarity index 95% rename from include/ce/ceI2C.h rename to include/ce/cei2cx.h index d2bac36..691fbd1 100644 --- a/include/ce/ceI2C.h +++ b/include/ce/cei2cx.h @@ -1,161 +1,161 @@ -///////////////////////////////////////////////////////////////////////////// -// File: cei2c.h -// Description: ceI2C class to use i2c communication -// WebSite: http://cool-emerald.blogspot.com -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -// Reference : http://elinux.org/Interfacing_with_I2C_Devices -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_MACROS_H -#define CE_MACROS_H - -#define CE_DBG_PRINT 0 // print dbg mes - -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif -#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif -#else - #ifndef CE_NOS - #define CE_NOS - #endif -#endif - -#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) - #ifndef CE_x86_64 - #define CE_x86_64 - #endif -#elif defined(__arm__) || defined(_M_ARM) - #ifndef CE_ARM - #define CE_ARM - #endif -#else - #ifndef CE_NARCH - #define CE_NARCH - #endif -#endif - -#endif // CE_MACROS_H - -#ifndef CEI2C_H -#define CEI2C_H - -#ifdef CE_LINUX - #include - #include - #include - #include -#endif - -#include -#include -#include -#include - -namespace ce { -class ceI2C -{ - public: - ceI2C(); - ceI2C(int bus_id,int slave_address); - ~ceI2C(); - bool Begin(int bus_id,int slave_address); - bool Write(char* buf,int n); - bool Read(char* buf,int n); - void Close(); - template - std::string ToString(T Number); - private: - int fd; -}; - -///////////////////////////////////////////////////////////////////////////// -// Implementation - -template -std::string ceI2C::ToString(T a) -{ - std::ostringstream ss; - ss << a; - return ss.str(); -} - -inline ceI2C::ceI2C() -{ - //ctor -} - -inline ceI2C::ceI2C(int bus_id, int slave_address) -{ - Begin(bus_id, slave_address); -} - -inline ceI2C::~ceI2C() -{ - //dtor -#ifdef CE_LINUX - close(fd); -#else -#endif -} - -inline bool ceI2C::Begin(int bus_id, int slave_address) -{ - std::string filename = "/dev/i2c-"; - filename += ToString(bus_id); -#ifdef CE_LINUX - if ((fd = open(filename.c_str(), O_RDWR)) < 0) { - perror("Failed to open the i2c bus\n"); - return false; - } - if (ioctl(fd, I2C_SLAVE, slave_address) < 0) { - perror("Failed to acquire bus access and/or talk to slave.\n"); - return false; - } -#else -#endif - return true; -} - -inline bool ceI2C::Write(char* buf, int n) -{ -#ifdef CE_LINUX - if (write(fd, buf, n) != n) { - perror("Failed to write to the i2c bus.\n"); - return false; - } -#else -#endif - return true; -} - -inline bool ceI2C::Read(char* buf, int n) -{ -#ifdef CE_LINUX - if (read(fd, buf, n) != n) { - perror("Failed to read from the i2c bus.\n"); - return false; - } -#else -#endif - return true; -} - -inline void ceI2C::Close() -{ -#ifdef CE_LINUX - close(fd); -#else -#endif -} - -///////////////////////////////////////////////////////////////////////////// - -} // namespace ce -#endif // CEI2C_H +///////////////////////////////////////////////////////////////////////////// +// File: cei2c.h +// Description: ceI2C class to use i2c communication +// WebSite: http://cool-emerald.blogspot.com +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye + +// Reference : http://elinux.org/Interfacing_with_I2C_Devices +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + +#ifndef CEI2C_H +#define CEI2C_H + +#ifdef CE_LINUX + #include + #include + #include + #include +#endif + +#include +#include +#include +#include + +namespace ce { +class ceI2C +{ + public: + ceI2C(); + ceI2C(int bus_id,int slave_address); + ~ceI2C(); + bool Begin(int bus_id,int slave_address); + bool Write(char* buf,int n); + bool Read(char* buf,int n); + void Close(); + template + std::string ToString(T Number); + private: + int fd; +}; + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +template +std::string ceI2C::ToString(T a) +{ + std::ostringstream ss; + ss << a; + return ss.str(); +} + +inline ceI2C::ceI2C() +{ + //ctor +} + +inline ceI2C::ceI2C(int bus_id, int slave_address) +{ + Begin(bus_id, slave_address); +} + +inline ceI2C::~ceI2C() +{ + //dtor +#ifdef CE_LINUX + close(fd); +#else +#endif +} + +inline bool ceI2C::Begin(int bus_id, int slave_address) +{ + std::string filename = "/dev/i2c-"; + filename += ToString(bus_id); +#ifdef CE_LINUX + if ((fd = open(filename.c_str(), O_RDWR)) < 0) { + perror("Failed to open the i2c bus\n"); + return false; + } + if (ioctl(fd, I2C_SLAVE, slave_address) < 0) { + perror("Failed to acquire bus access and/or talk to slave.\n"); + return false; + } +#else +#endif + return true; +} + +inline bool ceI2C::Write(char* buf, int n) +{ +#ifdef CE_LINUX + if (write(fd, buf, n) != n) { + perror("Failed to write to the i2c bus.\n"); + return false; + } +#else +#endif + return true; +} + +inline bool ceI2C::Read(char* buf, int n) +{ +#ifdef CE_LINUX + if (read(fd, buf, n) != n) { + perror("Failed to read from the i2c bus.\n"); + return false; + } +#else +#endif + return true; +} + +inline void ceI2C::Close() +{ +#ifdef CE_LINUX + close(fd); +#else +#endif +} + +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce +#endif // CEI2C_H diff --git a/include/ce/ceLog.h b/include/ce/celogx.h similarity index 95% rename from include/ce/ceLog.h rename to include/ce/celogx.h index 9afac48..02dbf41 100644 --- a/include/ce/ceLog.h +++ b/include/ce/celogx.h @@ -1,319 +1,319 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: celog.h -// Description: logging module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef ceLog_H -#define ceLog_H - -#ifndef CE_MACROS_H -#define CE_MACROS_H - -#define CE_DBG_PRINT 0 // print dbg mes - -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif -#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif -#else - #ifndef CE_NOS - #define CE_NOS - #endif -#endif - -#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) - #ifndef CE_x86_64 - #define CE_x86_64 - #endif -#elif defined(__arm__) || defined(_M_ARM) - #ifndef CE_ARM - #define CE_ARM - #endif -#else - #ifndef CE_NARCH - #define CE_NARCH - #endif -#endif - -#endif // CE_MACROS_H - -#include -#include -#include -#include -#include -#include -#include "ce/cedt.h" - -#if defined(CE_WINDOWS) - #include - #define stat _stat -#else - #include - #include - #include - #include -#endif - -#define ceLog_PRINT 0 -#define LOG_PATH "./log/" - -namespace ce { -class ceLog{ - std::string m_path; - ceDateTime m_dt; - ceDateTime m_ft; - double m_expiry_days; - std::string m_extension; - bool m_enPrintf; -public: - ceLog(); - ceLog(std::string path,double expdays); - ~ceLog(); - void SetPath(std::string path); - std::string GetPath(); - void SetExtension(std::string ext); - std::string GetExtension(); - void SetExpiry(double days); - double GetExpiry(); - int Write(std::string mes); // write to file only - void Clean();//clean old log files - void Clean(std::string path,std::string extension,double expiry_seconds); - void SetTimezone(double a); - void SetTimezone();//local time - double GetTimezone(); - void ReadDir(const std::string& name, std::vector& v); - double LastModified(const std::string& name);//return julian date - int Print(std::string mes); // write to file and echo on std output - bool GetEnPrintf(); - void SetEnPrintf(bool en); -}; - -///////////////////////////////////////////////////////////////////////////// -// Implementation - -inline ceLog::ceLog() -{ - SetPath(LOG_PATH); - SetExpiry(30); - SetExtension(".log"); - SetEnPrintf(false); -} - -inline ceLog::ceLog(std::string path, double expdays) -{ - SetPath(path); - SetExpiry(expdays); - SetExtension(".log"); - SetEnPrintf(true); -} - -inline void ceLog::SetPath(std::string path) -{ - this->m_path = path; -} - -inline std::string ceLog::GetPath() -{ - return this->m_path; -} - -inline void ceLog::SetExtension(std::string ext) -{ - this->m_extension = ext; -} - -inline std::string ceLog::GetExtension() -{ - return this->m_extension; -} - -inline ceLog::~ceLog() -{ - -} - -inline bool ceLog::GetEnPrintf() -{ - return this->m_enPrintf; -} - -inline void ceLog::SetEnPrintf(bool en) -{ - this->m_enPrintf = en; -} - -inline double ceLog::GetExpiry() -{ - return this->m_expiry_days; -} - -inline void ceLog::SetExpiry(double days) -{ - this->m_expiry_days = days; -} - -inline void ceLog::SetTimezone(double a)//set time zone -{ - this->m_dt.SetTimezone(a); -} - -inline void ceLog::SetTimezone()//set local time zone -{ - this->m_dt.SetTimezone(); -} - -inline double ceLog::GetTimezone()//get time zone -{ - return this->m_dt.tz(); -} - -inline int ceLog::Write(std::string mes) -{ - std::ofstream wfile; - int r = -1; - this->m_dt.Set2Now(); - std::string logpath = this->m_path + "L" + this->m_dt.ToString("%yyyy-%mm-%dd") + ".log"; - try { - wfile.open(logpath.c_str(), std::fstream::out | std::fstream::app); - if (wfile.is_open()) { - wfile << this->m_dt.ToString("%HH:%nn:%ss.%lll") << " " << mes << std::endl; - r = 0; - } - wfile.close(); - } - catch (...) { - perror("ceLog error in writing"); - } - return r; -} - -inline int ceLog::Print(std::string mes) -{ - if (this->m_enPrintf) { - // printf("%s\n",mes.c_str()); - std::cout << mes << std::endl; - } - return Write(mes); -} - -inline void ceLog::Clean(std::string path, std::string extension, double expiry_seconds) -{ - std::vector filenames; - std::string fn = ""; - std::string fpath = ""; - double fileage = 0; - int pos = 0; - - try { - ReadDir(path, filenames); - int nfiles = (int)filenames.size(); -#if ceLog_PRINT == 1 - printf("Number of items: %d \n", nfiles); -#endif - - if (nfiles <= 2) { //if only . and .. - return; - } - this->m_dt.Set2Now(); - - for (int i = 0; i < nfiles; i++) { - fn = filenames.at(i); -#if ceLog_PRINT == 1 - printf("File name: %s \n", fn.c_str()); -#endif - pos = (int)fn.find(extension); - if (pos >= 0) { - fpath = path + fn; - this->m_ft.SetJD(LastModified(fpath)); -#if ceLog_PRINT ==1 - printf("Modified time: %s \n", m_ft.DateTimeString().c_str()); -#endif - fileage = (this->m_dt.jd() - this->m_ft.jd()) * 86400.0; - if (fileage > expiry_seconds) { - remove(fpath.c_str()); -#if ceLog_PRINT == 1 - printf("%s has been deleted \n", fpath.c_str()); - //this->Write("Deleted "+fp); -#endif - } - } - } - } - catch (...) { - perror("ceLog error in cleaning\n"); - } -} -inline void ceLog::Clean() //clean old log files -{ - this->Clean(this->m_path, this->m_extension, this->m_expiry_days * 86400); -} - -//http://www.martinbroadhurst.com/list-the-files-in-a-directory-in-c.html -#ifdef CE_WINDOWS -inline void ceLog::ReadDir(const std::string& name, std::vector& v) -{ - std::string pattern(name); - pattern.append("\\*"); - //WIN32_FIND_DATA data; - WIN32_FIND_DATAA data; - HANDLE hFind; - - WCHAR wstr[256]; - //http://msdn.microsoft.com/en-us/library/cc500362.aspx - MultiByteToWideChar(0, 0, pattern.c_str(), (int)pattern.length(), wstr, 256); - // LPCSTR lstr = wstr; - LPBOOL useddefault = FALSE; - // char fn[256]; - - if ((hFind = FindFirstFileA(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE) { - //if ((hFind = FindFirstFile(wstr, &data)) != INVALID_HANDLE_VALUE) { - do { - //WideCharToMultiByte(0, 0, data.cFileName, -1, fn, 256, NULL, useddefault); - //v.push_back(string(fn)); - v.push_back(data.cFileName); - } while (FindNextFileA(hFind, &data) != 0); - FindClose(hFind); - } -} -#else -inline void ceLog::ReadDir(const string& name, vector& v) -{ - DIR* dirp = opendir(name.c_str()); - struct dirent* dp; - while ((dp = readdir(dirp)) != NULL) { - v.push_back(dp->d_name); - } - closedir(dirp); -} -#endif - -inline double ceLog::LastModified(const std::string& name) -{ - struct stat attrib; - struct tm* fmt; - ceDateTime dt; - if (stat(name.c_str(), &attrib) == 0) - { - fmt = localtime(&(attrib.st_mtime)); - dt.SetDateTime(fmt->tm_year + 1900, fmt->tm_mon + 1, fmt->tm_mday, - fmt->tm_hour, fmt->tm_min, fmt->tm_sec); - // printf("Modified time: %s \n",dt.DateTimeString().c_str()); - } - else { - // printf("Error in using stat.\n"); - } - return dt.jd(); -} - -///////////////////////////////////////////////////////////////////////////// - -} // namespace ce - - -#endif +///////////////////////////////////////////////////////////////////////////// +// Name: celog.h +// Description: logging module +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef ceLog_H +#define ceLog_H + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + +#include +#include +#include +#include +#include +#include +#include "ce/cedt.h" + +#if defined(CE_WINDOWS) + #include + #define stat _stat +#else + #include + #include + #include + #include +#endif + +#define ceLog_PRINT 0 +#define LOG_PATH "./log/" + +namespace ce { +class ceLog{ + std::string m_path; + ceDateTime m_dt; + ceDateTime m_ft; + double m_expiry_days; + std::string m_extension; + bool m_enPrintf; +public: + ceLog(); + ceLog(std::string path,double expdays); + ~ceLog(); + void SetPath(std::string path); + std::string GetPath(); + void SetExtension(std::string ext); + std::string GetExtension(); + void SetExpiry(double days); + double GetExpiry(); + int Write(std::string mes); // write to file only + void Clean();//clean old log files + void Clean(std::string path,std::string extension,double expiry_seconds); + void SetTimezone(double a); + void SetTimezone();//local time + double GetTimezone(); + void ReadDir(const std::string& name, std::vector& v); + double LastModified(const std::string& name);//return julian date + int Print(std::string mes); // write to file and echo on std output + bool GetEnPrintf(); + void SetEnPrintf(bool en); +}; + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +inline ceLog::ceLog() +{ + SetPath(LOG_PATH); + SetExpiry(30); + SetExtension(".log"); + SetEnPrintf(false); +} + +inline ceLog::ceLog(std::string path, double expdays) +{ + SetPath(path); + SetExpiry(expdays); + SetExtension(".log"); + SetEnPrintf(true); +} + +inline void ceLog::SetPath(std::string path) +{ + this->m_path = path; +} + +inline std::string ceLog::GetPath() +{ + return this->m_path; +} + +inline void ceLog::SetExtension(std::string ext) +{ + this->m_extension = ext; +} + +inline std::string ceLog::GetExtension() +{ + return this->m_extension; +} + +inline ceLog::~ceLog() +{ + +} + +inline bool ceLog::GetEnPrintf() +{ + return this->m_enPrintf; +} + +inline void ceLog::SetEnPrintf(bool en) +{ + this->m_enPrintf = en; +} + +inline double ceLog::GetExpiry() +{ + return this->m_expiry_days; +} + +inline void ceLog::SetExpiry(double days) +{ + this->m_expiry_days = days; +} + +inline void ceLog::SetTimezone(double a)//set time zone +{ + this->m_dt.SetTimezone(a); +} + +inline void ceLog::SetTimezone()//set local time zone +{ + this->m_dt.SetTimezone(); +} + +inline double ceLog::GetTimezone()//get time zone +{ + return this->m_dt.tz(); +} + +inline int ceLog::Write(std::string mes) +{ + std::ofstream wfile; + int r = -1; + this->m_dt.Set2Now(); + std::string logpath = this->m_path + "L" + this->m_dt.ToString("%yyyy-%mm-%dd") + ".log"; + try { + wfile.open(logpath.c_str(), std::fstream::out | std::fstream::app); + if (wfile.is_open()) { + wfile << this->m_dt.ToString("%HH:%nn:%ss.%lll") << " " << mes << std::endl; + r = 0; + } + wfile.close(); + } + catch (...) { + perror("ceLog error in writing"); + } + return r; +} + +inline int ceLog::Print(std::string mes) +{ + if (this->m_enPrintf) { + // printf("%s\n",mes.c_str()); + std::cout << mes << std::endl; + } + return Write(mes); +} + +inline void ceLog::Clean(std::string path, std::string extension, double expiry_seconds) +{ + std::vector filenames; + std::string fn = ""; + std::string fpath = ""; + double fileage = 0; + int pos = 0; + + try { + ReadDir(path, filenames); + int nfiles = (int)filenames.size(); +#if ceLog_PRINT == 1 + printf("Number of items: %d \n", nfiles); +#endif + + if (nfiles <= 2) { //if only . and .. + return; + } + this->m_dt.Set2Now(); + + for (int i = 0; i < nfiles; i++) { + fn = filenames.at(i); +#if ceLog_PRINT == 1 + printf("File name: %s \n", fn.c_str()); +#endif + pos = (int)fn.find(extension); + if (pos >= 0) { + fpath = path + fn; + this->m_ft.SetJD(LastModified(fpath)); +#if ceLog_PRINT ==1 + printf("Modified time: %s \n", m_ft.DateTimeString().c_str()); +#endif + fileage = (this->m_dt.jd() - this->m_ft.jd()) * 86400.0; + if (fileage > expiry_seconds) { + remove(fpath.c_str()); +#if ceLog_PRINT == 1 + printf("%s has been deleted \n", fpath.c_str()); + //this->Write("Deleted "+fp); +#endif + } + } + } + } + catch (...) { + perror("ceLog error in cleaning\n"); + } +} +inline void ceLog::Clean() //clean old log files +{ + this->Clean(this->m_path, this->m_extension, this->m_expiry_days * 86400); +} + +//http://www.martinbroadhurst.com/list-the-files-in-a-directory-in-c.html +#ifdef CE_WINDOWS +inline void ceLog::ReadDir(const std::string& name, std::vector& v) +{ + std::string pattern(name); + pattern.append("\\*"); + //WIN32_FIND_DATA data; + WIN32_FIND_DATAA data; + HANDLE hFind; + + WCHAR wstr[256]; + //http://msdn.microsoft.com/en-us/library/cc500362.aspx + MultiByteToWideChar(0, 0, pattern.c_str(), (int)pattern.length(), wstr, 256); + // LPCSTR lstr = wstr; + LPBOOL useddefault = FALSE; + // char fn[256]; + + if ((hFind = FindFirstFileA(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE) { + //if ((hFind = FindFirstFile(wstr, &data)) != INVALID_HANDLE_VALUE) { + do { + //WideCharToMultiByte(0, 0, data.cFileName, -1, fn, 256, NULL, useddefault); + //v.push_back(string(fn)); + v.push_back(data.cFileName); + } while (FindNextFileA(hFind, &data) != 0); + FindClose(hFind); + } +} +#else +inline void ceLog::ReadDir(const string& name, vector& v) +{ + DIR* dirp = opendir(name.c_str()); + struct dirent* dp; + while ((dp = readdir(dirp)) != NULL) { + v.push_back(dp->d_name); + } + closedir(dirp); +} +#endif + +inline double ceLog::LastModified(const std::string& name) +{ + struct stat attrib; + struct tm* fmt; + ceDateTime dt; + if (stat(name.c_str(), &attrib) == 0) + { + fmt = localtime(&(attrib.st_mtime)); + dt.SetDateTime(fmt->tm_year + 1900, fmt->tm_mon + 1, fmt->tm_mday, + fmt->tm_hour, fmt->tm_min, fmt->tm_sec); + // printf("Modified time: %s \n",dt.DateTimeString().c_str()); + } + else { + // printf("Error in using stat.\n"); + } + return dt.jd(); +} + +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce + + +#endif diff --git a/include/ce/ceMisc.h b/include/ce/cemiscx.h similarity index 96% rename from include/ce/ceMisc.h rename to include/ce/cemiscx.h index 96ca496..31a8347 100644 --- a/include/ce/ceMisc.h +++ b/include/ce/cemiscx.h @@ -1,309 +1,309 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: cemisc.h -// Description: utility module -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEMISC_H -#define CEMISC_H - -#ifndef CE_MACROS_H -#define CE_MACROS_H - -#define CE_DBG_PRINT 0 // print dbg mes - -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif -#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif -#else - #ifndef CE_NOS - #define CE_NOS - #endif -#endif - -#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) - #ifndef CE_x86_64 - #define CE_x86_64 - #endif -#elif defined(__arm__) || defined(_M_ARM) - #ifndef CE_ARM - #define CE_ARM - #endif -#else - #ifndef CE_NARCH - #define CE_NARCH - #endif -#endif - -#endif // CE_MACROS_H - -#include -#include -#include -#include -#include -#include - -#if defined(CE_WINDOWS) -#include -#include // for kbhit -#else -#include -#include -#include // for kbhit -#include // " -#endif - -namespace ce { -class ceMisc { -private: -public: - static std::string alnum(std::string str); // filter the string for alphanumeric characters only - static std::vector hex2cvec(std::string str); // convert hex string to char vector - static std::string hex2str(std::string str); // convert hex string to byte string - static std::string cvec2hex(std::vector bv); // convert char vector to hex string - - static std::string ToStr16(unsigned int u);// to hexadecimal string - static std::string ToStr16(int u);// to hexadecimal string - static std::string ToStr16(unsigned char c);// to hexadecimal string - static std::string ToStr16(char c);// to hexadecimal string - static std::string ToStr16(std::vector bv, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string - static std::string ToStr16(std::vector bv, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string - static std::string ToStr16(std::string str, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string - - static std::string cvec2str(std::vector bv); // convert char vector to string - static std::vector cptr2cvec(char* cstr, int n); // char* to char vector - static std::string cptr2str(char* cstr, int n); // convert char* to string - static void cvec2cptr(std::vector& v,char*&cstr, int& n); // character vector to char* - static std::vector str2cvec(std::string str); // string to char vector - static std::string f2s(float f, int n = 1); // float to string - static std::vector splitStr(std::string str, std::string delimiter); - - static std::string exepath(); // get the path of executing binary program - static std::string exedir(); // get the directory of executing binary program - - static bool kb_hit(); // check keyboard hit - static char get_ch(); // get char -}; - -///////////////////////////////////////////////////////////////////////////// -// Implementation - -// filter the string for alphanumeric characters only -inline std::string ceMisc::alnum(std::string str) -{ - str.erase(remove_if(str.begin(), str.end(), [](char ch) { - return !( - (ch >= '0' && ch <= '9') || - (ch >= 'A' && ch <= 'Z') || - (ch >= 'a' && ch <= 'z')); }), str.end()); - return str; -} - -// convert hex string to char vector -inline std::vector ceMisc::hex2cvec(std::string str) -{ - std::vector v; - str = ceMisc::alnum(str);// filter for alphanumeric characters - int n = (int)str.length(); - for (int i = 0; i < n; i += 2) - v.push_back((char)stoi(str.substr(i, 2), NULL, 16)); - return v; -} - -// convert hex string to byte string -inline std::string ceMisc::hex2str(std::string str) -{ - return ceMisc::cvec2str(ceMisc::hex2cvec(str)); -} - -// convert to hexadecimal string -inline std::string ceMisc::ToStr16(unsigned int u) -{ - std::ostringstream ss; - ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u; - return ss.str(); -} - -inline std::string ceMisc::ToStr16(int i) -{ - return ceMisc::ToStr16((unsigned int)i); -} - -inline std::string ceMisc::ToStr16(unsigned char c) -{ - return ceMisc::ToStr16((unsigned int)c); -} - -inline std::string ceMisc::ToStr16(char c) -{ - return ceMisc::ToStr16((unsigned char)c); -} - -// convert vector to hexadecimal string -inline std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { - std::vector uv(bv.begin(), bv.end()); - return ceMisc::ToStr16(uv, separator, prefix, postfix); -} - -// convert vector to hexadecimal string -inline std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { - std::ostringstream ss; - unsigned int u; - for (auto& c : bv) { - u = (unsigned char)c; - ss << prefix; - ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u << postfix; - if (&c != &bv.back()) ss << separator; - } - return ss.str(); -} - -// to hexadecimal string -inline std::string ceMisc::ToStr16(std::string str, std::string separator, std::string prefix, std::string postfix) -{ - return ceMisc::ToStr16(ceMisc::str2cvec(str), separator, prefix, postfix); -} - -// convert char vector to hex string -inline std::string ceMisc::cvec2hex(std::vector bv) { - std::ostringstream ss; - unsigned int u; - for (char& c : bv) { - u = (unsigned char)c; - ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u << " "; - } - return ss.str(); -} - -// convert char vector to string -inline std::string ceMisc::cvec2str(std::vector bv) { - std::ostringstream ss; - for (char& c : bv) { - ss << c; - } - return ss.str(); -} - - -// character vector to char* -inline void ceMisc::cvec2cptr(std::vector& v, char*& cstr, int& n) { - n = (int)v.size(); - cstr = v.data(); // reinterpret_cast(v.data()); -} - -// char* to char vector -inline std::vector ceMisc::cptr2cvec(char* cstr, int n) { - std::vector v(cstr, cstr + n); - return v; -} - -// convert char* to string -inline std::string ceMisc::cptr2str(char* cstr, int n) { - std::ostringstream ss; - for (int i = 0; i < n; i++) { - ss << cstr[i]; - } - return ss.str(); -} - -// string to char vector -inline std::vector ceMisc::str2cvec(std::string str) { - std::vector v(str.begin(), str.end()); - return v; -} - -inline std::string ceMisc::f2s(float f, int n) { - std::stringstream ss; - ss << std::fixed << std::setprecision(n) << f; - return ss.str(); -} - -inline std::vector ceMisc::splitStr(std::string str, std::string delimiter) -{ - size_t pos = 0; - std::vector tokens; - while ((pos = str.find(delimiter)) != std::string::npos) { - tokens.push_back(str.substr(0, pos)); - str.erase(0, pos + delimiter.length()); - } - tokens.push_back(str); - return tokens; -} - -inline std::string ceMisc::exepath() -{ -#ifdef CE_WINDOWS - char result[MAX_PATH]; - return std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); -#else - char result[PATH_MAX]; - ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); - return std::string(result, (count > 0) ? count : 0); -#endif -} - -inline std::string ceMisc::exedir() -{ - std::string str = exepath(); - std::size_t found = str.find_last_of("/\\"); - return str.substr(0, found + 1); -} - -inline bool ceMisc::kb_hit() // check keyboard hit -{ -#if defined(CE_WINDOWS) - return _kbhit(); -#else - // https://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux - termios term; - tcgetattr(0, &term); - - termios term2 = term; - term2.c_lflag &= ~ICANON; - tcsetattr(0, TCSANOW, &term2); - - int byteswaiting; - ioctl(0, FIONREAD, &byteswaiting); - - tcsetattr(0, TCSANOW, &term); - - return byteswaiting > 0; -#endif -} - -inline char ceMisc::get_ch() // get char -{ -#if defined(CE_WINDOWS) - return _getch(); -#else - //https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed - char buf = 0; - struct termios old = { 0 }; - if (tcgetattr(0, &old) < 0) - perror("tcsetattr()"); - old.c_lflag &= ~ICANON; - old.c_lflag &= ~ECHO; - old.c_cc[VMIN] = 1; - old.c_cc[VTIME] = 0; - if (tcsetattr(0, TCSANOW, &old) < 0) - perror("tcsetattr ICANON"); - if (read(0, &buf, 1) < 0) - perror("read()"); - old.c_lflag |= ICANON; - old.c_lflag |= ECHO; - if (tcsetattr(0, TCSADRAIN, &old) < 0) - perror("tcsetattr ~ICANON"); - return (buf); -#endif -} - -///////////////////////////////////////////////////////////////////////////// - -} // namespace ce -#endif // CEMISC_H +///////////////////////////////////////////////////////////////////////////// +// Name: cemisc.h +// Description: utility module +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEMISC_H +#define CEMISC_H + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + +#include +#include +#include +#include +#include +#include + +#if defined(CE_WINDOWS) +#include +#include // for kbhit +#else +#include +#include +#include // for kbhit +#include // " +#endif + +namespace ce { +class ceMisc { +private: +public: + static std::string alnum(std::string str); // filter the string for alphanumeric characters only + static std::vector hex2cvec(std::string str); // convert hex string to char vector + static std::string hex2str(std::string str); // convert hex string to byte string + static std::string cvec2hex(std::vector bv); // convert char vector to hex string + + static std::string ToStr16(unsigned int u);// to hexadecimal string + static std::string ToStr16(int u);// to hexadecimal string + static std::string ToStr16(unsigned char c);// to hexadecimal string + static std::string ToStr16(char c);// to hexadecimal string + static std::string ToStr16(std::vector bv, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string + static std::string ToStr16(std::vector bv, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string + static std::string ToStr16(std::string str, std::string separator = "", std::string prefix = "", std::string postfix = "");// to hexadecimal string + + static std::string cvec2str(std::vector bv); // convert char vector to string + static std::vector cptr2cvec(char* cstr, int n); // char* to char vector + static std::string cptr2str(char* cstr, int n); // convert char* to string + static void cvec2cptr(std::vector& v,char*&cstr, int& n); // character vector to char* + static std::vector str2cvec(std::string str); // string to char vector + static std::string f2s(float f, int n = 1); // float to string + static std::vector splitStr(std::string str, std::string delimiter); + + static std::string exepath(); // get the path of executing binary program + static std::string exedir(); // get the directory of executing binary program + + static bool kb_hit(); // check keyboard hit + static char get_ch(); // get char +}; + +///////////////////////////////////////////////////////////////////////////// +// Implementation + +// filter the string for alphanumeric characters only +inline std::string ceMisc::alnum(std::string str) +{ + str.erase(remove_if(str.begin(), str.end(), [](char ch) { + return !( + (ch >= '0' && ch <= '9') || + (ch >= 'A' && ch <= 'Z') || + (ch >= 'a' && ch <= 'z')); }), str.end()); + return str; +} + +// convert hex string to char vector +inline std::vector ceMisc::hex2cvec(std::string str) +{ + std::vector v; + str = ceMisc::alnum(str);// filter for alphanumeric characters + int n = (int)str.length(); + for (int i = 0; i < n; i += 2) + v.push_back((char)stoi(str.substr(i, 2), NULL, 16)); + return v; +} + +// convert hex string to byte string +inline std::string ceMisc::hex2str(std::string str) +{ + return ceMisc::cvec2str(ceMisc::hex2cvec(str)); +} + +// convert to hexadecimal string +inline std::string ceMisc::ToStr16(unsigned int u) +{ + std::ostringstream ss; + ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u; + return ss.str(); +} + +inline std::string ceMisc::ToStr16(int i) +{ + return ceMisc::ToStr16((unsigned int)i); +} + +inline std::string ceMisc::ToStr16(unsigned char c) +{ + return ceMisc::ToStr16((unsigned int)c); +} + +inline std::string ceMisc::ToStr16(char c) +{ + return ceMisc::ToStr16((unsigned char)c); +} + +// convert vector to hexadecimal string +inline std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { + std::vector uv(bv.begin(), bv.end()); + return ceMisc::ToStr16(uv, separator, prefix, postfix); +} + +// convert vector to hexadecimal string +inline std::string ceMisc::ToStr16(std::vector bv, std::string separator, std::string prefix, std::string postfix) { + std::ostringstream ss; + unsigned int u; + for (auto& c : bv) { + u = (unsigned char)c; + ss << prefix; + ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u << postfix; + if (&c != &bv.back()) ss << separator; + } + return ss.str(); +} + +// to hexadecimal string +inline std::string ceMisc::ToStr16(std::string str, std::string separator, std::string prefix, std::string postfix) +{ + return ceMisc::ToStr16(ceMisc::str2cvec(str), separator, prefix, postfix); +} + +// convert char vector to hex string +inline std::string ceMisc::cvec2hex(std::vector bv) { + std::ostringstream ss; + unsigned int u; + for (char& c : bv) { + u = (unsigned char)c; + ss << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << u << " "; + } + return ss.str(); +} + +// convert char vector to string +inline std::string ceMisc::cvec2str(std::vector bv) { + std::ostringstream ss; + for (char& c : bv) { + ss << c; + } + return ss.str(); +} + + +// character vector to char* +inline void ceMisc::cvec2cptr(std::vector& v, char*& cstr, int& n) { + n = (int)v.size(); + cstr = v.data(); // reinterpret_cast(v.data()); +} + +// char* to char vector +inline std::vector ceMisc::cptr2cvec(char* cstr, int n) { + std::vector v(cstr, cstr + n); + return v; +} + +// convert char* to string +inline std::string ceMisc::cptr2str(char* cstr, int n) { + std::ostringstream ss; + for (int i = 0; i < n; i++) { + ss << cstr[i]; + } + return ss.str(); +} + +// string to char vector +inline std::vector ceMisc::str2cvec(std::string str) { + std::vector v(str.begin(), str.end()); + return v; +} + +inline std::string ceMisc::f2s(float f, int n) { + std::stringstream ss; + ss << std::fixed << std::setprecision(n) << f; + return ss.str(); +} + +inline std::vector ceMisc::splitStr(std::string str, std::string delimiter) +{ + size_t pos = 0; + std::vector tokens; + while ((pos = str.find(delimiter)) != std::string::npos) { + tokens.push_back(str.substr(0, pos)); + str.erase(0, pos + delimiter.length()); + } + tokens.push_back(str); + return tokens; +} + +inline std::string ceMisc::exepath() +{ +#ifdef CE_WINDOWS + char result[MAX_PATH]; + return std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); +#else + char result[PATH_MAX]; + ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); + return std::string(result, (count > 0) ? count : 0); +#endif +} + +inline std::string ceMisc::exedir() +{ + std::string str = exepath(); + std::size_t found = str.find_last_of("/\\"); + return str.substr(0, found + 1); +} + +inline bool ceMisc::kb_hit() // check keyboard hit +{ +#if defined(CE_WINDOWS) + return _kbhit(); +#else + // https://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux + termios term; + tcgetattr(0, &term); + + termios term2 = term; + term2.c_lflag &= ~ICANON; + tcsetattr(0, TCSANOW, &term2); + + int byteswaiting; + ioctl(0, FIONREAD, &byteswaiting); + + tcsetattr(0, TCSANOW, &term); + + return byteswaiting > 0; +#endif +} + +inline char ceMisc::get_ch() // get char +{ +#if defined(CE_WINDOWS) + return _getch(); +#else + //https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed + char buf = 0; + struct termios old = { 0 }; + if (tcgetattr(0, &old) < 0) + perror("tcsetattr()"); + old.c_lflag &= ~ICANON; + old.c_lflag &= ~ECHO; + old.c_cc[VMIN] = 1; + old.c_cc[VTIME] = 0; + if (tcsetattr(0, TCSANOW, &old) < 0) + perror("tcsetattr ICANON"); + if (read(0, &buf, 1) < 0) + perror("read()"); + old.c_lflag |= ICANON; + old.c_lflag |= ECHO; + if (tcsetattr(0, TCSADRAIN, &old) < 0) + perror("tcsetattr ~ICANON"); + return (buf); +#endif +} + +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce +#endif // CEMISC_H diff --git a/include/ce/ceModbus.h b/include/ce/cemodbusx.h similarity index 96% rename from include/ce/ceModbus.h rename to include/ce/cemodbusx.h index 2bd04a2..1632819 100644 --- a/include/ce/ceModbus.h +++ b/include/ce/cemodbusx.h @@ -1,244 +1,244 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceModbus.h -// Description: Sending and receiving modbus frames -// Modbus RTU frame format (primarily used on asynchronous serial data lines like RS-485/EIA-485) -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com -///////////////////////////////////////////////////////////////////////////// - -#ifndef CE_MODBUS_H -#define CE_MODBUS_H -#include "ce/ceframe.h" -#define CR 0x0D -#define LF 0x0A -#define CE_NUMBER_OF_TICKS_TO_RESET 10 -#include -#include -namespace ce { -//----------------------------------------------------------------------------- -class ceModbus : public ceFrame { -private: -protected: - size_t _count; // receiving count - size_t _frameSize;// frame size - int _tick_n; - int _reset_tick; -public: - ceModbus(); - size_t SetTxFrame(char* d, size_t n) override; - uint16_t CRC16(char* s, size_t len, uint16_t crc) override; - size_t ReceiveRxFrame(char c) override;//get receiving frame from received char - int Tick();// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx - void SetCmd(std::vector v); - void SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data); - void SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay=0); - void SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len); - std::vector GetStatus(char* d, size_t n); - std::vector GetTxVec(); - std::vector GetRxVec(); - void SetResetTickCount(int n); - int GetResetTickCount(); -}; -//----------------------------------------------------------------------------- -///////////////////////////////////////////////////////////////////////////// - -//----------------------------------------------------------------------------- -inline ceModbus::ceModbus() :ceFrame(), _count(0), _frameSize(8), _tick_n(0), _reset_tick(CE_NUMBER_OF_TICKS_TO_RESET) { -} -//----------------------------------------------------------------------------- -//Prepare transmitting frame -inline size_t ceModbus::SetTxFrame(char* d, size_t n) -{ - if (n > (CE_FRAME_TX_BUF_SIZE - 2)) return 0;// size error - uint16_t txcrc = 0xFFFF;//initialize crc - char c; - size_t i = 0, j = 0; - for (j = 0; j < n; j++) { - c = d[j]; - // no need to check c in building Modbus frame - this->tb[i++] = c; - } - txcrc = this->CRC16((char*)d, n, txcrc);//calculate crc - this->tb[i++] = txcrc & 0xFF; - this->tb[i++] = (txcrc >> 8) & 0xFF; - this->TxN = i; - return TxN; -} -//----------------------------------------------------------------------------- -//Inputs -//s : pointer to input char string -//len: string len (maximum 255) -//crc: initial CRC value - -//Output -//Returns calculated CRC - -// Ref: http://cool-emerald.blogspot.com/2009/09/crc-calculation-in-vb-and-c.html -inline uint16_t ceModbus::CRC16(char* s, size_t len, uint16_t crc) -{ - //CRC Order: 16 - //CRC Poly: 0x8005 <=> A001 - //Operational initial value: 0xFFFF - //Final xor value: 0 - size_t i, j; - for (i = 0; i < len; i++, s++) { - crc ^= ((unsigned int)(*s)) & 0xFF; - for (j = 0; j < 8; j++) { - if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; - else crc >>= 1; - } - } - return (crc & 0xFFFF);//truncate last 16 bit -} -//----------------------------------------------------------------------------- -// process receiving char -// return RXN if a frame is successfully received, else retrun 0 -// CRC16 is also included -inline size_t ceModbus::ReceiveRxFrame(char c) -{ - // accept any value even 0x0D to get 8 bytes - // (not using start and end 28 bit length mark condition) - this->_tick_n = 0; // reset for every rx ch - this->RxN = 0; - this->rb[this->_count++] = c; - - if (this->_count == 3) { - // check function - if (this->rb[1] == 0x06) { - this->_frameSize = 8; // reply for control cmd - } - else if (this->rb[1] == 0x03) { - uint8_t len = (uint8_t)this->rb[2]; - this->_frameSize = 5 + len; // reply for read cmd - } - } - - // instead use frame size for particular frame - if (this->_count >= this->_frameSize) { - this->rb[this->_count] = 0;//null termination - this->RxN = this->_count; - this->_count = 0; - this->_frameSize = 8;// default - this->_tick_n = 0; // will clear RxN when time out - // for (int i = 0; i < this->RxN; i++) printf("%02X ", (unsigned int)this->rb[i] & 0xFF); - // uint16_t rxcrc = ((uint16_t)this->rb[this->RxN-1] << 8 | ((uint16_t)this->rb[this->RxN - 2] & 0xFF)) & 0xFFFF;//get received crc - uint16_t computed_crc = 0xFFFF;//initialize CRC - computed_crc = this->CRC16(rb, RxN, computed_crc);//calculate crc - // printf("\nComputed crc: %02X \n",computed_crc); - if (computed_crc == 0) { - //this->RxN -= 2; - return (this->RxN); //if crc is correct return bytes including crc - } - else { this->RxN = 0; }//discard the frame - } - return 0; -} - -// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx -// return = 0 : if no reset, 1 : if reset -inline int ceModbus::Tick() -{ - if (this->_tick_n <= this->_reset_tick) { - this->_tick_n++; - } - else { - this->_count = 0; - this->_frameSize = 8;// default - this->RxN = 0; - } - return this->_tick_n; -} - -// command vector without CRC16 -// CRC16 will be calculated and appended -inline void ceModbus::SetCmd(std::vector v) -{ - this->SetTxFrame((char*)v.data(), v.size()); -} - -inline void ceModbus::SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data) -{ - uint8_t ah = uint8_t((addr >> 8) & 0xFF); - uint8_t al = uint8_t(addr & 0xFF); - std::vector v = { slaveid,func,ah,al }; - v.insert(v.end(), data.begin(), data.end()); - this->SetCmd(v); -} - -inline void ceModbus::SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay) -{ - uint8_t ah = uint8_t((addr >> 8) & 0xFF); - uint8_t al = uint8_t(addr & 0xFF); - std::vector v = { slaveid,0x06,ah,al,command,delay }; - this->SetCmd(v); -} - -inline void ceModbus::SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len) -{ - uint8_t ah = uint8_t((startAddr >> 8) & 0xFF); - uint8_t al = uint8_t(startAddr & 0xFF); - uint8_t lh = uint8_t((len >> 8) & 0xFF); - uint8_t ll = uint8_t(len & 0xFF); - std::vector v = { slaveid,0x03,ah,al,lh,ll }; - this->SetCmd(v); -} - -// extract vector of status from received byte array -// crc16 bytes will be neglected if included -inline std::vector ceModbus::GetStatus(char* d, size_t n) -{ - std::vector v; - if (n < 3) { - // perror("Modbus frame error in getting status"); - return v; - } - - if (d[1] != 0x03) { - // perror("Frame must be Modbus read status return to get status"); - return v; - } - - uint8_t len = (uint8_t)d[2]; // get len - if (n < ((size_t)len + 3)) { - // perror("Modbus frame length error in getting status"); - return v; - } - - uint16_t s; - uint8_t count = len >> 1;// 2 bytes each - for (uint8_t i = 0; i < count; i++) { - // for big endian - s = (uint8_t)d[3 + ((uint64_t)i << 1)]; - s <<= 8; - s |= (uint8_t)d[4 + ((uint64_t)i << 1)]; - v.push_back(s); - } - return v; -} - -inline std::vector ceModbus::GetTxVec() -{ - std::vector v((char*)tb, (char*)tb + this->TxN); - return v; -} - -inline std::vector ceModbus::GetRxVec() -{ - std::vector v((char*)rb, (char*)rb + this->RxN); - return v; -} - -inline void ceModbus::SetResetTickCount(int n) -{ - this->_reset_tick = n; -} - -inline int ceModbus::GetResetTickCount() -{ - return this->_reset_tick; -} - -///////////////////////////////////////////////////////////////////////////// -} // namespace ce - +///////////////////////////////////////////////////////////////////////////// +// Name: ceModbus.h +// Description: Sending and receiving modbus frames +// Modbus RTU frame format (primarily used on asynchronous serial data lines like RS-485/EIA-485) +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com +///////////////////////////////////////////////////////////////////////////// + +#ifndef CE_MODBUS_H +#define CE_MODBUS_H +#include "ce/ceframe.h" +#define CR 0x0D +#define LF 0x0A +#define CE_NUMBER_OF_TICKS_TO_RESET 10 +#include +#include +namespace ce { +//----------------------------------------------------------------------------- +class ceModbus : public ceFrame { +private: +protected: + size_t _count; // receiving count + size_t _frameSize;// frame size + int _tick_n; + int _reset_tick; +public: + ceModbus(); + size_t SetTxFrame(char* d, size_t n) override; + uint16_t CRC16(char* s, size_t len, uint16_t crc) override; + size_t ReceiveRxFrame(char c) override;//get receiving frame from received char + int Tick();// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx + void SetCmd(std::vector v); + void SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data); + void SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay=0); + void SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len); + std::vector GetStatus(char* d, size_t n); + std::vector GetTxVec(); + std::vector GetRxVec(); + void SetResetTickCount(int n); + int GetResetTickCount(); +}; +//----------------------------------------------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +inline ceModbus::ceModbus() :ceFrame(), _count(0), _frameSize(8), _tick_n(0), _reset_tick(CE_NUMBER_OF_TICKS_TO_RESET) { +} +//----------------------------------------------------------------------------- +//Prepare transmitting frame +inline size_t ceModbus::SetTxFrame(char* d, size_t n) +{ + if (n > (CE_FRAME_TX_BUF_SIZE - 2)) return 0;// size error + uint16_t txcrc = 0xFFFF;//initialize crc + char c; + size_t i = 0, j = 0; + for (j = 0; j < n; j++) { + c = d[j]; + // no need to check c in building Modbus frame + this->tb[i++] = c; + } + txcrc = this->CRC16((char*)d, n, txcrc);//calculate crc + this->tb[i++] = txcrc & 0xFF; + this->tb[i++] = (txcrc >> 8) & 0xFF; + this->TxN = i; + return TxN; +} +//----------------------------------------------------------------------------- +//Inputs +//s : pointer to input char string +//len: string len (maximum 255) +//crc: initial CRC value + +//Output +//Returns calculated CRC + +// Ref: http://cool-emerald.blogspot.com/2009/09/crc-calculation-in-vb-and-c.html +inline uint16_t ceModbus::CRC16(char* s, size_t len, uint16_t crc) +{ + //CRC Order: 16 + //CRC Poly: 0x8005 <=> A001 + //Operational initial value: 0xFFFF + //Final xor value: 0 + size_t i, j; + for (i = 0; i < len; i++, s++) { + crc ^= ((unsigned int)(*s)) & 0xFF; + for (j = 0; j < 8; j++) { + if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; + else crc >>= 1; + } + } + return (crc & 0xFFFF);//truncate last 16 bit +} +//----------------------------------------------------------------------------- +// process receiving char +// return RXN if a frame is successfully received, else retrun 0 +// CRC16 is also included +inline size_t ceModbus::ReceiveRxFrame(char c) +{ + // accept any value even 0x0D to get 8 bytes + // (not using start and end 28 bit length mark condition) + this->_tick_n = 0; // reset for every rx ch + this->RxN = 0; + this->rb[this->_count++] = c; + + if (this->_count == 3) { + // check function + if (this->rb[1] == 0x06) { + this->_frameSize = 8; // reply for control cmd + } + else if (this->rb[1] == 0x03) { + uint8_t len = (uint8_t)this->rb[2]; + this->_frameSize = 5 + len; // reply for read cmd + } + } + + // instead use frame size for particular frame + if (this->_count >= this->_frameSize) { + this->rb[this->_count] = 0;//null termination + this->RxN = this->_count; + this->_count = 0; + this->_frameSize = 8;// default + this->_tick_n = 0; // will clear RxN when time out + // for (int i = 0; i < this->RxN; i++) printf("%02X ", (unsigned int)this->rb[i] & 0xFF); + // uint16_t rxcrc = ((uint16_t)this->rb[this->RxN-1] << 8 | ((uint16_t)this->rb[this->RxN - 2] & 0xFF)) & 0xFFFF;//get received crc + uint16_t computed_crc = 0xFFFF;//initialize CRC + computed_crc = this->CRC16(rb, RxN, computed_crc);//calculate crc + // printf("\nComputed crc: %02X \n",computed_crc); + if (computed_crc == 0) { + //this->RxN -= 2; + return (this->RxN); //if crc is correct return bytes including crc + } + else { this->RxN = 0; }//discard the frame + } + return 0; +} + +// to reset frame receiving after CE_NUMBER_OF_TICKS_TO_RESET of no char rx +// return = 0 : if no reset, 1 : if reset +inline int ceModbus::Tick() +{ + if (this->_tick_n <= this->_reset_tick) { + this->_tick_n++; + } + else { + this->_count = 0; + this->_frameSize = 8;// default + this->RxN = 0; + } + return this->_tick_n; +} + +// command vector without CRC16 +// CRC16 will be calculated and appended +inline void ceModbus::SetCmd(std::vector v) +{ + this->SetTxFrame((char*)v.data(), v.size()); +} + +inline void ceModbus::SetCmd(uint8_t slaveid, uint8_t func, uint16_t addr, std::vector data) +{ + uint8_t ah = uint8_t((addr >> 8) & 0xFF); + uint8_t al = uint8_t(addr & 0xFF); + std::vector v = { slaveid,func,ah,al }; + v.insert(v.end(), data.begin(), data.end()); + this->SetCmd(v); +} + +inline void ceModbus::SetControl(uint8_t slaveid, uint16_t addr, uint8_t command, uint8_t delay) +{ + uint8_t ah = uint8_t((addr >> 8) & 0xFF); + uint8_t al = uint8_t(addr & 0xFF); + std::vector v = { slaveid,0x06,ah,al,command,delay }; + this->SetCmd(v); +} + +inline void ceModbus::SetReadStatus(uint8_t slaveid, uint16_t startAddr, uint16_t len) +{ + uint8_t ah = uint8_t((startAddr >> 8) & 0xFF); + uint8_t al = uint8_t(startAddr & 0xFF); + uint8_t lh = uint8_t((len >> 8) & 0xFF); + uint8_t ll = uint8_t(len & 0xFF); + std::vector v = { slaveid,0x03,ah,al,lh,ll }; + this->SetCmd(v); +} + +// extract vector of status from received byte array +// crc16 bytes will be neglected if included +inline std::vector ceModbus::GetStatus(char* d, size_t n) +{ + std::vector v; + if (n < 3) { + // perror("Modbus frame error in getting status"); + return v; + } + + if (d[1] != 0x03) { + // perror("Frame must be Modbus read status return to get status"); + return v; + } + + uint8_t len = (uint8_t)d[2]; // get len + if (n < ((size_t)len + 3)) { + // perror("Modbus frame length error in getting status"); + return v; + } + + uint16_t s; + uint8_t count = len >> 1;// 2 bytes each + for (uint8_t i = 0; i < count; i++) { + // for big endian + s = (uint8_t)d[3 + ((uint64_t)i << 1)]; + s <<= 8; + s |= (uint8_t)d[4 + ((uint64_t)i << 1)]; + v.push_back(s); + } + return v; +} + +inline std::vector ceModbus::GetTxVec() +{ + std::vector v((char*)tb, (char*)tb + this->TxN); + return v; +} + +inline std::vector ceModbus::GetRxVec() +{ + std::vector v((char*)rb, (char*)rb + this->RxN); + return v; +} + +inline void ceModbus::SetResetTickCount(int n) +{ + this->_reset_tick = n; +} + +inline int ceModbus::GetResetTickCount() +{ + return this->_reset_tick; +} + +///////////////////////////////////////////////////////////////////////////// +} // namespace ce + #endif // CE_MODBUS_H \ No newline at end of file diff --git a/include/ce/cePCA9535.h b/include/ce/cepca9535x.h similarity index 96% rename from include/ce/cePCA9535.h rename to include/ce/cepca9535x.h index 1c97ff6..d76c665 100644 --- a/include/ce/cePCA9535.h +++ b/include/ce/cepca9535x.h @@ -1,129 +1,129 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: cepca9535.h -// Description: cePCA9535 - Digital IO chip -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/cei2c.h" -#ifndef cePCA9535_H -#define cePCA9535_H -#ifndef PCA9535_REGISTERS - #define PCA9535_REGISTERS - #define PCA9535_INPUT_P0_ADDR 0 - #define PCA9535_INPUT_P1_ADDR 1 - #define PCA9535_OUTPUT_P0_ADDR 2 - #define PCA9535_OUTPUT_P1_ADDR 3 - #define PCA9535_POLARITY_P0_ADDR 4 - #define PCA9535_POLARITY_P1_ADDR 5 - #define PCA9535_CONF_P0_ADDR 6 - #define PCA9535_CONF_P1_ADDR 7 -#endif -namespace ce { - -class cePCA9535 { -public: - cePCA9535(uint8_t i2cBusNo, uint8_t Addr); - ~cePCA9535(); - bool SetReg(uint8_t rVal, uint8_t rAddr); - bool GetReg(uint8_t& rVal, uint8_t rAddr); - bool Init(unsigned char outp0,unsigned char outp1, - unsigned char polarity0,unsigned char polarity1, - unsigned char conf0,unsigned char conf1); -private: - uint8_t _bus; // i2c bus number - uint8_t _addr; // addr2 jumper open (0) or close (1) - bool SetReg(uint8_t chipAddr, uint8_t rVal, uint8_t rAddr, uint8_t i2cBus); - bool GetReg(uint8_t chipAddr, uint8_t& rVal, uint8_t rAddr, uint8_t i2cBus); - - // initialize PCA9535 - bool Init(unsigned char chipAddr, - unsigned char outp0,unsigned char outp1, - unsigned char polarity0,unsigned char polarity1, - unsigned char conf0,unsigned char conf1, int i2cBus); -}; - -///////////////////////////////////////////////////////////////////////////// - -inline cePCA9535::cePCA9535(uint8_t i2cBusNo, uint8_t Addr) : _bus(i2cBusNo), _addr(Addr) -{ - -} - -inline cePCA9535::~cePCA9535() -{ - -} - -inline bool cePCA9535::SetReg(uint8_t rVal, uint8_t rAddr) -{ - return this->SetReg(_addr, rVal, rAddr, _bus); -} - -inline bool cePCA9535::GetReg(uint8_t& rVal, uint8_t rAddr) -{ - return this->GetReg(_addr, rVal, rAddr, _bus); -} - -inline bool cePCA9535::Init(unsigned char outp0, unsigned char outp1, - unsigned char polarity0, unsigned char polarity1, - unsigned char conf0, unsigned char conf1) -{ - return this->Init(_addr, - outp0, outp1, - polarity0, polarity1, - conf0, conf1, _bus); -} - -inline bool cePCA9535::SetReg(uint8_t chipAddr, uint8_t rVal, uint8_t rAddr, uint8_t i2cBus) -{ - char d[] = { 0,0 }; - ce::ceI2C chip1(i2cBus, chipAddr); - d[0] = rAddr; - d[1] = rVal; - bool r = chip1.Write(d, 2); // send new register data - chip1.Close(); - if (r == false) { - printf("cePCA9535 I2C error at bus = %d, addr = 0x%X\n", i2cBus, chipAddr); - // perror("cePCA9535 I2C error"); - } - return r; -} - -inline bool cePCA9535::GetReg(uint8_t chipAddr, uint8_t& rVal, uint8_t rAddr, uint8_t i2cBus) -{ - char d[] = { 0,0 }; - ce::ceI2C chip1(i2cBus, chipAddr); - d[0] = rAddr; - bool r = chip1.Write(d, 1); // send new register data - r = r && chip1.Read(d, 1); - chip1.Close(); - if (r) { - rVal = d[0]; - } - else { - printf("cePCA9535 I2C error at bus = %d, addr = 0x%X\n", i2cBus, chipAddr); - // perror("cePCA9535 I2C error"); - } - return r; -} - -// initialize PCA9535 -inline bool cePCA9535::Init(unsigned char chipAddr, - unsigned char outp0, unsigned char outp1, - unsigned char polarity0, unsigned char polarity1, - unsigned char conf0, unsigned char conf1, int i2cbus) -{ - bool r = true; - r = r && this->SetReg(chipAddr, polarity0, PCA9535_POLARITY_P0_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, polarity1, PCA9535_POLARITY_P1_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, conf0, PCA9535_CONF_P0_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, conf1, PCA9535_CONF_P1_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, outp0, PCA9535_OUTPUT_P0_ADDR, i2cbus); - r = r && this->SetReg(chipAddr, outp1, PCA9535_OUTPUT_P1_ADDR, i2cbus); - return r; -} - -///////////////////////////////////////////////////////////////////////////// - -} // namespace ce -#endif // cePCA9535_H +///////////////////////////////////////////////////////////////////////////// +// Name: cepca9535.h +// Description: cePCA9535 - Digital IO chip +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// +#include +#include "ce/cei2c.h" +#ifndef cePCA9535_H +#define cePCA9535_H +#ifndef PCA9535_REGISTERS + #define PCA9535_REGISTERS + #define PCA9535_INPUT_P0_ADDR 0 + #define PCA9535_INPUT_P1_ADDR 1 + #define PCA9535_OUTPUT_P0_ADDR 2 + #define PCA9535_OUTPUT_P1_ADDR 3 + #define PCA9535_POLARITY_P0_ADDR 4 + #define PCA9535_POLARITY_P1_ADDR 5 + #define PCA9535_CONF_P0_ADDR 6 + #define PCA9535_CONF_P1_ADDR 7 +#endif +namespace ce { + +class cePCA9535 { +public: + cePCA9535(uint8_t i2cBusNo, uint8_t Addr); + ~cePCA9535(); + bool SetReg(uint8_t rVal, uint8_t rAddr); + bool GetReg(uint8_t& rVal, uint8_t rAddr); + bool Init(unsigned char outp0,unsigned char outp1, + unsigned char polarity0,unsigned char polarity1, + unsigned char conf0,unsigned char conf1); +private: + uint8_t _bus; // i2c bus number + uint8_t _addr; // addr2 jumper open (0) or close (1) + bool SetReg(uint8_t chipAddr, uint8_t rVal, uint8_t rAddr, uint8_t i2cBus); + bool GetReg(uint8_t chipAddr, uint8_t& rVal, uint8_t rAddr, uint8_t i2cBus); + + // initialize PCA9535 + bool Init(unsigned char chipAddr, + unsigned char outp0,unsigned char outp1, + unsigned char polarity0,unsigned char polarity1, + unsigned char conf0,unsigned char conf1, int i2cBus); +}; + +///////////////////////////////////////////////////////////////////////////// + +inline cePCA9535::cePCA9535(uint8_t i2cBusNo, uint8_t Addr) : _bus(i2cBusNo), _addr(Addr) +{ + +} + +inline cePCA9535::~cePCA9535() +{ + +} + +inline bool cePCA9535::SetReg(uint8_t rVal, uint8_t rAddr) +{ + return this->SetReg(_addr, rVal, rAddr, _bus); +} + +inline bool cePCA9535::GetReg(uint8_t& rVal, uint8_t rAddr) +{ + return this->GetReg(_addr, rVal, rAddr, _bus); +} + +inline bool cePCA9535::Init(unsigned char outp0, unsigned char outp1, + unsigned char polarity0, unsigned char polarity1, + unsigned char conf0, unsigned char conf1) +{ + return this->Init(_addr, + outp0, outp1, + polarity0, polarity1, + conf0, conf1, _bus); +} + +inline bool cePCA9535::SetReg(uint8_t chipAddr, uint8_t rVal, uint8_t rAddr, uint8_t i2cBus) +{ + char d[] = { 0,0 }; + ce::ceI2C chip1(i2cBus, chipAddr); + d[0] = rAddr; + d[1] = rVal; + bool r = chip1.Write(d, 2); // send new register data + chip1.Close(); + if (r == false) { + printf("cePCA9535 I2C error at bus = %d, addr = 0x%X\n", i2cBus, chipAddr); + // perror("cePCA9535 I2C error"); + } + return r; +} + +inline bool cePCA9535::GetReg(uint8_t chipAddr, uint8_t& rVal, uint8_t rAddr, uint8_t i2cBus) +{ + char d[] = { 0,0 }; + ce::ceI2C chip1(i2cBus, chipAddr); + d[0] = rAddr; + bool r = chip1.Write(d, 1); // send new register data + r = r && chip1.Read(d, 1); + chip1.Close(); + if (r) { + rVal = d[0]; + } + else { + printf("cePCA9535 I2C error at bus = %d, addr = 0x%X\n", i2cBus, chipAddr); + // perror("cePCA9535 I2C error"); + } + return r; +} + +// initialize PCA9535 +inline bool cePCA9535::Init(unsigned char chipAddr, + unsigned char outp0, unsigned char outp1, + unsigned char polarity0, unsigned char polarity1, + unsigned char conf0, unsigned char conf1, int i2cbus) +{ + bool r = true; + r = r && this->SetReg(chipAddr, polarity0, PCA9535_POLARITY_P0_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, polarity1, PCA9535_POLARITY_P1_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, conf0, PCA9535_CONF_P0_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, conf1, PCA9535_CONF_P1_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, outp0, PCA9535_OUTPUT_P0_ADDR, i2cbus); + r = r && this->SetReg(chipAddr, outp1, PCA9535_OUTPUT_P1_ADDR, i2cbus); + return r; +} + +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce +#endif // cePCA9535_H diff --git a/include/ce/ceSerial.h b/include/ce/ceserialx.h similarity index 96% rename from include/ce/ceSerial.h rename to include/ce/ceserialx.h index dd2d2e2..3a4d614 100644 --- a/include/ce/ceSerial.h +++ b/include/ce/ceserialx.h @@ -1,660 +1,660 @@ -// File: ceSerial.h -// Description: ceSerial communication class for Windows and Linux -// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2018 Yan Naing Aye - -// References -// https://en.wikibooks.org/wiki/Serial_Programming/termios -// http://www.silabs.com/documents/public/application-notes/an197.pdf -// https://msdn.microsoft.com/en-us/library/ff802693.aspx -// http://www.cplusplus.com/forum/unices/10491/ - -#ifndef CESERIAL_H -#define CESERIAL_H -#include -#include -#include -#include - -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif -#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif -#else - #ifndef CE_NOS - #define CE_NOS - #endif -#endif - -#ifdef CE_WINDOWS - #include -#endif - -class ceSerial { -private: - char rxchar; - std::string port; - long baud; - long dsize; - char parity; - float stopbits; - bool stdbaud; -#ifdef CE_WINDOWS - HANDLE hComm; //handle - OVERLAPPED osReader; - OVERLAPPED osWrite; - BOOL fWaitingOnRead; - COMMTIMEOUTS timeouts_ori; -#else - long fd;//serial_fd -#endif -public: - static void Delay(unsigned long ms); - ceSerial(); - ceSerial(std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits); - ~ceSerial(); - long Open(void);//return 0 if success - void Close(); - char ReadChar(bool& success);//return read char if success - bool WriteChar(const char ch);////return success flag - bool Write(const char *data);//write null terminated string and return success flag - bool Write(const char *data,long n); - bool SetRTS(bool value);//return success flag - bool SetDTR(bool value);//return success flag - bool GetCTS(bool& success); - bool GetDSR(bool& success); - bool GetRI(bool& success); - bool GetCD(bool& success); - bool IsOpened(); - void SetPortName(std::string Port); - std::string GetPort(); - void SetBaudRate(long baudrate); - long GetBaudRate(); - void SetDataSize(long nbits); - long GetDataSize(); - void SetParity(char p); - char GetParity(); - void SetStopBits(float nbits); - float GetStopBits(); -}; - -//----------------------------------------------------------------------------- -#ifdef CE_WINDOWS - #define READ_TIMEOUT 10 // milliseconds -#else - #include - #include - #include - #include - #include -#endif - -inline void ceSerial::Delay(unsigned long ms) { -#ifdef CE_WINDOWS - Sleep(ms); -#else - usleep(ms*1000); -#endif -} - -inline ceSerial::ceSerial() : -#ifdef CE_WINDOWS - ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1) -#else - ceSerial("/dev/ttyS0", 9600, 8, 'N', 1) -#endif -{ - -} - -inline ceSerial::ceSerial(std::string Device, long BaudRate,long DataSize,char ParityType,float NStopBits):stdbaud(true) { -#ifdef CE_WINDOWS - hComm = INVALID_HANDLE_VALUE; -#else - fd = -1; -#endif // defined - SetBaudRate(BaudRate); - SetDataSize(DataSize); - SetParity(ParityType); - SetStopBits(NStopBits); - SetPortName(Device); -} - -inline ceSerial::~ceSerial() { - Close(); -} - -inline void ceSerial::SetPortName(std::string Device) { - port = Device; -} - -inline std::string ceSerial::GetPort() { - return port; -} - -inline void ceSerial::SetDataSize(long nbits) { - if ((nbits < 5) || (nbits > 8)) nbits = 8; - dsize=nbits; -} - -inline long ceSerial::GetDataSize() { - return dsize; -} - -inline void ceSerial::SetParity(char p) { - if ((p != 'N') && (p != 'E') && (p != 'O')) { -#ifdef CE_WINDOWS - if ((p != 'M') && (p != 'S')) p = 'N'; -#else - p = 'N'; -#endif - } - parity = p; -} - -inline char ceSerial::GetParity() { - return parity; -} - -inline void ceSerial::SetStopBits(float nbits) { - if (nbits >= 2) stopbits = 2; -#ifdef CE_WINDOWS - else if(nbits >= 1.5) stopbits = 1.5; -#endif - else stopbits = 1; -} - -inline float ceSerial::GetStopBits() { - return stopbits; -} - - -#ifdef CE_WINDOWS - -inline void ceSerial::SetBaudRate(long baudrate) { - stdbaud = true; - if (baudrate == 110) baud = CBR_110; - else if (baudrate == 300) baud = CBR_300; - else if (baudrate == 600) baud = CBR_600; - else if (baudrate == 1200) baud = CBR_1200; - else if (baudrate == 2400) baud = CBR_2400; - else if (baudrate == 4800) baud = CBR_4800; - else if (baudrate == 9600) baud = CBR_9600; - else if (baudrate == 14400) baud = CBR_14400; - else if (baudrate == 19200) baud = CBR_19200; - else if (baudrate == 38400) baud = CBR_38400; - else if (baudrate == 57600) baud = CBR_57600; - else if (baudrate == 115200) baud = CBR_115200; - else if (baudrate == 128000) baud = CBR_128000; - else if (baudrate == 256000) baud = CBR_256000; - else { - baud = baudrate; - stdbaud = false; - } -} - -inline long ceSerial::GetBaudRate() { - return baud; -} - -inline long ceSerial::Open() { - if (IsOpened()) return 0; -#ifdef UNICODE - std::wstring wtext(port.begin(),port.end()); -#else - std::string wtext = port; -#endif - hComm = CreateFile(wtext.c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, - 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, - 0); - if (hComm == INVALID_HANDLE_VALUE) {return -1;} - - if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) {return -1;}//purge - - //get initial state - DCB dcbOri; - bool fSuccess; - fSuccess = GetCommState(hComm, &dcbOri); - if (!fSuccess) {return -1;} - - DCB dcb1 = dcbOri; - - dcb1.BaudRate = baud; - - if (parity == 'E') dcb1.Parity = EVENPARITY; - else if (parity == 'O') dcb1.Parity = ODDPARITY; - else if (parity == 'M') dcb1.Parity = MARKPARITY; - else if (parity == 'S') dcb1.Parity = SPACEPARITY; - else dcb1.Parity = NOPARITY; - - dcb1.ByteSize = (BYTE)dsize; - - if(stopbits==2) dcb1.StopBits = TWOSTOPBITS; - else if (stopbits == 1.5) dcb1.StopBits = ONE5STOPBITS; - else dcb1.StopBits = ONESTOPBIT; - - dcb1.fOutxCtsFlow = false; - dcb1.fOutxDsrFlow = false; - dcb1.fOutX = false; - dcb1.fDtrControl = DTR_CONTROL_DISABLE; - dcb1.fRtsControl = RTS_CONTROL_DISABLE; - fSuccess = SetCommState(hComm, &dcb1); - this->Delay(60); - if (!fSuccess) {return -1;} - - fSuccess = GetCommState(hComm, &dcb1); - if (!fSuccess) {return -1;} - - osReader = { 0 };// Create the overlapped event. - // Must be closed before exiting to avoid a handle leak. - osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - - if (osReader.hEvent == NULL) {return -1;}// Error creating overlapped event; abort. - fWaitingOnRead = FALSE; - - osWrite = { 0 }; - osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if (osWrite.hEvent == NULL) {return -1;} - - if (!GetCommTimeouts(hComm, &timeouts_ori)) { return -1; } // Error getting time-outs. - COMMTIMEOUTS timeouts; - timeouts.ReadIntervalTimeout = 20; - timeouts.ReadTotalTimeoutMultiplier = 15; - timeouts.ReadTotalTimeoutConstant = 100; - timeouts.WriteTotalTimeoutMultiplier = 15; - timeouts.WriteTotalTimeoutConstant = 100; - if (!SetCommTimeouts(hComm, &timeouts)) { return -1;} // Error setting time-outs. - return 0; -} - -inline void ceSerial::Close() { - if (IsOpened()) - { - SetCommTimeouts(hComm, &timeouts_ori); - CloseHandle(osReader.hEvent); - CloseHandle(osWrite.hEvent); - CloseHandle(hComm);//close comm port - hComm = INVALID_HANDLE_VALUE; - } -} - -inline bool ceSerial::IsOpened() { - if(hComm == INVALID_HANDLE_VALUE) return false; - else return true; -} - -inline bool ceSerial::Write(const char *data) { - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - long n = strlen(data); - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { - // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -inline bool ceSerial::Write(const char *data,long n) { - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { - // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -inline bool ceSerial::WriteChar(const char ch) { - char s[2]; - s[0]=ch; - s[1]=0;//null terminated - return Write(s); -} - -inline char ceSerial::ReadChar(bool& success) { - success = false; - if (!IsOpened()) {return 0;} - - DWORD dwRead; - DWORD length=1; - BYTE* data = (BYTE*)(&rxchar); - //the creation of the overlapped read operation - if (!fWaitingOnRead) { - // Issue read operation. - if (!ReadFile(hComm, data, length, &dwRead, &osReader)) { - if (GetLastError() != ERROR_IO_PENDING) { /*Error*/} - else { fWaitingOnRead = TRUE; /*Waiting*/} - } - else {if(dwRead==length) success = true;}//success - } - - - //detection of the completion of an overlapped read operation - DWORD dwRes; - if (fWaitingOnRead) { - dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT); - switch (dwRes) - { - // Read completed. - case WAIT_OBJECT_0: - if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) {/*Error*/ } - else { - if (dwRead == length) success = true; - fWaitingOnRead = FALSE; - // Reset flag so that another opertion can be issued. - }// Read completed successfully. - break; - - case WAIT_TIMEOUT: - // Operation isn't complete yet. - break; - - default: - // Error in the WaitForSingleObject; - break; - } - } - return rxchar; -} - -inline bool ceSerial::SetRTS(bool value) { - bool r = false; - if (IsOpened()) { - if (value) { - if (EscapeCommFunction(hComm, SETRTS)) r = true; - } - else { - if (EscapeCommFunction(hComm, CLRRTS)) r = true; - } - } - return r; -} - -inline bool ceSerial::SetDTR(bool value) { - bool r = false; - if (IsOpened()) { - if (value) { - if (EscapeCommFunction(hComm, SETDTR)) r = true; - } - else { - if (EscapeCommFunction(hComm, CLRDTR)) r = true; - } - } - return r; -} - -inline bool ceSerial::GetCTS(bool& success) { - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)){ - r = MS_CTS_ON & dwModemStatus; - success = true; - } - } - return r; -} - -inline bool ceSerial::GetDSR(bool& success) { - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_DSR_ON & dwModemStatus; - success = true; - } - } - return r; -} - -inline bool ceSerial::GetRI(bool& success) { - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_RING_ON & dwModemStatus; - success = true; - } - } - return r; -} - -inline bool ceSerial::GetCD(bool& success) { - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_RLSD_ON & dwModemStatus; - success = true; - } - } - return r; -} - -#else //for POSIX - -inline long ceSerial::Open(void) { - struct serial_struct serinfo; - struct termios settings; - memset(&settings, 0, sizeof(settings)); - settings.c_iflag = 0; - settings.c_oflag = 0; - - settings.c_cflag = CREAD | CLOCAL;//see termios.h for more information - if(dsize==5) settings.c_cflag |= CS5;//no change - else if (dsize == 6) settings.c_cflag |= CS6; - else if (dsize == 7) settings.c_cflag |= CS7; - else settings.c_cflag |= CS8; - - if(stopbits==2) settings.c_cflag |= CSTOPB; - - if(parity!='N') settings.c_cflag |= PARENB; - - if (parity == 'O') settings.c_cflag |= PARODD; - - settings.c_lflag = 0; - settings.c_cc[VMIN] = 1; - settings.c_cc[VTIME] = 0; - - fd = open(port.c_str(), O_RDWR | O_NONBLOCK); - if (fd == -1) { - return -1; - } - - if (!stdbaud) { - // serial driver to interpret the value B38400 differently - serinfo.reserved_char[0] = 0; - if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1;} - serinfo.flags &= ~ASYNC_SPD_MASK; - serinfo.flags |= ASYNC_SPD_CUST; - serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud; - if (serinfo.custom_divisor < 1) serinfo.custom_divisor = 1; - if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { return -1; } - if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1; } - if (serinfo.custom_divisor * baud != serinfo.baud_base) { - /* - warnx("actual baudrate is %d / %d = %f\n", - serinfo.baud_base, serinfo.custom_divisor, - (float)serinfo.baud_base / serinfo.custom_divisor); - */ - } - cfsetospeed(&settings, B38400); - cfsetispeed(&settings, B38400); - } - else { - cfsetospeed(&settings, baud); - cfsetispeed(&settings, baud); - } - tcsetattr(fd, TCSANOW, &settings); - int flags = fcntl(fd, F_GETFL, 0); - fcntl(fd, F_SETFL, flags | O_NONBLOCK); - - if (!stdbaud) { - // driver to interpret B38400 as 38400 baud again - ioctl(fd, TIOCGSERIAL, &serinfo); - serinfo.flags &= ~ASYNC_SPD_MASK; - ioctl(fd, TIOCSSERIAL, &serinfo); - } - return 0; -} - -inline void ceSerial::Close() { - if(IsOpened()) close(fd); - fd=-1; -} - -inline bool ceSerial::IsOpened() { - if(fd== (-1)) return false; - else return true; -} - -inline void ceSerial::SetBaudRate(long baudrate) { - stdbaud = true; - if (baudrate == 0) baud = B0; - else if (baudrate == 50) baud = B50; - else if (baudrate == 75) baud = B75; - else if (baudrate == 110) baud = B110; - else if (baudrate == 134) baud = B134; - else if (baudrate == 150) baud = B150; - else if (baudrate == 200) baud = B200; - else if (baudrate == 300) baud = B300; - else if (baudrate == 600) baud = B600; - else if (baudrate == 1200) baud = B1200; - else if (baudrate == 2400) baud = B2400; - else if (baudrate == 4800) baud = B4800; - else if (baudrate == 9600) baud = B9600; - else if (baudrate == 19200) baud = B19200; - else if (baudrate == 38400) baud = B38400; - else if (baudrate == 57600) baud = B57600; - else if (baudrate == 115200) baud = B115200; - else if (baudrate == 230400) baud = B230400; - else { - baud = baudrate; - stdbaud = false; - } -} - -inline long ceSerial::GetBaudRate() { - return baud; -} - -inline char ceSerial::ReadChar(bool& success) { - success=false; - if (!IsOpened()) {return 0; } - success=read(fd, &rxchar, 1)==1; - return rxchar; -} - -inline bool ceSerial::Write(const char *data) { - if (!IsOpened()) {return false; } - long n = strlen(data); - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -inline bool ceSerial::Write(const char *data,long n) { - if (!IsOpened()) {return false; } - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -inline bool ceSerial::WriteChar(const char ch) { - char s[2]; - s[0]=ch; - s[1]=0;//null terminated - return Write(s); -} - -inline bool ceSerial::SetRTS(bool value) { - long RTS_flag = TIOCM_RTS; - bool success=true; - if (value) {//Set RTS pin - if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) success=false; - } - else {//Clear RTS pin - if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) success=false; - } - return success; -} - -inline bool ceSerial::SetDTR(bool value) { - long DTR_flag = TIOCM_DTR; - bool success=true; - if (value) {//Set DTR pin - if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) success=false; - } - else {//Clear DTR pin - if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) success=false; - } - return success; -} - -inline bool ceSerial::GetCTS(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_CTS) != 0); -} - -inline bool ceSerial::GetDSR(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_DSR) != 0); -} - -inline bool ceSerial::GetRI(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_RI) != 0); -} - -inline bool ceSerial::GetCD(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_CD) != 0); -} -#endif - -#endif // CESERIAL_H +// File: ceSerial.h +// Description: ceSerial communication class for Windows and Linux +// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2018 Yan Naing Aye + +// References +// https://en.wikibooks.org/wiki/Serial_Programming/termios +// http://www.silabs.com/documents/public/application-notes/an197.pdf +// https://msdn.microsoft.com/en-us/library/ff802693.aspx +// http://www.cplusplus.com/forum/unices/10491/ + +#ifndef CESERIAL_H +#define CESERIAL_H +#include +#include +#include +#include + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#ifdef CE_WINDOWS + #include +#endif + +class ceSerial { +private: + char rxchar; + std::string port; + long baud; + long dsize; + char parity; + float stopbits; + bool stdbaud; +#ifdef CE_WINDOWS + HANDLE hComm; //handle + OVERLAPPED osReader; + OVERLAPPED osWrite; + BOOL fWaitingOnRead; + COMMTIMEOUTS timeouts_ori; +#else + long fd;//serial_fd +#endif +public: + static void Delay(unsigned long ms); + ceSerial(); + ceSerial(std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits); + ~ceSerial(); + long Open(void);//return 0 if success + void Close(); + char ReadChar(bool& success);//return read char if success + bool WriteChar(const char ch);////return success flag + bool Write(const char *data);//write null terminated string and return success flag + bool Write(const char *data,long n); + bool SetRTS(bool value);//return success flag + bool SetDTR(bool value);//return success flag + bool GetCTS(bool& success); + bool GetDSR(bool& success); + bool GetRI(bool& success); + bool GetCD(bool& success); + bool IsOpened(); + void SetPortName(std::string Port); + std::string GetPort(); + void SetBaudRate(long baudrate); + long GetBaudRate(); + void SetDataSize(long nbits); + long GetDataSize(); + void SetParity(char p); + char GetParity(); + void SetStopBits(float nbits); + float GetStopBits(); +}; + +//----------------------------------------------------------------------------- +#ifdef CE_WINDOWS + #define READ_TIMEOUT 10 // milliseconds +#else + #include + #include + #include + #include + #include +#endif + +inline void ceSerial::Delay(unsigned long ms) { +#ifdef CE_WINDOWS + Sleep(ms); +#else + usleep(ms*1000); +#endif +} + +inline ceSerial::ceSerial() : +#ifdef CE_WINDOWS + ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1) +#else + ceSerial("/dev/ttyS0", 9600, 8, 'N', 1) +#endif +{ + +} + +inline ceSerial::ceSerial(std::string Device, long BaudRate,long DataSize,char ParityType,float NStopBits):stdbaud(true) { +#ifdef CE_WINDOWS + hComm = INVALID_HANDLE_VALUE; +#else + fd = -1; +#endif // defined + SetBaudRate(BaudRate); + SetDataSize(DataSize); + SetParity(ParityType); + SetStopBits(NStopBits); + SetPortName(Device); +} + +inline ceSerial::~ceSerial() { + Close(); +} + +inline void ceSerial::SetPortName(std::string Device) { + port = Device; +} + +inline std::string ceSerial::GetPort() { + return port; +} + +inline void ceSerial::SetDataSize(long nbits) { + if ((nbits < 5) || (nbits > 8)) nbits = 8; + dsize=nbits; +} + +inline long ceSerial::GetDataSize() { + return dsize; +} + +inline void ceSerial::SetParity(char p) { + if ((p != 'N') && (p != 'E') && (p != 'O')) { +#ifdef CE_WINDOWS + if ((p != 'M') && (p != 'S')) p = 'N'; +#else + p = 'N'; +#endif + } + parity = p; +} + +inline char ceSerial::GetParity() { + return parity; +} + +inline void ceSerial::SetStopBits(float nbits) { + if (nbits >= 2) stopbits = 2; +#ifdef CE_WINDOWS + else if(nbits >= 1.5) stopbits = 1.5; +#endif + else stopbits = 1; +} + +inline float ceSerial::GetStopBits() { + return stopbits; +} + + +#ifdef CE_WINDOWS + +inline void ceSerial::SetBaudRate(long baudrate) { + stdbaud = true; + if (baudrate == 110) baud = CBR_110; + else if (baudrate == 300) baud = CBR_300; + else if (baudrate == 600) baud = CBR_600; + else if (baudrate == 1200) baud = CBR_1200; + else if (baudrate == 2400) baud = CBR_2400; + else if (baudrate == 4800) baud = CBR_4800; + else if (baudrate == 9600) baud = CBR_9600; + else if (baudrate == 14400) baud = CBR_14400; + else if (baudrate == 19200) baud = CBR_19200; + else if (baudrate == 38400) baud = CBR_38400; + else if (baudrate == 57600) baud = CBR_57600; + else if (baudrate == 115200) baud = CBR_115200; + else if (baudrate == 128000) baud = CBR_128000; + else if (baudrate == 256000) baud = CBR_256000; + else { + baud = baudrate; + stdbaud = false; + } +} + +inline long ceSerial::GetBaudRate() { + return baud; +} + +inline long ceSerial::Open() { + if (IsOpened()) return 0; +#ifdef UNICODE + std::wstring wtext(port.begin(),port.end()); +#else + std::string wtext = port; +#endif + hComm = CreateFile(wtext.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + 0); + if (hComm == INVALID_HANDLE_VALUE) {return -1;} + + if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) {return -1;}//purge + + //get initial state + DCB dcbOri; + bool fSuccess; + fSuccess = GetCommState(hComm, &dcbOri); + if (!fSuccess) {return -1;} + + DCB dcb1 = dcbOri; + + dcb1.BaudRate = baud; + + if (parity == 'E') dcb1.Parity = EVENPARITY; + else if (parity == 'O') dcb1.Parity = ODDPARITY; + else if (parity == 'M') dcb1.Parity = MARKPARITY; + else if (parity == 'S') dcb1.Parity = SPACEPARITY; + else dcb1.Parity = NOPARITY; + + dcb1.ByteSize = (BYTE)dsize; + + if(stopbits==2) dcb1.StopBits = TWOSTOPBITS; + else if (stopbits == 1.5) dcb1.StopBits = ONE5STOPBITS; + else dcb1.StopBits = ONESTOPBIT; + + dcb1.fOutxCtsFlow = false; + dcb1.fOutxDsrFlow = false; + dcb1.fOutX = false; + dcb1.fDtrControl = DTR_CONTROL_DISABLE; + dcb1.fRtsControl = RTS_CONTROL_DISABLE; + fSuccess = SetCommState(hComm, &dcb1); + this->Delay(60); + if (!fSuccess) {return -1;} + + fSuccess = GetCommState(hComm, &dcb1); + if (!fSuccess) {return -1;} + + osReader = { 0 };// Create the overlapped event. + // Must be closed before exiting to avoid a handle leak. + osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + + if (osReader.hEvent == NULL) {return -1;}// Error creating overlapped event; abort. + fWaitingOnRead = FALSE; + + osWrite = { 0 }; + osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (osWrite.hEvent == NULL) {return -1;} + + if (!GetCommTimeouts(hComm, &timeouts_ori)) { return -1; } // Error getting time-outs. + COMMTIMEOUTS timeouts; + timeouts.ReadIntervalTimeout = 20; + timeouts.ReadTotalTimeoutMultiplier = 15; + timeouts.ReadTotalTimeoutConstant = 100; + timeouts.WriteTotalTimeoutMultiplier = 15; + timeouts.WriteTotalTimeoutConstant = 100; + if (!SetCommTimeouts(hComm, &timeouts)) { return -1;} // Error setting time-outs. + return 0; +} + +inline void ceSerial::Close() { + if (IsOpened()) + { + SetCommTimeouts(hComm, &timeouts_ori); + CloseHandle(osReader.hEvent); + CloseHandle(osWrite.hEvent); + CloseHandle(hComm);//close comm port + hComm = INVALID_HANDLE_VALUE; + } +} + +inline bool ceSerial::IsOpened() { + if(hComm == INVALID_HANDLE_VALUE) return false; + else return true; +} + +inline bool ceSerial::Write(const char *data) { + if (!IsOpened()) { + return false; + } + BOOL fRes; + DWORD dwWritten; + long n = strlen(data); + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + // WriteFile failed, but it isn't delayed. Report error and abort. + if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} + else {// Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; + else fRes = TRUE;// Write operation completed successfully. + } + } + else fRes = TRUE;// WriteFile completed immediately. + return fRes; +} + +inline bool ceSerial::Write(const char *data,long n) { + if (!IsOpened()) { + return false; + } + BOOL fRes; + DWORD dwWritten; + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + // WriteFile failed, but it isn't delayed. Report error and abort. + if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} + else {// Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; + else fRes = TRUE;// Write operation completed successfully. + } + } + else fRes = TRUE;// WriteFile completed immediately. + return fRes; +} + +inline bool ceSerial::WriteChar(const char ch) { + char s[2]; + s[0]=ch; + s[1]=0;//null terminated + return Write(s); +} + +inline char ceSerial::ReadChar(bool& success) { + success = false; + if (!IsOpened()) {return 0;} + + DWORD dwRead; + DWORD length=1; + BYTE* data = (BYTE*)(&rxchar); + //the creation of the overlapped read operation + if (!fWaitingOnRead) { + // Issue read operation. + if (!ReadFile(hComm, data, length, &dwRead, &osReader)) { + if (GetLastError() != ERROR_IO_PENDING) { /*Error*/} + else { fWaitingOnRead = TRUE; /*Waiting*/} + } + else {if(dwRead==length) success = true;}//success + } + + + //detection of the completion of an overlapped read operation + DWORD dwRes; + if (fWaitingOnRead) { + dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT); + switch (dwRes) + { + // Read completed. + case WAIT_OBJECT_0: + if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) {/*Error*/ } + else { + if (dwRead == length) success = true; + fWaitingOnRead = FALSE; + // Reset flag so that another opertion can be issued. + }// Read completed successfully. + break; + + case WAIT_TIMEOUT: + // Operation isn't complete yet. + break; + + default: + // Error in the WaitForSingleObject; + break; + } + } + return rxchar; +} + +inline bool ceSerial::SetRTS(bool value) { + bool r = false; + if (IsOpened()) { + if (value) { + if (EscapeCommFunction(hComm, SETRTS)) r = true; + } + else { + if (EscapeCommFunction(hComm, CLRRTS)) r = true; + } + } + return r; +} + +inline bool ceSerial::SetDTR(bool value) { + bool r = false; + if (IsOpened()) { + if (value) { + if (EscapeCommFunction(hComm, SETDTR)) r = true; + } + else { + if (EscapeCommFunction(hComm, CLRDTR)) r = true; + } + } + return r; +} + +inline bool ceSerial::GetCTS(bool& success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)){ + r = MS_CTS_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetDSR(bool& success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_DSR_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetRI(bool& success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_RING_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetCD(bool& success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_RLSD_ON & dwModemStatus; + success = true; + } + } + return r; +} + +#else //for POSIX + +inline long ceSerial::Open(void) { + struct serial_struct serinfo; + struct termios settings; + memset(&settings, 0, sizeof(settings)); + settings.c_iflag = 0; + settings.c_oflag = 0; + + settings.c_cflag = CREAD | CLOCAL;//see termios.h for more information + if(dsize==5) settings.c_cflag |= CS5;//no change + else if (dsize == 6) settings.c_cflag |= CS6; + else if (dsize == 7) settings.c_cflag |= CS7; + else settings.c_cflag |= CS8; + + if(stopbits==2) settings.c_cflag |= CSTOPB; + + if(parity!='N') settings.c_cflag |= PARENB; + + if (parity == 'O') settings.c_cflag |= PARODD; + + settings.c_lflag = 0; + settings.c_cc[VMIN] = 1; + settings.c_cc[VTIME] = 0; + + fd = open(port.c_str(), O_RDWR | O_NONBLOCK); + if (fd == -1) { + return -1; + } + + if (!stdbaud) { + // serial driver to interpret the value B38400 differently + serinfo.reserved_char[0] = 0; + if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1;} + serinfo.flags &= ~ASYNC_SPD_MASK; + serinfo.flags |= ASYNC_SPD_CUST; + serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud; + if (serinfo.custom_divisor < 1) serinfo.custom_divisor = 1; + if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { return -1; } + if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1; } + if (serinfo.custom_divisor * baud != serinfo.baud_base) { + /* + warnx("actual baudrate is %d / %d = %f\n", + serinfo.baud_base, serinfo.custom_divisor, + (float)serinfo.baud_base / serinfo.custom_divisor); + */ + } + cfsetospeed(&settings, B38400); + cfsetispeed(&settings, B38400); + } + else { + cfsetospeed(&settings, baud); + cfsetispeed(&settings, baud); + } + tcsetattr(fd, TCSANOW, &settings); + int flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + + if (!stdbaud) { + // driver to interpret B38400 as 38400 baud again + ioctl(fd, TIOCGSERIAL, &serinfo); + serinfo.flags &= ~ASYNC_SPD_MASK; + ioctl(fd, TIOCSSERIAL, &serinfo); + } + return 0; +} + +inline void ceSerial::Close() { + if(IsOpened()) close(fd); + fd=-1; +} + +inline bool ceSerial::IsOpened() { + if(fd== (-1)) return false; + else return true; +} + +inline void ceSerial::SetBaudRate(long baudrate) { + stdbaud = true; + if (baudrate == 0) baud = B0; + else if (baudrate == 50) baud = B50; + else if (baudrate == 75) baud = B75; + else if (baudrate == 110) baud = B110; + else if (baudrate == 134) baud = B134; + else if (baudrate == 150) baud = B150; + else if (baudrate == 200) baud = B200; + else if (baudrate == 300) baud = B300; + else if (baudrate == 600) baud = B600; + else if (baudrate == 1200) baud = B1200; + else if (baudrate == 2400) baud = B2400; + else if (baudrate == 4800) baud = B4800; + else if (baudrate == 9600) baud = B9600; + else if (baudrate == 19200) baud = B19200; + else if (baudrate == 38400) baud = B38400; + else if (baudrate == 57600) baud = B57600; + else if (baudrate == 115200) baud = B115200; + else if (baudrate == 230400) baud = B230400; + else { + baud = baudrate; + stdbaud = false; + } +} + +inline long ceSerial::GetBaudRate() { + return baud; +} + +inline char ceSerial::ReadChar(bool& success) { + success=false; + if (!IsOpened()) {return 0; } + success=read(fd, &rxchar, 1)==1; + return rxchar; +} + +inline bool ceSerial::Write(const char *data) { + if (!IsOpened()) {return false; } + long n = strlen(data); + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + return (write(fd, data, n)==n); +} + +inline bool ceSerial::Write(const char *data,long n) { + if (!IsOpened()) {return false; } + if (n < 0) n = 0; + else if(n > 1024) n = 1024; + return (write(fd, data, n)==n); +} + +inline bool ceSerial::WriteChar(const char ch) { + char s[2]; + s[0]=ch; + s[1]=0;//null terminated + return Write(s); +} + +inline bool ceSerial::SetRTS(bool value) { + long RTS_flag = TIOCM_RTS; + bool success=true; + if (value) {//Set RTS pin + if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) success=false; + } + else {//Clear RTS pin + if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) success=false; + } + return success; +} + +inline bool ceSerial::SetDTR(bool value) { + long DTR_flag = TIOCM_DTR; + bool success=true; + if (value) {//Set DTR pin + if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) success=false; + } + else {//Clear DTR pin + if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) success=false; + } + return success; +} + +inline bool ceSerial::GetCTS(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_CTS) != 0); +} + +inline bool ceSerial::GetDSR(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_DSR) != 0); +} + +inline bool ceSerial::GetRI(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_RI) != 0); +} + +inline bool ceSerial::GetCD(bool& success) { + success=true; + long status; + if(ioctl(fd, TIOCMGET, &status)== -1) success=false; + return ((status & TIOCM_CD) != 0); +} +#endif + +#endif // CESERIAL_H diff --git a/src/ceSHA1.cpp b/include/ce/cesha1x.h similarity index 74% rename from src/ceSHA1.cpp rename to include/ce/cesha1x.h index e82861e..f9e7198 100644 --- a/src/ceSHA1.cpp +++ b/include/ce/cesha1x.h @@ -1,317 +1,364 @@ -// Description: Functions to calculate SHA1 -// Class implementation of the following repository: https://github.com/clibs/sha1 - -/* -SHA-1 in C -By Steve Reid -100% Public Domain - -Test Vectors (from FIPS PUB 180-1) -"abc" - A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D -"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 -A million repetitions of "a" - 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F -*/ - -/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ -/* #define SHA1HANDSOFF * Copies data before messing with it. */ - -#define SHA1HANDSOFF - -#include -#include - -/* for uint32_t */ -#include - -#include "ce/ceSHA1.h" - - -#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -/* blk0() and blk() perform the initial expand. */ -/* I got the idea of expanding during the round function from SSLeay */ -#if BYTE_ORDER == LITTLE_ENDIAN -#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ - |(rol(block->l[i],8)&0x00FF00FF)) -#elif BYTE_ORDER == BIG_ENDIAN -#define blk0(i) block->l[i] -#else -#error "Endianness not defined!" -#endif -#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ - ^block->l[(i+2)&15]^block->l[i&15],1)) - -/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ -#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); -#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); -#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); - -namespace ce { -/* Hash a single 512-bit block. This is the core of the algorithm. */ - -void ceSHA1::SHA1Transform( - uint32_t state[5], - const unsigned char buffer[64] -) -{ - uint32_t a, b, c, d, e; - - typedef union - { - unsigned char c[64]; - uint32_t l[16]; - } CHAR64LONG16; - -#ifdef SHA1HANDSOFF - CHAR64LONG16 block[1]; /* use array to appear as a pointer */ - - memcpy(block, buffer, 64); -#else - /* The following had better never be used because it causes the - * pointer-to-const buffer to be cast into a pointer to non-const. - * And the result is written through. I threw a "const" in, hoping - * this will cause a diagnostic. - */ - CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer; -#endif - /* Copy context->state[] to working vars */ - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - /* 4 rounds of 20 operations each. Loop unrolled. */ - R0(a, b, c, d, e, 0); - R0(e, a, b, c, d, 1); - R0(d, e, a, b, c, 2); - R0(c, d, e, a, b, 3); - R0(b, c, d, e, a, 4); - R0(a, b, c, d, e, 5); - R0(e, a, b, c, d, 6); - R0(d, e, a, b, c, 7); - R0(c, d, e, a, b, 8); - R0(b, c, d, e, a, 9); - R0(a, b, c, d, e, 10); - R0(e, a, b, c, d, 11); - R0(d, e, a, b, c, 12); - R0(c, d, e, a, b, 13); - R0(b, c, d, e, a, 14); - R0(a, b, c, d, e, 15); - R1(e, a, b, c, d, 16); - R1(d, e, a, b, c, 17); - R1(c, d, e, a, b, 18); - R1(b, c, d, e, a, 19); - R2(a, b, c, d, e, 20); - R2(e, a, b, c, d, 21); - R2(d, e, a, b, c, 22); - R2(c, d, e, a, b, 23); - R2(b, c, d, e, a, 24); - R2(a, b, c, d, e, 25); - R2(e, a, b, c, d, 26); - R2(d, e, a, b, c, 27); - R2(c, d, e, a, b, 28); - R2(b, c, d, e, a, 29); - R2(a, b, c, d, e, 30); - R2(e, a, b, c, d, 31); - R2(d, e, a, b, c, 32); - R2(c, d, e, a, b, 33); - R2(b, c, d, e, a, 34); - R2(a, b, c, d, e, 35); - R2(e, a, b, c, d, 36); - R2(d, e, a, b, c, 37); - R2(c, d, e, a, b, 38); - R2(b, c, d, e, a, 39); - R3(a, b, c, d, e, 40); - R3(e, a, b, c, d, 41); - R3(d, e, a, b, c, 42); - R3(c, d, e, a, b, 43); - R3(b, c, d, e, a, 44); - R3(a, b, c, d, e, 45); - R3(e, a, b, c, d, 46); - R3(d, e, a, b, c, 47); - R3(c, d, e, a, b, 48); - R3(b, c, d, e, a, 49); - R3(a, b, c, d, e, 50); - R3(e, a, b, c, d, 51); - R3(d, e, a, b, c, 52); - R3(c, d, e, a, b, 53); - R3(b, c, d, e, a, 54); - R3(a, b, c, d, e, 55); - R3(e, a, b, c, d, 56); - R3(d, e, a, b, c, 57); - R3(c, d, e, a, b, 58); - R3(b, c, d, e, a, 59); - R4(a, b, c, d, e, 60); - R4(e, a, b, c, d, 61); - R4(d, e, a, b, c, 62); - R4(c, d, e, a, b, 63); - R4(b, c, d, e, a, 64); - R4(a, b, c, d, e, 65); - R4(e, a, b, c, d, 66); - R4(d, e, a, b, c, 67); - R4(c, d, e, a, b, 68); - R4(b, c, d, e, a, 69); - R4(a, b, c, d, e, 70); - R4(e, a, b, c, d, 71); - R4(d, e, a, b, c, 72); - R4(c, d, e, a, b, 73); - R4(b, c, d, e, a, 74); - R4(a, b, c, d, e, 75); - R4(e, a, b, c, d, 76); - R4(d, e, a, b, c, 77); - R4(c, d, e, a, b, 78); - R4(b, c, d, e, a, 79); - /* Add the working vars back into context.state[] */ - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - /* Wipe variables */ - a = b = c = d = e = 0; -#ifdef SHA1HANDSOFF - memset(block, '\0', sizeof(block)); -#endif -} - - -/* SHA1Init - Initialize new context */ - -void ceSHA1::SHA1Init( - SHA1_CTX * context -) -{ - /* SHA1 initialization constants */ - context->state[0] = 0x67452301; - context->state[1] = 0xEFCDAB89; - context->state[2] = 0x98BADCFE; - context->state[3] = 0x10325476; - context->state[4] = 0xC3D2E1F0; - context->count[0] = context->count[1] = 0; -} - - -/* Run your data through this. */ - -void ceSHA1::SHA1Update( - SHA1_CTX * context, - const unsigned char *data, - uint32_t len -) -{ - uint32_t i; - - uint32_t j; - - j = context->count[0]; - if ((context->count[0] += len << 3) < j) - context->count[1]++; - context->count[1] += (len >> 29); - j = (j >> 3) & 63; - if ((j + len) > 63) - { - memcpy(&context->buffer[j], data, (i = 64 - j)); - SHA1Transform(context->state, context->buffer); - for (; i + 63 < len; i += 64) - { - SHA1Transform(context->state, &data[i]); - } - j = 0; - } - else - i = 0; - memcpy(&context->buffer[j], &data[i], len - i); -} - - -/* Add padding and return the message digest. */ - -void ceSHA1::SHA1Final( - unsigned char digest[20], - SHA1_CTX * context -) -{ - unsigned i; - - unsigned char finalcount[8]; - - unsigned char c; - -#if 0 /* untested "improvement" by DHR */ - /* Convert context->count to a sequence of bytes - * in finalcount. Second element first, but - * big-endian order within element. - * But we do it all backwards. - */ - unsigned char *fcp = &finalcount[8]; - - for (i = 0; i < 2; i++) - { - uint32_t t = context->count[i]; - - int j; - - for (j = 0; j < 4; t >>= 8, j++) - *--fcp = (unsigned char) t} -#else - for (i = 0; i < 8; i++) - { - finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ - } -#endif - c = 0200; - SHA1Update(context, &c, 1); - while ((context->count[0] & 504) != 448) - { - c = 0000; - SHA1Update(context, &c, 1); - } - SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ - for (i = 0; i < 20; i++) - { - digest[i] = (unsigned char) - ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); - } - /* Wipe variables */ - memset(context, '\0', sizeof(*context)); - memset(&finalcount, '\0', sizeof(finalcount)); -} - -void ceSHA1::SHA1( - char *hash_out, - const char *str, - uint32_t len) -{ - SHA1_CTX ctx; - unsigned int ii; - - SHA1Init(&ctx); - for (ii=0; ii + 100% Public Domain + */ + // Description: Functions to calculate SHA1 + // Class implementation of the following repository: https://github.com/clibs/sha1 +///////////////////////////////////////////////////////////////////////////// +#include +#include +#include + +namespace ce { +typedef struct +{ + uint32_t state[5]; + uint32_t count[2]; + unsigned char buffer[64]; +} SHA1_CTX; + +class ceSHA1 { +private: + SHA1_CTX sha; + //----------------------------------------------------------------------------- + void SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] + ); + + void SHA1Init( + SHA1_CTX* context + ); + + void SHA1Update( + SHA1_CTX* context, + const unsigned char* data, + uint32_t len + ); + + void SHA1Final( + unsigned char digest[20], + SHA1_CTX* context + ); + void SHA1( + char* hash_out, + const char* str, + uint32_t len); +public: + void Init(); + void Update(std::string str); + std::string Final(); +}; +///////////////////////////////////////////////////////////////////////////// +/* +SHA-1 in C +By Steve Reid +100% Public Domain + +Test Vectors (from FIPS PUB 180-1) +"abc" +A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D +"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" +84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 +A million repetitions of "a" +34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F +*/ + +/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ +/* #define SHA1HANDSOFF * Copies data before messing with it. */ + +#define SHA1HANDSOFF + +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) + +/* blk0() and blk() perform the initial expand. */ +/* I got the idea of expanding during the round function from SSLeay */ +#if BYTE_ORDER == LITTLE_ENDIAN +#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ + |(rol(block->l[i],8)&0x00FF00FF)) +#elif BYTE_ORDER == BIG_ENDIAN +#define blk0(i) block->l[i] +#else +#error "Endianness not defined!" +#endif +#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ + ^block->l[(i+2)&15]^block->l[i&15],1)) + +/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ +#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); +#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); +#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); + + +/* Hash a single 512-bit block. This is the core of the algorithm. */ + +void ceSHA1::SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] +) +{ + uint32_t a, b, c, d, e; + + typedef union + { + unsigned char c[64]; + uint32_t l[16]; + } CHAR64LONG16; + +#ifdef SHA1HANDSOFF + CHAR64LONG16 block[1]; /* use array to appear as a pointer */ + + memcpy(block, buffer, 64); +#else + /* The following had better never be used because it causes the + * pointer-to-const buffer to be cast into a pointer to non-const. + * And the result is written through. I threw a "const" in, hoping + * this will cause a diagnostic. + */ + CHAR64LONG16* block = (const CHAR64LONG16*)buffer; +#endif + /* Copy context->state[] to working vars */ + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + /* 4 rounds of 20 operations each. Loop unrolled. */ + R0(a, b, c, d, e, 0); + R0(e, a, b, c, d, 1); + R0(d, e, a, b, c, 2); + R0(c, d, e, a, b, 3); + R0(b, c, d, e, a, 4); + R0(a, b, c, d, e, 5); + R0(e, a, b, c, d, 6); + R0(d, e, a, b, c, 7); + R0(c, d, e, a, b, 8); + R0(b, c, d, e, a, 9); + R0(a, b, c, d, e, 10); + R0(e, a, b, c, d, 11); + R0(d, e, a, b, c, 12); + R0(c, d, e, a, b, 13); + R0(b, c, d, e, a, 14); + R0(a, b, c, d, e, 15); + R1(e, a, b, c, d, 16); + R1(d, e, a, b, c, 17); + R1(c, d, e, a, b, 18); + R1(b, c, d, e, a, 19); + R2(a, b, c, d, e, 20); + R2(e, a, b, c, d, 21); + R2(d, e, a, b, c, 22); + R2(c, d, e, a, b, 23); + R2(b, c, d, e, a, 24); + R2(a, b, c, d, e, 25); + R2(e, a, b, c, d, 26); + R2(d, e, a, b, c, 27); + R2(c, d, e, a, b, 28); + R2(b, c, d, e, a, 29); + R2(a, b, c, d, e, 30); + R2(e, a, b, c, d, 31); + R2(d, e, a, b, c, 32); + R2(c, d, e, a, b, 33); + R2(b, c, d, e, a, 34); + R2(a, b, c, d, e, 35); + R2(e, a, b, c, d, 36); + R2(d, e, a, b, c, 37); + R2(c, d, e, a, b, 38); + R2(b, c, d, e, a, 39); + R3(a, b, c, d, e, 40); + R3(e, a, b, c, d, 41); + R3(d, e, a, b, c, 42); + R3(c, d, e, a, b, 43); + R3(b, c, d, e, a, 44); + R3(a, b, c, d, e, 45); + R3(e, a, b, c, d, 46); + R3(d, e, a, b, c, 47); + R3(c, d, e, a, b, 48); + R3(b, c, d, e, a, 49); + R3(a, b, c, d, e, 50); + R3(e, a, b, c, d, 51); + R3(d, e, a, b, c, 52); + R3(c, d, e, a, b, 53); + R3(b, c, d, e, a, 54); + R3(a, b, c, d, e, 55); + R3(e, a, b, c, d, 56); + R3(d, e, a, b, c, 57); + R3(c, d, e, a, b, 58); + R3(b, c, d, e, a, 59); + R4(a, b, c, d, e, 60); + R4(e, a, b, c, d, 61); + R4(d, e, a, b, c, 62); + R4(c, d, e, a, b, 63); + R4(b, c, d, e, a, 64); + R4(a, b, c, d, e, 65); + R4(e, a, b, c, d, 66); + R4(d, e, a, b, c, 67); + R4(c, d, e, a, b, 68); + R4(b, c, d, e, a, 69); + R4(a, b, c, d, e, 70); + R4(e, a, b, c, d, 71); + R4(d, e, a, b, c, 72); + R4(c, d, e, a, b, 73); + R4(b, c, d, e, a, 74); + R4(a, b, c, d, e, 75); + R4(e, a, b, c, d, 76); + R4(d, e, a, b, c, 77); + R4(c, d, e, a, b, 78); + R4(b, c, d, e, a, 79); + /* Add the working vars back into context.state[] */ + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + /* Wipe variables */ + a = b = c = d = e = 0; +#ifdef SHA1HANDSOFF + memset(block, '\0', sizeof(block)); +#endif +} + + +/* SHA1Init - Initialize new context */ + +void ceSHA1::SHA1Init( + SHA1_CTX* context +) +{ + /* SHA1 initialization constants */ + context->state[0] = 0x67452301; + context->state[1] = 0xEFCDAB89; + context->state[2] = 0x98BADCFE; + context->state[3] = 0x10325476; + context->state[4] = 0xC3D2E1F0; + context->count[0] = context->count[1] = 0; +} + + +/* Run your data through this. */ + +void ceSHA1::SHA1Update( + SHA1_CTX* context, + const unsigned char* data, + uint32_t len +) +{ + uint32_t i; + + uint32_t j; + + j = context->count[0]; + if ((context->count[0] += len << 3) < j) + context->count[1]++; + context->count[1] += (len >> 29); + j = (j >> 3) & 63; + if ((j + len) > 63) + { + memcpy(&context->buffer[j], data, (i = 64 - j)); + SHA1Transform(context->state, context->buffer); + for (; i + 63 < len; i += 64) + { + SHA1Transform(context->state, &data[i]); + } + j = 0; + } + else + i = 0; + memcpy(&context->buffer[j], &data[i], len - i); +} + + +/* Add padding and return the message digest. */ + +void ceSHA1::SHA1Final( + unsigned char digest[20], + SHA1_CTX* context +) +{ + unsigned i; + + unsigned char finalcount[8]; + + unsigned char c; + +#if 0 /* untested "improvement" by DHR */ + /* Convert context->count to a sequence of bytes + * in finalcount. Second element first, but + * big-endian order within element. + * But we do it all backwards. + */ + unsigned char* fcp = &finalcount[8]; + + for (i = 0; i < 2; i++) + { + uint32_t t = context->count[i]; + + int j; + + for (j = 0; j < 4; t >>= 8, j++) + *--fcp = (unsigned char)t + } +#else + for (i = 0; i < 8; i++) + { + finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ + } +#endif + c = 0200; + SHA1Update(context, &c, 1); + while ((context->count[0] & 504) != 448) + { + c = 0000; + SHA1Update(context, &c, 1); + } + SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ + for (i = 0; i < 20; i++) + { + digest[i] = (unsigned char) + ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); + } + /* Wipe variables */ + memset(context, '\0', sizeof(*context)); + memset(&finalcount, '\0', sizeof(finalcount)); +} + +void ceSHA1::SHA1( + char* hash_out, + const char* str, + uint32_t len) +{ + SHA1_CTX ctx; + unsigned int ii; + + SHA1Init(&ctx); + for (ii = 0; ii < len; ii += 1) + SHA1Update(&ctx, (const unsigned char*)str + ii, 1); + SHA1Final((unsigned char*)hash_out, &ctx); +} + +void ceSHA1::Init() +{ + SHA1Init(&sha); +} + +void ceSHA1::Update(std::string str) +{ + SHA1Update(&sha, (uint8_t*)str.c_str(), str.length()); +} + +std::string ceSHA1::Final() +{ + uint8_t results[20]; + SHA1Final(results, &sha); + std::string r((char*)results, 20); + return r; +} +///////////////////////////////////////////////////////////////////////////// +} // namespace ce + +#endif /* SHA1_H */ diff --git a/include/ce/ceTcpClient.h b/include/ce/cetcpcli.h similarity index 67% rename from include/ce/ceTcpClient.h rename to include/ce/cetcpcli.h index 8735cee..1f964aa 100644 --- a/include/ce/ceTcpClient.h +++ b/include/ce/cetcpcli.h @@ -7,7 +7,43 @@ #ifndef CETCPCLIENT_H #define CETCPCLIENT_H -#include "ce/ceMacros.h" // macros + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_WX 1 // include WX +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + #if CE_WX==1 #include #include diff --git a/include/ce/ceUDP.h b/include/ce/ceudpx.h similarity index 69% rename from include/ce/ceUDP.h rename to include/ce/ceudpx.h index 188edd0..27bb951 100644 --- a/include/ce/ceUDP.h +++ b/include/ce/ceudpx.h @@ -1,58 +1,93 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceUDP.h -// Description: UDP communication module -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEUDP_H -#define CEUDP_H - -#include "ce/ceMacros.h" // macros -#if CE_WX==1 -#include -#include -#include -#include "wx/wx.h" -#include "wx/socket.h" -// this example is currently written to use only IP or only IPv4 sockets, it -// should be extended to allow using either in the future -//#if wxUSE_IPV6 -//typedef wxIPV6address IPaddress; -//#else -typedef wxIPV4address IPaddress; -//#endif - -#define CE_UDP_RX_BUF_SIZE 32768 - -namespace ce { -class ceUDP : public wxEvtHandler { -public: - ceUDP(wxEvtHandler* app, int socketid, int rx_port); // rx_port = 0 for not listening - ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port); - ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost); - int Tx(std::vector bv); // return 0 = success, 1 = error - int Tx(std::vector bv, std::string remoteHost, int txPort); // return 0 = success, 1 = error - int Open(); // return 0 = success, 1 = error - void Close(); - int GetRxPort(); - void SetRxPort(int rx_port); - int GetTxPort(); - void SetTxPort(int tx_port); - std::string GetRemotehost(); - void SetRemotehost(std::string remoteHost); -private: - void Rx(int socketid, std::vector bv, std::string ip, int port); - void OnSocketEvent(wxSocketEvent& event); - wxEvtHandler* _app; - int SOCKET_ID; - int udp_port_rx; - int udp_port_tx; - std::string udp_remote_host; - wxDatagramSocket *sock; - int _ok; -}; - -} // namespace ce -#endif // CE_WX -#endif // CEUDP_H +///////////////////////////////////////////////////////////////////////////// +// Name: ceUDP.h +// Description: UDP communication module +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEUDP_H +#define CEUDP_H + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_WX 1 // include WX +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + +#if CE_WX==1 +#include +#include +#include +#include "wx/wx.h" +#include "wx/socket.h" +// this example is currently written to use only IP or only IPv4 sockets, it +// should be extended to allow using either in the future +//#if wxUSE_IPV6 +//typedef wxIPV6address IPaddress; +//#else +typedef wxIPV4address IPaddress; +//#endif + +#define CE_UDP_RX_BUF_SIZE 32768 + +namespace ce { +class ceUDP : public wxEvtHandler { +public: + ceUDP(wxEvtHandler* app, int socketid, int rx_port); // rx_port = 0 for not listening + ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port); + ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost); + int Tx(std::vector bv); // return 0 = success, 1 = error + int Tx(std::vector bv, std::string remoteHost, int txPort); // return 0 = success, 1 = error + int Open(); // return 0 = success, 1 = error + void Close(); + int GetRxPort(); + void SetRxPort(int rx_port); + int GetTxPort(); + void SetTxPort(int tx_port); + std::string GetRemotehost(); + void SetRemotehost(std::string remoteHost); +private: + void Rx(int socketid, std::vector bv, std::string ip, int port); + void OnSocketEvent(wxSocketEvent& event); + wxEvtHandler* _app; + int SOCKET_ID; + int udp_port_rx; + int udp_port_tx; + std::string udp_remote_host; + wxDatagramSocket *sock; + int _ok; +}; + +} // namespace ce +#endif // CE_WX +#endif // CEUDP_H diff --git a/include/ce/cewxcvMisc.h b/include/ce/cewxcvMisc.h index 6a140fe..4ef6a70 100644 --- a/include/ce/cewxcvMisc.h +++ b/include/ce/cewxcvMisc.h @@ -7,8 +7,44 @@ #ifndef CEWXCVMISC_H #define CEWXCVMISC_H +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_WX 1 // include WX +#define CE_CV 1 // include CV +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + #include -#include "ce/ceMacros.h" // macros #if CE_WX==1 #include "wx/wx.h" #endif // CE_WX diff --git a/vcprj/ceutil.vcxproj b/vcprj/ceutil.vcxproj index 9f2d81f..3228bfe 100644 --- a/vcprj/ceutil.vcxproj +++ b/vcprj/ceutil.vcxproj @@ -31,10 +31,12 @@ - + + + - - + + diff --git a/vcprj/ceutil.vcxproj.filters b/vcprj/ceutil.vcxproj.filters index c328023..b493a41 100644 --- a/vcprj/ceutil.vcxproj.filters +++ b/vcprj/ceutil.vcxproj.filters @@ -21,21 +21,12 @@ Header Files - - Header Files - Header Files - - Header Files - Header Files - - Header Files - Header Files @@ -66,6 +57,21 @@ Header Files + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + From cd7028b5735aff82582bd89f82056727cff85b99 Mon Sep 17 00:00:00 2001 From: yan9a Date: Sat, 24 Aug 2024 19:40:05 +1200 Subject: [PATCH 05/10] Update header files --- include/ce/{cedesx.h => cedes.h} | 0 include/ce/{cefracmdx.h => cefracmd.h} | 0 include/ce/{ceframex.h => ceframe.h} | 0 include/ce/{cei2cx.h => cei2c.h} | 0 include/ce/{celogx.h => celog.h} | 0 include/ce/{cemiscx.h => cemisc.h} | 0 include/ce/{cemodbusx.h => cemodbus.h} | 0 include/ce/{cepca9535x.h => cepca9535.h} | 0 include/ce/cersaos.h | 231 +++++++++++++++--- include/ce/{ceserialx.h => ceserial.h} | 0 include/ce/{cesha1x.h => cesha1.h} | 16 +- include/ce/cetcpcli.h | 175 +++++++++++++- include/ce/ceudp.h | 269 +++++++++++++++++++++ include/ce/ceudpx.h | 93 ------- include/ce/{cewxcvMisc.h => cewxcvmiscx.h} | 175 ++++++++------ src/ceRSA_OS.cpp | 184 -------------- src/ceTcpClient.cpp | 185 -------------- src/ceUDP.cpp | 187 -------------- src/cewxcvMisc.cpp | 45 ---- vcprj/ceutil.vcxproj | 4 - vcprj/ceutil.vcxproj.filters | 12 - 21 files changed, 759 insertions(+), 817 deletions(-) rename include/ce/{cedesx.h => cedes.h} (100%) rename include/ce/{cefracmdx.h => cefracmd.h} (100%) rename include/ce/{ceframex.h => ceframe.h} (100%) rename include/ce/{cei2cx.h => cei2c.h} (100%) rename include/ce/{celogx.h => celog.h} (100%) rename include/ce/{cemiscx.h => cemisc.h} (100%) rename include/ce/{cemodbusx.h => cemodbus.h} (100%) rename include/ce/{cepca9535x.h => cepca9535.h} (100%) rename include/ce/{ceserialx.h => ceserial.h} (100%) rename include/ce/{cesha1x.h => cesha1.h} (97%) create mode 100644 include/ce/ceudp.h delete mode 100644 include/ce/ceudpx.h rename include/ce/{cewxcvMisc.h => cewxcvmiscx.h} (55%) delete mode 100644 src/ceRSA_OS.cpp delete mode 100644 src/ceTcpClient.cpp delete mode 100644 src/ceUDP.cpp delete mode 100644 src/cewxcvMisc.cpp diff --git a/include/ce/cedesx.h b/include/ce/cedes.h similarity index 100% rename from include/ce/cedesx.h rename to include/ce/cedes.h diff --git a/include/ce/cefracmdx.h b/include/ce/cefracmd.h similarity index 100% rename from include/ce/cefracmdx.h rename to include/ce/cefracmd.h diff --git a/include/ce/ceframex.h b/include/ce/ceframe.h similarity index 100% rename from include/ce/ceframex.h rename to include/ce/ceframe.h diff --git a/include/ce/cei2cx.h b/include/ce/cei2c.h similarity index 100% rename from include/ce/cei2cx.h rename to include/ce/cei2c.h diff --git a/include/ce/celogx.h b/include/ce/celog.h similarity index 100% rename from include/ce/celogx.h rename to include/ce/celog.h diff --git a/include/ce/cemiscx.h b/include/ce/cemisc.h similarity index 100% rename from include/ce/cemiscx.h rename to include/ce/cemisc.h diff --git a/include/ce/cemodbusx.h b/include/ce/cemodbus.h similarity index 100% rename from include/ce/cemodbusx.h rename to include/ce/cemodbus.h diff --git a/include/ce/cepca9535x.h b/include/ce/cepca9535.h similarity index 100% rename from include/ce/cepca9535x.h rename to include/ce/cepca9535.h diff --git a/include/ce/cersaos.h b/include/ce/cersaos.h index a146f40..f344c80 100644 --- a/include/ce/cersaos.h +++ b/include/ce/cersaos.h @@ -22,44 +22,219 @@ #include #include namespace ce { - class ceRSA_OS { - public: - // ---------------------------------------------------------------------------- - static std::string bn2str(BIGNUM* bigN); +class ceRSA_OS { +public: + // ---------------------------------------------------------------------------- + static std::string bn2str(BIGNUM* bigN); - // Load public key from file - static RSA* loadPublicKey(std::string publicKeyFile); + // Load public key from file + static RSA* loadPublicKey(std::string publicKeyFile); - // Load private key from file - static RSA* loadPrivateKey(std::string privateKeyFile); + // Load private key from file + static RSA* loadPrivateKey(std::string privateKeyFile); - // Encrypt data using public key - static std::string encrypt(const std::string& message, RSA* rsa_key); + // Encrypt data using public key + static std::string encrypt(const std::string& message, RSA* rsa_key); - // Decrypt data using private key - static std::string decrypt(const std::string& ciphertext, RSA* rsa_key); + // Decrypt data using private key + static std::string decrypt(const std::string& ciphertext, RSA* rsa_key); - // Generate a public-private key pair and save to files - static RSA* generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t bit_len = 2048, uint32_t exp = 3); + // Generate a public-private key pair and save to files + static RSA* generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t bit_len = 2048, uint32_t exp = 3); - // Generate a public-private key pair and returns RSA - static RSA* generateKeyPair(uint32_t bit_len = 2048, uint32_t exp = 3); + // Generate a public-private key pair and returns RSA + static RSA* generateKeyPair(uint32_t bit_len = 2048, uint32_t exp = 3); - // Encrypt data using public key - static std::string encrypt(const std::string& message, std::string publicKeyFile); + // Encrypt data using public key + static std::string encrypt(const std::string& message, std::string publicKeyFile); - // Decrypt data using private key - static std::string decrypt(const std::string& ciphertext, std::string privateKeyFile); + // Decrypt data using private key + static std::string decrypt(const std::string& ciphertext, std::string privateKeyFile); - // Encrypt data using modulus n and exponent e - static std::string encrypt(const std::string& message, std::string n, std::string e); + // Encrypt data using modulus n and exponent e + static std::string encrypt(const std::string& message, std::string n, std::string e); - // Decrypt data using secret number d, modulus n and exponent e - static std::string decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e); + // Decrypt data using secret number d, modulus n and exponent e + static std::string decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e); - // Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key - static void getBN(RSA* key, std::string& d, std::string& n, std::string& e); - }; -} // namespace ce + // Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key + static void getBN(RSA* key, std::string& d, std::string& n, std::string& e); +}; + +#ifdef CE_WINDOWS +#ifdef _MSC_VER +#pragma warning(disable : 4996) +#endif +#endif + +// ---------------------------------------------------------------------------- + +// Load public key from file +inline RSA* ceRSA_OS::loadPublicKey(std::string publicKeyFile) { + RSA* keypair = RSA_new(); + FILE* publicKey = fopen(publicKeyFile.c_str(), "r"); + PEM_read_RSAPublicKey(publicKey, &keypair, NULL, NULL); + fclose(publicKey); + return keypair; +} + +// Load private key from file +inline RSA* ceRSA_OS::loadPrivateKey(std::string privateKeyFile) { + RSA* keypair = RSA_new(); + FILE* bigN = fopen(privateKeyFile.c_str(), "r"); + PEM_read_RSAPrivateKey(bigN, &keypair, NULL, NULL); + fclose(bigN); + return keypair; +} + +// Encrypt data using public key +inline std::string ceRSA_OS::encrypt(const std::string& message, RSA* rsa_key) { + int rsa_size = RSA_size(rsa_key); + std::vector ciphertext(rsa_size); + + int len = RSA_public_encrypt(message.size(), reinterpret_cast(message.data()), + ciphertext.data(), rsa_key, RSA_NO_PADDING); + //ciphertext.data(), rsa_key, RSA_PKCS1_PADDING); + + if (len < 0) { + // std::cerr << "Encryption failed" << std::endl; + return ""; + } + + return std::string(reinterpret_cast(ciphertext.data()), len); +} + +// Decrypt data using private key +inline std::string ceRSA_OS::decrypt(const std::string& ciphertext, RSA* rsa_key) { + int rsa_size = RSA_size(rsa_key); + std::vector message(rsa_size); + + int len = RSA_private_decrypt(ciphertext.size(), reinterpret_cast(ciphertext.data()), + message.data(), rsa_key, RSA_NO_PADDING); + + if (len < 0) { + // std::cerr << "Decryption failed" << std::endl; + return ""; + } + + return std::string(reinterpret_cast(message.data()), len); +} + +inline std::string ceRSA_OS::bn2str(BIGNUM* bigN) +{ + // Convert BIGNUM to binary representation + size_t bnSize = BN_num_bytes(bigN); + unsigned char* bnStr = new unsigned char[bnSize]; + BN_bn2bin(bigN, bnStr); + std::string bnString((char*)bnStr, bnSize); + return bnString; +} + +// ---------------------------------------------------------------------------- + +// Generate a public-private key pair and save to files +inline RSA* ceRSA_OS::generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t keyLength, uint32_t exp) { + RSA* keypair = RSA_new(); + BIGNUM* e = BN_new(); + BN_set_word(e, exp); + RSA_generate_key_ex(keypair, keyLength, e, NULL); + FILE* publicKey = fopen(publicKeyFile.c_str(), "w"); + PEM_write_RSAPublicKey(publicKey, keypair); + fclose(publicKey); + + FILE* bigN = fopen(privateKeyFile.c_str(), "w"); + PEM_write_RSAPrivateKey(bigN, keypair, NULL, NULL, 0, NULL, NULL); + fclose(bigN); + + BN_free(e); + return keypair; +} + +// Generate a public-private key pair and returns RSA +inline RSA* ceRSA_OS::generateKeyPair(uint32_t keyLength, uint32_t exp) { + RSA* keypair = RSA_new(); + BIGNUM* e = BN_new(); + BN_set_word(e, exp); + RSA_generate_key_ex(keypair, keyLength, e, NULL); + BN_free(e); + return keypair; +} + +// Encrypt data using public key +inline std::string ceRSA_OS::encrypt(const std::string& message, std::string publicKeyFile) +{ + // Load public key + RSA* public_key = loadPublicKey(publicKeyFile); + std::string encrypted = encrypt(message, public_key); + return encrypted; +} + +// Decrypt data using private key +inline std::string ceRSA_OS::decrypt(const std::string& ciphertext, std::string privateKeyFile) +{ + // Load private key + RSA* private_key = loadPrivateKey(privateKeyFile); + std::string decrypted = decrypt(ciphertext, private_key); + return decrypted; +} + +// Encrypt data using modulus n and exponent e +inline std::string ceRSA_OS::encrypt(const std::string& message, std::string n, std::string e) +{ + BIGNUM* bn_e3 = BN_new(); + BIGNUM* bn_n3 = BN_new(); + + if (BN_bin2bn((const unsigned char*)e.c_str(), e.length(), bn_e3) == NULL) { + printf("Failed to convert modulus"); + } + if (BN_bin2bn((const unsigned char*)n.c_str(), n.length(), bn_n3) == NULL) { + printf("Failed to convert exponent"); + } + + RSA* public_key3 = RSA_new(); + RSA_set0_key(public_key3, bn_n3, bn_e3, NULL); + + std::string encrypted = encrypt(message, public_key3); + return encrypted; +} + +// Decrypt data using secret number d, modulus n and exponent e +inline std::string ceRSA_OS::decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e) +{ + BIGNUM* bn_d3 = BN_new(); + BIGNUM* bn_e3 = BN_new(); + BIGNUM* bn_n3 = BN_new(); + if (BN_bin2bn((const unsigned char*)d.c_str(), d.length(), bn_d3) == NULL) { + printf("Failed to convert d"); + } + if (BN_bin2bn((const unsigned char*)e.c_str(), e.length(), bn_e3) == NULL) { + printf("Failed to convert modulus"); + } + if (BN_bin2bn((const unsigned char*)n.c_str(), n.length(), bn_n3) == NULL) { + printf("Failed to convert exponent"); + } + + RSA* private_key3 = RSA_new(); + RSA_set0_key(private_key3, bn_n3, bn_e3, bn_d3); + + std::string decrypted = decrypt(ciphertext, private_key3); + return decrypted; +} + +// Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key +inline void ceRSA_OS::getBN(RSA* key, std::string& d, std::string& n, std::string& e) +{ + // Obtain the key components as BIGNUM + BIGNUM* bn_d = BN_dup(RSA_get0_d(key)); + BIGNUM* bn_e = BN_dup(RSA_get0_e(key)); + BIGNUM* bn_n = BN_dup(RSA_get0_n(key)); + + d = bn2str(bn_d); + e = bn2str(bn_e); + n = bn2str(bn_n); +} + +// ---------------------------------------------------------------------------- +} // namespace ce #endif // CERSA_OS_H diff --git a/include/ce/ceserialx.h b/include/ce/ceserial.h similarity index 100% rename from include/ce/ceserialx.h rename to include/ce/ceserial.h diff --git a/include/ce/cesha1x.h b/include/ce/cesha1.h similarity index 97% rename from include/ce/cesha1x.h rename to include/ce/cesha1.h index f9e7198..71cc198 100644 --- a/include/ce/cesha1x.h +++ b/include/ce/cesha1.h @@ -98,7 +98,7 @@ A million repetitions of "a" /* Hash a single 512-bit block. This is the core of the algorithm. */ -void ceSHA1::SHA1Transform( +inline void ceSHA1::SHA1Transform( uint32_t state[5], const unsigned char buffer[64] ) @@ -226,7 +226,7 @@ void ceSHA1::SHA1Transform( /* SHA1Init - Initialize new context */ -void ceSHA1::SHA1Init( +inline void ceSHA1::SHA1Init( SHA1_CTX* context ) { @@ -242,7 +242,7 @@ void ceSHA1::SHA1Init( /* Run your data through this. */ -void ceSHA1::SHA1Update( +inline void ceSHA1::SHA1Update( SHA1_CTX* context, const unsigned char* data, uint32_t len @@ -275,7 +275,7 @@ void ceSHA1::SHA1Update( /* Add padding and return the message digest. */ -void ceSHA1::SHA1Final( +inline void ceSHA1::SHA1Final( unsigned char digest[20], SHA1_CTX* context ) @@ -327,7 +327,7 @@ void ceSHA1::SHA1Final( memset(&finalcount, '\0', sizeof(finalcount)); } -void ceSHA1::SHA1( +inline void ceSHA1::SHA1( char* hash_out, const char* str, uint32_t len) @@ -341,17 +341,17 @@ void ceSHA1::SHA1( SHA1Final((unsigned char*)hash_out, &ctx); } -void ceSHA1::Init() +inline void ceSHA1::Init() { SHA1Init(&sha); } -void ceSHA1::Update(std::string str) +inline void ceSHA1::Update(std::string str) { SHA1Update(&sha, (uint8_t*)str.c_str(), str.length()); } -std::string ceSHA1::Final() +inline std::string ceSHA1::Final() { uint8_t results[20]; SHA1Final(results, &sha); diff --git a/include/ce/cetcpcli.h b/include/ce/cetcpcli.h index 1f964aa..0c5cb6f 100644 --- a/include/ce/cetcpcli.h +++ b/include/ce/cetcpcli.h @@ -45,7 +45,7 @@ #endif // CE_MACROS_H #if CE_WX==1 -#include +#include #include #include #include "wx/wx.h" @@ -89,7 +89,180 @@ class ceTcpClient : public wxEvtHandler { wxSocketClient* _socketClient{}; void PrintLog(std::string str); }; +///////////////////////////////////////////////////////////////////////////// +// Implementation + +inline void ceTcpClient::PrintLog(std::string str) +{ + // printf("%s \n",str.c_str()); +} + +inline ceTcpClient::ceTcpClient(wxEvtHandler* app, int socketid) : + _app(app), _socket_id(socketid) +{ + // Create the socket + this->_socketClient = new wxSocketClient(); + // Setup the event handler and subscribe to most events + _socketClient->SetEventHandler(*this, _socket_id); + _socketClient->SetNotify(wxSOCKET_CONNECTION_FLAG | + wxSOCKET_INPUT_FLAG | + wxSOCKET_LOST_FLAG); + _socketClient->Notify(true); + Connect(_socket_id, wxEVT_SOCKET, wxSocketEventHandler(ceTcpClient::OnSocketEvent)); +} + +inline ceTcpClient::~ceTcpClient() +{ + this->Close(); + Disconnect(_socket_id, wxEVT_SOCKET); + _socketClient->Destroy(); +} + +inline void ceTcpClient::SetRemote(std::string remotehost, int port) +{ + _remotehost = remotehost; + _port = port; +} + +inline void ceTcpClient::SetRemotehost(std::string remotehost) +{ + _remotehost = remotehost; +} + +inline void ceTcpClient::SetPort(int port) +{ + _port = port; +} + +inline std::string ceTcpClient::GetRemotehost() +{ + return _remotehost; +} + +inline int ceTcpClient::GetPort() +{ + return _port; +} + +inline void ceTcpClient::Open() +{ + // Create the address + IPaddress addr; + //addr.AnyAddress(); + addr.Hostname(_remotehost); + addr.Service(_port); + PrintLog("Trying to connect to " + addr.IPAddress().ToStdString() + + ":" + std::to_string(addr.Service())); + + // we connect asynchronously and will get a wxSOCKET_CONNECTION event when + // the connection is really established + // + // if you want to make sure that connection is established right here you + // could call WaitOnConnect(timeout) instead + _socketClient->Connect(addr, false); +} + +inline void ceTcpClient::Close() +{ + _socketClient->Close(); +} + +inline void ceTcpClient::OnSocketEvent(wxSocketEvent& event) +{ + PrintLog("OnSocketEvent"); + wxSocketBase* sockBase = event.GetSocket(); + std::vector vc; + char buf[CE_TCPCLIENT_RX_BUF_SIZE]; + + // First, print a message + switch (event.GetSocketEvent()) + { + case wxSOCKET_INPUT: + this->PrintLog("wxSOCKET_INPUT"); + break; + case wxSOCKET_LOST: + this->PrintLog("wxSOCKET_LOST"); + break; + case wxSOCKET_CONNECTION: + this->PrintLog("wxSOCKET_CONNECTION"); + break; + default: + this->PrintLog("Unexpected event"); + break; + } + + // Now we process the event + switch (event.GetSocketEvent()) + { + case wxSOCKET_INPUT: + { + // We disable input events, so that the test doesn't trigger + // wxSocketEvent again. + sockBase->SetNotify(wxSOCKET_LOST_FLAG); + + // Receive data from socket and send it back. We will first + // get a byte with the buffer size, so we can specify the + // exact size and use the wxSOCKET_WAITALL flag. Also, we + // disabled input events so we won't have unwanted reentrance. + // This way we can avoid the infamous wxSOCKET_BLOCK flag. + // sockBase->SetFlags(wxSOCKET_WAITALL); + + // Read the message + size_t lenRd = sockBase->Read(buf, sizeof(buf)).LastCount(); + if (!lenRd) { + PrintLog("Failed to read message"); + return; + } + else { + PrintLog("Read " + std::to_string(lenRd) + " bytes"); + // string str(buf,lenRd); + // PrintLog("Rx: " + str) + } + // Enable input events again. + sockBase->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG); + vc.assign(buf, buf + lenRd); + wxThreadEvent eventskt(wxEVT_THREAD, _socket_id); + eventskt.SetPayload>(vc); + eventskt.SetString(_remotehost); + eventskt.SetInt(_port); + wxQueueEvent(_app, eventskt.Clone()); + break; + } + default: + break; + } +} + +inline int ceTcpClient::Tx(std::vector bv) +{ + size_t txn = 0; + if (this->_socketClient->IsOk() && this->_socketClient->IsConnected()) { + // Write to pointed client + txn = bv.size(); + size_t n = _socketClient->Write(bv.data(), txn).LastCount(); + if (n != txn) { + perror("ceTcpClient write error"); + txn = n; + } + else { + PrintLog("Tx: " + ceMisc::cvec2hex(bv)); + } + } + return int(txn); +} + +inline bool ceTcpClient::IsConnected() +{ + return this->_socketClient->IsConnected(); +} + +inline bool ceTcpClient::IsOK() +{ + return this->_socketClient->IsOk(); +} + +///////////////////////////////////////////////////////////////////////////// } // namespace ce #endif // CE_WX #endif // CETCPCLIENT_H diff --git a/include/ce/ceudp.h b/include/ce/ceudp.h new file mode 100644 index 0000000..58431ec --- /dev/null +++ b/include/ce/ceudp.h @@ -0,0 +1,269 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: ceudp.h +// Description: UDP communication module +// Author: Yan Naing Aye +// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEUDP_H +#define CEUDP_H + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_WX 1 // include WX +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + +#if CE_WX==1 +#include +#include +#include +#include "wx/wx.h" +#include "wx/socket.h" +// this example is currently written to use only IP or only IPv4 sockets, it +// should be extended to allow using either in the future +//#if wxUSE_IPV6 +//typedef wxIPV6address IPaddress; +//#else +typedef wxIPV4address IPaddress; +//#endif + +#define CE_UDP_RX_BUF_SIZE 32768 + +namespace ce { +class ceUDP : public wxEvtHandler { +public: + ceUDP(wxEvtHandler* app, int socketid, int rx_port); // rx_port = 0 for not listening + ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port); + ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost); + int Tx(std::vector bv); // return 0 = success, 1 = error + int Tx(std::vector bv, std::string remoteHost, int txPort); // return 0 = success, 1 = error + int Open(); // return 0 = success, 1 = error + void Close(); + int GetRxPort(); + void SetRxPort(int rx_port); + int GetTxPort(); + void SetTxPort(int tx_port); + std::string GetRemotehost(); + void SetRemotehost(std::string remoteHost); +private: + void Rx(int socketid, std::vector bv, std::string ip, int port); + void OnSocketEvent(wxSocketEvent& event); + wxEvtHandler* _app; + int SOCKET_ID; + int udp_port_rx; + int udp_port_tx; + std::string udp_remote_host; + wxDatagramSocket *sock; + int _ok; +}; + +///////////////////////////////////////////////////////////////////////////// +inline ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port) : + _app(app), SOCKET_ID(socketid), udp_port_rx(rx_port), udp_port_tx(rx_port), udp_remote_host("localhost") +{ + _ok = false; +} + +inline ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port) : + _app(app), SOCKET_ID(socketid), udp_port_rx(rx_port), udp_port_tx(tx_port), udp_remote_host("localhost") +{ + _ok = false; +} + +inline ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost) : + _app(app), SOCKET_ID(socketid), udp_port_rx(rx_port), udp_port_tx(tx_port), udp_remote_host(remotehost) +{ + _ok = false; +} + +inline int ceUDP::GetRxPort() +{ + return this->udp_port_rx; +} + +inline void ceUDP::SetRxPort(int rx_port) +{ + this->udp_port_rx = rx_port; +} + +inline int ceUDP::GetTxPort() +{ + return this->udp_port_tx; +} + +inline void ceUDP::SetTxPort(int tx_port) +{ + this->udp_port_tx = tx_port; +} + +inline std::string ceUDP::GetRemotehost() +{ + return this->udp_remote_host; +} + +inline void ceUDP::SetRemotehost(std::string remoteHost) +{ + this->udp_remote_host = remoteHost; +} + +inline int ceUDP::Open() +{ + // Create the address - defaults to localhost:0 initially + IPaddress addr; + addr.AnyAddress(); + if (udp_port_rx != 0) addr.Service(udp_port_rx); + std::string tmp; + // printf("UDP: creating socket at %s : %d \n",addr.IPAddress().ToStdString().c_str(),addr.Service()); + + // Create the socket + sock = new wxDatagramSocket(addr); + + // We use IsOk() here to see if the server is really listening + if (!sock->IsOk()) { + perror("ceUDP could not listen at the specified port"); + return 1; + } + + IPaddress addrReal; + if (!sock->GetLocal(addrReal)) { + perror("ceUDP couldn't get the address we bound to."); + return 1; + } + else { + // std::string tmp = "UDP server listening at "+addrReal.IPAddress().ToStdString()+" : "+std::to_string(addrReal.Service()); + // printf("%s\n",tmp.c_str()); + } + // Setup the event handler + sock->SetEventHandler(*this, SOCKET_ID); + sock->SetNotify(wxSOCKET_INPUT_FLAG); + sock->Notify(true); + Connect(SOCKET_ID, wxEVT_SOCKET, wxSocketEventHandler(ceUDP::OnSocketEvent)); + _ok = true; + return 0; +} + +inline void ceUDP::Close() +{ + _ok = false; + sock->Close(); +} + +inline int ceUDP::Tx(std::vector bv, std::string remoteHost, int txPort) +{ + if (!_ok) return 1; + size_t txn = bv.size(); + // IPaddress addrLocal; + // addrLocal.AnyAddress(); + //addrLocal.Hostname("192.168.1.10"); + // wxDatagramSocket sock2tx(addrLocal); + // if ( !sock2tx.IsOk() ) + // { + // perror("ceUDP Tx failed to create UDP socket"); + // return; + // } + // write("UDP TX: created "+ddrLocal.IPAddress().ToStdString()+" : "+to_string(addrLocal.Service())); + + IPaddress raddr; + //raddr.Hostname("localhost"); + raddr.Hostname(remoteHost); + raddr.Service(txPort); + + if (sock->SendTo(raddr, bv.data(), txn).LastCount() != txn) + { + perror("ceUDP Tx error"); + return 1; + } + else { + // std::string tmp ="UDP TX: "+util::cvec2hex(bv); + // printf("%s\n",tmp.c_str()); + // printf("ceUDPTx n= %ld \n",txn); + // fflush(stdout); + } + return 0; +} + +inline int ceUDP::Tx(std::vector bv) +{ + return this->Tx(bv, udp_remote_host, udp_port_tx); +} + +inline void ceUDP::OnSocketEvent(wxSocketEvent& event) +{ + IPaddress addr; + addr.Service(udp_port_rx); + char buf[CE_UDP_RX_BUF_SIZE]; + size_t n; + int socketid = event.GetId(); + std::string tmp; // = ("UDP RX: id = " + to_string(socketid)); + std::vector vc; + switch (event.GetSocketEvent()) + { + case wxSOCKET_INPUT: + sock->Notify(false); + n = sock->RecvFrom(addr, buf, sizeof(buf)).LastCount(); + sock->Notify(true); + if (!n) { + perror("ceUDP Rx failed"); + return; + } + vc.assign(buf, buf + n); + // printf("Received \'%s\' from %s:%u. \n", + // util::cvec2hex(util::cptr2cvec(buf, n)).c_str(), + // addr.IPAddress().ToStdString().c_str(), + // addr.Service()); + // printf("ceUDPRx n= %ld \n",n); + // fflush(stdout); + this->Rx(socketid, vc, addr.IPAddress().ToStdString(), addr.Service()); + break; + default: + perror("ceUDP Rx unexpected event"); + break; + } +} + +inline void ceUDP::Rx(int socketid, std::vector bv, std::string ip, int port) +{ + // ("UDP rx" + to_string(socketid) + ": " + util::cvec2hex(bv)); + wxString ws(ip); + wxThreadEvent event(wxEVT_THREAD, socketid); + event.SetPayload>(bv); + event.SetString(ws); + event.SetInt(port); + wxQueueEvent(_app, event.Clone()); +} +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce +#endif // CE_WX +#endif // CEUDP_H diff --git a/include/ce/ceudpx.h b/include/ce/ceudpx.h deleted file mode 100644 index 27bb951..0000000 --- a/include/ce/ceudpx.h +++ /dev/null @@ -1,93 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceUDP.h -// Description: UDP communication module -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEUDP_H -#define CEUDP_H - -#ifndef CE_MACROS_H -#define CE_MACROS_H - -#define CE_WX 1 // include WX -#define CE_DBG_PRINT 0 // print dbg mes - -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif -#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif -#else - #ifndef CE_NOS - #define CE_NOS - #endif -#endif - -#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) - #ifndef CE_x86_64 - #define CE_x86_64 - #endif -#elif defined(__arm__) || defined(_M_ARM) - #ifndef CE_ARM - #define CE_ARM - #endif -#else - #ifndef CE_NARCH - #define CE_NARCH - #endif -#endif - -#endif // CE_MACROS_H - -#if CE_WX==1 -#include -#include -#include -#include "wx/wx.h" -#include "wx/socket.h" -// this example is currently written to use only IP or only IPv4 sockets, it -// should be extended to allow using either in the future -//#if wxUSE_IPV6 -//typedef wxIPV6address IPaddress; -//#else -typedef wxIPV4address IPaddress; -//#endif - -#define CE_UDP_RX_BUF_SIZE 32768 - -namespace ce { -class ceUDP : public wxEvtHandler { -public: - ceUDP(wxEvtHandler* app, int socketid, int rx_port); // rx_port = 0 for not listening - ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port); - ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost); - int Tx(std::vector bv); // return 0 = success, 1 = error - int Tx(std::vector bv, std::string remoteHost, int txPort); // return 0 = success, 1 = error - int Open(); // return 0 = success, 1 = error - void Close(); - int GetRxPort(); - void SetRxPort(int rx_port); - int GetTxPort(); - void SetTxPort(int tx_port); - std::string GetRemotehost(); - void SetRemotehost(std::string remoteHost); -private: - void Rx(int socketid, std::vector bv, std::string ip, int port); - void OnSocketEvent(wxSocketEvent& event); - wxEvtHandler* _app; - int SOCKET_ID; - int udp_port_rx; - int udp_port_tx; - std::string udp_remote_host; - wxDatagramSocket *sock; - int _ok; -}; - -} // namespace ce -#endif // CE_WX -#endif // CEUDP_H diff --git a/include/ce/cewxcvMisc.h b/include/ce/cewxcvmiscx.h similarity index 55% rename from include/ce/cewxcvMisc.h rename to include/ce/cewxcvmiscx.h index 4ef6a70..457c7e5 100644 --- a/include/ce/cewxcvMisc.h +++ b/include/ce/cewxcvmiscx.h @@ -1,70 +1,105 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: cewxcvMisc.h -// Description: utility module using wxWidgets and OpenCV -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// - -#ifndef CEWXCVMISC_H -#define CEWXCVMISC_H - -#ifndef CE_MACROS_H -#define CE_MACROS_H - -#define CE_WX 1 // include WX -#define CE_CV 1 // include CV -#define CE_DBG_PRINT 0 // print dbg mes - -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif -#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif -#else - #ifndef CE_NOS - #define CE_NOS - #endif -#endif - -#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) - #ifndef CE_x86_64 - #define CE_x86_64 - #endif -#elif defined(__arm__) || defined(_M_ARM) - #ifndef CE_ARM - #define CE_ARM - #endif -#else - #ifndef CE_NARCH - #define CE_NARCH - #endif -#endif - -#endif // CE_MACROS_H - -#include -#if CE_WX==1 -#include "wx/wx.h" -#endif // CE_WX -#if CE_CV==1 -#include -using namespace cv; -#endif // CE_WX -namespace ce { -class cewxcvMisc { -private: -public: -#if CE_WX==1 - // wxWidgets - static void printTime(); -#if CE_CV==1 - static wxImage wx_from_mat(cv::Mat &img); - static cv::Mat mat_from_wx(wxImage &wx); -#endif // CE_CV -#endif // CE_WX -}; - -} // namespace ce -#endif // CEWXCVMISC_H +///////////////////////////////////////////////////////////////////////////// +// Name: cewxcvmisc.h +// Description: utility module using wxWidgets and OpenCV +// Author: Yan Naing Aye +///////////////////////////////////////////////////////////////////////////// + +#ifndef CEWXCVMISC_H +#define CEWXCVMISC_H + +#ifndef CE_MACROS_H +#define CE_MACROS_H + +#define CE_WX 1 // include WX +#define CE_CV 1 // include CV +#define CE_DBG_PRINT 0 // print dbg mes + +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) + #ifndef CE_WINDOWS + #define CE_WINDOWS + #endif +#elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) + #ifndef CE_LINUX + #define CE_LINUX + #endif +#else + #ifndef CE_NOS + #define CE_NOS + #endif +#endif + +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__amd64) + #ifndef CE_x86_64 + #define CE_x86_64 + #endif +#elif defined(__arm__) || defined(_M_ARM) + #ifndef CE_ARM + #define CE_ARM + #endif +#else + #ifndef CE_NARCH + #define CE_NARCH + #endif +#endif + +#endif // CE_MACROS_H + +#include +#if CE_WX==1 +#include "wx/wx.h" +#endif // CE_WX +#if CE_CV==1 +#include +#endif // CE_WX +namespace ce { +class cewxcvMisc { +private: +public: +#if CE_WX==1 + // wxWidgets + static void printTime(); +#if CE_CV==1 + static wxImage wx_from_mat(cv::Mat &img); + static cv::Mat mat_from_wx(wxImage &wx); +#endif // CE_CV +#endif // CE_WX +}; + +///////////////////////////////////////////////////////////////////////////// +// Implementation +#if CE_WX==1 +inline void cewxcvMisc::printTime() +{ + wxDateTime* wdt; + wdt = new wxDateTime(); + wdt->SetToCurrent(); + wxString wstr = wdt->Format(wxT("%Y-%m-%d %H:%M:%S"), wxDateTime::Local); + // wxPuts(wstr); + std::string str = wstr.ToStdString(); + printf("%s\n", str.c_str()); +} +#if CE_CV==1 +inline wxImage cewxcvMisc::wx_from_mat(cv::Mat& img) { + cv::Mat im2; + if (img.channels() == 1) { cvtColor(img, im2, cv::COLOR_GRAY2RGB); } + else if (img.channels() == 4) { cvtColor(img, im2, cv::COLOR_BGRA2RGB); } + else { cvtColor(img, im2, cv::COLOR_BGR2RGB); } + long imsize = im2.rows * im2.cols * im2.channels(); + wxImage wx(im2.cols, im2.rows, (unsigned char*)malloc(imsize), false); + unsigned char* s = im2.data; + unsigned char* d = wx.GetData(); + for (long i = 0; i < imsize; i++) { d[i] = s[i]; } + return wx; +} + +inline cv::Mat cewxcvMisc::mat_from_wx(wxImage& wx) { + cv::Mat im2(cv::Size(wx.GetWidth(), wx.GetHeight()), CV_8UC3, wx.GetData()); + cvtColor(im2, im2, cv::COLOR_RGB2BGR); + return im2; +} +#endif // CE_CV +#endif // CE_WX +///////////////////////////////////////////////////////////////////////////// + +} // namespace ce +#endif // CEWXCVMISC_H diff --git a/src/ceRSA_OS.cpp b/src/ceRSA_OS.cpp deleted file mode 100644 index d282b34..0000000 --- a/src/ceRSA_OS.cpp +++ /dev/null @@ -1,184 +0,0 @@ -// Description: Functions to calculate SHA1 -// Class implementation of the following repository: https://github.com/clibs/sha1 - -#include "ce/ceMacros.h" -#include "ce/ceRSA_OS.h" - -#ifdef CE_WINDOWS -#ifdef _MSC_VER -#pragma warning(disable : 4996) -#endif -#endif - -using namespace std; -namespace ce { -// ---------------------------------------------------------------------------- - -// Load public key from file -RSA* ceRSA_OS::loadPublicKey(std::string publicKeyFile) { - RSA* keypair = RSA_new(); - FILE* publicKey = fopen(publicKeyFile.c_str(), "r"); - PEM_read_RSAPublicKey(publicKey, &keypair, NULL, NULL); - fclose(publicKey); - return keypair; -} - -// Load private key from file -RSA* ceRSA_OS::loadPrivateKey(std::string privateKeyFile) { - RSA* keypair = RSA_new(); - FILE* bigN = fopen(privateKeyFile.c_str(), "r"); - PEM_read_RSAPrivateKey(bigN, &keypair, NULL, NULL); - fclose(bigN); - return keypair; -} - -// Encrypt data using public key -std::string ceRSA_OS::encrypt(const std::string& message, RSA* rsa_key) { - int rsa_size = RSA_size(rsa_key); - std::vector ciphertext(rsa_size); - - int len = RSA_public_encrypt(message.size(), reinterpret_cast(message.data()), - ciphertext.data(), rsa_key, RSA_NO_PADDING); - //ciphertext.data(), rsa_key, RSA_PKCS1_PADDING); - - if (len < 0) { - // std::cerr << "Encryption failed" << std::endl; - return ""; - } - - return std::string(reinterpret_cast(ciphertext.data()), len); -} - -// Decrypt data using private key -std::string ceRSA_OS::decrypt(const std::string& ciphertext, RSA* rsa_key) { - int rsa_size = RSA_size(rsa_key); - std::vector message(rsa_size); - - int len = RSA_private_decrypt(ciphertext.size(), reinterpret_cast(ciphertext.data()), - message.data(), rsa_key, RSA_NO_PADDING); - - if (len < 0) { - // std::cerr << "Decryption failed" << std::endl; - return ""; - } - - return std::string(reinterpret_cast(message.data()), len); -} - -string ceRSA_OS::bn2str(BIGNUM* bigN) -{ - // Convert BIGNUM to binary representation - size_t bnSize = BN_num_bytes(bigN); - unsigned char* bnStr = new unsigned char[bnSize]; - BN_bn2bin(bigN, bnStr); - string bnString((char*)bnStr, bnSize); - return bnString; -} - -// ---------------------------------------------------------------------------- - -// Generate a public-private key pair and save to files -RSA* ceRSA_OS::generateKeyPair(std::string publicKeyFile, std::string privateKeyFile, uint32_t keyLength, uint32_t exp) { - RSA* keypair = RSA_new(); - BIGNUM* e = BN_new(); - BN_set_word(e, exp); - - RSA_generate_key_ex(keypair, keyLength, e, NULL); - FILE* publicKey = fopen(publicKeyFile.c_str(), "w"); - PEM_write_RSAPublicKey(publicKey, keypair); - fclose(publicKey); - - FILE* bigN = fopen(privateKeyFile.c_str(), "w"); - PEM_write_RSAPrivateKey(bigN, keypair, NULL, NULL, 0, NULL, NULL); - fclose(bigN); - - BN_free(e); - return keypair; -} - -// Generate a public-private key pair and returns RSA -RSA* ceRSA_OS::generateKeyPair(uint32_t keyLength, uint32_t exp) { - RSA* keypair = RSA_new(); - BIGNUM* e = BN_new(); - BN_set_word(e, exp); - RSA_generate_key_ex(keypair, keyLength, e, NULL); - BN_free(e); - return keypair; -} - -// Encrypt data using public key -std::string ceRSA_OS::encrypt(const std::string& message, std::string publicKeyFile) -{ - // Load public key - RSA* public_key = loadPublicKey(publicKeyFile); - std::string encrypted = encrypt(message, public_key); - return encrypted; -} - -// Decrypt data using private key -std::string ceRSA_OS::decrypt(const std::string& ciphertext, std::string privateKeyFile) -{ - // Load private key - RSA* private_key = loadPrivateKey(privateKeyFile); - std::string decrypted = decrypt(ciphertext, private_key); - return decrypted; -} - -// Encrypt data using modulus n and exponent e -std::string ceRSA_OS::encrypt(const std::string& message, std::string n, std::string e) -{ - BIGNUM* bn_e3 = BN_new(); - BIGNUM* bn_n3 = BN_new(); - - if (BN_bin2bn((const unsigned char*)e.c_str(), e.length(), bn_e3) == NULL) { - printf("Failed to convert modulus"); - } - if (BN_bin2bn((const unsigned char*)n.c_str(), n.length(), bn_n3) == NULL) { - printf("Failed to convert exponent"); - } - - RSA* public_key3 = RSA_new(); - RSA_set0_key(public_key3, bn_n3, bn_e3, NULL); - - std::string encrypted = encrypt(message, public_key3); - return encrypted; -} - -// Decrypt data using secret number d, modulus n and exponent e -std::string ceRSA_OS::decrypt(const std::string& ciphertext, std::string d, std::string n, std::string e) -{ - BIGNUM* bn_d3 = BN_new(); - BIGNUM* bn_e3 = BN_new(); - BIGNUM* bn_n3 = BN_new(); - if (BN_bin2bn((const unsigned char*)d.c_str(), d.length(), bn_d3) == NULL) { - printf("Failed to convert d"); - } - if (BN_bin2bn((const unsigned char*)e.c_str(), e.length(), bn_e3) == NULL) { - printf("Failed to convert modulus"); - } - if (BN_bin2bn((const unsigned char*)n.c_str(), n.length(), bn_n3) == NULL) { - printf("Failed to convert exponent"); - } - - RSA* private_key3 = RSA_new(); - RSA_set0_key(private_key3, bn_n3, bn_e3, bn_d3); - - std::string decrypted = decrypt(ciphertext, private_key3); - return decrypted; -} - -// Get big numbers as strings for secret number d, modulus n and exponent e as reference from RSA key -void ceRSA_OS::getBN(RSA* key, std::string& d, std::string& n, std::string& e) -{ - // Obtain the key components as BIGNUM - BIGNUM* bn_d = BN_dup(RSA_get0_d(key)); - BIGNUM* bn_e = BN_dup(RSA_get0_e(key)); - BIGNUM* bn_n = BN_dup(RSA_get0_n(key)); - - d = bn2str(bn_d); - e = bn2str(bn_e); - n = bn2str(bn_n); -} - -// ---------------------------------------------------------------------------- -} // namespace ce \ No newline at end of file diff --git a/src/ceTcpClient.cpp b/src/ceTcpClient.cpp deleted file mode 100644 index 8492e3d..0000000 --- a/src/ceTcpClient.cpp +++ /dev/null @@ -1,185 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceTcpClient.cpp -// Description: TCP client module -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -///////////////////////////////////////////////////////////////////////////// -#include -#include "ce/ceTcpClient.h" -using namespace std; - -#if CE_WX==1 -namespace ce { - -void ceTcpClient::PrintLog(string str) -{ - // printf("%s \n",str.c_str()); -} - -ceTcpClient::ceTcpClient(wxEvtHandler* app, int socketid): -_app(app),_socket_id(socketid) -{ - // Create the socket - this->_socketClient = new wxSocketClient(); - // Setup the event handler and subscribe to most events - _socketClient->SetEventHandler(*this, _socket_id); - _socketClient->SetNotify(wxSOCKET_CONNECTION_FLAG | - wxSOCKET_INPUT_FLAG | - wxSOCKET_LOST_FLAG); - _socketClient->Notify(true); - Connect(_socket_id, wxEVT_SOCKET, wxSocketEventHandler(ceTcpClient::OnSocketEvent)); -} - -ceTcpClient::~ceTcpClient() -{ - this->Close(); - Disconnect(_socket_id, wxEVT_SOCKET); - _socketClient->Destroy(); -} - -void ceTcpClient::SetRemote(string remotehost, int port) -{ - _remotehost = remotehost; - _port = port; -} - -void ceTcpClient::SetRemotehost(std::string remotehost) -{ - _remotehost = remotehost; -} - -void ceTcpClient::SetPort(int port) -{ - _port = port; -} - -std::string ceTcpClient::GetRemotehost() -{ - return _remotehost; -} - -int ceTcpClient::GetPort() -{ - return _port; -} - -void ceTcpClient::Open() -{ - // Create the address - IPaddress addr; - //addr.AnyAddress(); - addr.Hostname(_remotehost); - addr.Service(_port); - PrintLog("Trying to connect to " + addr.IPAddress().ToStdString() - + ":" + to_string(addr.Service())); - - // we connect asynchronously and will get a wxSOCKET_CONNECTION event when - // the connection is really established - // - // if you want to make sure that connection is established right here you - // could call WaitOnConnect(timeout) instead - - _socketClient->Connect(addr, false); -} - -void ceTcpClient::Close() -{ - _socketClient->Close(); -} - -void ceTcpClient::OnSocketEvent(wxSocketEvent& event) -{ - PrintLog("OnSocketEvent"); - wxSocketBase *sockBase = event.GetSocket(); - std::vector vc; - char buf[CE_TCPCLIENT_RX_BUF_SIZE]; - - // First, print a message - switch (event.GetSocketEvent()) - { - case wxSOCKET_INPUT: - this->PrintLog("wxSOCKET_INPUT"); - break; - case wxSOCKET_LOST: - this->PrintLog("wxSOCKET_LOST"); - break; - case wxSOCKET_CONNECTION: - this->PrintLog("wxSOCKET_CONNECTION"); - break; - default: - this->PrintLog("Unexpected event"); - break; - } - - // Now we process the event - switch (event.GetSocketEvent()) - { - case wxSOCKET_INPUT: - { - // We disable input events, so that the test doesn't trigger - // wxSocketEvent again. - sockBase->SetNotify(wxSOCKET_LOST_FLAG); - - // Receive data from socket and send it back. We will first - // get a byte with the buffer size, so we can specify the - // exact size and use the wxSOCKET_WAITALL flag. Also, we - // disabled input events so we won't have unwanted reentrance. - // This way we can avoid the infamous wxSOCKET_BLOCK flag. - // sockBase->SetFlags(wxSOCKET_WAITALL); - - // Read the message - size_t lenRd = sockBase->Read(buf, sizeof(buf)).LastCount(); - if (!lenRd) { - PrintLog("Failed to read message"); - return; - } - else { - PrintLog("Read " + to_string(lenRd) + " bytes"); - // string str(buf,lenRd); - // PrintLog("Rx: " + str) - } - // Enable input events again. - sockBase->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG); - vc.assign(buf, buf + lenRd); - wxThreadEvent eventskt(wxEVT_THREAD, _socket_id); - eventskt.SetPayload>(vc); - eventskt.SetString(_remotehost); - eventskt.SetInt(_port); - wxQueueEvent(_app, eventskt.Clone()); - break; - } - default: - break; - } -} - -int ceTcpClient::Tx(std::vector bv) -{ - size_t txn = 0; - if (this->_socketClient->IsOk() && this->_socketClient->IsConnected()) { - // Write to pointed client - txn = bv.size(); - size_t n = _socketClient->Write(bv.data(), txn).LastCount(); - if ( n!= txn) { - perror("ceTcpClient write error"); - txn = n; - } - else { - PrintLog("Tx: " + ceMisc::cvec2hex(bv)); - } - } - return int(txn); -} - -bool ceTcpClient::IsConnected() -{ - return this->_socketClient->IsConnected(); -} - -bool ceTcpClient::IsOK() -{ - return this->_socketClient->IsOk(); -} - -} // namespace ce -#endif // CE_WX \ No newline at end of file diff --git a/src/ceUDP.cpp b/src/ceUDP.cpp deleted file mode 100644 index 491624f..0000000 --- a/src/ceUDP.cpp +++ /dev/null @@ -1,187 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: ceUDP.cpp -// Description: UDP communication module -// Author: Yan Naing Aye -// Ref: http://cool-emerald.blogspot.com/2018/01/udptcp-socket-programming-with-wxwidgets.html -///////////////////////////////////////////////////////////////////////////// - -#include "ce/ceUDP.h" -#if CE_WX==1 -namespace ce { - -ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port) : -_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(rx_port),udp_remote_host("localhost") -{ - _ok = false; -} - -ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port) : -_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(tx_port),udp_remote_host("localhost") -{ - _ok = false; -} - -ceUDP::ceUDP(wxEvtHandler* app, int socketid, int rx_port, int tx_port, std::string remotehost) : -_app(app),SOCKET_ID(socketid),udp_port_rx(rx_port),udp_port_tx(tx_port),udp_remote_host(remotehost) -{ - _ok = false; -} - -int ceUDP::GetRxPort() -{ - return this->udp_port_rx; -} - -void ceUDP::SetRxPort(int rx_port) -{ - this->udp_port_rx = rx_port; -} - -int ceUDP::GetTxPort() -{ - return this->udp_port_tx; -} - -void ceUDP::SetTxPort(int tx_port) -{ - this->udp_port_tx = tx_port; -} - -std::string ceUDP::GetRemotehost() -{ - return this->udp_remote_host; -} - -void ceUDP::SetRemotehost(std::string remoteHost) -{ - this->udp_remote_host = remoteHost; -} - -int ceUDP::Open() -{ - // Create the address - defaults to localhost:0 initially - IPaddress addr; - addr.AnyAddress(); - if(udp_port_rx !=0) addr.Service(udp_port_rx); - std::string tmp; - // printf("UDP: creating socket at %s : %d \n",addr.IPAddress().ToStdString().c_str(),addr.Service()); - - // Create the socket - sock = new wxDatagramSocket(addr); - - // We use IsOk() here to see if the server is really listening - if (!sock->IsOk()){ - perror("ceUDP could not listen at the specified port"); - return 1; - } - - IPaddress addrReal; - if (!sock->GetLocal(addrReal)){ - perror("ceUDP couldn't get the address we bound to."); - return 1; - } - else{ - // std::string tmp = "UDP server listening at "+addrReal.IPAddress().ToStdString()+" : "+std::to_string(addrReal.Service()); - // printf("%s\n",tmp.c_str()); - } - // Setup the event handler - sock->SetEventHandler(*this,SOCKET_ID); - sock->SetNotify(wxSOCKET_INPUT_FLAG); - sock->Notify(true); - Connect(SOCKET_ID,wxEVT_SOCKET,wxSocketEventHandler(ceUDP::OnSocketEvent)); - _ok = true; - return 0; -} - -void ceUDP::Close() -{ - _ok = false; - sock->Close(); -} - -int ceUDP::Tx(std::vector bv, std::string remoteHost, int txPort) -{ - if(!_ok) return 1; - size_t txn = bv.size(); - // IPaddress addrLocal; - // addrLocal.AnyAddress(); - //addrLocal.Hostname("192.168.1.10"); - // wxDatagramSocket sock2tx(addrLocal); - // if ( !sock2tx.IsOk() ) - // { - // perror("ceUDP Tx failed to create UDP socket"); - // return; - // } - // write("UDP TX: created "+ddrLocal.IPAddress().ToStdString()+" : "+to_string(addrLocal.Service())); - - IPaddress raddr; - //raddr.Hostname("localhost"); - raddr.Hostname(remoteHost); - raddr.Service(txPort); - - if (sock->SendTo(raddr, bv.data(), txn).LastCount() != txn) - { - perror("ceUDP Tx error"); - return 1; - } - else { - // std::string tmp ="UDP TX: "+util::cvec2hex(bv); - // printf("%s\n",tmp.c_str()); - // printf("ceUDPTx n= %ld \n",txn); - // fflush(stdout); - } - return 0; -} - -int ceUDP::Tx(std::vector bv) -{ - return this->Tx(bv,udp_remote_host,udp_port_tx); -} - -void ceUDP::OnSocketEvent(wxSocketEvent& event) -{ - IPaddress addr; - addr.Service(udp_port_rx); - char buf[CE_UDP_RX_BUF_SIZE]; - size_t n; - int socketid = event.GetId(); - std::string tmp; // = ("UDP RX: id = " + to_string(socketid)); - std::vector vc; - switch(event.GetSocketEvent()) - { - case wxSOCKET_INPUT: - sock->Notify(false); - n = sock->RecvFrom(addr, buf, sizeof(buf)).LastCount(); - sock->Notify(true); - if (!n){ - perror("ceUDP Rx failed"); - return; - } - vc.assign(buf,buf+n); -// printf("Received \'%s\' from %s:%u. \n", -// util::cvec2hex(util::cptr2cvec(buf, n)).c_str(), -// addr.IPAddress().ToStdString().c_str(), -// addr.Service()); - // printf("ceUDPRx n= %ld \n",n); - // fflush(stdout); - this->Rx(socketid,vc,addr.IPAddress().ToStdString(),addr.Service()); - break; - default: - perror("ceUDP Rx unexpected event"); - break; - } -} - -void ceUDP::Rx(int socketid, std::vector bv, std::string ip, int port) -{ - // ("UDP rx" + to_string(socketid) + ": " + util::cvec2hex(bv)); - wxString ws(ip); - wxThreadEvent event(wxEVT_THREAD, socketid); - event.SetPayload>(bv); - event.SetString(ws); - event.SetInt(port); - wxQueueEvent(_app, event.Clone()); -} - -} // namespace ce -#endif // CE_WX diff --git a/src/cewxcvMisc.cpp b/src/cewxcvMisc.cpp deleted file mode 100644 index 186e2d5..0000000 --- a/src/cewxcvMisc.cpp +++ /dev/null @@ -1,45 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// Name: cewxcvMisc.cpp -// Description: utility module using wxWidgets and OpenCV -// Author: Yan Naing Aye -///////////////////////////////////////////////////////////////////////////// -#include "ce/cewxcvMisc.h" -using namespace std; -#if CE_CV==1 -using namespace cv; -#endif // CE_WX -namespace ce { - -#if CE_WX==1 - void cewxcvMisc::printTime() - { - wxDateTime* wdt; - wdt = new wxDateTime(); - wdt->SetToCurrent(); - wxString wstr = wdt->Format(wxT("%Y-%m-%d %H:%M:%S"), wxDateTime::Local); - // wxPuts(wstr); - std::string str = wstr.ToStdString(); - printf("%s\n",str.c_str()); - } -#if CE_CV==1 - wxImage cewxcvMisc::wx_from_mat(Mat &img) { - Mat im2; - if(img.channels()==1){cvtColor(img,im2,COLOR_GRAY2RGB);} - else if (img.channels() == 4) { cvtColor(img, im2, COLOR_BGRA2RGB);} - else {cvtColor(img,im2,COLOR_BGR2RGB);} - long imsize = im2.rows*im2.cols*im2.channels(); - wxImage wx(im2.cols, im2.rows,(unsigned char*)malloc(imsize), false); - unsigned char* s=im2.data; - unsigned char* d=wx.GetData(); - for (long i = 0; i < imsize; i++) { d[i] = s[i];} - return wx; - } - - Mat cewxcvMisc::mat_from_wx(wxImage &wx) { - Mat im2(Size(wx.GetWidth(),wx.GetHeight()),CV_8UC3,wx.GetData()); - cvtColor(im2,im2,COLOR_RGB2BGR); - return im2; - } -#endif // CE_CV -#endif // CE_WX -} // namespace ce \ No newline at end of file diff --git a/vcprj/ceutil.vcxproj b/vcprj/ceutil.vcxproj index 3228bfe..278958c 100644 --- a/vcprj/ceutil.vcxproj +++ b/vcprj/ceutil.vcxproj @@ -39,10 +39,6 @@ - - - - diff --git a/vcprj/ceutil.vcxproj.filters b/vcprj/ceutil.vcxproj.filters index b493a41..f3848ca 100644 --- a/vcprj/ceutil.vcxproj.filters +++ b/vcprj/ceutil.vcxproj.filters @@ -74,21 +74,9 @@ - - Source Files - Source Files - - Source Files - - - Source Files - - - Source Files - From 0c44757d96d1bc99cd10cdd71422fdd093cec03c Mon Sep 17 00:00:00 2001 From: yan9a Date: Mon, 26 Aug 2024 10:42:59 +1200 Subject: [PATCH 06/10] Update examples --- .gitattributes | 19 + ceutil.sh | 8 + ceutilw.bat | 3 + examples/I2C/src/I2C.cpp | 3 +- examples/Log/src/Log.cpp | 2 +- examples/Log/{Log => vsprj}/Log.sln | 62 +-- examples/Log/{Log => vsprj}/Log.vcxproj | 268 +++++------ .../Log/{Log => vsprj}/Log.vcxproj.filters | 42 +- examples/Modbus/Modbus/Modbus.sln | 31 -- examples/Modbus/src/Modbus.cpp | 6 +- examples/Modbus/vsprj/Modbus.sln | 31 ++ .../Modbus/{Modbus => vsprj}/Modbus.vcxproj | 268 +++++------ .../{Modbus => vsprj}/Modbus.vcxproj.filters | 42 +- examples/ModbusCmd/CMakeLists.txt | 12 - examples/ModbusCmd/ModbusCmd.sh | 60 --- examples/ModbusCmd/ModbusCmd/ModbusCmd.sln | 31 -- .../ModbusCmd/ModbusCmd/ModbusCmd.vcxproj | 162 ------- .../ModbusCmd/ModbusCmd.vcxproj.filters | 22 - examples/ModbusCmd/modbuscmdw.bat | 11 - examples/ModbusCmd/src/ModbusCmd.cpp | 406 ---------------- examples/Serial/src/Serial.cpp | 3 +- examples/Serial/{Serial => vsprj}/Serial.sln | 62 +-- .../Serial/{Serial => vsprj}/Serial.vcxproj | 269 +++++------ .../{Serial => vsprj}/Serial.vcxproj.filters | 42 +- examples/SerialGui/CMakeLists.txt | 12 - examples/SerialGui/SerialGui.sh | 60 --- examples/SerialGui/SerialGui/SerialGui.sln | 31 -- .../SerialGui/SerialGui/SerialGui.vcxproj | 162 ------- .../SerialGui/SerialGui.vcxproj.filters | 22 - examples/SerialGui/serialguiw.bat | 11 - examples/SerialGui/src/SerialGui.cpp | 442 ------------------ examples/SerialGui/src/sample.xpm | 44 -- examples/UDP/UDP.sh | 120 ++--- examples/UDP/src/UDP.cpp | 4 +- examples/kbhit/kbhit.sh | 120 ++--- examples/kbhit/src/main.cpp | 3 +- examples/kbhit/{kbhit => vsprj}/kbhit.sln | 62 +-- examples/kbhit/{kbhit => vsprj}/kbhit.vcxproj | 322 ++++++------- .../{kbhit => vsprj}/kbhit.vcxproj.filters | 42 +- examples/rsakeygen/rsakeygen.sh | 120 ++--- examples/rsakeygen/src/rsakeygen.cpp | 6 +- .../{rsakeygen => vsprj}/public_key.pem | 0 .../{rsakeygen => vsprj}/rsakeygen.sln | 62 +-- .../{rsakeygen => vsprj}/rsakeygen.vcxproj | 274 +++++------ examples/tcpclient/src/tcpclient.cpp | 3 +- examples/tcpsvr/src/tcpsvr.cpp | 2 +- include/ce/celog.h | 2 +- include/ce/cetcpcli.h | 3 +- include/ce/{cewxcvmiscx.h => cewxcvmisc.h} | 0 test.sh | 24 +- test/testDES/main.cpp | 4 +- test/testJson/main.cpp | 2 +- test/testRSA_OS/main.cpp | 4 +- test/testSHA1/main.cpp | 4 +- vcprj/ceutil.sln | 62 +-- vcprj/ceutil.vcxproj | 3 - vcprj/ceutil.vcxproj.filters | 5 - 57 files changed, 1221 insertions(+), 2681 deletions(-) create mode 100644 .gitattributes create mode 100644 ceutil.sh create mode 100644 ceutilw.bat rename examples/Log/{Log => vsprj}/Log.sln (97%) rename examples/Log/{Log => vsprj}/Log.vcxproj (97%) rename examples/Log/{Log => vsprj}/Log.vcxproj.filters (97%) delete mode 100644 examples/Modbus/Modbus/Modbus.sln create mode 100644 examples/Modbus/vsprj/Modbus.sln rename examples/Modbus/{Modbus => vsprj}/Modbus.vcxproj (93%) rename examples/Modbus/{Modbus => vsprj}/Modbus.vcxproj.filters (92%) delete mode 100644 examples/ModbusCmd/CMakeLists.txt delete mode 100644 examples/ModbusCmd/ModbusCmd.sh delete mode 100644 examples/ModbusCmd/ModbusCmd/ModbusCmd.sln delete mode 100644 examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj delete mode 100644 examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj.filters delete mode 100644 examples/ModbusCmd/modbuscmdw.bat delete mode 100644 examples/ModbusCmd/src/ModbusCmd.cpp rename examples/Serial/{Serial => vsprj}/Serial.sln (97%) rename examples/Serial/{Serial => vsprj}/Serial.vcxproj (95%) rename examples/Serial/{Serial => vsprj}/Serial.vcxproj.filters (97%) delete mode 100644 examples/SerialGui/CMakeLists.txt delete mode 100644 examples/SerialGui/SerialGui.sh delete mode 100644 examples/SerialGui/SerialGui/SerialGui.sln delete mode 100644 examples/SerialGui/SerialGui/SerialGui.vcxproj delete mode 100644 examples/SerialGui/SerialGui/SerialGui.vcxproj.filters delete mode 100644 examples/SerialGui/serialguiw.bat delete mode 100644 examples/SerialGui/src/SerialGui.cpp delete mode 100644 examples/SerialGui/src/sample.xpm rename examples/kbhit/{kbhit => vsprj}/kbhit.sln (97%) rename examples/kbhit/{kbhit => vsprj}/kbhit.vcxproj (97%) rename examples/kbhit/{kbhit => vsprj}/kbhit.vcxproj.filters (97%) rename examples/rsakeygen/{rsakeygen => vsprj}/public_key.pem (100%) rename examples/rsakeygen/{rsakeygen => vsprj}/rsakeygen.sln (97%) rename examples/rsakeygen/{rsakeygen => vsprj}/rsakeygen.vcxproj (98%) rename include/ce/{cewxcvmiscx.h => cewxcvmisc.h} (100%) diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..065420e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,19 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto + +# Explicitly declare text files you want to always be normalized and converted +# to native line endings on checkout. +# *.c text +# *.h text + +# Declare files that will always have CRLF line endings on checkout. +*.sln text eol=crlf +*.vcproj text eol=crlf + +# Declare files that will always have LF line endings on checkout. +*.sh text eol=lf +id_dsa text eol=lf + +# Denote all files that are truly binary and should not be modified. +*.png binary +*.jpg binary diff --git a/ceutil.sh b/ceutil.sh new file mode 100644 index 0000000..804d857 --- /dev/null +++ b/ceutil.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +# fix script +# sed -i -e 's/\r$//' ceutil.sh +# chmod +x ceutil.sh + +# install ce header files in /usr/local/include +sudo cp -r include/ce /usr/local/include \ No newline at end of file diff --git a/ceutilw.bat b/ceutilw.bat new file mode 100644 index 0000000..83d56b2 --- /dev/null +++ b/ceutilw.bat @@ -0,0 +1,3 @@ +@REM To run the script set VCPKG_ROOT environmental variable for vcpkg root folder + +xcopy ".\include" "%VCPKG_ROOT%\installed\x64-windows\include" /E /H /C /I /Y diff --git a/examples/I2C/src/I2C.cpp b/examples/I2C/src/I2C.cpp index 965fca9..3c9bd2e 100644 --- a/examples/I2C/src/I2C.cpp +++ b/examples/I2C/src/I2C.cpp @@ -1,4 +1,5 @@ -#include "ce/ceUtil.h" +#include "ce/cepca9535.h" +#include "wx/wx.h" using namespace ce; int main(){ diff --git a/examples/Log/src/Log.cpp b/examples/Log/src/Log.cpp index f21ec8c..49186a7 100644 --- a/examples/Log/src/Log.cpp +++ b/examples/Log/src/Log.cpp @@ -1,5 +1,5 @@ #include -#include "ce/ceUtil.h" +#include "ce/celog.h" using namespace ce; int main(){ ceLog l("./",1); diff --git a/examples/Log/Log/Log.sln b/examples/Log/vsprj/Log.sln similarity index 97% rename from examples/Log/Log/Log.sln rename to examples/Log/vsprj/Log.sln index c1067ef..23322e9 100644 --- a/examples/Log/Log/Log.sln +++ b/examples/Log/vsprj/Log.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Log", "Log.vcxproj", "{FF0CBEC6-2040-4D74-9966-7E4530656E20}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.ActiveCfg = Debug|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.Build.0 = Debug|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.ActiveCfg = Debug|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.Build.0 = Debug|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.ActiveCfg = Release|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.Build.0 = Release|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.ActiveCfg = Release|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {963C9ECC-7676-4360-A9B1-A31048A8D673} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Log", "Log.vcxproj", "{FF0CBEC6-2040-4D74-9966-7E4530656E20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.ActiveCfg = Debug|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.Build.0 = Debug|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.ActiveCfg = Debug|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.Build.0 = Debug|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.ActiveCfg = Release|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.Build.0 = Release|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.ActiveCfg = Release|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {963C9ECC-7676-4360-A9B1-A31048A8D673} + EndGlobalSection +EndGlobal diff --git a/examples/Log/Log/Log.vcxproj b/examples/Log/vsprj/Log.vcxproj similarity index 97% rename from examples/Log/Log/Log.vcxproj rename to examples/Log/vsprj/Log.vcxproj index c66c80f..cd49230 100644 --- a/examples/Log/Log/Log.vcxproj +++ b/examples/Log/vsprj/Log.vcxproj @@ -1,135 +1,135 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - {FF0CBEC6-2040-4D74-9966-7E4530656E20} - Log - 10.0 - - - - Application - true - v143 - MultiByte - - - Application - false - v143 - true - MultiByte - - - Application - true - v143 - MultiByte - - - Application - false - v143 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - MaxSpeed - true - true - true - true - - - Console - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - Console - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + {FF0CBEC6-2040-4D74-9966-7E4530656E20} + Log + 10.0 + + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + MaxSpeed + true + true + true + true + + + Console + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) + WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + Console + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + + + + \ No newline at end of file diff --git a/examples/Log/Log/Log.vcxproj.filters b/examples/Log/vsprj/Log.vcxproj.filters similarity index 97% rename from examples/Log/Log/Log.vcxproj.filters rename to examples/Log/vsprj/Log.vcxproj.filters index 322bf43..b14fdbe 100644 --- a/examples/Log/Log/Log.vcxproj.filters +++ b/examples/Log/vsprj/Log.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/Modbus/Modbus/Modbus.sln b/examples/Modbus/Modbus/Modbus.sln deleted file mode 100644 index 7e5e3e0..0000000 --- a/examples/Modbus/Modbus/Modbus.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testModbus", "testModbus.vcxproj", "{850665AF-0AF1-4CF0-9447-2ACC1E2596E3}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x64.ActiveCfg = Debug|x64 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x64.Build.0 = Debug|x64 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x86.ActiveCfg = Debug|Win32 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Debug|x86.Build.0 = Debug|Win32 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x64.ActiveCfg = Release|x64 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x64.Build.0 = Release|x64 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x86.ActiveCfg = Release|Win32 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {16967C37-6C30-4296-BE8C-88110AB29EE9} - EndGlobalSection -EndGlobal diff --git a/examples/Modbus/src/Modbus.cpp b/examples/Modbus/src/Modbus.cpp index 888756e..a3a6e8e 100644 --- a/examples/Modbus/src/Modbus.cpp +++ b/examples/Modbus/src/Modbus.cpp @@ -4,9 +4,9 @@ // MIT License (https://opensource.org/licenses/MIT) // Copyright (c) 2021 Yan Naing Aye -#include -#include "ce/ceSerial.h" -#include "ce/ceModbus.h" +#include +#include "ce/ceserial.h" +#include "ce/cemodbus.h" #include using namespace std; using namespace ce; diff --git a/examples/Modbus/vsprj/Modbus.sln b/examples/Modbus/vsprj/Modbus.sln new file mode 100644 index 0000000..66b2576 --- /dev/null +++ b/examples/Modbus/vsprj/Modbus.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34330.188 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Modbus", "Modbus.vcxproj", "{A9F3B146-820B-438D-BB60-09A687BF0E7D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A9F3B146-820B-438D-BB60-09A687BF0E7D}.Debug|x64.ActiveCfg = Debug|x64 + {A9F3B146-820B-438D-BB60-09A687BF0E7D}.Debug|x64.Build.0 = Debug|x64 + {A9F3B146-820B-438D-BB60-09A687BF0E7D}.Debug|x86.ActiveCfg = Debug|Win32 + {A9F3B146-820B-438D-BB60-09A687BF0E7D}.Debug|x86.Build.0 = Debug|Win32 + {A9F3B146-820B-438D-BB60-09A687BF0E7D}.Release|x64.ActiveCfg = Release|x64 + {A9F3B146-820B-438D-BB60-09A687BF0E7D}.Release|x64.Build.0 = Release|x64 + {A9F3B146-820B-438D-BB60-09A687BF0E7D}.Release|x86.ActiveCfg = Release|Win32 + {A9F3B146-820B-438D-BB60-09A687BF0E7D}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {16967C37-6C30-4296-BE8C-88110AB29EE9} + EndGlobalSection +EndGlobal diff --git a/examples/Modbus/Modbus/Modbus.vcxproj b/examples/Modbus/vsprj/Modbus.vcxproj similarity index 93% rename from examples/Modbus/Modbus/Modbus.vcxproj rename to examples/Modbus/vsprj/Modbus.vcxproj index ca35e58..d8dfc51 100644 --- a/examples/Modbus/Modbus/Modbus.vcxproj +++ b/examples/Modbus/vsprj/Modbus.vcxproj @@ -1,135 +1,135 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - {850665AF-0AF1-4CF0-9447-2ACC1E2596E3} - testModbus - 10.0 - - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - MaxSpeed - true - true - true - true - - - Console - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - C:\Users\yana\ws\ceutil\include;%(AdditionalIncludeDirectories) - WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - Console - true - true - C:\Users\yana\ws\ceutil\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {A9F3B146-820B-438D-BB60-09A687BF0E7D} + testModbus + 10.0 + + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + MaxSpeed + true + true + true + true + + + Console + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + C:\Users\yana\ws\ceutil\include;%(AdditionalIncludeDirectories) + WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + Console + true + true + C:\Users\yana\ws\ceutil\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/Modbus/Modbus/Modbus.vcxproj.filters b/examples/Modbus/vsprj/Modbus.vcxproj.filters similarity index 92% rename from examples/Modbus/Modbus/Modbus.vcxproj.filters rename to examples/Modbus/vsprj/Modbus.vcxproj.filters index a8e9e67..0968464 100644 --- a/examples/Modbus/Modbus/Modbus.vcxproj.filters +++ b/examples/Modbus/vsprj/Modbus.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/ModbusCmd/CMakeLists.txt b/examples/ModbusCmd/CMakeLists.txt deleted file mode 100644 index e5598c9..0000000 --- a/examples/ModbusCmd/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(ModbusCmd VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/ModbusCmd/ModbusCmd.sh b/examples/ModbusCmd/ModbusCmd.sh deleted file mode 100644 index 84086f0..0000000 --- a/examples/ModbusCmd/ModbusCmd.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - diff --git a/examples/ModbusCmd/ModbusCmd/ModbusCmd.sln b/examples/ModbusCmd/ModbusCmd/ModbusCmd.sln deleted file mode 100644 index d0c5e1a..0000000 --- a/examples/ModbusCmd/ModbusCmd/ModbusCmd.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ModbusCmd", "ModbusCmd.vcxproj", "{D7016C30-0709-40AF-A1B2-24AF8606C639}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x64.ActiveCfg = Debug|x64 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x64.Build.0 = Debug|x64 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x86.ActiveCfg = Debug|Win32 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Debug|x86.Build.0 = Debug|Win32 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x64.ActiveCfg = Release|x64 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x64.Build.0 = Release|x64 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x86.ActiveCfg = Release|Win32 - {D7016C30-0709-40AF-A1B2-24AF8606C639}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {9BE80EB7-72E9-44FE-B724-BECFCCF2A3ED} - EndGlobalSection -EndGlobal diff --git a/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj b/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj deleted file mode 100644 index 765c28c..0000000 --- a/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj +++ /dev/null @@ -1,162 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {D7016C30-0709-40AF-A1B2-24AF8606C639} - Win32Proj - ModbusCmd - 10.0 - - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - Application - true - v142 - Unicode - - - Application - false - v142 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - - \ No newline at end of file diff --git a/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj.filters b/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj.filters deleted file mode 100644 index 7ba81f1..0000000 --- a/examples/ModbusCmd/ModbusCmd/ModbusCmd.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - - \ No newline at end of file diff --git a/examples/ModbusCmd/modbuscmdw.bat b/examples/ModbusCmd/modbuscmdw.bat deleted file mode 100644 index 39d8f22..0000000 --- a/examples/ModbusCmd/modbuscmdw.bat +++ /dev/null @@ -1,11 +0,0 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -ModbusCmd.exe -@REM cpack --verbose -cd ../.. diff --git a/examples/ModbusCmd/src/ModbusCmd.cpp b/examples/ModbusCmd/src/ModbusCmd.cpp deleted file mode 100644 index 2abeac1..0000000 --- a/examples/ModbusCmd/src/ModbusCmd.cpp +++ /dev/null @@ -1,406 +0,0 @@ -// File: ModbusCmd.cpp -// Description: Modbus RTS communication for RS485 switches -// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html -// MIT License (https://opensource.org/licenses/MIT) -// Copyright (c) 2021 Yan Naing Aye - -#include "wx/wx.h" -#include -#include -#include -#include -#include -// ---------------------------------------------------------------------------- -// private classes -#include "ce/ceUtil.h" -using namespace std; -using namespace ce; -// ---------------------------------------------------------------------------- -#define MODBUS_ID_MAX 31 -#define MODBUS_ADDR_MAX 16 -#define MODBUS_ACTION_MAX 8 -#define MODBUS_DURATION_MAX 255 -#define N_LOG_LIST_LINES 30 - -#define MODBUS_DIALOG_BTN_SEND 100 -#define MODBUS_DIALOG_BTN_CMD 101 - -#define MODBUS_DIALOG_SPN_ID 102 -#define MODBUS_DIALOG_SPN_ADDR 103 -#define MODBUS_DIALOG_CBO_FUNC 104 -#define MODBUS_DIALOG_CBO_ACTION 105 -#define MODBUS_DIALOG_SPN_DURATION 106 -#define MODBUS_DIALOG_TXT_CMD 107 -#define ID_BAUDRATE_MNU 108 -#define ID_TIMER 109 -#define ID_WXSERIAL 110 -#define ID_SELPORT_MNU 111 -#define ID_OPEN_MNU 112 -#define ID_CLOSE_MNU 113 -#define ID_CLEAR_MNU 114 -#define GUI_LST_LOG_ID 115 -// wxID_EXIT for quit -// wxID_ABOUT for about -// ---------------------------------------------------------------------------- -class MyFrame; -class MyApp : public wxApp -{ -public: - virtual bool OnInit(); - MyFrame* _fra; - ceWxSerial* _com; - ceModbus* _modbus; - void OnSerialEvent(wxThreadEvent& event); -}; - -// Define a new frame type: this is going to be our main frame -class MyFrame : public wxFrame -{ -public: - // ctor(s) - MyFrame(MyApp* app, const wxString& title); - - // event handlers (these functions should _not_ be virtual) - void OnQuit(wxCommandEvent& event); - void OnAbout(wxCommandEvent& event); - void OnOpen(wxCommandEvent& event); - void OnClose(wxCommandEvent& event); - void SelPort(wxCommandEvent& event); - void SetBaud(wxCommandEvent& event); - void OnClear(wxCommandEvent& event); - void OnSend(wxCommandEvent& event); - void OnTimer(wxTimerEvent& event); - void OnSendHex(wxCommandEvent& event); - void WriteList(std::string mes); - void ModbusControl(uint8_t id, uint8_t func, uint16_t addr, uint8_t action, uint8_t delay); - void ModbusCmd(std::vector cmd); -private: - MyApp* _app; - wxSpinCtrl* spnId; - wxSpinCtrl* spnAddr; - wxSpinCtrl* spnDuration; - wxButton* btnSend; - wxComboBox* cboFunc; - wxComboBox* cboAction; - wxTextCtrl* txtCmd; - wxButton* btnCmd; - wxTimer tmr; - wxListBox* logList; -}; - -IMPLEMENT_APP(MyApp) - -bool MyApp::OnInit() -{ - if ( !wxApp::OnInit() ) - return false; - _fra = new MyFrame(this, wxT("Modbus RS485 Relay Board Control")); - - _modbus = new ceModbus(); - string device; -#if defined(CE_WINDOWS) - device = "\\\\.\\COM1"; -#else - device = "/dev/ttyUSB0"; -#endif - _com = new ceWxSerial(this, ID_WXSERIAL, 10, device, 9600, 8, 'N', 1); - Connect(ID_WXSERIAL, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); - _fra->Show(true); - return true; -} - -void MyApp::OnSerialEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - char ch; - for (int i = 0; i < v.size(); i++) { - ch = v[i]; - // printf("%02X ", (unsigned int)ch & 0xFF); - if (_modbus->ReceiveRxFrame(ch)) { - char* buf = _modbus->GetRxBuf(); - size_t rn = _modbus->GetRxN(); - if (buf[1] == 6) { - _fra->WriteList("Received control reply"); - } - else if (buf[1] == 3) { - _fra->WriteList("Received read reply"); - std::vector rstatus = _modbus->GetStatus(buf, rn); - for (uint16_t& s : rstatus) { - _fra->WriteList("Status: "+ to_string(s)); - } - } - } - } - // wxMessageBox(wxT("Serial event")); -} - -// ---------------------------------------------------------------------------- -// main frame -// ---------------------------------------------------------------------------- - -// frame constructor -MyFrame::MyFrame(MyApp* app, const wxString& title) - : wxFrame(NULL, wxID_ANY, title,wxDefaultPosition,wxSize(480, 600), wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),tmr(this, ID_TIMER), _app(app) -{ - -#if wxUSE_MENUS - // create a menu bar - wxMenu *fileMenu = new wxMenu; - - //Edit menu - wxMenu *editMenu = new wxMenu; - - // the "About" item should be in the help menu - wxMenu *helpMenu = new wxMenu; - - helpMenu->Append(wxID_ABOUT, wxT("&About\tF1"), wxT("Show about dialog")); - Connect(wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnAbout)); - - fileMenu->Append(ID_OPEN_MNU, wxT("&Open\tAlt-O"), wxT("Open serial port")); - Connect(ID_OPEN_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnOpen)); - fileMenu->Append(ID_CLOSE_MNU, wxT("&Close\tAlt-C"), wxT("Close serial port")); - Connect(ID_CLOSE_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnClose)); - editMenu->Append(ID_CLEAR_MNU, wxT("Clea&r\tAlt-R"), wxT("Clear")); - Connect(ID_CLEAR_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnClear)); - fileMenu->Append(ID_SELPORT_MNU, wxT("&Serial Port\tAlt-S"), wxT("Select serial port")); - Connect(ID_SELPORT_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SelPort)); - fileMenu->Append(ID_BAUDRATE_MNU, wxT("&Baud Rate\tAlt-B"), wxT("Set baud rate")); - Connect(ID_BAUDRATE_MNU, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetBaud)); - fileMenu->Append(wxID_EXIT, wxT("E&xit\tAlt-X"), wxT("Quit this program")); - Connect(wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnQuit)); - - // now append the freshly created menu to the menu bar... - wxMenuBar *menuBar = new wxMenuBar(); - menuBar->Append(fileMenu, wxT("&File")); - menuBar->Append(editMenu, wxT("&Edit")); - menuBar->Append(helpMenu, wxT("&Help")); - - // ... and attach this menu bar to the frame - SetMenuBar(menuBar); -#endif // wxUSE_MENUS - -#if wxUSE_STATUSBAR - // create a status bar just for fun (by default with 1 pane only) - CreateStatusBar(2); - SetStatusText(wxT("Modbus switch control")); -#endif // wxUSE_STATUSBAR - - // id 0 - 31 - wxStaticText* lblId = new wxStaticText(this, -1, wxT("Board:"), - wxPoint(10, 25), wxSize(55, 30)); - this->spnId = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_ID, wxT("1"), - wxPoint(80, 20), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_ID_MAX, 0, wxT("ID")); - - // function - wxStaticText* lblFunc = new wxStaticText(this, -1, wxT("Func:"), - wxPoint(230, 25), wxSize(55, 30)); - wxArrayString funcList; - funcList.Add("6 - Control"); - funcList.Add("3 - Read"); - cboFunc = new wxComboBox(this, MODBUS_DIALOG_CBO_FUNC, wxT("6 - Control"), - wxPoint(290, 20), wxSize(120, 25), funcList, wxCB_READONLY); - - // Address - wxStaticText* lblAddr = new wxStaticText(this, -1, wxT("Relay:"), - wxPoint(10, 85), wxSize(60, 30)); - this->spnAddr = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_ADDR, wxT("1"), - wxPoint(80, 80), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_ADDR_MAX, 0, wxT("RELAY")); - - // delay - wxStaticText* lblDuration = new wxStaticText(this, -1, wxT("Seconds:"), - wxPoint(10, 145), wxSize(60, 30)); - this->spnDuration = new wxSpinCtrl(this, MODBUS_DIALOG_SPN_DURATION, wxT("0"), - wxPoint(80, 140), wxSize(120, 25), wxTE_PROCESS_ENTER, 0, MODBUS_DURATION_MAX, 500); - - // Action - wxStaticText* lblAction = new wxStaticText(this, -1, wxT("Action:"), - wxPoint(230, 85), wxSize(55, 30)); - wxArrayString actList; - actList.Add("0 - Default"); - actList.Add("1 - Open"); - actList.Add("2 - Close"); - actList.Add("3 - Toggle"); - actList.Add("4 - Latch"); - actList.Add("5 - Momentary"); - actList.Add("6 - Delay"); - actList.Add("7 - Open all"); - actList.Add("8 - Close all"); - cboAction = new wxComboBox(this, MODBUS_DIALOG_CBO_ACTION, wxT("3 - Toggle"), - wxPoint(290, 80), wxSize(120, 30), actList, wxCB_READONLY); - - this->btnSend = new wxButton(this, MODBUS_DIALOG_BTN_SEND, wxT("Send"), - wxPoint(310, 140), wxSize(100, 30)); - Connect(MODBUS_DIALOG_BTN_SEND, wxEVT_COMMAND_BUTTON_CLICKED, - wxCommandEventHandler(MyFrame::OnSend)); - - wxStaticText* lblDes = new wxStaticText(this, -1, wxT("For the following hex cmd, CRC will be appended"), - wxPoint(10, 180), wxSize(-1,-1)); - wxStaticText* lblCmd = new wxStaticText(this, -1, wxT("Cmd:"), - wxPoint(10, 215), wxSize(55, 30)); - this->txtCmd = new wxTextCtrl(this, MODBUS_DIALOG_TXT_CMD, wxT("01 06 00 0A 03 00"), - wxPoint(80, 210), wxSize(210, 30)); - this->btnCmd = new wxButton(this, MODBUS_DIALOG_BTN_CMD, wxT("Send Cmd"), - wxPoint(310, 210), wxSize(100, 30)); - Connect(MODBUS_DIALOG_BTN_CMD, wxEVT_COMMAND_BUTTON_CLICKED, - wxCommandEventHandler(MyFrame::OnSendHex)); - - wxArrayString astr; - logList = new wxListBox(this, GUI_LST_LOG_ID, wxPoint(10,270), wxSize(400, 230), astr, wxLB_HSCROLL); - - Connect(ID_TIMER, wxEVT_TIMER, wxTimerEventHandler(MyFrame::OnTimer)); - tmr.Start(250); -} - -void MyFrame::WriteList(string mes) -{ - int nl = logList->GetCount(); - if (nl >= N_LOG_LIST_LINES) { - logList->Delete(0); - } - wxString wstr = mes; - //wxDateTime wdt; - //wdt.SetToCurrent(); - //wstr = wdt.Format(wxT("%Y-%m-%d %H:%M:%S"), wxDateTime::Local)+" : "+wstr; // add timestamp - wxArrayString astr; - astr.Add(wstr); - nl = logList->GetCount(); - logList->InsertItems(astr, nl); - logList->SetSelection(nl); -} - -// event handlers - -void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) -{ - // true is to force the frame to close - Close(true); -} - -void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) -{ - wxMessageBox(wxString::Format( - wxT("Modbus Switch Command Utility \n ") - wxT("Author: Yan Naing Aye \n ") - wxT("Web: https://github.com/yan9a/serial") - ), - wxT("About Modbus Switch"), - wxOK | wxICON_INFORMATION, - this); -} - -void MyFrame::OnOpen(wxCommandEvent& WXUNUSED(event)) -{ - if(_app->_com->Open()) this->WriteList(wxString::Format(wxT("Error opening port %s.\n"),_app->_com->GetPort()).ToStdString()); - else this->WriteList(wxString::Format(wxT("Port %s is opened.\n"), _app->_com->GetPort()).ToStdString()); -} - -void MyFrame::OnClose(wxCommandEvent& WXUNUSED(event)) -{ - _app->_com->Close(); - this->WriteList(wxString::Format(wxT("Port %s is closed.\n"), _app->_com->GetPort()).ToStdString()); -} - -void MyFrame::SelPort(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - this->WriteList(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort()).ToStdString()); - } - else { - wxString cdev=wxString::Format(wxT("%s"), _app->_com->GetPort()); - wxString device = wxGetTextFromUser(wxT("Enter the port"), wxT("Set Port"), cdev); - string str = device.ToStdString(); - if (str.length() > 0) { - _app->_com->SetPortName(str); - } - - this->WriteList(wxString::Format(wxT("Port: %s\n"), _app->_com->GetPort()).ToStdString()); - } -} - -void MyFrame::SetBaud(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - this->WriteList(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort()).ToStdString()); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the baud rate"), wxT("Baud rate"), wxT("Set Baud Rate"),_app->_com->GetBaudRate(),0, 1000000); - if (n >= 0) { - _app->_com->SetBaudRate(n); - } - this->WriteList(wxString::Format(wxT("Baud rate: %ld\n"), _app->_com->GetBaudRate()).ToStdString()); - } -} - -void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) -{ - uint8_t board = uint8_t(this->spnId->GetValue()); - - uint8_t func; - int v = this->cboFunc->GetSelection(); - if (v == wxNOT_FOUND || v == 0) func = 6; - else func = 3; - - uint16_t addr = uint16_t(this->spnAddr->GetValue()); - - v = this->cboAction->GetSelection(); - if (v == wxNOT_FOUND || func == 3) v = 0; - uint8_t action = uint8_t(v); - - uint8_t delay = uint8_t(this->spnDuration->GetValue()); - if (func == 3) delay = 1; // to read 1 relay when not using custom cmd - else if (action != 6) delay = 0; - this->ModbusControl(board, func, addr, action, delay); -} - -void MyFrame::OnSendHex(wxCommandEvent& WXUNUSED(event)) -{ - wxString ws = this->txtCmd->GetValue(); - std::string str = ws.ToStdString(); - vector v = ceMisc::hex2cvec(str); - vector cmd(v.begin(), v.end()); - this->ModbusCmd(cmd); -} - -void MyFrame::ModbusControl(uint8_t id, uint8_t func, uint16_t addr, uint8_t action, uint8_t delay) -{ - string str = "Board = " + to_string(id) + ", func = " + to_string(func) - + ", switch = " + to_string(addr); - if (func == 6) { - str += ", action = " + to_string(action) + ", delay = " + to_string(delay); - } - - uint8_t ah = uint8_t((addr >> 8) & 0xFF); - uint8_t al = uint8_t(addr & 0xFF); - std::vector cmd = { id,func,ah,al,action,delay }; - this->_app->_modbus->SetCmd(cmd); - if (this->_app->_com->Write(this->_app->_modbus->GetTxBuf(), (long)this->_app->_modbus->GetTxN())) { - this->WriteList(str); - } - else { - this->WriteList("Error in sending command"); - } -} - -void MyFrame::ModbusCmd(vector cmd) -{ - vector v(cmd.begin(), cmd.end()); - string str = "Cmd = " + ceMisc::cvec2hex(v); - this->_app->_modbus->SetCmd(cmd); - if (this->_app->_com->Write(this->_app->_modbus->GetTxBuf(), (long)this->_app->_modbus->GetTxN())) { - this->WriteList(str); - } - else { - this->WriteList("Error in sending command"); - } - -} - -void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event)) -{ - this->_app->_modbus->Tick(); -} - -void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event)) -{ - logList->Clear(); -} diff --git a/examples/Serial/src/Serial.cpp b/examples/Serial/src/Serial.cpp index 0fcd72a..4a884c3 100644 --- a/examples/Serial/src/Serial.cpp +++ b/examples/Serial/src/Serial.cpp @@ -5,9 +5,8 @@ // Copyright (c) 2018 Yan Naing Aye #include -#include "ce/ceSerial.h" +#include "ce/ceserial.h" using namespace std; -using namespace ce; int main() { diff --git a/examples/Serial/Serial/Serial.sln b/examples/Serial/vsprj/Serial.sln similarity index 97% rename from examples/Serial/Serial/Serial.sln rename to examples/Serial/vsprj/Serial.sln index 71d3783..f09b788 100644 --- a/examples/Serial/Serial/Serial.sln +++ b/examples/Serial/vsprj/Serial.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Serial", "Serial.vcxproj", "{78C78AC9-F3C1-4551-B5D2-797594E5CB20}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x64.ActiveCfg = Debug|x64 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x64.Build.0 = Debug|x64 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x86.ActiveCfg = Debug|Win32 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x86.Build.0 = Debug|Win32 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x64.ActiveCfg = Release|x64 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x64.Build.0 = Release|x64 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x86.ActiveCfg = Release|Win32 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {CAE2F3A7-6A5E-480F-A7E3-7263E51CA67D} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Serial", "Serial.vcxproj", "{78C78AC9-F3C1-4551-B5D2-797594E5CB20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x64.ActiveCfg = Debug|x64 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x64.Build.0 = Debug|x64 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x86.ActiveCfg = Debug|Win32 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Debug|x86.Build.0 = Debug|Win32 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x64.ActiveCfg = Release|x64 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x64.Build.0 = Release|x64 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x86.ActiveCfg = Release|Win32 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {CAE2F3A7-6A5E-480F-A7E3-7263E51CA67D} + EndGlobalSection +EndGlobal diff --git a/examples/Serial/Serial/Serial.vcxproj b/examples/Serial/vsprj/Serial.vcxproj similarity index 95% rename from examples/Serial/Serial/Serial.vcxproj rename to examples/Serial/vsprj/Serial.vcxproj index 606e3df..d9eb94b 100644 --- a/examples/Serial/Serial/Serial.vcxproj +++ b/examples/Serial/vsprj/Serial.vcxproj @@ -1,135 +1,136 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {78C78AC9-F3C1-4551-B5D2-797594E5CB20} - Serial - 10.0 - - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - Application - true - v142 - MultiByte - - - Application - false - v142 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - MaxSpeed - true - true - true - true - - - Console - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - C:\Users\yana\ws\ceutil\include;%(AdditionalIncludeDirectories) - WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - Console - true - true - C:\Users\yana\ws\ceutil\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {78C78AC9-F3C1-4551-B5D2-797594E5CB20} + Serial + 10.0 + + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + Disabled + true + true + $(VCPKG_ROOT)\installed\x64-windows\include;%(AdditionalIncludeDirectories) + + + Console + + + + + Level3 + MaxSpeed + true + true + true + true + + + Console + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + C:\Users\yana\ws\ceutil\include;%(AdditionalIncludeDirectories) + WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + Console + true + true + C:\Users\yana\ws\ceutil\ceUtil\x64\Release;%(AdditionalLibraryDirectories) + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/Serial/Serial/Serial.vcxproj.filters b/examples/Serial/vsprj/Serial.vcxproj.filters similarity index 97% rename from examples/Serial/Serial/Serial.vcxproj.filters rename to examples/Serial/vsprj/Serial.vcxproj.filters index 96339c1..dec564e 100644 --- a/examples/Serial/Serial/Serial.vcxproj.filters +++ b/examples/Serial/vsprj/Serial.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/SerialGui/CMakeLists.txt b/examples/SerialGui/CMakeLists.txt deleted file mode 100644 index 1de8158..0000000 --- a/examples/SerialGui/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -cmake_minimum_required(VERSION 3.0.0) -# directory name to be used as project name -project(SerialGui VERSION 1.0.1) -set(ADDCV NO) -# CMakeM1 checks ADDCV variable whether to include OpenCV -# and return LIBS variable with the list of libraries to link -# and also set WIN32OPT variable with WIN32 for Windows -include(${PROJECT_SOURCE_DIR}/../../CMakeM1.txt) -add_executable(${PROJECT_NAME} ${WIN32OPT} -${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}.cpp -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) diff --git a/examples/SerialGui/SerialGui.sh b/examples/SerialGui/SerialGui.sh deleted file mode 100644 index 84086f0..0000000 --- a/examples/SerialGui/SerialGui.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - diff --git a/examples/SerialGui/SerialGui/SerialGui.sln b/examples/SerialGui/SerialGui/SerialGui.sln deleted file mode 100644 index d62b793..0000000 --- a/examples/SerialGui/SerialGui/SerialGui.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SerialGui", "SerialGui.vcxproj", "{9E6EFA9E-8164-4807-B820-F97C9CFBFED1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.ActiveCfg = Debug|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x64.Build.0 = Debug|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.ActiveCfg = Debug|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Debug|x86.Build.0 = Debug|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.ActiveCfg = Release|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x64.Build.0 = Release|x64 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.ActiveCfg = Release|Win32 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {D0A51A18-2F03-4C7F-9C10-DB3BA0B948C1} - EndGlobalSection -EndGlobal diff --git a/examples/SerialGui/SerialGui/SerialGui.vcxproj b/examples/SerialGui/SerialGui/SerialGui.vcxproj deleted file mode 100644 index 7ca8b69..0000000 --- a/examples/SerialGui/SerialGui/SerialGui.vcxproj +++ /dev/null @@ -1,162 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {9E6EFA9E-8164-4807-B820-F97C9CFBFED1} - Win32Proj - SerialGui - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - NotSet - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Windows - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release;%(AdditionalLibraryDirectories) - ceUtil.lib;%(AdditionalDependencies) - - - - - - \ No newline at end of file diff --git a/examples/SerialGui/SerialGui/SerialGui.vcxproj.filters b/examples/SerialGui/SerialGui/SerialGui.vcxproj.filters deleted file mode 100644 index 429c563..0000000 --- a/examples/SerialGui/SerialGui/SerialGui.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - - \ No newline at end of file diff --git a/examples/SerialGui/serialguiw.bat b/examples/SerialGui/serialguiw.bat deleted file mode 100644 index 718d911..0000000 --- a/examples/SerialGui/serialguiw.bat +++ /dev/null @@ -1,11 +0,0 @@ -@REM To run the script set VCPKGDIR environmental variable for vcpkg root folder -if exist ./buildw/ ( -rmdir /s /q ./buildw -) -cmake -B ./buildw -S ./ -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=%VCPKGDIR%/scripts/buildsystems/vcpkg.cmake -D CMAKE_INSTALL_PREFIX=./installed/ &&^ -cmake --build ./buildw --config Release -@REM cmake --install ./buildw --config Release -cd buildw/Release -SerialGui.exe -@REM cpack --verbose -cd ../.. diff --git a/examples/SerialGui/src/SerialGui.cpp b/examples/SerialGui/src/SerialGui.cpp deleted file mode 100644 index 34ecebf..0000000 --- a/examples/SerialGui/src/SerialGui.cpp +++ /dev/null @@ -1,442 +0,0 @@ -//File: wxserial.cpp -//Description: Serial communication for wxWidgets -//WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html -//MIT License (https://opensource.org/licenses/MIT) -//Copyright (c) 2017 Yan Naing Aye - -// For compilers that support precompilation, includes "wx/wx.h". -#include "wx/wxprec.h" - -#ifdef __BORLANDC__ - #pragma hdrstop -#endif - -// for all others, include the necessary headers (this file is usually all you -// need because it includes almost all "standard" wxWidgets headers) -#ifndef WX_PRECOMP - #include "wx/wx.h" -#endif - -// the application icon (under Windows and OS/2 it is in resources and even -// though we could still include the XPM here it would be unused) -#ifndef wxHAS_IMAGES_IN_RESOURCES - #include "sample.xpm" -#endif - -#include -// ---------------------------------------------------------------------------- -// private classes -#include "ce/ceWxSerial.h" -using namespace std; -using namespace ce; -// ---------------------------------------------------------------------------- -class MyFrame; -// Define a new application type, each program should derive a class from wxApp -class MyApp : public wxApp -{ -public: - // override base class virtuals - // ---------------------------- - - // this one is called on application startup and is a good place for the app - // initialization (doing it here and not in the ctor allows to have an error - // return: if OnInit() returns false, the application terminates) - virtual bool OnInit(); - MyFrame* _fra; - ceWxSerial* _com; - void OnSerialEvent(wxThreadEvent& event); -}; - -// Define a new frame type: this is going to be our main frame -class MyFrame : public wxFrame -{ -public: - // ctor(s) - MyFrame(MyApp* app, const wxString& title); - MyApp* _app; - wxButton *btnSend; - wxTextCtrl *txtSend; - wxTimer m_timer; - wxTextCtrl *txtRx; - wxCheckBox *chkRTS; - wxCheckBox *chkDTR; - wxCheckBox *chkCTS; - wxCheckBox *chkDSR; - wxCheckBox *chkRI; - wxCheckBox *chkCD; - // event handlers (these functions should _not_ be virtual) - void OnQuit(wxCommandEvent& event); - void OnAbout(wxCommandEvent& event); - void OnOpen(wxCommandEvent& event); - void OnClose(wxCommandEvent& event); - void SelPort(wxCommandEvent& event); - void SetDataSize(wxCommandEvent& event); - void SetParity(wxCommandEvent& event); - void SetStopBits(wxCommandEvent& event); - void SetBaud(wxCommandEvent& event); - void OnSend(wxCommandEvent& event); - void OnTimer(wxTimerEvent& event); - void ProcessChar(char ch); - void ClearText(wxCommandEvent& event); - void OnChkRTS(wxCommandEvent& event); - void OnChkDTR(wxCommandEvent& event); - void UpdateCommStatus(); -private: - -}; - -// ---------------------------------------------------------------------------- -// constants -// ---------------------------------------------------------------------------- - -// IDs for the controls and the menu commands -const int ID_BTNSEND = 101; -const int ID_TXTSEND = 102; -const int ID_CHKRTS = 103; -const int ID_BAUDRATE = 103; -const int ID_TIMER = 104; -const int ID_TXTRX = 105; -const int ID_CHKDTR = 106; -const int ID_SELPORT = 107; -const int ID_CHKCTS = 108; -const int ID_CHKDSR = 109; -const int ID_CHKRI = 110; -const int ID_CHKCD = 111; -const int ID_DATASIZE = 112; -const int ID_PARITY = 113; -const int ID_STOPBITS = 114; -const int ID_WXSERIAL = 115; - -enum -{ - Button_Send = ID_BTNSEND, - Txt_Send = ID_TXTSEND, - Chk_RTS = ID_CHKRTS, - Serial_Baud = ID_BAUDRATE, - Timer1 = ID_TIMER, - Txt_Rx =ID_TXTRX, - Chk_DTR = ID_CHKDTR, - Serial_Port = ID_SELPORT, - Serial_DataSize=ID_DATASIZE, - Serial_Parity=ID_PARITY, - Serial_StopBits=ID_STOPBITS, - Txt_Clear = wxID_CLEAR, - Serial_Open = wxID_OPEN, - Serial_Close = wxID_CLOSE, - Minimal_Quit = wxID_EXIT, - Wx_Serial = ID_WXSERIAL, - - // it is important for the id corresponding to the "About" command to have - // this standard value as otherwise it won't be handled properly under Mac - // (where it is special and put into the "Apple" menu) - Minimal_About = wxID_ABOUT - -}; - -// Create a new application object: this macro will allow wxWidgets to create -// the application object during program execution (it's better than using a -// static object for many reasons) and also implements the accessor function -// wxGetApp() which will return the reference of the right type (i.e. MyApp and -// not wxApp) -IMPLEMENT_APP(MyApp) - -// ============================================================================ -// implementation -// ============================================================================ - -// ---------------------------------------------------------------------------- -// the application class -// ---------------------------------------------------------------------------- - -// 'Main program' equivalent: the program execution "starts" here -bool MyApp::OnInit() -{ - // call the base class initialization method, currently it only parses a - // few common command-line options but it could be do more in the future - if ( !wxApp::OnInit() ) - return false; - - // create the main application window - _fra = new MyFrame(this, wxT("Serial Com")); - - string device; -#if defined(CE_WINDOWS) - device = "\\\\.\\COM6"; -#else - device = "/dev/ttyUSB0"; -#endif - _com = new ceWxSerial(this, ID_WXSERIAL, 10, device, 9600, 8, 'N', 1); - Connect(ID_WXSERIAL, wxEVT_THREAD, wxThreadEventHandler(MyApp::OnSerialEvent)); - - // and show it (the frames, unlike simple controls, are not shown when - // created initially) - _fra->Show(true); - - - // success: wxApp::OnRun() will be called which will enter the main message - // loop and the application will run. If we returned false here, the - // application would exit immediately. - return true; -} - -void MyApp::OnSerialEvent(wxThreadEvent& event) -{ - std::vector v = event.GetPayload>(); - char ch; - for (int i = 0; i < v.size(); i++) { - ch = v[i]; - _fra->ProcessChar(ch); - } - // wxMessageBox(wxT("Serial event")); -} - -// ---------------------------------------------------------------------------- -// main frame -// ---------------------------------------------------------------------------- - -// frame constructor -MyFrame::MyFrame(MyApp* app, const wxString& title) - : wxFrame(NULL, wxID_ANY, title,wxDefaultPosition,wxSize(390, 280), wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),m_timer(this, ID_TIMER), _app(app) -{ - // set the frame icon - SetIcon(wxICON(sample)); - -#if wxUSE_MENUS - // create a menu bar - wxMenu *fileMenu = new wxMenu; - - //Edit menu - wxMenu *editMenu = new wxMenu; - - // the "About" item should be in the help menu - wxMenu *helpMenu = new wxMenu; - - helpMenu->Append(Minimal_About, wxT("&About\tF1"), wxT("Show about dialog")); - fileMenu->Append(Serial_Open, wxT("&Open\tAlt-O"), wxT("Open serial port")); - fileMenu->Append(Serial_Close, wxT("&Close\tAlt-C"), wxT("Close serial port")); - editMenu->Append(Txt_Clear, wxT("Clea&r\tAlt-R"), wxT("Clear text")); - fileMenu->Append(Serial_Port, wxT("&Serial Port\tAlt-S"), wxT("Select serial port")); - fileMenu->Append(Serial_Baud, wxT("&Baud Rate\tAlt-B"), wxT("Set baud rate")); - fileMenu->Append(Serial_DataSize, wxT("&Data Size\tAlt-D"), wxT("Set data size")); - fileMenu->Append(Serial_Parity, wxT("&Parity\tAlt-P"), wxT("Set parity")); - fileMenu->Append(Serial_StopBits, wxT("S&top Bits\tAlt-t"), wxT("Set stop bits")); - fileMenu->Append(Minimal_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program")); - - - // now append the freshly created menu to the menu bar... - wxMenuBar *menuBar = new wxMenuBar(); - menuBar->Append(fileMenu, wxT("&File")); - menuBar->Append(editMenu, wxT("&Edit")); - menuBar->Append(helpMenu, wxT("&Help")); - - // ... and attach this menu bar to the frame - SetMenuBar(menuBar); -#endif // wxUSE_MENUS - -#if wxUSE_STATUSBAR - // create a status bar just for fun (by default with 1 pane only) - CreateStatusBar(2); - SetStatusText(wxT("Serial Communication")); -#endif // wxUSE_STATUSBAR - btnSend = new wxButton(this,Button_Send,wxT( "Send"), wxPoint(5, 5), wxSize(100, 25)); - txtSend = new wxTextCtrl(this,Txt_Send,wxT("Hello!"),wxPoint(120,5),wxSize(250,25)); - //lblRx = new wxStaticText(this, ID_LBLRX, wxT("Rx:"), wxPoint(5, 75), wxSize(35, 25)); - txtRx = new wxTextCtrl(this, Txt_Rx, wxT(""), wxPoint(5, 35), wxSize(365, 125), wxTE_MULTILINE); - chkRTS = new wxCheckBox(this, Chk_RTS, wxT("RTS"), wxPoint(5, 170), wxDefaultSize); - chkDTR = new wxCheckBox(this, Chk_DTR, wxT("DTR"), wxPoint(55, 170), wxDefaultSize); - chkCTS = new wxCheckBox(this, ID_CHKCTS, wxT("CTS"), wxPoint(155, 170), wxDefaultSize); - chkDSR = new wxCheckBox(this, ID_CHKDSR, wxT("DSR"), wxPoint(205, 170), wxDefaultSize); - chkRI = new wxCheckBox(this, ID_CHKRI, wxT("RI"), wxPoint(255, 170), wxDefaultSize); - chkCD = new wxCheckBox(this, ID_CHKCD, wxT("CD"), wxPoint(305, 170), wxDefaultSize); - - Connect(Button_Send, wxEVT_COMMAND_BUTTON_CLICKED,wxCommandEventHandler(MyFrame::OnSend)); - Connect(Minimal_About,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnAbout)); - Connect(Minimal_Quit,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnQuit)); - Connect(Serial_Open,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnOpen)); - Connect(Serial_Close,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnClose)); - Connect(Serial_Port, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SelPort)); - Connect(Serial_Baud, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetBaud)); - Connect(Serial_DataSize, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetDataSize)); - Connect(Serial_Parity, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetParity)); - Connect(Serial_StopBits, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetStopBits)); - Connect(Timer1,wxEVT_TIMER, wxTimerEventHandler(MyFrame::OnTimer)); - Connect(Txt_Clear, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::ClearText)); - Connect(Chk_RTS,wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkRTS)); - Connect(Chk_DTR,wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkDTR)); - //Bind(wxEVT_MENU, &MyFrame::OnClose, this, Serial_Close); - - chkCTS->Disable(); - chkDSR->Disable(); - chkRI->Disable(); - chkCD->Disable(); - - m_timer.Start(250); -} - - -// event handlers - -void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) -{ - // true is to force the frame to close - Close(true); -} - -void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) -{ - wxMessageBox(wxString::Format( - wxT("Serial Communication! \n ") - wxT("Author: Yan Naing Aye \n ") - wxT("Web: https://github.com/yan9a/serial") - ), - wxT("About Serial Comm"), - wxOK | wxICON_INFORMATION, - this); -} - -void MyFrame::OnOpen(wxCommandEvent& WXUNUSED(event)) -{ - if(_app->_com->Open()) txtRx->AppendText(wxString::Format(wxT("Error opening port %s.\n"),_app->_com->GetPort())); - else txtRx->AppendText(wxString::Format(wxT("Port %s is opened.\n"), _app->_com->GetPort())); -} - -void MyFrame::OnClose(wxCommandEvent& WXUNUSED(event)) -{ - _app->_com->Close(); - txtRx->AppendText(wxString::Format(wxT("Port %s is closed.\n"), _app->_com->GetPort())); -} - -void MyFrame::SelPort(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort())); - } - else { - wxString cdev=wxString::Format(wxT("%s"), _app->_com->GetPort()); - wxString device = wxGetTextFromUser(wxT("Enter the port"), wxT("Set Port"), cdev); - string str = device.ToStdString(); - if (str.length() > 0) { - _app->_com->SetPortName(str); - } - - txtRx->AppendText(wxString::Format(wxT("Port: %s\n"), _app->_com->GetPort())); - } -} - -void MyFrame::SetParity(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), _app->_com->GetPort())); - } - else { - wxString cdev = wxString::Format(wxT("%c"), _app->_com->GetParity()); -#if defined(__WINDOWS__) - wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, O, M, or S )"), wxT("Set Parity"), cdev); -#else - wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, or O )"), wxT("Set Parity"), cdev); -#endif - - string pstr = parity.ToStdString(); - if (pstr.length() > 0) { - _app->_com->SetParity(pstr.at(0)); - } - txtRx->AppendText(wxString::Format(wxT("Parity: %c\n"), _app->_com->GetParity())); - } -} - -void MyFrame::SetBaud(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the baud rate"), wxT("Baud rate"), wxT("Set Baud Rate"),_app->_com->GetBaudRate(),0, 1000000); - if (n >= 0) { - _app->_com->SetBaudRate(n); - } - txtRx->AppendText(wxString::Format(wxT("Baud rate: %ld\n"), _app->_com->GetBaudRate())); - } -} - -void MyFrame::SetDataSize(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the data size"), wxT("Data Size"), wxT("Set Data Size"), _app->_com->GetDataSize(), 5, 8); - if (n >= 0) { - _app->_com->SetDataSize(n); - } - txtRx->AppendText(wxString::Format(wxT("Data size: %ld\n"), _app->_com->GetDataSize())); - } -} - -void MyFrame::SetStopBits(wxCommandEvent& WXUNUSED(event)) -{ - if (_app->_com->IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), _app->_com->GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the number of stop bits"), wxT("Data Size"), wxT("Set stop bits"), long(_app->_com->GetStopBits()), 1, 2); - if (n > 0) { - _app->_com->SetStopBits(float(n)); - } - txtRx->AppendText(wxString::Format(wxT("Stop bits: %ld\n"), long(_app->_com->GetStopBits()))); - } -} - -void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) -{ - wxString str = txtSend->GetValue(); - wxCharBuffer buffer = str.ToUTF8(); - if (_app->_com->Write(buffer.data())) { - txtRx->AppendText(str); - } - else { - txtRx->AppendText(wxT("Write error.\n")); - } -} - -void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event)) -{ - UpdateCommStatus(); -} - -void MyFrame::ProcessChar(char ch) -{ - this->txtRx->AppendText(wxString::Format(wxT("%c"), ch)); -} - -void MyFrame::ClearText(wxCommandEvent& WXUNUSED(event)) -{ - txtRx->Clear(); -} - -void MyFrame::OnChkRTS(wxCommandEvent& WXUNUSED(event)) -{ - if (!_app->_com->SetRTS(chkRTS->IsChecked())) { - txtRx->AppendText(wxT("RTS error.\n")); - } -} - -void MyFrame::OnChkDTR(wxCommandEvent& WXUNUSED(event)) -{ - if (!_app->_com->SetDTR(chkDTR->IsChecked())) { - txtRx->AppendText(wxT("DTR error.\n")); - } -} - -void MyFrame::UpdateCommStatus() -{ - bool s; - bool v; - v = _app->_com->GetCTS(s); - if (s) chkCTS->SetValue(v); - v = _app->_com->GetDSR(s); - if (s) chkDSR->SetValue(v); - v = _app->_com->GetRI(s); - if (s) chkRI->SetValue(v); - v = _app->_com->GetCD(s); - if (s) chkCD->SetValue(v); -} diff --git a/examples/SerialGui/src/sample.xpm b/examples/SerialGui/src/sample.xpm deleted file mode 100644 index 9c0a107..0000000 --- a/examples/SerialGui/src/sample.xpm +++ /dev/null @@ -1,44 +0,0 @@ -/* XPM */ -static const char *const sample_xpm[] = { -/* columns rows colors chars-per-pixel */ -"32 32 6 1", -" c black", -". c navy", -"X c red", -"o c yellow", -"O c gray100", -"+ c None", -/* pixels */ -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++ ++++++++++", -"++++++++ ............ ++++++++++", -"++++++++ ............ ++++++++++", -"++++++++ .OO......... ++++++++++", -"++++++++ .OO......... ++++++++++", -"++++++++ .OO......... ++++++++++", -"++++++++ .OO...... ", -"++++++++ .OO...... oooooooooooo ", -" .OO...... oooooooooooo ", -" XXXXXXX .OO...... oOOooooooooo ", -" XXXXXXX .OO...... oOOooooooooo ", -" XOOXXXX ......... oOOooooooooo ", -" XOOXXXX ......... oOOooooooooo ", -" XOOXXXX oOOooooooooo ", -" XOOXXXXXXXXX ++++ oOOooooooooo ", -" XOOXXXXXXXXX ++++ oOOooooooooo ", -" XOOXXXXXXXXX ++++ oOOooooooooo ", -" XOOXXXXXXXXX ++++ oooooooooooo ", -" XOOXXXXXXXXX ++++ oooooooooooo ", -" XXXXXXXXXXXX ++++ ", -" XXXXXXXXXXXX ++++++++++++++++++", -" ++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++", -"++++++++++++++++++++++++++++++++" -}; diff --git a/examples/UDP/UDP.sh b/examples/UDP/UDP.sh index 84086f0..6979d63 100644 --- a/examples/UDP/UDP.sh +++ b/examples/UDP/UDP.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/UDP/src/UDP.cpp b/examples/UDP/src/UDP.cpp index b1b2142..b9cb9d8 100644 --- a/examples/UDP/src/UDP.cpp +++ b/examples/UDP/src/UDP.cpp @@ -1,4 +1,6 @@ -#include "ce/ceUtil.h" +#include +#include "ce/ceudp.h" +#include "ce/cemisc.h" using namespace ce; #define CE_TMR_ID1 202 #define CE_UDP_ID1 203 diff --git a/examples/kbhit/kbhit.sh b/examples/kbhit/kbhit.sh index 84086f0..6979d63 100644 --- a/examples/kbhit/kbhit.sh +++ b/examples/kbhit/kbhit.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/kbhit/src/main.cpp b/examples/kbhit/src/main.cpp index 6f0890d..191cfaa 100644 --- a/examples/kbhit/src/main.cpp +++ b/examples/kbhit/src/main.cpp @@ -1,6 +1,5 @@ #include -#include "ce/ceMacros.h" -#include "ce/ceMisc.h" +#include "ce/cemisc.h" #include using namespace std; using namespace ce; diff --git a/examples/kbhit/kbhit/kbhit.sln b/examples/kbhit/vsprj/kbhit.sln similarity index 97% rename from examples/kbhit/kbhit/kbhit.sln rename to examples/kbhit/vsprj/kbhit.sln index df33992..042c6a6 100644 --- a/examples/kbhit/kbhit/kbhit.sln +++ b/examples/kbhit/vsprj/kbhit.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbhit", "kbhit.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbhit", "kbhit.vcxproj", "{669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.ActiveCfg = Debug|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x64.Build.0 = Debug|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.ActiveCfg = Debug|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Debug|x86.Build.0 = Debug|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.ActiveCfg = Release|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x64.Build.0 = Release|x64 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.ActiveCfg = Release|Win32 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BA256B6F-8D89-4E97-99FF-F9D74A38819E} + EndGlobalSection +EndGlobal diff --git a/examples/kbhit/kbhit/kbhit.vcxproj b/examples/kbhit/vsprj/kbhit.vcxproj similarity index 97% rename from examples/kbhit/kbhit/kbhit.vcxproj rename to examples/kbhit/vsprj/kbhit.vcxproj index 10712c1..d898b2d 100644 --- a/examples/kbhit/kbhit/kbhit.vcxproj +++ b/examples/kbhit/vsprj/kbhit.vcxproj @@ -1,162 +1,162 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} - Win32Proj - kbhit - 10.0 - - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - Application - true - v143 - Unicode - - - Application - false - v143 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - - - Level3 - Disabled - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - - - - - - - Level3 - Disabled - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - - - - - - - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - - - Console - true - true - true - - - - - - - Level3 - MaxSpeed - true - true - true - NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - $(SolutionDir)..\..\..\include - - - Console - true - true - true - $(SolutionDir)..\..\..\ceUtil\x64\Release - ceUtil.lib;%(AdditionalDependencies) - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + 16.0 + {669BFB79-DBC4-4DB1-9DFB-B366F8B33ABB} + Win32Proj + kbhit + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + Disabled + true + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_WINDOWS;WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + $(SolutionDir)..\..\..\include + + + Console + true + true + true + $(SolutionDir)..\..\..\ceUtil\x64\Release + ceUtil.lib;%(AdditionalDependencies) + + + + + \ No newline at end of file diff --git a/examples/kbhit/kbhit/kbhit.vcxproj.filters b/examples/kbhit/vsprj/kbhit.vcxproj.filters similarity index 97% rename from examples/kbhit/kbhit/kbhit.vcxproj.filters rename to examples/kbhit/vsprj/kbhit.vcxproj.filters index bf96c1c..1e69fa7 100644 --- a/examples/kbhit/kbhit/kbhit.vcxproj.filters +++ b/examples/kbhit/vsprj/kbhit.vcxproj.filters @@ -1,22 +1,22 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + \ No newline at end of file diff --git a/examples/rsakeygen/rsakeygen.sh b/examples/rsakeygen/rsakeygen.sh index 84086f0..6979d63 100644 --- a/examples/rsakeygen/rsakeygen.sh +++ b/examples/rsakeygen/rsakeygen.sh @@ -1,60 +1,60 @@ -#!/bin/bash - -SCRIPTNAME=`basename "$0"` -PRJNAME="${SCRIPTNAME%.*}" -SCRIPTDIR="${0%/$PRJNAME.*}" -echo "Project: $PRJNAME" -echo "Script directory: $SCRIPTDIR" - -if [ $# == 1 ]; then - opt_sh=$1 -else - echo "You can input argument:" - echo " 'cmake' : to generate cmake files, build, and install" - echo " 'build': to build and run" - echo " ..." - read -p "Input an option: " opt_sh -fi - -if [[ "$opt_sh" == "" ]]; then - opt_sh="build" -fi - -echo "Option: $opt_sh" -echo " ." -echo " ." -echo " ." - -cd $SCRIPTDIR -if [[ "$opt_sh" == "cmake" ]]; then - echo "Preparing cmake file" - if [[ ! -d "./build" ]]; then - mkdir -p build - fi - rm -r ./build/* - cd build - cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=/usr/local \ - .. - cd .. - echo " ." - echo " ." - echo " ." -fi - -if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then - echo "Building ..." - cd $SCRIPTDIR/build && make # && sudo make install - if [[ $? == 0 ]]; then - echo "Build successful" - echo "Running ..." - ./$PRJNAME - else - echo "Error in compiling" - fi -else - echo "Running ..." - ./$PRJNAME -fi - - +#!/bin/bash + +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + +cd $SCRIPTDIR +if [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd $SCRIPTDIR/build && make # && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + echo "Running ..." + ./$PRJNAME + else + echo "Error in compiling" + fi +else + echo "Running ..." + ./$PRJNAME +fi + + diff --git a/examples/rsakeygen/src/rsakeygen.cpp b/examples/rsakeygen/src/rsakeygen.cpp index 84f615c..cb96a9d 100644 --- a/examples/rsakeygen/src/rsakeygen.cpp +++ b/examples/rsakeygen/src/rsakeygen.cpp @@ -1,5 +1,9 @@ #include -#include "ce/ceUtil.h" +#include "ce/cersaos.h" +#include "ce/celog.h" +#include "ce/cemisc.h" +#include + #include using namespace ce; using namespace std; diff --git a/examples/rsakeygen/rsakeygen/public_key.pem b/examples/rsakeygen/vsprj/public_key.pem similarity index 100% rename from examples/rsakeygen/rsakeygen/public_key.pem rename to examples/rsakeygen/vsprj/public_key.pem diff --git a/examples/rsakeygen/rsakeygen/rsakeygen.sln b/examples/rsakeygen/vsprj/rsakeygen.sln similarity index 97% rename from examples/rsakeygen/rsakeygen/rsakeygen.sln rename to examples/rsakeygen/vsprj/rsakeygen.sln index 802a57c..120577c 100644 --- a/examples/rsakeygen/rsakeygen/rsakeygen.sln +++ b/examples/rsakeygen/vsprj/rsakeygen.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rsakeygen", "rsakeygen.vcxproj", "{FF0CBEC6-2040-4D74-9966-7E4530656E20}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.ActiveCfg = Debug|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.Build.0 = Debug|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.ActiveCfg = Debug|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.Build.0 = Debug|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.ActiveCfg = Release|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.Build.0 = Release|x64 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.ActiveCfg = Release|Win32 - {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {963C9ECC-7676-4360-A9B1-A31048A8D673} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rsakeygen", "rsakeygen.vcxproj", "{FF0CBEC6-2040-4D74-9966-7E4530656E20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.ActiveCfg = Debug|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x64.Build.0 = Debug|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.ActiveCfg = Debug|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Debug|x86.Build.0 = Debug|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.ActiveCfg = Release|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x64.Build.0 = Release|x64 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.ActiveCfg = Release|Win32 + {FF0CBEC6-2040-4D74-9966-7E4530656E20}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {963C9ECC-7676-4360-A9B1-A31048A8D673} + EndGlobalSection +EndGlobal diff --git a/examples/rsakeygen/rsakeygen/rsakeygen.vcxproj b/examples/rsakeygen/vsprj/rsakeygen.vcxproj similarity index 98% rename from examples/rsakeygen/rsakeygen/rsakeygen.vcxproj rename to examples/rsakeygen/vsprj/rsakeygen.vcxproj index fef9a65..e2fbbf6 100644 --- a/examples/rsakeygen/rsakeygen/rsakeygen.vcxproj +++ b/examples/rsakeygen/vsprj/rsakeygen.vcxproj @@ -1,138 +1,138 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - {FF0CBEC6-2040-4D74-9966-7E4530656E20} - rsakeygen - 10.0 - - - - Application - true - v143 - MultiByte - - - Application - false - v143 - true - MultiByte - - - Application - true - v143 - MultiByte - - - Application - false - v143 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - - - Console - - - - - Level3 - Disabled - true - true - $(SolutionDir)..\..\..\include; - - - Console - ceUtil.lib;%(AdditionalDependencies) - $CEDIR\ceutil\x64\Debug;%(AdditionalLibraryDirectories) - - - - - Level3 - MaxSpeed - true - true - true - true - - - Console - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) - WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - Console - true - true - $CEDIR\ceutil\x64\Release;%(AdditionalLibraryDirectories) - ceutil.lib;%(AdditionalDependencies) - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + {FF0CBEC6-2040-4D74-9966-7E4530656E20} + rsakeygen + 10.0 + + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + Application + true + v143 + MultiByte + + + Application + false + v143 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + + + Console + + + + + Level3 + Disabled + true + true + $(SolutionDir)..\..\..\include; + + + Console + ceUtil.lib;%(AdditionalDependencies) + $CEDIR\ceutil\x64\Debug;%(AdditionalLibraryDirectories) + + + + + Level3 + MaxSpeed + true + true + true + true + + + Console + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + $(SolutionDir)..\..\..\include;%(AdditionalIncludeDirectories) + WXUSINGDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + Console + true + true + $CEDIR\ceutil\x64\Release;%(AdditionalLibraryDirectories) + ceutil.lib;%(AdditionalDependencies) + + + + + + + + \ No newline at end of file diff --git a/examples/tcpclient/src/tcpclient.cpp b/examples/tcpclient/src/tcpclient.cpp index f5bd547..66f0b1c 100644 --- a/examples/tcpclient/src/tcpclient.cpp +++ b/examples/tcpclient/src/tcpclient.cpp @@ -11,7 +11,8 @@ // [2] Julian Smart and Kevin Hock, "Cross-Platform GUI Programming with wxWidgets," // Pearson Education, Inc. 2006. ISBN: 0-13-147381-6. -#include "ce/ceUtil.h" +#include "ce/cetcpcli.h" +#include "ce/cemisc.h" using namespace ce; // IDs for the controls and the menu commandscm enum diff --git a/examples/tcpsvr/src/tcpsvr.cpp b/examples/tcpsvr/src/tcpsvr.cpp index 9d958f8..8260978 100644 --- a/examples/tcpsvr/src/tcpsvr.cpp +++ b/examples/tcpsvr/src/tcpsvr.cpp @@ -12,7 +12,7 @@ // Pearson Education, Inc. 2006. ISBN: 0-13-147381-6. #include "ce/cetcpsvr.h" -#include "ce/ceMisc.h" +#include "ce/cemisc.h" // #include "myicon.xpm" using namespace ce; diff --git a/include/ce/celog.h b/include/ce/celog.h index 02dbf41..d34a1fd 100644 --- a/include/ce/celog.h +++ b/include/ce/celog.h @@ -282,7 +282,7 @@ inline void ceLog::ReadDir(const std::string& name, std::vector& v) } } #else -inline void ceLog::ReadDir(const string& name, vector& v) +inline void ceLog::ReadDir(const std::string& name, std::vector& v) { DIR* dirp = opendir(name.c_str()); struct dirent* dp; diff --git a/include/ce/cetcpcli.h b/include/ce/cetcpcli.h index 0c5cb6f..e6b4d4f 100644 --- a/include/ce/cetcpcli.h +++ b/include/ce/cetcpcli.h @@ -50,7 +50,6 @@ #include #include "wx/wx.h" #include "wx/socket.h" -#include "ce/ceMisc.h" // utilities // this example is currently written to use only IP or only IPv4 sockets, it // should be extended to allow using either in the future //#if wxUSE_IPV6 @@ -246,7 +245,7 @@ inline int ceTcpClient::Tx(std::vector bv) txn = n; } else { - PrintLog("Tx: " + ceMisc::cvec2hex(bv)); + // PrintLog("Tx: " + ceMisc::cvec2hex(bv)); } } return int(txn); diff --git a/include/ce/cewxcvmiscx.h b/include/ce/cewxcvmisc.h similarity index 100% rename from include/ce/cewxcvmiscx.h rename to include/ce/cewxcvmisc.h diff --git a/test.sh b/test.sh index 599740f..97409a5 100644 --- a/test.sh +++ b/test.sh @@ -1,12 +1,12 @@ -#!/bin/bash -cd test -if [[ ! -d "./build" ]]; then - mkdir -p build -fi -rm -r ./build/* -cmake -B ./build -S . -DCMAKE_BUILD_TYPE=Release -cmake --build ./build --config Release -cd build -ctest -N -ctest --verbose -C Release -cd .. +#!/bin/bash +cd test +if [[ ! -d "./build" ]]; then + mkdir -p build +fi +rm -r ./build/* +cmake -B ./build -S . -DCMAKE_BUILD_TYPE=Release +cmake --build ./build --config Release +cd build +ctest -N +ctest --verbose -C Release +cd .. diff --git a/test/testDES/main.cpp b/test/testDES/main.cpp index 814082f..8ecac28 100644 --- a/test/testDES/main.cpp +++ b/test/testDES/main.cpp @@ -9,8 +9,8 @@ #include #include #include -#include "ce/ceDES.h" -#include "ce/ceMisc.h" +#include "ce/cedes.h" +#include "ce/cemisc.h" using namespace std; using namespace ce; int main() { diff --git a/test/testJson/main.cpp b/test/testJson/main.cpp index f5bb70b..58fd8f3 100644 --- a/test/testJson/main.cpp +++ b/test/testJson/main.cpp @@ -9,7 +9,7 @@ #include #include #include -#include "ce/ceConfig.h" +#include "ce/ceconf.h" using namespace std; using namespace ce; int main() { diff --git a/test/testRSA_OS/main.cpp b/test/testRSA_OS/main.cpp index 8375231..c916743 100644 --- a/test/testRSA_OS/main.cpp +++ b/test/testRSA_OS/main.cpp @@ -9,8 +9,8 @@ #include #include #include -#include "ce/ceRSA_OS.h" -#include "ce/ceMisc.h" +#include "ce/cersaos.h" +#include "ce/cemisc.h" using namespace std; using namespace ce; // ---------------------------------------------------------------------------- diff --git a/test/testSHA1/main.cpp b/test/testSHA1/main.cpp index 656c7fa..f171e0b 100644 --- a/test/testSHA1/main.cpp +++ b/test/testSHA1/main.cpp @@ -9,8 +9,8 @@ #include #include #include -#include "ce/ceSHA1.h" -#include "ce/ceMisc.h" +#include "ce/cesha1.h" +#include "ce/cemisc.h" using namespace std; using namespace ce; int main() { diff --git a/vcprj/ceutil.sln b/vcprj/ceutil.sln index c029e36..a724365 100644 --- a/vcprj/ceutil.sln +++ b/vcprj/ceutil.sln @@ -1,31 +1,31 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29503.13 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ceutil", "ceutil.vcxproj", "{5397B256-872B-44E9-A100-8EE02B070E5A}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5397B256-872B-44E9-A100-8EE02B070E5A}.Debug|x64.ActiveCfg = Debug|x64 - {5397B256-872B-44E9-A100-8EE02B070E5A}.Debug|x64.Build.0 = Debug|x64 - {5397B256-872B-44E9-A100-8EE02B070E5A}.Debug|x86.ActiveCfg = Debug|Win32 - {5397B256-872B-44E9-A100-8EE02B070E5A}.Debug|x86.Build.0 = Debug|Win32 - {5397B256-872B-44E9-A100-8EE02B070E5A}.Release|x64.ActiveCfg = Release|x64 - {5397B256-872B-44E9-A100-8EE02B070E5A}.Release|x64.Build.0 = Release|x64 - {5397B256-872B-44E9-A100-8EE02B070E5A}.Release|x86.ActiveCfg = Release|Win32 - {5397B256-872B-44E9-A100-8EE02B070E5A}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {62E0A6B7-C4BF-43D4-AD01-6EBD678CD8C4} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34330.188 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ceutil", "ceutil.vcxproj", "{5397B256-872B-44E9-A100-8EE02B070E5A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5397B256-872B-44E9-A100-8EE02B070E5A}.Debug|x64.ActiveCfg = Debug|x64 + {5397B256-872B-44E9-A100-8EE02B070E5A}.Debug|x64.Build.0 = Debug|x64 + {5397B256-872B-44E9-A100-8EE02B070E5A}.Debug|x86.ActiveCfg = Debug|Win32 + {5397B256-872B-44E9-A100-8EE02B070E5A}.Debug|x86.Build.0 = Debug|Win32 + {5397B256-872B-44E9-A100-8EE02B070E5A}.Release|x64.ActiveCfg = Release|x64 + {5397B256-872B-44E9-A100-8EE02B070E5A}.Release|x64.Build.0 = Release|x64 + {5397B256-872B-44E9-A100-8EE02B070E5A}.Release|x86.ActiveCfg = Release|Win32 + {5397B256-872B-44E9-A100-8EE02B070E5A}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {62E0A6B7-C4BF-43D4-AD01-6EBD678CD8C4} + EndGlobalSection +EndGlobal diff --git a/vcprj/ceutil.vcxproj b/vcprj/ceutil.vcxproj index 278958c..7f63e05 100644 --- a/vcprj/ceutil.vcxproj +++ b/vcprj/ceutil.vcxproj @@ -38,9 +38,6 @@ - - - diff --git a/vcprj/ceutil.vcxproj.filters b/vcprj/ceutil.vcxproj.filters index f3848ca..c8fda15 100644 --- a/vcprj/ceutil.vcxproj.filters +++ b/vcprj/ceutil.vcxproj.filters @@ -73,11 +73,6 @@ Header Files - - - Source Files - - etc From 88981a4b48a84cb81fdc320eace097239ee869aa Mon Sep 17 00:00:00 2001 From: yan9a Date: Mon, 26 Aug 2024 10:53:19 +1200 Subject: [PATCH 07/10] Update cmake --- CMakeLists.txt | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index af00bf6..af8287b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,11 +57,22 @@ if(ADDCV) endif() message(STATUS "List of libraries = ${LIBS}") include_directories(${PROJECT_SOURCE_DIR}/include) -add_library(${PROJECT_NAME} +# add_library(${PROJECT_NAME} + +# ) +# target_link_libraries(${PROJECT_NAME} ${LIBS}) +# install(TARGETS ${PROJECT_NAME} DESTINATION lib) + +add_subdirectory(examples/I2C) +add_subdirectory(examples/kbhit) +add_subdirectory(examples/Log) +add_subdirectory(examples/Modbus) +# add_subdirectory(examples/rsakeygen) +add_subdirectory(examples/Serial) +add_subdirectory(examples/tcpclient) +add_subdirectory(examples/tcpsvr) +add_subdirectory(examples/UDP) -) -target_link_libraries(${PROJECT_NAME} ${LIBS}) -install(TARGETS ${PROJECT_NAME} DESTINATION lib) install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/ce DESTINATION include FILES_MATCHING From 78f285285cac4787a470b5a17a1491d817856697 Mon Sep 17 00:00:00 2001 From: yan9a Date: Mon, 26 Aug 2024 11:14:42 +1200 Subject: [PATCH 08/10] Update cmake --- CMakeLists.txt | 2 +- CMakeM1.txt | 1 - README.md | 14 ++----- ceutil.sh | 102 ++++++++++++++++++++++++++++++++++++++++++++++++- ceutilw.bat | 14 ++++++- 5 files changed, 117 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index af8287b..f4a1467 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.0.0) +cmake_minimum_required(VERSION 3.5.0) project (ceutil VERSION 2.1.3) # version 1.0.0 Added DES, SHA, RSA # version 2.0.0 Replace wxAppConsole with wxEvtHandler, add TCP server, header only diff --git a/CMakeM1.txt b/CMakeM1.txt index 954a685..bb58a3a 100644 --- a/CMakeM1.txt +++ b/CMakeM1.txt @@ -49,7 +49,6 @@ else() endif() # ------------------------------------------------------------------ set(LIBS - ceutil ${JSONCPP_LIBRARIES} ${wxWidgets_LIBRARIES} OpenSSL::SSL OpenSSL::Crypto diff --git a/README.md b/README.md index 67a9725..242d123 100644 --- a/README.md +++ b/README.md @@ -11,10 +11,10 @@ If you want to use wxIPV6address for it, you can modify IPAddress definition in ## Linux Setup -After cloning the repository, you can use the following command to install the library. +After cloning the repository, you can use the following command to install the library. It basically copies header files to /usr/local/include cd ceutil - ./ceutil.sh install + ./ceutil.sh If you encounter problems such as "bad interpreter" in running the script, especially when you copied the files from a Windows system, you can try to fix line end and change its mode to be executable as follows. @@ -115,18 +115,10 @@ for other options. #### Installed Location -Compiled library will be installed under - - "$(VCPKG_ROOT)\installed\x64-windows\lib" - -under respective configuration. It will also install the include files under +The include files are installed under "$(VCPKG_ROOT)\installed\x64-windows\include". ### Open an Example Project After setting up the requried libraries, you can now open an example solution in examples directory of the cloned repository. - -### Docker - -Docker image 'yan9a/cebian' has all the required libraries for ceutil setup. Its Dockerfile can also be found in the root folder. \ No newline at end of file diff --git a/ceutil.sh b/ceutil.sh index 804d857..696ea0c 100644 --- a/ceutil.sh +++ b/ceutil.sh @@ -4,5 +4,103 @@ # sed -i -e 's/\r$//' ceutil.sh # chmod +x ceutil.sh -# install ce header files in /usr/local/include -sudo cp -r include/ce /usr/local/include \ No newline at end of file +SCRIPTNAME=`basename "$0"` +PRJNAME="${SCRIPTNAME%.*}" +SCRIPTDIR="${0%/$PRJNAME.*}" +echo "Project: $PRJNAME" +echo "Script directory: $SCRIPTDIR" + +opt_sh="build" + +if [ $# == 1 ]; then + opt_sh=$1 +else + echo "You can input argument:" + echo " 'install' : to install prerequisite packages, generate cmake files, build and install the header files" + echo " 'cmake' : to generate cmake files, build, and install" + echo " 'build': to build and run" + echo " ..." + read -p "Input an option: " opt_sh +fi + +if [[ "$opt_sh" == "" ]]; then + opt_sh="build" +fi + +echo "Option: $opt_sh" +echo " ." +echo " ." +echo " ." + + +if [[ "$opt_sh" == "install" ]]; then + # add the user to groups + opt_au="y" + read -p "Do you want to add current user to netdev and dialout groups [y/N]?: " opt_au + if [ $opt_au == "y" ] || [ $opt_au == "Y" ]; then + echo "Adding $USER to groups" + sudo usermod -a -G netdev $USER + sudo usermod -a -G dialout $USER + fi + opt_reqlib="y" + read -p "Do you want to install required libraries [y/N]?: " opt_reqlib + if [ $opt_reqlib == "y" ] || [ $opt_reqlib == "Y" ]; then + # install required lib + echo "Installing required lib ..." + sudo apt update \ + && sudo apt install --no-install-recommends --no-install-suggests -y build-essential cmake cmake-extras gdb\ + libgtk-3-dev checkinstall libwxgtk3.0-gtk3-dev \ + git pkg-config libavcodec-dev libavformat-dev libswscale-dev libopencv-dev \ + libjsoncpp-dev apt-transport-https ca-certificates \ + autoconf automake libtool gdb cmake-extras \ + libssl-dev openssl + fi + echo " ." + echo " ." + echo " ." +fi # lib + +cd $SCRIPTDIR +if [[ "$opt_sh" == "install" ]] || [[ "$opt_sh" == "cmake" ]]; then + echo "Preparing cmake file" + if [[ ! -d "./build" ]]; then + mkdir -p build + fi + rm -r ./build/* + cd build + cmake -D CMAKE_BUILD_TYPE=Release \ + -D BUILD_SHARED_LIBS=ON \ + -D CMAKE_INSTALL_PREFIX=/usr/local \ + .. + cd .. + echo " ." + echo " ." + echo " ." +fi + +if [[ $opt_sh == "install" ]] || [[ $opt_sh == "cmake" ]] || [[ $opt_sh == "build" ]]; then + echo "Building ..." + cd build && make && sudo make install + if [[ $? == 0 ]]; then + echo "Build successful" + # ls -l *ceutil.so + # ldd *ceutil.so + # ls -l *$ceutil.a + # ar -t *$ceutil.a + else + echo "Error in compiling" + fi +else + echo "Invalid option for $PRJNAME ..." +fi + +# if [[ "$opt_sh" == "install" ]]; then +# echo "Configuring lib path ..." +# sudo sh -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/ceutil.conf" +# sudo ldconfig +# echo " ." +# echo " ." +# echo " ." +# fi # config + + diff --git a/ceutilw.bat b/ceutilw.bat index 83d56b2..1d02e91 100644 --- a/ceutilw.bat +++ b/ceutilw.bat @@ -1,3 +1,15 @@ @REM To run the script set VCPKG_ROOT environmental variable for vcpkg root folder +if exist buildw ( +echo deleting +rmdir /s /q buildw +) +cmake -G "Visual Studio 17 2022" -A x64 -B ./buildw -S ./ -DCMAKE_TOOLCHAIN_FILE="%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake" -DCMAKE_INSTALL_PREFIX="%VCPKG_ROOT%/installed/x64-windows/" -DCMAKE_DEBUG_POSTFIX=d +cd buildw +cmake --build . --config Release +cmake --install . --config Release +cmake --build . --config Debug +cmake --install . --config Debug -xcopy ".\include" "%VCPKG_ROOT%\installed\x64-windows\include" /E /H /C /I /Y +cd .. + +@xcopy ".\include" "%VCPKG_ROOT%\installed\x64-windows\include" /E /H /C /I /Y From 58a0fd2846d430de78a4c3bd8a9d9fc05197fa80 Mon Sep 17 00:00:00 2001 From: yan9a Date: Mon, 26 Aug 2024 11:27:42 +1200 Subject: [PATCH 09/10] Update cmake --- CMakeLists.txt | 2 +- examples/CMakeLists.txt | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f4a1467..af8287b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5.0) +cmake_minimum_required(VERSION 3.0.0) project (ceutil VERSION 2.1.3) # version 1.0.0 Added DES, SHA, RSA # version 2.0.0 Replace wxAppConsole with wxEvtHandler, add TCP server, header only diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index f4b5e91..714a0d5 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -2,14 +2,17 @@ cmake_minimum_required(VERSION 3.0.0) project (ceutileg) message(STATUS "Base dir = ${CMAKE_SOURCE_DIR}") +add_subdirectory(I2C) +add_subdirectory(kbhit) add_subdirectory(Log) add_subdirectory(Modbus) -add_subdirectory(ModbusCmd) add_subdirectory(Serial) -add_subdirectory(SerialGui) -add_subdirectory(Timer) add_subdirectory(UDP) -add_subdirectory(WxSerial) +# add_subdirectory(rsakeygen) +add_subdirectory(tcpclient) +add_subdirectory(tcpsvr) +add_subdirectory(UDP) + if(WIN32) else() From 8ac453f86dffa32a517a6eff11177bb0fe790278 Mon Sep 17 00:00:00 2001 From: yan9a Date: Mon, 26 Aug 2024 11:31:05 +1200 Subject: [PATCH 10/10] Update workflow --- .github/workflows/cmake.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index b76fe72..0975cbd 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -49,9 +49,9 @@ jobs: # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail run: ctest -C ${{env.BUILD_TYPE}} - - name: Configure CMake for examples - run: cmake -B ${{env.WS_DIR}}/examples/build -S ${{env.WS_DIR}}/examples -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} + # - name: Configure CMake for examples + # run: cmake -B ${{env.WS_DIR}}/examples/build -S ${{env.WS_DIR}}/examples -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} - - name: Build examples - # Build your program with the given configuration - run: cmake --build ${{env.WS_DIR}}/examples/build --config ${{env.BUILD_TYPE}} \ No newline at end of file + # - name: Build examples + # # Build your program with the given configuration + # run: cmake --build ${{env.WS_DIR}}/examples/build --config ${{env.BUILD_TYPE}} \ No newline at end of file