.gradle/
import-summary.txt
app/build/
+app/debug/
+app/.cxx/
+app/src/main/obj/
180 298 629212657 D:/workspace/AG3335/ag3335m_download_demo/app/src/main/libs/armeabi-v7a/libag3335m_jni.so cd54a85d3f95cd9c
3 166 629212765 CMakeFiles/ag3335m_jni.dir/gps_hardware.c.o 5030b5dc47b1ded0
166 278 629212765 D:/workspace/AG3335/ag3335m_download_demo/app/src/main/libs/armeabi-v7a/libag3335m_jni.so cd54a85d3f95cd9c
+4 145 629284464 CMakeFiles/ag3335m_jni.dir/native-lib.c.o d65a650a7422a54
+10 285 629284464 CMakeFiles/ag3335m_jni.dir/gps_hardware.c.o 5030b5dc47b1ded0
+285 478 629284464 D:/workspace/AG3335/ag3335m_download_demo/app/src/main/libs/armeabi-v7a/libag3335m_jni.so cd54a85d3f95cd9c
+0 12 0 clean 90041b927f7328d8
+3 178 629284489 CMakeFiles/ag3335m_jni.dir/native-lib.c.o d65a650a7422a54
+10 258 629284489 CMakeFiles/ag3335m_jni.dir/gps_hardware.c.o 5030b5dc47b1ded0
+258 410 629284489 D:/workspace/AG3335/ag3335m_download_demo/app/src/main/libs/armeabi-v7a/libag3335m_jni.so cd54a85d3f95cd9c
+3 164 629284556 CMakeFiles/ag3335m_jni.dir/gps_hardware.c.o 5030b5dc47b1ded0
+164 288 629284557 D:/workspace/AG3335/ag3335m_download_demo/app/src/main/libs/armeabi-v7a/libag3335m_jni.so cd54a85d3f95cd9c
+0 14 0 clean 90041b927f7328d8
+5 255 629293022 CMakeFiles/ag3335m_jni.dir/native-lib.c.o d65a650a7422a54
+19 342 629293023 CMakeFiles/ag3335m_jni.dir/gps_hardware.c.o 5030b5dc47b1ded0
+342 556 629293023 D:/workspace/AG3335/ag3335m_download_demo/app/src/main/libs/armeabi-v7a/libag3335m_jni.so cd54a85d3f95cd9c
"project": {
"compilerSettingsCacheFolder": "D:\\workspace\\AG3335\\ag3335m_download_demo\\.cxx",
"cxxFolder": "D:\\workspace\\AG3335\\ag3335m_download_demo\\.cxx",
+ "ideBuildTargetAbi": "armeabi-v7a,armeabi",
"isBuildOnlyTargetAbiEnabled": true,
"isCmakeBuildCohabitationEnabled": false,
"isNativeCompilerSettingsCacheEnabled": false,
},
{
"level": "INFO",
- "message": "- CMake found in SDK at \u0027C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\cmake\\3.10.2.4988404\u0027 had version \u00273.10.2\u0027",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "rebuilding JSON D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\.cxx\\cmake\\release\\armeabi-v7a\\android_gradle_build.json due to:",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "- command changed from previous, will remove stale json folder",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\24.0.1\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "removing stale contents from \u0027D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\.cxx\\cmake\\release\\armeabi-v7a\u0027",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\25.0.1\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "created folder \u0027D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\.cxx\\cmake\\release\\armeabi-v7a\u0027",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\26.0.2\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "executing cmake Executable : C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\cmake\\3.10.2.4988404\\bin\\cmake.exe\narguments : \n-HD:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\n-DCMAKE_FIND_ROOT_PATH\u003dD:\\workspace\\AG3335\\ag3335m_download_demo\\app\\.cxx\\cmake\\release\\prefab\\armeabi-v7a\\prefab\n-DCMAKE_BUILD_TYPE\u003dRelease\n-DCMAKE_TOOLCHAIN_FILE\u003dC:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\ndk\\20.1.5948944\\build\\cmake\\android.toolchain.cmake\n-DANDROID_ABI\u003darmeabi-v7a\n-DANDROID_NDK\u003dC:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\ndk\\20.1.5948944\n-DANDROID_PLATFORM\u003dandroid-19\n-DCMAKE_ANDROID_ARCH_ABI\u003darmeabi-v7a\n-DCMAKE_ANDROID_NDK\u003dC:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\ndk\\20.1.5948944\n-DCMAKE_EXPORT_COMPILE_COMMANDS\u003dON\n-DCMAKE_LIBRARY_OUTPUT_DIRECTORY\u003dD:\\workspace\\AG3335\\ag3335m_download_demo\\app\\build\\intermediates\\cmake\\release\\obj\\armeabi-v7a\n-DCMAKE_MAKE_PROGRAM\u003dC:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\cmake\\3.10.2.4988404\\bin\\ninja.exe\n-DCMAKE_SYSTEM_NAME\u003dAndroid\n-DCMAKE_SYSTEM_VERSION\u003d19\n-BD:\\workspace\\AG3335\\ag3335m_download_demo\\app\\.cxx\\cmake\\release\\armeabi-v7a\n-GNinja\njvmArgs : \n\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\27.0.3\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\28.0.0\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "[\u003d\u003d \"CMake Server\" \u003d\u003d[\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\28.0.2\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"supportedProtocolVersions\":[{\"isExperimental\":true,\"major\":1,\"minor\":1}],\"type\":\"hello\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\28.0.3\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "]\u003d\u003d \"CMake Server\" \u003d\u003d]\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\29.0.2\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\n \"type\": \"handshake\",\n \"cookie\": \"gradle-cmake-cookie\",\n \"protocolVersion\": {\n \"isExperimental\": true,\n \"major\": 1,\n \"minor\": 1\n },\n \"sourceDirectory\": \"D:/workspace/AG3335/ag3335m_download_demo/app/src/main/jni\",\n \"buildDirectory\": \"D:/workspace/AG3335/ag3335m_download_demo/app/.cxx/cmake/release/armeabi-v7a\",\n \"generator\": \"Ninja\"\n}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\build-tools\\29.0.3\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"gradle-cmake-cookie\",\"inReplyTo\":\"handshake\",\"type\":\"reply\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\cmake\\3.10.2.4988404\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\n \"type\": \"configure\",\n \"cacheArguments\": [\n \"\",\n \"-DCMAKE_FIND_ROOT_PATH\\u003dD:\\\\workspace\\\\AG3335\\\\ag3335m_download_demo\\\\app\\\\.cxx\\\\cmake\\\\release\\\\prefab\\\\armeabi-v7a\\\\prefab\",\n \"-DCMAKE_BUILD_TYPE\\u003dRelease\",\n \"-DCMAKE_TOOLCHAIN_FILE\\u003dC:\\\\Users\\\\incar\\\\AppData\\\\Local\\\\Android\\\\Sdk\\\\ndk\\\\20.1.5948944\\\\build\\\\cmake\\\\android.toolchain.cmake\",\n \"-DANDROID_ABI\\u003darmeabi-v7a\",\n \"-DANDROID_NDK\\u003dC:\\\\Users\\\\incar\\\\AppData\\\\Local\\\\Android\\\\Sdk\\\\ndk\\\\20.1.5948944\",\n \"-DANDROID_PLATFORM\\u003dandroid-19\",\n \"-DCMAKE_ANDROID_ARCH_ABI\\u003darmeabi-v7a\",\n \"-DCMAKE_ANDROID_NDK\\u003dC:\\\\Users\\\\incar\\\\AppData\\\\Local\\\\Android\\\\Sdk\\\\ndk\\\\20.1.5948944\",\n \"-DCMAKE_EXPORT_COMPILE_COMMANDS\\u003dON\",\n \"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY\\u003dD:\\\\workspace\\\\AG3335\\\\ag3335m_download_demo\\\\app\\\\build\\\\intermediates\\\\cmake\\\\release\\\\obj\\\\armeabi-v7a\",\n \"-DCMAKE_MAKE_PROGRAM\\u003dC:\\\\Users\\\\incar\\\\AppData\\\\Local\\\\Android\\\\Sdk\\\\cmake\\\\3.10.2.4988404\\\\bin\\\\ninja.exe\",\n \"-DCMAKE_SYSTEM_NAME\\u003dAndroid\",\n \"-DCMAKE_SYSTEM_VERSION\\u003d19\"\n ]\n}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\emulator\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Check for working C compiler: C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/bin/clang.exe\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\extras\\android\\m2repository\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Check for working C compiler: C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/bin/clang.exe",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\extras\\google\\m2repository\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":33,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\extras\\intel\\Hardware_Accelerated_Execution_Manager\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Check for working C compiler: C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/bin/clang.exe -- works\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\extras\\m2repository\\com\\android\\support\\constraint\\constraint-layout-solver\\1.0.2\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Check for working C compiler: C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/bin/clang.exe -- works",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\extras\\m2repository\\com\\android\\support\\constraint\\constraint-layout\\1.0.2\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Detecting C compiler ABI info\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\ndk\\20.0.5594570\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Detecting C compiler ABI info",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\ndk\\20.1.5948944\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":65,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\ndk\\21.1.6352462\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Detecting C compiler ABI info - done\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\patcher\\v4\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Detecting C compiler ABI info - done",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platform-tools\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Detecting C compile features\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platforms\\android-18\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Detecting C compile features",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platforms\\android-19\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":96,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platforms\\android-20\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":126,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platforms\\android-23\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":155,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platforms\\android-25\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Detecting C compile features - done\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platforms\\android-27\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Detecting C compile features - done",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platforms\\android-28\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Check for working CXX compiler: C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/bin/clang++.exe\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\platforms\\android-29\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Check for working CXX compiler: C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/bin/clang++.exe",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\sources\\android-19\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":184,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\sources\\android-20\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Check for working CXX compiler: C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/bin/clang++.exe -- works\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\sources\\android-25\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Check for working CXX compiler: C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/bin/clang++.exe -- works",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\sources\\android-27\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Detecting CXX compiler ABI info\",\"type\":\"message\"}\n",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\system-images\\android-19\\default\\armeabi-v7a\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "Detecting CXX compiler ABI info",
+ "message": "Parsing C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\tools\\package.xml",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":211,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Detecting CXX compiler ABI info - done\",\"type\":\"message\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "Detecting CXX compiler ABI info - done",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Detecting CXX compile features\",\"type\":\"message\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "Detecting CXX compile features",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":237,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":262,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":287,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":311,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Detecting CXX compile features - done\",\"type\":\"message\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "Detecting CXX compile features - done",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"progressCurrent\":1000,\"progressMaximum\":1000,\"progressMessage\":\"Configuring\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"message\":\"Configuring done\",\"type\":\"message\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "Configuring done",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"configure\",\"type\":\"reply\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"type\":\"compute\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"compute\",\"progressCurrent\":1000,\"progressMaximum\":1000,\"progressMessage\":\"Generating\",\"progressMinimum\":0,\"type\":\"progress\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"compute\",\"message\":\"Generating done\",\"type\":\"message\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "Generating done",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"cookie\":\"\",\"inReplyTo\":\"compute\",\"type\":\"reply\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"type\":\"cmakeInputs\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"buildFiles\":[{\"isCMake\":true,\"isTemporary\":false,\"sources\":[\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineSystem.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android-Determine.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeSystem.cmake.in\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeSystemSpecificInitialize.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android-Initialize.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineCCompiler.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineCompiler.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android-Determine-C.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android/Determine-Compiler.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeFindBinUtils.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-FindBinUtils.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCCompiler.cmake.in\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineCXXCompiler.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineCompiler.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android-Determine-CXX.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android/Determine-Compiler.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeFindBinUtils.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-FindBinUtils.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCXXCompiler.cmake.in\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeSystemSpecificInformation.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeGenericSystem.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Linux.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/UnixPaths.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCInformation.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeLanguageInformation.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-C.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/CMakeCommonCompilerMacros.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/GNU.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/CMakeCommonCompilerMacros.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android-Clang-C.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android-Clang.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCommonLanguageInclude.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeTestCCompiler.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeTestCompilerCommon.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineCompilerABI.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeParseImplicitLinkInfo.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCCompilerABI.c\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineCompileFeatures.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Internal/FeatureTesting.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-C-FeatureTests.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-C-FeatureTests.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-C-FeatureTests.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCCompiler.cmake.in\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCXXInformation.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeLanguageInformation.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android-Clang-CXX.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Platform/Android-Clang.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCommonLanguageInclude.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeTestCXXCompiler.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeTestCompilerCommon.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineCompilerABI.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeParseImplicitLinkInfo.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeDetermineCompileFeatures.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Internal/FeatureTesting.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX-FeatureTests.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX-TestableFeatures.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX-FeatureTests.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX-TestableFeatures.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX-FeatureTests.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX-TestableFeatures.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX-FeatureTests.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/Compiler/Clang-CXX-TestableFeatures.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10/Modules/CMakeCXXCompiler.cmake.in\"]},{\"isCMake\":false,\"isTemporary\":false,\"sources\":[\"CMakeLists.txt\",\"C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/build/cmake/android.toolchain.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/build/cmake/platforms.cmake\",\"C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/build/cmake/android.toolchain.cmake\"]},{\"isCMake\":false,\"isTemporary\":true,\"sources\":[\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/3.10.2/CMakeSystem.cmake\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/3.10.2/CMakeCCompiler.cmake\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/3.10.2/CMakeCXXCompiler.cmake\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/feature_tests.c\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/feature_tests.c\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/feature_tests.c\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/3.10.2/CMakeCCompiler.cmake\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/feature_tests.cxx\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/feature_tests.cxx\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/feature_tests.cxx\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/feature_tests.cxx\",\"../../../.cxx/cmake/release/armeabi-v7a/CMakeFiles/3.10.2/CMakeCXXCompiler.cmake\"]}],\"cmakeRootDirectory\":\"C:/Users/incar/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/share/cmake-3.10\",\"cookie\":\"\",\"inReplyTo\":\"cmakeInputs\",\"sourceDirectory\":\"D:/workspace/AG3335/ag3335m_download_demo/app/src/main/jni\",\"type\":\"reply\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"type\":\"codemodel\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "{\"configurations\":[{\"name\":\"Release\",\"projects\":[{\"buildDirectory\":\"D:/workspace/AG3335/ag3335m_download_demo/app/.cxx/cmake/release/armeabi-v7a\",\"name\":\"Project\",\"sourceDirectory\":\"D:/workspace/AG3335/ag3335m_download_demo/app/src/main/jni\",\"targets\":[{\"artifacts\":[\"D:/workspace/AG3335/ag3335m_download_demo/app/src/main/libs/armeabi-v7a/libag3335m_jni.so\"],\"buildDirectory\":\"D:/workspace/AG3335/ag3335m_download_demo/app/.cxx/cmake/release/armeabi-v7a\",\"fileGroups\":[{\"compileFlags\":\"-g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -fno-addrsig -march\u003darmv7-a -mthumb -Wa,--noexecstack -Wformat -Werror\u003dformat-security -Oz -DNDEBUG -fPIC \",\"defines\":[\"ag3335m_jni_EXPORTS\"],\"isGenerated\":false,\"language\":\"C\",\"sources\":[\"native-lib.c\",\"gps_hardware.c\"]}],\"fullName\":\"libag3335m_jni.so\",\"linkFlags\":\"-Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libatomic.a -static-libstdc++ -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--exclude-libs,libunwind.a -Wl,--no-undefined -Qunused-arguments -Wl,-z,noexecstack\",\"linkLibraries\":\"-llog -latomic -lm\",\"linkerLanguage\":\"C\",\"name\":\"ag3335m_jni\",\"sourceDirectory\":\"D:/workspace/AG3335/ag3335m_download_demo/app/src/main/jni\",\"sysroot\":\"C:/Users/incar/AppData/Local/Android/Sdk/ndk/20.1.5948944/toolchains/llvm/prebuilt/windows-x86_64/sysroot\",\"type\":\"SHARED_LIBRARY\"}]}]}],\"cookie\":\"\",\"inReplyTo\":\"codemodel\",\"type\":\"reply\"}\n",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "done executing cmake",
- "file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
- "tag": "release|armeabi-v7a"
- },
- {
- "level": "INFO",
- "message": "write build output D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\.cxx\\cmake\\release\\armeabi-v7a\\build_output.txt",
+ "message": "- CMake found in SDK at \u0027C:\\Users\\incar\\AppData\\Local\\Android\\Sdk\\cmake\\3.10.2.4988404\u0027 had version \u00273.10.2\u0027",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
{
"level": "INFO",
- "message": "write command file D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\.cxx\\cmake\\release\\armeabi-v7a\\build_command.txt",
+ "message": "JSON \u0027D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\.cxx\\cmake\\release\\armeabi-v7a\\android_gradle_build.json\u0027 was up-to-date",
"file": "D:\\workspace\\AG3335\\ag3335m_download_demo\\app\\src\\main\\jni\\CMakeLists.txt",
"tag": "release|armeabi-v7a"
},
version "3.10.2"
}
}
+
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
+++ /dev/null
-{
- "version": 2,
- "artifactType": {
- "type": "APK",
- "kind": "Directory"
- },
- "applicationId": "com.ic.jni",
- "variantName": "processDebugResources",
- "elements": [
- {
- "type": "SINGLE",
- "filters": [],
- "versionCode": 1,
- "versionName": "1.0",
- "outputFile": "app-debug.apk"
- }
- ]
-}
\ No newline at end of file
--- /dev/null
+package com.antu.nmea.annotation;
+
+public class FieldSetting {
+
+ private boolean isRequired;
+
+ private int fieldWidth;
+
+ private int precision;
+
+ private String defaultValue;
+
+ private String groupItemClass;
+
+ public FieldSetting(SentenceField annotation) {
+
+ this.isRequired = annotation.isRequired();
+ this.fieldWidth = annotation.fieldWidth();
+ this.precision = annotation.precision();
+ this.defaultValue = annotation.defaultValue();
+ this.groupItemClass = annotation.groupItemClass();
+ }
+
+ public FieldSetting(MessageField annotation) {
+ this.defaultValue = annotation.defaultValue();
+ this.fieldWidth = annotation.requiredBits();
+ this.groupItemClass = annotation.groupItemClass();
+ }
+
+ public FieldSetting(GroupItem annotation) {
+ this.defaultValue = annotation.defaultValue();
+ this.fieldWidth = annotation.fieldWidth();
+ }
+
+ public boolean isRequired() {
+ return isRequired;
+ }
+
+ public int getFieldWidth() {
+ return fieldWidth;
+ }
+
+ public int getPrecision() {
+ return precision;
+ }
+
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+ public String groupItemClass() {
+ return groupItemClass;
+ }
+}
--- /dev/null
+package com.antu.nmea.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * annotation for items in a group in nmea sentence.
+ * @author yining
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD})
+public @interface GroupItem {
+
+ int order();
+
+ String itemType();
+
+ boolean isRequired() default false;
+
+ String defaultValue() default "";
+
+ int fieldWidth() default 1;
+}
--- /dev/null
+package com.antu.nmea.annotation;
+
+import java.lang.reflect.Field;
+import java.util.Comparator;
+
+public class GroupItemAnnotationSorter implements Comparator<Field> {
+
+ @Override
+ public int compare(Field o1, Field o2) {
+
+ MessageField a = o1.getAnnotation(MessageField.class);
+ MessageField b = o2.getAnnotation(MessageField.class);
+
+ return new Integer(a.order()).compareTo(new Integer(b.order()));
+ }
+}
--- /dev/null
+package com.antu.nmea.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Annotation for encapsulated NMEA sentence fields
+ * @author yining
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD})
+public @interface MessageField {
+
+ int startBit() default -1;
+
+ /**
+ * How many bits this field requires
+ * @return
+ */
+ int requiredBits() default 0;
+
+ /**
+ * Type of the field, used to get MessageFieldCodec.
+ * @return
+ */
+ String fieldType();
+
+ int order();
+
+ boolean isGroup() default false;
+
+ String defaultValue() default "";
+
+ /**
+ * Specifies the full class name of the items in the set
+ * @return
+ */
+ String groupItemClass() default "";
+}
--- /dev/null
+package com.antu.nmea.annotation;
+
+import java.lang.reflect.Field;
+import java.util.Comparator;
+
+public class MessageFieldAnnotationSorter implements Comparator<Field> {
+
+ @Override
+ public int compare(Field o1, Field o2) {
+
+ MessageField a = o1.getAnnotation(MessageField.class);
+ MessageField b = o2.getAnnotation(MessageField.class);
+
+ return new Integer(a.order()).compareTo(new Integer(b.order()));
+ }
+
+}
--- /dev/null
+package com.antu.nmea.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Demarkates a field in the parsed nmea object
+ * @author yining
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD})
+public @interface SentenceField {
+
+ /**
+ * type of the field, this is used by the codec to decode and encode
+ * the fields. if the fullCodecPath is specified, this field is not used.
+ * this field can be used with the packageName field to specify a codec
+ * full class name. by default, the class name is XXXSentenceFieldCodec,
+ * where XXX is replaced by the value of fieldType with the first letter
+ * capitalized. default package is com.antu.nmea.sentence.field.codec
+ *
+ * @return
+ */
+ String fieldType() default "";
+
+ /**
+ * can be used together with the fieldType to specify a custom codec. if
+ * left empty, the default package name for codec is com.antu.nmea.sentence.field.codec.
+ * This field is ignored if fullCodecPath is specified.
+ * @return
+ */
+ String packageName() default "";
+
+ /**
+ * Allows user to specify a full class name for a specific codec.
+ * @return
+ */
+ String fullCodecPath() default "";
+
+ /**
+ * Specifies whether a field is required, if a parsing failure or empty field
+ * is given, this will result in the abandoning of the encoding/decoding process.
+ * @return
+ */
+ boolean isRequired() default true;
+
+ /**
+ * a numeric order for the alignment of the fields, does not have to be continunous,
+ * but has to be in order per nmea spec.
+ * @return
+ */
+ int order();
+
+ /**
+ * specifies whether the item comes in sets. used together with groupItemType
+ * @return
+ */
+ boolean isGroup() default false;
+
+ /**
+ * specifies the type of set, currently only supports "list", which will result in
+ * the generation of a PrintableList
+ * @return
+ */
+ String groupType() default "list";
+
+ /**
+ * Specifies the full class name of the items in the set
+ * @return
+ */
+ String groupItemClass() default "";
+
+ int precision() default 0;
+
+ /**
+ * This is used to form multi and encapsulation sentences to make
+ * sure each sentence does not exceed the 80 char length limit. As well
+ * as for fields that require a specific number of characters, such as 2 chars
+ * for month, etc.
+ * @return
+ */
+ int fieldWidth() default 1;
+
+ /**
+ * One can use this field to indicate a default value when the field is left empty
+ * @return
+ */
+ String defaultValue() default "";
+
+ /**
+ * This is used for sentences that come with group items. When
+ * group items are involved, and there are fields after the group
+ * items to be parsed, this field need to be specified to calculate
+ * the number of items that can go into the group.
+ * @return
+ */
+ int reservedSegments() default 0;
+
+ boolean isIgnoredInReconstruction() default false;
+}
--- /dev/null
+package com.antu.nmea.annotation;
+
+import java.lang.reflect.Field;
+import java.util.Comparator;
+
+public class SentenceFieldAnnotationSorter implements Comparator<Field> {
+
+ @Override
+ public int compare(Field o1, Field o2) {
+
+ SentenceField a = o1.getAnnotation(SentenceField.class);
+ SentenceField b = o2.getAnnotation(SentenceField.class);
+
+ return new Integer(a.order()).compareTo(new Integer(b.order()));
+ }
+
+}
--- /dev/null
+package com.antu.nmea.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * A SentenceMessage annotation is to be used by encapsulated messages.
+ *
+ * As some messages can contain fields with undetermined length, this is required
+ * during encoding/decoding. This is not needed for all encapsulated messages
+ * @author yining
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE})
+public @interface SentenceMessage {
+
+ /**
+ * specifies whether encoding need to pad bits at the end to make total
+ * number of bits multiples of 6
+ * @return
+ */
+ boolean alignBytes() default false;
+}
--- /dev/null
+package com.antu.nmea.annotation.exception;
+
+public class MultipleGroupItemException extends RuntimeException {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -7879896680348549612L;
+
+ public MultipleGroupItemException() {
+ super();
+ }
+
+ public MultipleGroupItemException(String message) {
+ super(message);
+ }
+
+ public MultipleGroupItemException(Throwable cause) {
+ super(cause);
+ }
+
+ public MultipleGroupItemException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public MultipleGroupItemException(String message, Throwable cause,
+ boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.util.Date;
+
+import com.antu.nmea.sentence.AbmSentence;
+import com.antu.nmea.sentence.EncapsulationSentence;
+import com.antu.nmea.sentence.IEncapsulatedSentence;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.ais.IEncapsulatedAisMessage;
+import com.antu.util.GenericFactory;
+
+public class AbmSentenceCodec extends EncapsulationSentenceCodec{
+
+ private GenericFactory<IEncapsulatedAisMessage> factory;
+
+ public AbmSentenceCodec() {
+
+ factory = new GenericFactory<IEncapsulatedAisMessage>("com.antu.nmea.sentence.ais", "AisMessage?");
+ }
+
+ @Override
+ protected IEncapsulatedSentence createEncapsulatedSentence(
+ EncapsulationSentence sentence) throws ClassNotFoundException,
+ InstantiationException, IllegalAccessException {
+
+ if (sentence instanceof AbmSentence) {
+ return factory.createBySymbol(new Integer(((AbmSentence) sentence).messageId).toString());
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ protected int getMessageId(EncapsulationSentence sentence) {
+
+ if (sentence instanceof AbmSentence) {
+ return ((AbmSentence) sentence).messageId;
+ } else {
+ return 0;
+ }
+ }
+
+ @Override
+ public String getCodecType() {
+ return "abm";
+ }
+
+ @Override
+ protected INmeaSentence createSentence(Date timestamp, String sentenceType) {
+ return new AbmSentence(timestamp);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Observable;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.GroupItemAnnotationSorter;
+import com.antu.nmea.annotation.MessageFieldAnnotationSorter;
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.annotation.SentenceFieldAnnotationSorter;
+import com.antu.nmea.annotation.exception.MultipleGroupItemException;
+import com.antu.nmea.codec.exception.MessageFieldCodecNotFoundException;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.field.codec.AbstractSentenceFieldCodec;
+import com.antu.nmea.sentence.field.codec.IGroupSentenceFieldCodec;
+import com.antu.nmea.sentence.field.codec.ISentenceFieldCodec;
+import com.antu.nmea.util.StringHelper;
+import com.antu.util.GenericFactory;
+import com.antu.util.PrintableList;
+
+/**
+ *
+ * @author yining
+ *
+ * This is a base class for all sentence codecs. Unlike CodecManager, which is just a wrapper
+ * that delegates to underlying codecs, this is the part where the actual encoding/decoding
+ * takes place.
+ *
+ * In
+ */
+public abstract class AbstractNmeaSentenceCodec extends Observable {
+
+ protected GenericFactory<AbstractSentenceFieldCodec> sentenceFieldCodecFactory =
+ new GenericFactory<AbstractSentenceFieldCodec>("com.antu.nmea.sentence.field.codec", "?SentenceFieldCodec");
+
+ static private Log logger = LogFactory.getLog(AbstractNmeaSentenceCodec.class);
+
+ /**
+ * Codec type, this is no longer necessary
+ * @return
+ */
+ abstract public String getCodecType();
+
+ /**
+ * gets sentence field information for decoding segments
+ * @param sentence
+ * @return
+ */
+ static public List<Field> getSentenceFields(INmeaSentence sentence) {
+
+ List<Field> annotatedFields = new ArrayList<Field>();
+ for (Field field : sentence.getClass().getFields()) {
+ if (field.isAnnotationPresent(SentenceField.class)) {
+ annotatedFields.add(field);
+ }
+ }
+
+ Collections.sort(annotatedFields, new SentenceFieldAnnotationSorter());
+ return annotatedFields;
+ }
+
+ /**
+ * calculates checksum of a sentence
+ * @param sentence
+ * @return
+ */
+ static public short checksum(String sentence) {
+ short checksum = 0;
+
+ int checksumIndex = sentence.lastIndexOf('*');
+
+ if (checksumIndex > 0 && sentence.length() < checksumIndex + 3)
+ return 0;
+
+ if (checksumIndex < 0)
+ checksumIndex = sentence.length();
+
+ for (int i = 1; i < checksumIndex; i++) {
+ checksum ^= (short)sentence.charAt(i);
+ }
+
+ return checksum;
+ }
+
+ /**
+ * calculates checksum of a sentence, and append it.
+ * @param builder
+ */
+ protected void appendCheckSum(StringBuilder builder) {
+
+ short checksum = AbstractNmeaSentenceCodec.checksum(builder.toString());
+
+ char high = (char) ((checksum & 0x00F0) >> 4);
+ char low = (char) (checksum & 0x000F);
+
+ builder.append('*').append(StringHelper.fromHex(high)).append(StringHelper.fromHex(low));
+ }
+
+ static public List<Field> getGroupItems(Object obj) {
+
+ List<Field> annotatedFields = new ArrayList<Field>();
+ for (Field field : obj.getClass().getFields()) {
+ if (field.isAnnotationPresent(com.antu.nmea.annotation.GroupItem.class)) {
+ annotatedFields.add(field);
+ }
+ }
+
+ Collections.sort(annotatedFields, new GroupItemAnnotationSorter());
+ return annotatedFields;
+ }
+
+ /**
+ * gets message field information for encapsulated sentence
+ * @param sentence
+ * @return
+ */
+ static public List<Field> getMessageFields(Object sentence) {
+
+ List<Field> annotatedFields = new ArrayList<Field>();
+ for (Field field : sentence.getClass().getFields()) {
+ if (field.isAnnotationPresent(com.antu.nmea.annotation.MessageField.class)) {
+ annotatedFields.add(field);
+ }
+ }
+
+ Collections.sort(annotatedFields, new MessageFieldAnnotationSorter());
+ return annotatedFields;
+ }
+
+ public INmeaSentence decode(long timestampFromEpoch, String sentenceType, String[] segments)
+ throws SentenceFieldCodecNotFoundException,
+ ClassNotFoundException,
+ InstantiationException, IllegalAccessException {
+
+ Calendar cal = Calendar.getInstance();
+ cal.setTimeInMillis(timestampFromEpoch * 1000);
+
+ return this.decode(cal.getTime(), sentenceType, segments);
+ }
+
+ public INmeaSentence decode(Date timestamp, String sentenceType, String[] segments)
+ throws SentenceFieldCodecNotFoundException,
+ ClassNotFoundException,
+ InstantiationException, IllegalAccessException {
+
+ INmeaSentence sentence = this.createSentence(timestamp, sentenceType);
+ assert(sentence != null);
+
+ if (this.doDecode(sentenceType, sentence, segments))
+ return sentence;
+ else
+ return null;
+ }
+
+ public INmeaSentence decode(String sentenceType, String[] segments)
+ throws SentenceFieldCodecNotFoundException,
+ ClassNotFoundException,
+ InstantiationException, IllegalAccessException {
+ return this.decode(Calendar.getInstance().getTime(), sentenceType, segments);
+ }
+
+ abstract protected INmeaSentence createSentence(Date timestamp, String sentenceType);
+
+ protected AbstractSentenceFieldCodec getCodec(SentenceField annotation, String fieldName) {
+
+ if (annotation.fullCodecPath() != null && !annotation.fullCodecPath().isEmpty()) {
+
+ try {
+ AbstractSentenceFieldCodec codec = this.sentenceFieldCodecFactory.getByFullName(annotation.fullCodecPath());
+ AbstractNmeaSentenceCodec.logger.info("sentence field codec retrieved for field: " + fieldName);
+ return codec;
+ } catch (InstantiationException |
+ IllegalAccessException e) {
+ AbstractNmeaSentenceCodec.logger.info("unable to retrieve sentence field codec for field: " + fieldName + " with class name: " + annotation.fullCodecPath());
+ }
+ }
+
+ if (annotation.packageName() != null &&
+ !annotation.packageName().isEmpty() &&
+ this.sentenceFieldCodecFactory.isPackageRegistered(annotation.packageName())) {
+
+ AbstractNmeaSentenceCodec.logger.info("registering package name: " + annotation.packageName());
+ this.sentenceFieldCodecFactory.registerPackage(annotation.packageName());
+ }
+
+ if (annotation.fieldType() != null &&
+ !annotation.fieldType().isEmpty()) {
+
+ AbstractNmeaSentenceCodec.logger.info("retrieving sentence field codec from fieldType: " + annotation.fieldType());
+
+ try {
+ AbstractSentenceFieldCodec codec = this.sentenceFieldCodecFactory.getBySymbol(StringHelper.capitalizeFirstChar(annotation.fieldType()));
+ AbstractNmeaSentenceCodec.logger.info("sentence field codec with fieldType: " + annotation.fieldType() + " retrieved.");
+ return codec;
+ } catch (InstantiationException |
+ IllegalAccessException e) {
+ AbstractNmeaSentenceCodec.logger.error("failed retrieving sentence field codec with fieldType: " + annotation.fieldType());
+ return null;
+ }
+ }
+
+ return null;
+ }
+
+ protected IGroupSentenceFieldCodec getGroupCodec(SentenceField annotation) {
+
+ assert(annotation.isGroup() == true);
+ assert(annotation.groupType() != null && !annotation.groupType().isEmpty());
+ assert(annotation.groupItemClass() != null && !annotation.groupItemClass().isEmpty());
+
+ try {
+ AbstractSentenceFieldCodec codec = this.sentenceFieldCodecFactory.getBySymbol(StringHelper.capitalizeFirstChar(annotation.groupType()));
+ AbstractNmeaSentenceCodec.logger.info("retrieved group sentence field codec with groupType: " + annotation.groupType());
+
+ if (codec instanceof IGroupSentenceFieldCodec) {
+ return (IGroupSentenceFieldCodec)codec;
+ } else {
+ AbstractNmeaSentenceCodec.logger.error("group sentence field codec does not implement IGroupSentenceFieldCodec: " + codec.getClass().getName());
+ return null;
+ }
+ } catch (InstantiationException |
+ IllegalAccessException e) {
+ AbstractNmeaSentenceCodec.logger.error("failed retrieving group sentence field codec with groupType: " + annotation.groupType());
+ }
+
+ return null;
+ }
+
+ /**
+ * Checks if the fields have more than 1 SentenceField isGroup == true marked, and
+ *
+ *
+ * @param annotatedSentenceFields fields that are annotated with SentenceField annotation
+ * @throws MultipleGroupItemException throws exception if there are multiple fields annotated with isGroup == true, which
+ * is not allowed.
+ * @return the number of sentence segments required after a isGroup == true item.
+ */
+ protected int checkGroupItems(List<Field> annotatedSentenceFields)
+ throws SentenceFieldCodecNotFoundException {
+
+ boolean foundGroupItem = false;
+ int segmentsRequired = 0;
+
+ for (Field field : annotatedSentenceFields) {
+
+ SentenceField annotation = field.getAnnotation(SentenceField.class);
+
+ if (annotation.isGroup()) {
+ if (!foundGroupItem) {
+ foundGroupItem = true;
+ continue;
+ } else {
+ throw new MultipleGroupItemException(field.getName() +
+ ": " +annotation.fieldType());
+ }
+ }
+
+ if (foundGroupItem) {
+ ISentenceFieldCodec codec = this.getCodec(annotation, field.getName());
+
+ if (codec == null) {
+ throw new SentenceFieldCodecNotFoundException("Sentence field codec not found for field: " + field.getName());
+ } else {
+ segmentsRequired += codec.requiredSegments();
+ }
+ }
+ }
+
+ return segmentsRequired;
+ }
+
+ protected boolean doDecode(String sentenceType, INmeaSentence sentence, String[] segments)
+ throws SentenceFieldCodecNotFoundException {
+
+ List<Field> annotatedFields = AbstractNmeaSentenceCodec.getSentenceFields(sentence);
+
+ this.checkGroupItems(annotatedFields);
+
+ AbstractNmeaSentenceCodec.logger.info("decoding...");
+ int index = 1;
+ for (Field field : annotatedFields) {
+ SentenceField annotation = field.getAnnotation(SentenceField.class);
+
+ if (!annotation.isGroup()) {
+ ISentenceFieldCodec codec = this.getCodec(annotation, field.getName());
+
+ if (codec != null) {
+ if (codec.decode(segments, sentence, field, index)) {
+ index += codec.requiredSegments();
+ AbstractNmeaSentenceCodec.logger.info("decoded: " + field.getName());
+ } else {
+ if (annotation.isRequired()) {
+ AbstractNmeaSentenceCodec.logger.error("unable to decode a required field: " + field.getName());
+ return false;
+ } else {
+ index += codec.requiredSegments();
+ AbstractNmeaSentenceCodec.logger.info("unable to decode a non-required field: " + field.getName());
+ continue;
+ }
+ }
+ } else {
+ AbstractNmeaSentenceCodec.logger.info("sentence field codec not found: " + field.getName());
+ throw new SentenceFieldCodecNotFoundException("Sentence field codec not found for field: " + field.getName());
+ }
+ } else {
+ assert(annotation.groupItemClass() != null &&
+ !annotation.groupItemClass().isEmpty());
+
+ IGroupSentenceFieldCodec codec = this.getGroupCodec(annotation);
+
+ if (codec != null) {
+ Object groupItem = codec.createGroupItem(annotation.groupItemClass());
+
+ int segmentsPerItem = codec.segmentsPerItem(groupItem);
+ int totalItems = codec.totalItems(annotation, index, segments.length, segmentsPerItem);
+
+ if (totalItems % segmentsPerItem != 0) {
+ AbstractNmeaSentenceCodec.logger.error("segments for group item does not match: " + field.getName());
+ return false;
+ }
+
+ if (codec.decode(segments, sentence, field, index)) {
+ index += totalItems * segmentsPerItem;
+ } else {
+ if (annotation.isRequired()) {
+ return false;
+ }
+ else {
+ index += totalItems * segmentsPerItem;
+ continue;
+ }
+ }
+ } else {
+ throw new SentenceFieldCodecNotFoundException("Sentence field codec not found for field: " + field.getName());
+ }
+ }
+ }
+
+ AbstractNmeaSentenceCodec.logger.info("entering post-decode");
+ if (this.postDecodeProcess(sentence))
+ return true;
+ return false;
+ }
+
+ public List<String> encode(String talker, INmeaSentence sentence)
+ throws SentenceFieldCodecNotFoundException, MessageFieldCodecNotFoundException {
+
+ if (this.preEncodeProcess(sentence))
+ return this.doEncode(talker, sentence);
+ else
+ return new PrintableList<String>();
+ }
+
+ abstract protected List<String> doEncode(String talker, INmeaSentence sentence)
+ throws SentenceFieldCodecNotFoundException;
+
+ abstract protected boolean postDecodeProcess(INmeaSentence sentence);
+
+ abstract protected boolean preEncodeProcess(INmeaSentence sentence);
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.util.HashMap;
+
+public class AcceptanceList {
+
+ private HashMap<String, Boolean> publicAcceptanceList;
+ private HashMap<String, Boolean> proprietaryAcceptanceList;
+ private HashMap<String, HashMap<Integer, Boolean>> messageAcceptanceList;
+
+ public AcceptanceList() {
+ this.publicAcceptanceList = new HashMap<String, Boolean>();
+ this.proprietaryAcceptanceList = new HashMap<String, Boolean>();
+ this.messageAcceptanceList = new HashMap<String, HashMap<Integer, Boolean>>();
+ }
+
+ public void addPublicSentence(String sentenceType) {
+ if (!this.publicAcceptanceList.containsKey(sentenceType)) {
+ this.publicAcceptanceList.put(sentenceType.toUpperCase(), true);
+ }
+ }
+
+ public void addProprietarySentence(String sentenceType) {
+ if (!this.proprietaryAcceptanceList.containsKey(sentenceType)) {
+ this.proprietaryAcceptanceList.put(sentenceType.toUpperCase(), true);
+ }
+ }
+
+ public void addMessage(String sentenceType, int messageId) {
+
+ if (!this.messageAcceptanceList.containsKey(sentenceType.toUpperCase())) {
+ this.messageAcceptanceList.put(sentenceType.toUpperCase(), new HashMap<Integer, Boolean>());
+ }
+
+ if (!this.messageAcceptanceList.get(sentenceType.toUpperCase()).containsKey(messageId)) {
+ this.messageAcceptanceList.get(sentenceType.toUpperCase()).put(messageId, true);
+ }
+
+ if (!this.publicAcceptanceList.containsKey(sentenceType.toUpperCase())) {
+ this.publicAcceptanceList.put(sentenceType.toUpperCase(), true);
+ }
+ }
+
+ public void addAllMessages(String sentenceType) {
+ for (int i = 1; i <= 100; i++) {
+ this.addMessage(sentenceType, i);
+ }
+ }
+
+ public void removePublicSentence(String sentenceType) {
+ if (this.publicAcceptanceList.containsKey(sentenceType)) {
+ this.publicAcceptanceList.remove(sentenceType);
+ }
+
+ if (this.messageAcceptanceList.containsKey(sentenceType)) {
+ this.messageAcceptanceList.remove(sentenceType);
+ }
+ }
+
+ public void removeProprietarySentence(String sentenceType) {
+ if (this.proprietaryAcceptanceList.containsKey(sentenceType)) {
+ this.proprietaryAcceptanceList.remove(sentenceType);
+ }
+ }
+
+ public void removeMessage(String sentenceType, int messageId) {
+ if (this.messageAcceptanceList.containsKey(sentenceType)) {
+
+ HashMap<Integer, Boolean> messages = this.messageAcceptanceList.get(sentenceType);
+
+ if (messages.containsKey(messageId)) {
+ messages.remove(messageId);
+
+ if (messages.size() == 0 && this.publicAcceptanceList.containsKey(sentenceType)) {
+ this.publicAcceptanceList.remove(sentenceType);
+ }
+ }
+ }
+ }
+
+ public void removeAllMessages(String sentenceType) {
+ if (this.publicAcceptanceList.containsKey(sentenceType)) {
+ this.publicAcceptanceList.remove(sentenceType);
+ }
+
+ if (this.messageAcceptanceList.containsKey(sentenceType)) {
+ this.messageAcceptanceList.remove(sentenceType);
+ }
+ }
+
+ public boolean shouldAcceptPublic(String sentenceType) {
+ return this.publicAcceptanceList.containsKey(sentenceType.toUpperCase());
+ }
+
+ public boolean shouldAcceptProprietary(String sentenceType) {
+ return this.proprietaryAcceptanceList.containsKey(sentenceType.toUpperCase());
+ }
+
+ public boolean shouldAcceptMessage(String sentenceType, int messageId) {
+ return this.messageAcceptanceList.containsKey(sentenceType.toUpperCase()) &&
+ this.messageAcceptanceList.get(sentenceType.toUpperCase()).containsKey(messageId);
+ }
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.message.field.codec.MessageFieldCodecHelper;
+import com.antu.nmea.sentence.EncapsulationSentence;
+import com.antu.nmea.sentence.IEncapsulatedSentence;
+import com.antu.nmea.sentence.ais.IEncapsulatedAisMessage;
+import com.antu.util.GenericFactory;
+
+abstract public class AisSentenceCodec extends EncapsulationSentenceCodec {
+
+ private GenericFactory<IEncapsulatedAisMessage> factory;
+
+ static private Log logger = LogFactory.getLog(AisSentenceCodec.class);
+
+ public AisSentenceCodec() {
+ super();
+
+ factory = new GenericFactory<IEncapsulatedAisMessage>("com.antu.nmea.sentence.ais", "AisMessage?");
+ }
+
+ @Override
+ protected IEncapsulatedSentence createEncapsulatedSentence(
+ EncapsulationSentence sentence)
+ throws ClassNotFoundException,
+ InstantiationException,
+ IllegalAccessException {
+
+ int id = this.getMessageId(sentence);
+
+ IEncapsulatedSentence sent = null;
+ AisSentenceCodec.logger.info("message id is: " + new Integer(id).toString());
+ if (id > 0) {
+ if (id == 24) {
+ List<Byte> encapsulatedData = sentence.getRawData();
+
+ if (encapsulatedData.size() >= 40) {
+ Byte part = MessageFieldCodecHelper.parseByte(encapsulatedData, 38, 2, false);
+
+ if (part != null) {
+ if (part == 0)
+ sent = factory.createBySymbol("24A");
+ else if (part == 1)
+ sent = factory.createBySymbol("24B");
+ }
+ }
+ } else {
+ sent = factory.createBySymbol(new Integer(id).toString());
+ }
+ }
+
+ if (sent != null)
+ AisSentenceCodec.logger.info("encapsulated sentence type: " + sent.getClass().getName());
+ else
+ AisSentenceCodec.logger.info("encapsulated sentence is null");
+ return sent;
+ }
+
+ @Override
+ protected int getMessageId(EncapsulationSentence sentence) {
+
+ List<Byte> bits = sentence.getRawData();
+
+ if (bits != null && bits.size() > 0) {
+ Integer val = MessageFieldCodecHelper.parseInteger(bits, 0, 6, false);
+
+ if (val != null)
+ return val;
+ return 0;
+ }
+ return 0;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.util.Date;
+
+import com.antu.nmea.sentence.AbmSentence;
+import com.antu.nmea.sentence.BbmSentence;
+import com.antu.nmea.sentence.EncapsulationSentence;
+import com.antu.nmea.sentence.IEncapsulatedSentence;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.ais.IEncapsulatedAisMessage;
+import com.antu.util.GenericFactory;
+
+public class BbmSentenceCodec extends EncapsulationSentenceCodec {
+
+ private GenericFactory<IEncapsulatedAisMessage> factory;
+
+ public BbmSentenceCodec() {
+
+ factory = new GenericFactory<IEncapsulatedAisMessage>("com.antu.nmea.sentence.ais", "AisMessage?");
+ }
+
+ @Override
+ protected IEncapsulatedSentence createEncapsulatedSentence(
+ EncapsulationSentence sentence) throws ClassNotFoundException,
+ InstantiationException, IllegalAccessException {
+
+ if (sentence instanceof BbmSentence) {
+ return factory.createBySymbol(new Integer(((BbmSentence) sentence).messageId).toString());
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ protected int getMessageId(EncapsulationSentence sentence) {
+
+ if (sentence instanceof BbmSentence) {
+ return ((BbmSentence) sentence).messageId;
+ } else {
+ return 0;
+ }
+ }
+
+ @Override
+ public String getCodecType() {
+ return "bbm";
+ }
+
+ @Override
+ protected INmeaSentence createSentence(Date timestamp, String sentenceType) {
+ return new AbmSentence(timestamp);
+ }
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+import java.util.Observable;
+import java.util.Observer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.codec.exception.MessageFieldCodecNotFoundException;
+import com.antu.nmea.codec.exception.SentenceCodecNotFoundException;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.sentence.EncapsulationSentence;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.MultiSentenceTable;
+import com.antu.nmea.sentence.ParametricSentence;
+import com.antu.nmea.util.Buffer;
+import com.antu.nmea.util.StringHelper;
+import com.antu.util.GenericFactory;
+
+/**
+ *
+ * @author yining
+ *
+ * CodecManager is the entry point for all encoding and decoding of NMEA sentences from a single source,
+ * ie. each CodecManager should be instantiated and configured for each source generating NMEA messages,
+ * may it be a server socket, a client socket, a file or a serial port.
+ *
+ * A CodecManager implements Observer and extends Observable, it gets notified from underlying
+ * AbstractNmeaSentenceCodecs(Observable) when a sentence is fully decoded. Programs using a CodecManager
+ * should implement Oberver interface and add to this Observable to receive decoded sentence objects.
+ */
+public class CodecManager extends Observable implements Observer {
+
+ private Buffer buffer;
+ private ParametricSentenceCodec parametricSentenceCodec;
+ private QuerySentenceCodec querySentenceCodec;
+
+ private GenericFactory<AbstractNmeaSentenceCodec> multiSentenceCodecFactory;
+ private GenericFactory<AbstractNmeaSentenceCodec> encapsulationSentenceCodecFactory;
+ private GenericFactory<AbstractNmeaSentenceCodec> proprietarySentenceCodecFactory;
+
+ private AcceptanceList acceptanceList;
+
+ static private Log logger = LogFactory.getLog(GenericFactory.class);
+
+ /**
+ * Constructor for CodecManager
+ */
+ public CodecManager() {
+
+ this.buffer = new Buffer();
+ this.parametricSentenceCodec = new ParametricSentenceCodec();
+ this.querySentenceCodec = new QuerySentenceCodec();
+
+ this.parametricSentenceCodec.addObserver(this);
+ this.querySentenceCodec.addObserver(this);
+ this.acceptanceList = new AcceptanceList();
+
+ this.multiSentenceCodecFactory = new GenericFactory<AbstractNmeaSentenceCodec>("com.antu.nmea.codec", "?SentenceCodec");
+ this.encapsulationSentenceCodecFactory = new GenericFactory<AbstractNmeaSentenceCodec>("com.antu.nmea.codec", "?SentenceCodec");
+ this.proprietarySentenceCodecFactory = new GenericFactory<AbstractNmeaSentenceCodec>("com.antu.nmea.codec", "?SentenceCodec");
+ }
+
+ /**
+ * AcceptanceList is used to filter out certain sentence types. CodecManagers can
+ * receive all kinds of NMEA sentences and some may not need to be encoded/decoded
+ * based on different usage purposes. Use of this list can filter-out unwanted sentences
+ * and hence saving encoding/decoding time and computer resources.
+ *
+ * <strong>By default, it accepts no sentences.</strong>
+ *
+ * @return AcceptanceList for the codec manager
+ */
+ public AcceptanceList acceptanceList() {
+ return this.acceptanceList;
+ }
+
+ /**
+ * Decodes a sentence with timestamp.
+ *
+ * @param timestamp the time the sentence is received.
+ * @param content actual content of the sentence.
+ * @throws SentenceFieldCodecNotFoundException
+ * @throws SentenceCodecNotFoundException
+ * @throws IllegalAccessException
+ * @throws InstantiationException
+ * @throws ClassNotFoundException
+ */
+ public void decode(Date timestamp, String content)
+ throws SentenceFieldCodecNotFoundException, SentenceCodecNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException {
+ this.decode(timestamp, content.toCharArray());
+ }
+
+ /**
+ * Decodes a sentence with current time as the timestamp
+ * @param content
+ * @throws SentenceFieldCodecNotFoundException
+ * @throws SentenceCodecNotFoundException
+ * @throws ClassNotFoundException
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ */
+ public void decode(String content)
+ throws SentenceFieldCodecNotFoundException, SentenceCodecNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException {
+ this.decode(Calendar.getInstance().getTime(), content);
+ }
+
+ /**
+ * Decodes a sentence with time in milliseconds from epoch as the time
+ * @param timeInMillis
+ * @param content
+ * @throws SentenceFieldCodecNotFoundException
+ * @throws SentenceCodecNotFoundException
+ * @throws ClassNotFoundException
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ */
+ public void decode(long timeInMillis, String content)
+ throws SentenceFieldCodecNotFoundException, SentenceCodecNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException {
+ Calendar cal = Calendar.getInstance();
+ cal.setTimeInMillis(timeInMillis);
+ this.decode(cal.getTime(), content);
+ }
+
+ protected short hexValue(char c) {
+ switch (c) {
+ case 'A':
+ case 'a':
+ return 10;
+ case 'B':
+ case 'b':
+ return 11;
+ case 'C':
+ case 'c':
+ return 12;
+ case 'D':
+ case 'd':
+ return 13;
+ case 'E':
+ case 'e':
+ return 14;
+ case 'F':
+ case 'f':
+ return 15;
+
+ case '1':
+ return 1;
+ case '2':
+ return 2;
+ case '3':
+ return 3;
+ case '4':
+ return 4;
+ case '5':
+ return 5;
+ case '6':
+ return 6;
+ case '7':
+ return 7;
+ case '8':
+ return 8;
+ case '9':
+ return 9;
+
+ default:
+ return 0;
+ }
+ }
+
+ /**
+ * Finds out if the checksum is valid. Only does the checking
+ * if the sentence comes with a checksum.
+ * @param sentence
+ * @return true if checksum is valid, false otherwise.
+ */
+ protected boolean isChecksumValid(String sentence) {
+ short checksum = 0;
+
+ int checksumIndex = sentence.lastIndexOf('*');
+
+ if (sentence.length() < checksumIndex + 3)
+ return false;
+
+ checksum = AbstractNmeaSentenceCodec.checksum(sentence);
+
+ short high = (short) ((checksum & 0x00F0) >> 4);
+ short low = (short)(checksum & 0x000F);
+
+ return (high == this.hexValue(sentence.charAt(checksumIndex + 1))) &&
+ (low == this.hexValue(sentence.charAt(checksumIndex + 2)));
+ }
+
+ public void decode(char[] content)
+ throws SentenceFieldCodecNotFoundException, SentenceCodecNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException {
+ this.decode(Calendar.getInstance().getTime(), content);
+ }
+
+ public void decode(long timeInMillis, char[] content)
+ throws SentenceFieldCodecNotFoundException, SentenceCodecNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException {
+ Calendar cal = Calendar.getInstance();
+ cal.setTimeInMillis(timeInMillis);
+ this.decode(cal.getTime(), content);
+ }
+
+ public void decode(Date timestamp, char[] content) {
+
+ CodecManager.logger.debug("received: " + new String(content));
+
+ // break into complete NMEA sentences
+ ArrayList<String> rawSentences = this.buffer.append(content);
+
+ // for each sentence, do
+ for (String rawSentence : rawSentences) {
+
+ CodecManager.logger.debug("decoding sentence: " + rawSentence);
+
+ // if there is a checksum, verify it, otherwise, pass the sentence
+ int checkSumIndex = rawSentence.lastIndexOf('*');
+ if (checkSumIndex >= 0) {
+ if (!this.isChecksumValid(rawSentence)) {
+ CodecManager.logger.info("sentence checksum validation failed.");
+ continue;
+ }
+ CodecManager.logger.info("sentence checksum validation passed.");
+ }
+
+ // break sentence into segments separated by ','
+ String[] segments = null;
+ if (checkSumIndex >= 0) {
+ segments = rawSentence.substring(0, checkSumIndex).trim().split(",");
+ } else {
+ segments = rawSentence.trim().split(",");
+ }
+ CodecManager.logger.info("sentence segmented.");
+
+ try {
+ // proprietary sentence
+ if (rawSentence.startsWith("$P") || rawSentence.startsWith("!P")) {
+ CodecManager.logger.info("processing as proprietary sentence.");
+
+ String sentenceType = segments[0].substring(2);
+
+ if (sentenceType == null || sentenceType.length() < 3) {
+ CodecManager.logger.error("cannot determine sentence type for: " + rawSentence);
+ continue;
+ }
+
+ sentenceType = sentenceType.substring(0, 3).toLowerCase();
+
+ CodecManager.logger.debug("trying to resolve sentence type: " + sentenceType);
+
+ if (this.acceptanceList.shouldAcceptProprietary(sentenceType)) {
+ CodecManager.logger.info("sentenceType: " + sentenceType + " is accepted.");
+
+ AbstractNmeaSentenceCodec codec = this.proprietarySentenceCodecFactory.getBySymbol(
+ StringHelper.capitalizeFirstChar(sentenceType));
+
+ if (codec != null) {
+ codec.addObserver(this);
+ codec.decode(timestamp, sentenceType, segments);
+ } else {
+ CodecManager.logger.error("unable to find proprietary codec for sentence type: " + sentenceType);
+ }
+ } else {
+ CodecManager.logger.info("sentenceType: " + sentenceType + " is not in acceptance list.");
+ }
+ } else if (segments[0].startsWith("$") &&
+ segments[0].length() == 6 &&
+ segments[0].charAt(5) == 'Q') { // query sentence
+ CodecManager.logger.info("processing as query sentence.");
+ this.querySentenceCodec.decode(timestamp, null, segments);
+ } else { // parametric or encapsulation sentence
+
+ // proof check, make sure sentence header is valid
+ if (segments[0].length() == 6) {
+ String sentenceType = segments[0].substring(3).toLowerCase();
+ CodecManager.logger.debug("trying to resolve sentence type: " + sentenceType);
+
+ // if this codec manager is allowed to perform
+ // codec operation on this sentence
+ if (this.acceptanceList.shouldAcceptPublic(sentenceType)) {
+ CodecManager.logger.info("sentence type accepted.");
+
+ // parametric sentence
+ if (segments[0].startsWith("$")) {
+ CodecManager.logger.info("processing as parametric/multi-sentence sentence.");
+ // first check to see if it's a multisentence
+ if (MultiSentenceTable.instance().isMultiSentenceType(sentenceType)) {
+ CodecManager.logger.info("processing as multi-sentence sentence.");
+ AbstractNmeaSentenceCodec codec = //this.getMultiSentenceCodec(sentenceType);
+ this.multiSentenceCodecFactory.getBySymbol(
+ StringHelper.capitalizeFirstChar(sentenceType));
+
+ if (codec != null) {
+ codec.addObserver(this);
+ CodecManager.logger.info("codec located.");
+ codec.decode(timestamp, sentenceType, segments);
+ } else {
+ CodecManager.logger.error("unable to find multi-sentence codec for sentence type: " + sentenceType);
+ }
+ } else { // no, do as a regular parametric sentence.
+ CodecManager.logger.info("processing as parametric sentence.");
+ this.parametricSentenceCodec.decode(timestamp, sentenceType, segments);
+ }
+ }
+ else if (segments[0].startsWith("!")) { // encapsulation sentence
+ CodecManager.logger.info("processing as encapsulation sentence.");
+
+ AbstractNmeaSentenceCodec codec = //this.getEncapsulationSentenceCodec(sentenceType);
+ this.encapsulationSentenceCodecFactory.getBySymbol(
+ StringHelper.capitalizeFirstChar(sentenceType));
+
+ if (codec != null) {
+ codec.addObserver(this);
+ CodecManager.logger.info("codec for encapsulation sentence located.");
+ codec.decode(timestamp, sentenceType, segments);
+ } else {
+ CodecManager.logger.error("unable to find encapsulation sentence codec for sentence type: " + sentenceType);
+ }
+ }
+ } else {
+ CodecManager.logger.info("sentence type: " + sentenceType + " not accepted.");
+ }
+ }
+ }
+ } catch (ClassNotFoundException
+ | InstantiationException
+ | IllegalAccessException
+ | SentenceFieldCodecNotFoundException e) {
+ CodecManager.logger.error("error parsing sentence: " + rawSentence, e);
+ }
+ }
+ }
+
+ @Override
+ public void update(Observable o, Object arg) {
+
+ CodecManager.logger.info("parsed object received: " + arg.toString());
+ if (arg instanceof INmeaSentence) {
+
+ this.setChanged();
+ this.notifyObservers(arg);
+ }
+ }
+
+ public List<String> encode(String talker, INmeaSentence sentence) {
+
+ try {
+ if (talker == null || talker.length() != 2 || sentence == null)
+ return new ArrayList<String>();
+
+ // if a multisentence
+ if (MultiSentenceTable.instance().isMultiSentenceType(sentence.sentenceType())) {
+
+ CodecManager.logger.error("encoding multi-sentence sentence, type: " + sentence.sentenceType());
+
+ AbstractNmeaSentenceCodec codec =
+ this.multiSentenceCodecFactory.getBySymbol(StringHelper.capitalizeFirstChar(sentence.sentenceType()));
+ return codec.encode(talker, sentence);
+ } else if (sentence instanceof ParametricSentence) {
+
+ CodecManager.logger.error("encoding parametric sentence, type: " + sentence.sentenceType());
+
+ // if a parametric sentence
+ return this.parametricSentenceCodec.encode(talker, sentence);
+ } else if (sentence instanceof EncapsulationSentence) {
+
+ CodecManager.logger.error("encoding encapsulation sentence, type: " + sentence.sentenceType());
+
+ // if an encapsulation sentence
+ AbstractNmeaSentenceCodec codec =
+ this.encapsulationSentenceCodecFactory.getBySymbol(StringHelper.capitalizeFirstChar(sentence.sentenceType()));
+ return codec.encode(talker, sentence);
+ } else {
+ // must be a proprietary sentence
+ CodecManager.logger.error("encoding query sentence, type: " + sentence.sentenceType());
+
+ AbstractNmeaSentenceCodec codec =
+ this.proprietarySentenceCodecFactory.getBySymbol(StringHelper.capitalizeFirstChar(sentence.sentenceType()));
+ return codec.encode(talker, sentence);
+ }
+ } catch (SentenceFieldCodecNotFoundException |
+ MessageFieldCodecNotFoundException |
+ InstantiationException |
+ IllegalAccessException e) {
+ CodecManager.logger.error("exception occurred during encoding.", e);
+ return new ArrayList<String>();
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+import java.util.Timer;
+import java.util.TimerTask;
+
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.annotation.SentenceMessage;
+import com.antu.nmea.codec.exception.MessageFieldCodecNotFoundException;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.message.field.codec.IMessageFieldCodec;
+import com.antu.nmea.sentence.EncapsulationSentence;
+import com.antu.nmea.sentence.IEncapsulatedSentence;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.field.codec.ISentenceFieldCodec;
+import com.antu.nmea.util.Pair;
+import com.antu.nmea.util.SentenceStore;
+import com.antu.nmea.util.StringHelper;
+import com.antu.util.GenericFactory;
+import com.antu.util.PrintableList;
+
+abstract public class EncapsulationSentenceCodec extends AbstractNmeaSentenceCodec {
+
+ static public final long CHECK_INTERVAL = 500;
+ static public final long INIT_DELAY = 200;
+
+ private Timer checkTimer;
+
+ private int sequenceId;
+
+ static private Log logger = LogFactory.getLog(EncapsulationSentenceCodec.class);
+
+ private SentenceStore<Pair<Integer, Integer>, EncapsulationSentence> storedSentences =
+ new SentenceStore<Pair<Integer, Integer>, EncapsulationSentence>();
+
+ private GenericFactory<IMessageFieldCodec> messageFieldCodecFactory;
+
+ public EncapsulationSentenceCodec() {
+ this.checkTimer = new Timer(true);
+ this.checkTimer.scheduleAtFixedRate(new TimerTask() {
+
+ @Override
+ public void run() {
+ try {
+ check();
+ } catch (MessageFieldCodecNotFoundException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
+ }
+ }
+
+ }, INIT_DELAY, CHECK_INTERVAL);
+ messageFieldCodecFactory = new GenericFactory<IMessageFieldCodec>("com.antu.nmea.message.field.codec", "?MessageFieldCodec");
+ new GenericFactory<ISentenceFieldCodec>("com.antu.nmea.sentence.field.codec", "?SentenceFieldCodec");
+ }
+
+ /**
+ * Periodically checks to see if there are incomplete sentences and if
+ * so and if they stayed in the repository for too long, try to decode
+ * them even if they are not complete.
+ *
+ * @throws MessageFieldCodecNotFoundException
+ * @throws ClassNotFoundException
+ * @throws IllegalAccessException
+ * @throws InstantiationException
+ */
+ protected void check() throws MessageFieldCodecNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException {
+
+ Date now = Calendar.getInstance().getTime();
+
+ List<EncapsulationSentence> expiredSentences = this.storedSentences.getExpiredItems(now,
+ (int) EncapsulationSentenceCodec.CHECK_INTERVAL);
+
+ for (EncapsulationSentence sentence : expiredSentences) {
+ sentence.decodeStringData(sentence.getEncapsulatedData());
+ this.decodeMessageFields(sentence);
+ }
+ }
+
+ /**
+ * Each encapsulation sentence will have bits parsed at this stage, and hence knows how to create
+ * encapsulated sentences from those bits.
+ * @param sentence
+ * @return
+ * @throws ClassNotFoundException
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ */
+ abstract protected IEncapsulatedSentence createEncapsulatedSentence(EncapsulationSentence sentence)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException;
+
+ /**
+ * group item should be unique, although not necessarily the last field in a message
+ * @param embedded encapsulated sentence that contains the group item
+ * @return number of bits after the group item.
+ * @throws InstantiationException thrown if there are multiple group items in a message.
+ */
+ protected int isGroupItemCorrect(IEncapsulatedSentence embedded)
+ throws InstantiationException {
+
+ List<Field> fields = AbstractNmeaSentenceCodec.getMessageFields(embedded);
+
+ int groupIndex = fields.size();
+ int bits = 0;
+ for (int i = 0; i < fields.size(); i++) {
+
+ MessageField annotation = fields.get(i).getAnnotation(MessageField.class);
+ if (annotation.isGroup()) {
+
+ if (groupIndex == fields.size()) {
+ groupIndex = i;
+ } else {
+ throw new InstantiationException("multiple group items: " + embedded.getClass().getName());
+ }
+ } else if (groupIndex < fields.size()) {
+ bits += annotation.requiredBits();
+ }
+ }
+ return bits;
+ }
+
+ /**
+ * Decodes encapsulated sentence objects from parsed bits.
+ *
+ * @param sentence
+ * @throws MessageFieldCodecNotFoundException
+ * @throws ClassNotFoundException
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ */
+ protected void decodeMessageFields(EncapsulationSentence sentence)
+ throws MessageFieldCodecNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException {
+
+ IEncapsulatedSentence encapsulatedSentence = this.createEncapsulatedSentence(sentence);
+
+ try {
+ this.isGroupItemCorrect(encapsulatedSentence);
+ } catch (InstantiationException e) {
+ EncapsulationSentenceCodec.logger.error("multiple group items for: " + encapsulatedSentence.getClass().getName());
+ throw e;
+ }
+
+ sentence.setEncapsulatedSentence(encapsulatedSentence);
+
+ EncapsulationSentenceCodec.logger.info("encapsulated sentence set: " + encapsulatedSentence.getClass().getName());
+
+ List<Field> fields = AbstractNmeaSentenceCodec.getMessageFields(encapsulatedSentence);
+ List<Byte> bits = sentence.getRawData();
+
+ int bitIndex = 0;
+ for (Field field : fields) {
+ MessageField annotation = field.getAnnotation(MessageField.class);
+ Integer size = null;
+
+ EncapsulationSentenceCodec.logger.info("trying to find message field codec from symbol: " + annotation.fieldType());
+ try {
+ IMessageFieldCodec codec = //MessageFieldCodecManager.instance().getCodec(annotation.fieldType());
+ this.messageFieldCodecFactory.getBySymbol(StringHelper.capitalizeFirstChar(annotation.fieldType()));
+
+ EncapsulationSentenceCodec.logger.info("trying to decode field: " + field.getName());
+ if (codec == null) {
+ EncapsulationSentenceCodec.logger.error("message field codec not found: " + annotation.fieldType());
+ return;
+ } else {
+ size = codec.decode(bits, bitIndex, encapsulatedSentence, field);
+
+ if (size == null) {
+ EncapsulationSentenceCodec.logger.error("unable to decode field: " + field.getName());
+ return;
+ } else {
+ EncapsulationSentenceCodec.logger.info("field: " + field.getName() + "; value: " + field.get(encapsulatedSentence).toString());
+ }
+ }
+ } catch (Exception e) {
+ EncapsulationSentenceCodec.logger.error("error finding codec", e);
+ return;
+ }
+ bitIndex += size;
+
+ if (bitIndex >= bits.size())
+ break;
+ }
+
+ this.setChanged();
+ this.notifyObservers(sentence);
+ EncapsulationSentenceCodec.logger.info("message fields decoded, sentence: " + sentence.toString());
+ }
+
+ @Override
+ protected boolean postDecodeProcess(INmeaSentence sentence) {
+
+ if (sentence instanceof EncapsulationSentence) {
+ try {
+ this.storeSentence((EncapsulationSentence)sentence);
+ EncapsulationSentenceCodec.logger.info("post-decode complete");
+ return true;
+ } catch (MessageFieldCodecNotFoundException |
+ ClassNotFoundException |
+ InstantiationException |
+ IllegalAccessException e) {
+ EncapsulationSentenceCodec.logger.error("exception during post-decode process", e);
+ return false;
+ }
+ }
+ EncapsulationSentenceCodec.logger.error("sentence type mismatch, EncapsulationSentence expected, actual type: " + sentence.getClass().getName());
+ return false;
+ }
+
+ abstract protected int getMessageId(EncapsulationSentence sentence);
+
+ protected void storeSentence(EncapsulationSentence sentence)
+ throws MessageFieldCodecNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException {
+
+ if (sentence.getTotalNumberOfSentences() == 1) {
+ sentence.decodeStringData(sentence.getEncapsulatedData());
+ this.decodeMessageFields(sentence);
+ } else {
+ Pair<Integer, Integer> key = new Pair<Integer, Integer>(sentence.getSequentialMessageId(),
+ this.getMessageId(sentence));
+ EncapsulationSentence sent = this.storedSentences.addItem(key, sentence);
+
+ EncapsulationSentenceCodec.logger.info("sentence obtained: " + sent.getClass().getName());
+ if (sent != null && sent.decodeStringData(sent.getEncapsulatedData())) {
+ this.decodeMessageFields(sent);
+ }
+ }
+ }
+
+ @Override
+ public List<String> doEncode(String talker, INmeaSentence sentence)
+ throws SentenceFieldCodecNotFoundException {
+
+ List<String> result = new ArrayList<String>();
+ List<Field> fields = AbstractNmeaSentenceCodec.getSentenceFields(sentence);
+
+ if (talker.length() != 2)
+ return result;
+
+ int length = 7;
+ for (Field field : fields) {
+
+ SentenceField annotation = field.getAnnotation(SentenceField.class);
+
+ if (annotation.isIgnoredInReconstruction())
+ continue;
+
+ length += annotation.fieldWidth();
+ }
+
+ // calculate how many sentences needed
+ int maxChars = 80 - 8 - length;
+
+ int bodyLength = ((EncapsulationSentence) sentence).getEncapsulatedData().length();
+ int sentences = bodyLength / maxChars;
+ int remainder = bodyLength % maxChars;
+
+ if (remainder > 0)
+ sentences++;
+ int totalSentences = sentences;
+
+ List<StringBuilder> builders = new ArrayList<StringBuilder>();
+
+ // tries to construct sentence, anything that is ignored, everything
+ // after that has to be ignored as well.
+ for (int i = 1; i <= totalSentences; i++) {
+
+ StringBuilder sb = new StringBuilder("!");
+ sb.append(talker).append(sentence.sentenceType().toUpperCase());
+
+ ((EncapsulationSentence) sentence).setTotalSentenceCount(totalSentences);
+ ((EncapsulationSentence) sentence).setSentenceNumber(i);
+ if (totalSentences > 1)
+ ((EncapsulationSentence) sentence).setSequenceId(this.sequenceId);
+ else
+ ((EncapsulationSentence) sentence).setSequenceId(null);
+ for (Field field : fields) {
+
+ SentenceField annotation = field.getAnnotation(SentenceField.class);
+
+ if (annotation.isIgnoredInReconstruction())
+ continue;
+
+ length += annotation.fieldWidth();
+ ISentenceFieldCodec fieldCodec = this.getCodec(annotation, field.getName());
+
+ if (fieldCodec == null || !fieldCodec.encode(sb, sentence, field)) {
+ return new PrintableList<String>();
+ }
+ }
+
+ builders.add(sb);
+ }
+
+ if (totalSentences > 1) {
+ this.sequenceId++;
+ if (this.sequenceId > 9)
+ this.sequenceId -= 9;
+ }
+
+ List<StringBuilder> sentenceBuilders = this.breakSentences(builders,
+ (EncapsulationSentence) sentence, ((EncapsulationSentence) sentence).getTotalNumberOfSentences(),
+ length);
+
+ for (int i = 0; i < sentenceBuilders.size(); i++) {
+
+ StringBuilder sb = sentenceBuilders.get(i);
+
+ sb.append(',');
+ if (i != sentenceBuilders.size() - 1) {
+ sb.append('0');
+ } else {
+ sb.append(((EncapsulationSentence) sentence).getFillBits());
+ }
+
+ this.appendCheckSum(sb);
+ sb.append("\r\n");
+ result.add(sb.toString());
+ }
+ return result;
+ }
+
+
+ /**
+ * get encapsulated sentence and convert the message fields to bits
+ */
+ @Override
+ protected boolean preEncodeProcess(INmeaSentence sentence) {
+
+ assert(sentence != null);
+ assert(sentence instanceof EncapsulationSentence);
+
+ IEncapsulatedSentence encap = ((EncapsulationSentence)sentence).getEncapsulatedSentence();
+
+ assert(encap != null);
+
+ List<Field> messageFields = AbstractNmeaSentenceCodec.getMessageFields(encap);
+ List<Byte> bits = new ArrayList<Byte>();
+
+ boolean success = true;
+ for (Field field : messageFields) {
+ MessageField annotation = field.getAnnotation(MessageField.class);
+
+ IMessageFieldCodec codec = null;
+ try {
+ codec = this.messageFieldCodecFactory.getBySymbol(StringHelper.capitalizeFirstChar(annotation.fieldType()));
+ } catch (InstantiationException | IllegalAccessException e) {
+ EncapsulationSentenceCodec.logger.error("cannot create message codec", e);
+ return false;
+ }
+
+ if (codec != null) {
+ if (!codec.encode(bits, encap, field)) {
+ success = false;
+ break;
+ }
+ }
+ }
+
+ if (success) {
+
+ int remainder = bits.size() % 6;
+ int fillBits = (remainder == 0) ? 0 : 6 - remainder;
+
+ // if a sentence requires all byte to be aligned, set fill bits to 0
+ // and padd the bits.
+ if (encap.getClass().isAnnotationPresent(SentenceMessage.class)) {
+ SentenceMessage annot = encap.getClass().getAnnotation(SentenceMessage.class);
+
+ if (annot != null && annot.alignBytes()) {
+ for (int i = 0; i < fillBits; i++) {
+ bits.add((byte) 0);
+ }
+ fillBits = 0;
+ }
+ }
+
+ for (int i = 0; i < fillBits; i++) {
+ bits.add((byte) 0);
+ }
+
+ Byte[] bitArray = new Byte[bits.size()];
+ bitArray = bits.toArray(bitArray);
+
+ String encoded = EncapsulationSentence.convertSixBitsToString(bitArray);
+
+ ((EncapsulationSentence)sentence).setEncapsulatedData(encoded);
+ ((EncapsulationSentence)sentence).setFillBits(fillBits);
+ }
+ return success;
+ }
+
+
+ protected List<StringBuilder> breakSentences(List<StringBuilder> builders, EncapsulationSentence sentence,
+ int totalNumberOfSentences, int length) {
+
+ String content = sentence.getEncapsulatedData();
+ int maxLength = 80 - length - 8;
+ for (int i = 0; i < totalNumberOfSentences; i++) {
+ StringBuilder sb = builders.get(i);
+ sb.append(',');
+
+ if (i == totalNumberOfSentences - 1) {
+ sb.append(content.substring(i * totalNumberOfSentences));
+ } else {
+ sb.append(content.substring(i * totalNumberOfSentences, i * totalNumberOfSentences + maxLength));
+ }
+ }
+
+ return builders;
+ }
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import com.antu.nmea.sentence.INmeaSentence;
+
+/**
+ * Used for post processing of sentences after segments are decoded.
+ * @author yining
+ *
+ */
+public interface IDecodePostProcessor {
+ INmeaSentence process(INmeaSentence sentence);
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+/**
+ * Used to encode bits for encapsulated sentences
+ * @author yining
+ *
+ */
+public interface IEncodePreProcessor {
+
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.lang.reflect.Field;
+import java.util.Date;
+import java.util.List;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.ParametricSentenceFactory;
+import com.antu.nmea.sentence.field.codec.ISentenceFieldCodec;
+import com.antu.util.PrintableList;
+
+public class ParametricSentenceCodec extends AbstractNmeaSentenceCodec {
+
+ private ParametricSentenceFactory sentenceFactory;
+
+ public ParametricSentenceCodec() {
+
+ this.sentenceFactory = new ParametricSentenceFactory();
+ }
+
+ @Override
+ public String getCodecType() {
+ return "parametric";
+ }
+
+ @Override
+ protected INmeaSentence createSentence(Date timestamp, String sentenceType) {
+ return this.sentenceFactory.createSentence(timestamp, sentenceType);
+ }
+
+ @Override
+ protected boolean postDecodeProcess(INmeaSentence sentence) {
+
+ this.setChanged();
+ this.notifyObservers(sentence);
+ return true;
+ }
+
+ @Override
+ protected boolean preEncodeProcess(INmeaSentence sentence) {
+ return true;
+ }
+
+ @Override
+ protected List<String> doEncode(String talker, INmeaSentence sentence)
+ throws SentenceFieldCodecNotFoundException {
+
+ PrintableList<String> result = new PrintableList<String>();
+
+ List<Field> fields = AbstractNmeaSentenceCodec.getSentenceFields(sentence);
+
+ StringBuilder builder = new StringBuilder("$");
+
+ if (talker.length() != 2)
+ return result;
+
+ builder.append(talker).append(sentence.sentenceType().toUpperCase());
+
+ for (Field field : fields) {
+
+ SentenceField annotation = field.getAnnotation(SentenceField.class);
+ ISentenceFieldCodec fieldCodec = null;
+
+ if (annotation.isGroup())
+ fieldCodec = this.getGroupCodec(annotation);
+ else
+ fieldCodec = this.getCodec(annotation, field.getName());
+
+ if (fieldCodec == null) {
+ throw new SentenceFieldCodecNotFoundException("field codec not found for: " + field.getName());
+ }
+
+ if (!fieldCodec.encode(builder, sentence, field)) {
+ return result;
+ }
+ }
+
+ this.appendCheckSum(builder);
+ builder.append("\r\n");
+ result.add(builder.toString());
+ return result;
+ }
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.NmeaSentence;
+import com.antu.nmea.sentence.QuerySentence;
+
+public class QuerySentenceCodec extends AbstractNmeaSentenceCodec {
+
+ @Override
+ public String getCodecType() {
+ return "query";
+ }
+
+ @Override
+ protected NmeaSentence createSentence(Date timestamp, String sentenceType) {
+ return new QuerySentence(timestamp);
+ }
+
+ @Override
+ protected boolean doDecode(String sentenceType, INmeaSentence sentence,
+ String[] segments) {
+
+ if (segments == null || segments.length != 2)
+ return false;
+
+ if (!(sentence instanceof QuerySentence))
+ return false;
+
+ QuerySentence s = (QuerySentence) sentence;
+
+ if (segments[0].length() != 6)
+ return false;
+
+ s.requestTalker = segments[0].substring(1, 3);
+ s.requestedTalker = segments[0].substring(3, 5);
+
+ if (segments[1].indexOf('*') > 0) {
+ s.query = segments[1].substring(0, segments[1].indexOf('*'));
+ } else {
+ s.query = segments[1];
+ }
+
+ return true;
+ }
+
+ @Override
+ protected boolean postDecodeProcess(INmeaSentence sentence) {
+
+ this.setChanged();
+ this.notifyObservers(sentence);
+ return true;
+ }
+
+ @Override
+ protected boolean preEncodeProcess(INmeaSentence sentence) {
+ return true;
+ }
+
+ @Override
+ protected List<String> doEncode(String talker, INmeaSentence sentence)
+ throws SentenceFieldCodecNotFoundException {
+
+ ArrayList<String> result = new ArrayList<String>();
+
+ if (sentence instanceof QuerySentence) {
+ StringBuilder builder = new StringBuilder("$");
+
+ QuerySentence query = (QuerySentence)sentence;
+
+ if (query.requestTalker == null || query.requestTalker.length() != 2 ||
+ query.requestedTalker == null || query.requestedTalker.length() != 2 ||
+ query.query == null || query.query.length() == 0)
+ return result;
+
+ builder.append(query.requestTalker).append(query.requestedTalker).append('Q');
+ builder.append(',').append(query.query);
+
+ this.appendCheckSum(builder);
+ builder.append("\r\n");
+ result.add(builder.toString());
+
+ return result;
+ }
+ return result;
+ }
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.sentence.IGroupedSentence;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.NmeaSentence;
+import com.antu.nmea.sentence.TutSentence;
+import com.antu.nmea.sentence.field.codec.ISentenceFieldCodec;
+import com.antu.nmea.util.StringHelper;
+import com.antu.nmea.util.TranslationCodeTable;
+import com.antu.util.PrintableList;
+
+public class TutSentenceCodec extends AbstractNmeaSentenceCodec {
+
+ static public final long CHECK_INTERVAL = 500;
+ static public final long INIT_DELAY = 200;
+
+ public static class TutSegment extends NmeaSentence implements IGroupedSentence {
+
+ public TutSegment() {
+ super();
+ }
+
+ public TutSegment(Date date) {
+ super(date);
+ }
+
+ public TutSegment(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "tut";
+ }
+
+ @SentenceField(order = 1, fieldType="string")
+ public String sourceIdentifier = "";
+
+ @SentenceField(order = 2, fieldType="integer")
+ public int totalNumberOfSentences = 0;
+
+ @SentenceField(order = 3, fieldType="integer")
+ public int sentenceNumber = 0;
+
+ @SentenceField(order = 4, fieldType="integer")
+ public int sequentialMessageIdentifier = 0;
+
+ @SentenceField(order = 5, fieldType="string")
+ public String translationCode = "";
+
+ @SentenceField(order = 6, fieldType="string")
+ public String textBody = "";
+
+ @Override
+ public int getSequentialMessageId() {
+ return this.sequentialMessageIdentifier;
+ }
+
+ @Override
+ public int getTotalNumberOfSentences() {
+ return this.totalNumberOfSentences;
+ }
+
+ @Override
+ public int getSentenceNumber() {
+ return this.sentenceNumber;
+ }
+
+ @Override
+ public boolean isComplete() {
+ return this.totalNumberOfSentences == this.sentenceNumber;
+ }
+
+ @Override
+ public void concatenate(IGroupedSentence sentence) {
+
+ if (sentence instanceof TutSegment) {
+ TutSegment newSeg = (TutSegment)sentence;
+
+ this.textBody += newSeg.textBody;
+ this.sentenceNumber = newSeg.sentenceNumber;
+ }
+ }
+ }
+
+ private HashMap<String, HashMap<Integer, TutSegment>> sentences;
+
+ private short nextSentenceId = 0;
+
+ private Timer checkTimer;
+
+ public TutSentenceCodec() {
+
+ this.sentences = new HashMap<String, HashMap<Integer, TutSegment>>();
+ this.checkTimer = new Timer(true);
+ this.checkTimer.scheduleAtFixedRate(new TimerTask() {
+
+ @Override
+ public void run() {
+ check();
+ }
+
+ }, INIT_DELAY, CHECK_INTERVAL);
+ }
+
+ synchronized protected void check() {
+
+ List<TutSegment> incompleteSegments = new ArrayList<TutSegment>();
+ Date now = Calendar.getInstance().getTime();
+
+ for (String talker : this.sentences.keySet()) {
+ HashMap<Integer, TutSegment> segments = this.sentences.get(talker);
+
+ for (int sentenceId : segments.keySet()) {
+ TutSegment segment = segments.get(sentenceId);
+
+ if (now.getTime() - segment.getReceiveDate().getTime() >= CHECK_INTERVAL) {
+ incompleteSegments.add(segment);
+ }
+ }
+ }
+
+ for (TutSegment segment : incompleteSegments) {
+ this.decodeSegment(segment);
+
+ this.sentences.get(segment.sourceIdentifier).remove(segment.sequentialMessageIdentifier);
+ }
+ }
+
+ @Override
+ public String getCodecType() {
+ return "tut";
+ }
+
+ @Override
+ protected INmeaSentence createSentence(Date timestamp, String sentenceType) {
+ return new TutSegment(timestamp);
+ }
+
+ @Override
+ protected boolean doDecode(String sentenceType, INmeaSentence sentence,
+ String[] segments) throws SentenceFieldCodecNotFoundException {
+
+ if (!(sentence instanceof TutSegment)) {
+ return false;
+ }
+
+ List<Field> annotatedFields = AbstractNmeaSentenceCodec.getSentenceFields(sentence);
+
+ int index = 1;
+ for (Field field : annotatedFields) {
+ SentenceField annotation = field.getAnnotation(SentenceField.class);
+
+ ISentenceFieldCodec fieldCodec = this.getCodec(annotation, field.getName());
+
+ if (fieldCodec != null) {
+ boolean success = fieldCodec.decode(segments, sentence, field, index);
+ index += fieldCodec.requiredSegments();
+
+ if (!success){
+ if (annotation.isRequired())
+ return false;
+
+ index += fieldCodec.requiredSegments();
+ continue;
+ }
+ } else {
+ return false;
+ }
+ }
+
+ this.storeSentenceSegment((TutSegment)sentence);
+
+ return true;
+ }
+
+ protected void decodeSegment(TutSegment segment) {
+
+ TutSentence sentence = new TutSentence(segment.getReceiveDate());
+ sentence.sourceIdentifier = segment.sourceIdentifier;
+ sentence.translationCode = segment.translationCode;
+ sentence.isComplete = segment.sentenceNumber == segment.totalNumberOfSentences;
+ sentence.textBody = TranslationCodeTable.instance().decode(segment.translationCode, segment.textBody);
+ sentence.isTranslated = sentence.textBody != null;
+
+ this.setChanged();
+ this.notifyObservers(sentence);
+}
+
+ synchronized protected void storeSentenceSegment(TutSegment segment) {
+
+ if (segment.totalNumberOfSentences == 1) {
+ this.decodeSegment(segment);
+ } else if (this.sentences.containsKey(segment.sourceIdentifier)) {
+
+ HashMap<Integer, TutSegment> segments = this.sentences.get(segment.sourceIdentifier);
+
+ if (segments.containsKey(segment.sequentialMessageIdentifier)) {
+
+ if (segment.sentenceNumber == segment.totalNumberOfSentences) {
+ TutSegment storedSegment = segments.get(segment.sequentialMessageIdentifier);
+ if (segment.sentenceNumber == storedSegment.sentenceNumber + 1) {
+ storedSegment.textBody = storedSegment.textBody + segment.textBody;
+ storedSegment.sentenceNumber = segment.sentenceNumber;
+ segments.remove(segment.sequentialMessageIdentifier);
+
+ this.decodeSegment(storedSegment);
+ } else {
+ segments.remove(segment.sourceIdentifier);
+ this.decodeSegment(storedSegment);
+ }
+
+ } else {
+ TutSegment storedSegment = segments.get(segment.sequentialMessageIdentifier);
+ if (segment.sentenceNumber == storedSegment.sentenceNumber + 1) {
+ storedSegment.textBody = storedSegment.textBody + segment.textBody;
+ storedSegment.sentenceNumber = segment.sentenceNumber;
+ } else {
+ segments.remove(segment.sourceIdentifier);
+ this.decodeSegment(storedSegment);
+ }
+ }
+ } else {
+ segments.put(segment.sequentialMessageIdentifier, segment);
+ }
+ } else {
+
+ HashMap<Integer, TutSegment> segments = new HashMap<Integer, TutSegment>();
+ segments.put(segment.sequentialMessageIdentifier, segment);
+ this.sentences.put(segment.sourceIdentifier, segments);
+ }
+ }
+
+ @Override
+ public List<String> encode(String talker, INmeaSentence sentence) {
+
+ List<String> result = new PrintableList<String>();
+
+ if (talker == null || talker.length() != 2 || sentence == null)
+ return result;
+
+ if (sentence instanceof TutSentence) {
+ boolean isProprietary = TranslationCodeTable.instance().isTranslationCodeProprietary(((TutSentence) sentence).translationCode);
+
+ String encoded = TranslationCodeTable.instance().encode(((TutSentence) sentence).translationCode,
+ ((TutSentence) sentence).textBody);
+ int segmentLength = isProprietary ? 53 : 56;
+
+ int number = encoded.length() / segmentLength;
+ int remainder = encoded.length() % segmentLength;
+
+ if (remainder > 0)
+ number++;
+ if (number > 255)
+ return result;
+
+ if (encoded != null) {
+
+ for (int i = 0; i < number; i++) {
+
+ StringBuilder sb = new StringBuilder("$");
+ sb.append(talker).append(sentence.sentenceType().toUpperCase());
+ sb.append(",").append(((TutSentence) sentence).sourceIdentifier);
+ sb.append(",");
+ sb.append(StringHelper.fromHex((char) ((number & 0x00F0) >> 4))).append(StringHelper.fromHex((char) (number & 0x000F)));
+ sb.append(",");
+ sb.append(StringHelper.fromHex((char) (((i + 1) & 0x00F0) >> 4))).append(StringHelper.fromHex((char) ((i + 1) & 0x000F)));
+ sb.append(",");
+ sb.append(new Integer(this.nextSentenceId).toString());
+ sb.append(",").append(((TutSentence) sentence).translationCode);
+ sb.append(",");
+
+ if (i == number - 1) {
+ sb.append(encoded.substring(i * segmentLength));
+ } else {
+ sb.append(encoded.substring(i * segmentLength, (i + 1) * segmentLength));
+ }
+ this.appendCheckSum(sb);
+ sb.append("\r\n");
+ result.add(sb.toString());
+ }
+ }
+ }
+ this.nextSentenceId++;
+ if (this.nextSentenceId > 9)
+ this.nextSentenceId = 0;
+ return result;
+ }
+
+ @Override
+ protected boolean postDecodeProcess(INmeaSentence sentence) {
+
+ this.setChanged();
+ this.notifyObservers(sentence);
+ return true;
+ }
+
+ @Override
+ protected boolean preEncodeProcess(INmeaSentence sentence) {
+ return true;
+ }
+
+ /**
+ * method is not used.
+ */
+ @Override
+ protected List<String> doEncode(String talker, INmeaSentence sentence)
+ throws SentenceFieldCodecNotFoundException {
+ return null;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.util.Date;
+
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.VdmSentence;
+
+public class VdmSentenceCodec extends AisSentenceCodec {
+
+ public VdmSentenceCodec() {
+ super();
+ }
+
+ @Override
+ public String getCodecType() {
+ return "vdm";
+ }
+
+ @Override
+ protected INmeaSentence createSentence(Date timestamp, String sentenceType) {
+ return new VdmSentence(timestamp);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.codec;
+
+import java.util.Date;
+
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.sentence.VdoSentence;
+
+public class VdoSentenceCodec extends AisSentenceCodec {
+
+ public VdoSentenceCodec() {
+ super();
+ }
+
+ @Override
+ public String getCodecType() {
+ return "vdo";
+ }
+
+ @Override
+ protected INmeaSentence createSentence(Date timestamp, String sentenceType) {
+ return new VdoSentence(timestamp);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.codec.exception;
+
+public class MessageFieldCodecNotFoundException extends Exception {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4973817439298395761L;
+
+ public MessageFieldCodecNotFoundException() {
+ super();
+ }
+
+ public MessageFieldCodecNotFoundException(String message) {
+ super(message);
+ }
+
+ public MessageFieldCodecNotFoundException(Throwable cause) {
+ super(cause);
+ }
+
+ public MessageFieldCodecNotFoundException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public MessageFieldCodecNotFoundException(String message, Throwable cause,
+ boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.codec.exception;
+
+public class SentenceCodecNotFoundException extends Exception {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8679760373380789633L;
+
+ public SentenceCodecNotFoundException() {
+ super();
+ }
+
+ public SentenceCodecNotFoundException(String message) {
+ super(message);
+ }
+
+ public SentenceCodecNotFoundException(Throwable cause) {
+ super(cause);
+ }
+
+ public SentenceCodecNotFoundException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public SentenceCodecNotFoundException(String message, Throwable cause,
+ boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.codec.exception;
+
+public class SentenceFieldCodecNotFoundException extends Exception {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -3781512415506323300L;
+
+ public SentenceFieldCodecNotFoundException() {
+ super();
+ }
+
+ public SentenceFieldCodecNotFoundException(String message) {
+ super(message);
+ }
+
+ public SentenceFieldCodecNotFoundException(Throwable cause) {
+ super(cause);
+ }
+
+ public SentenceFieldCodecNotFoundException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public SentenceFieldCodecNotFoundException(String message, Throwable cause,
+ boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.annotation.GroupItem;
+import com.antu.nmea.annotation.MessageField;
+
+abstract public class AbstractMessageFieldCodec implements IMessageFieldCodec {
+
+ public AbstractMessageFieldCodec() {
+ }
+
+ @Override
+ public Integer decode(List<Byte> bits, int startIndex, Object obj, Field field) {
+
+ FieldSetting setting = null;
+
+ if (field.isAnnotationPresent(MessageField.class)) {
+ setting = new FieldSetting((MessageField)field.getAnnotation(MessageField.class));
+ } else if (field.isAnnotationPresent(GroupItem.class)) {
+ setting = new FieldSetting((GroupItem)field.getAnnotation(GroupItem.class));
+ }
+
+ if (setting == null)
+ return null;
+
+ return this.doDecode(bits, startIndex, obj, field, setting);
+ }
+
+ abstract protected Integer doDecode(List<Byte> bits, int startIndex, Object obj, Field field, FieldSetting setting);
+
+ @Override
+ public boolean encode(List<Byte> bits, Object obj, Field field) {
+
+ FieldSetting setting = null;
+
+ if (field.isAnnotationPresent(MessageField.class)) {
+ setting = new FieldSetting((MessageField)field.getAnnotation(MessageField.class));
+ } else if (field.isAnnotationPresent(GroupItem.class)) {
+ setting = new FieldSetting((GroupItem)field.getAnnotation(GroupItem.class));
+ }
+
+ if (setting == null)
+ return false;
+
+ return this.doEncode(bits, obj, field, setting);
+ }
+
+ abstract protected boolean doEncode(List<Byte> bits, Object obj, Field field, FieldSetting setting);
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.util.PrintableList;
+
+public class BitsMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public BitsMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "bits";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ PrintableList<Byte> result = new PrintableList<Byte>();
+
+ int length = (setting.getFieldWidth() == 0) ? bits.size() - startIndex : setting.getFieldWidth();
+ for (int i = 0; i < length; i++) {
+ result.add(bits.get(i + startIndex));
+ }
+
+ try {
+ field.set(obj, result);
+ return length;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object val = field.get(obj);
+
+ if (val instanceof List) {
+ for (Byte b : ((List<Byte>)val)) {
+ bits.add(b);
+ }
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class ByteMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public ByteMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "byte";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ int length = setting.getFieldWidth();
+ if (length == 0) {
+ length = (bits.size() - startIndex > 8) ? 8 : bits.size() - startIndex;
+ }
+
+ Byte b = MessageFieldCodecHelper.parseByte(bits, startIndex, setting.getFieldWidth(), false);
+
+ if (b == null)
+ return null;
+
+ try {
+ field.set(obj, b);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ if (!MessageFieldCodecHelper.byteToBits(bits, field.getByte(obj), setting.getFieldWidth(), false)) {
+ return false;
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public class CourseMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public CourseMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "course";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(setting.getFieldWidth() == 12);
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Short b = MessageFieldCodecHelper.parseShort(bits, startIndex, setting.getFieldWidth(), false);
+
+ if (b == null || b < 0 || b > 3600)
+ return null;
+
+ try {
+ if (b == 3600)
+ field.set(obj, AbstractAisSentence.COURSE_NOT_AVAILABLE);
+ else
+ field.set(obj, b / 10.0);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Double val = field.getDouble(obj);
+
+ short b = 3600;
+ if (val != null && val >= 0 && val < 360) {
+ b = (short) (val * 10);
+ }
+ if (!MessageFieldCodecHelper.shortToBits(bits, b, setting.getFieldWidth(), false)) {
+ return false;
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.util.DateTime;
+
+public class DateTimeMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ static private Log logger = LogFactory.getLog(DateTimeMessageFieldCodec.class);
+
+ public DateTimeMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "dateTime";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(setting.getFieldWidth() == 20);
+
+ if (startIndex + 20 > bits.size())
+ return null;
+
+ DateTime time = new DateTime();
+
+ Short value = MessageFieldCodecHelper.parseShort(bits, startIndex, 4, false);
+ if (value != null) {
+ time.month = value;
+ } else
+ return null;
+
+ value = MessageFieldCodecHelper.parseShort(bits, startIndex + 4, 5, false);
+ if (value != null) {
+ time.day = value;
+ } else
+ return null;
+
+ value = MessageFieldCodecHelper.parseShort(bits, startIndex + 9, 5, false);
+ if (value != null) {
+ time.hour = value;
+ } else
+ return null;
+
+ value = MessageFieldCodecHelper.parseShort(bits, startIndex + 14, 6, false);
+ if (value != null) {
+ time.minute = value;
+ } else
+ return null;
+
+ try {
+ field.set(obj, time);
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("unable to set field: " + field.getName(), e);
+ return null;
+ }
+
+ return 20;
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object val = field.get(obj);
+
+ if (val instanceof DateTime) {
+ DateTime time = (DateTime)val;
+
+ if (MessageFieldCodecHelper.shortToBits(bits, time.month, 4, false)) {
+ if (MessageFieldCodecHelper.shortToBits(bits, time.day, 5, false)) {
+ if (MessageFieldCodecHelper.shortToBits(bits, time.hour, 5, false)) {
+ if (MessageFieldCodecHelper.shortToBits(bits, time.minute, 6, false)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ } else {
+ logger.error("unable field is not of type DateTime: " + field.getName());
+ return false;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("unable to get value from field: " + field.getName(), e);
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.util.Dimension;
+
+public class DimensionMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ static private Log logger = LogFactory.getLog(DimensionMessageFieldCodec.class);
+
+ public DimensionMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "dimension";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(setting.getFieldWidth() == 30);
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Dimension dim = new Dimension();
+
+ Short value = MessageFieldCodecHelper.parseShort(bits, startIndex, 9, false);
+ if (value != null) {
+ dim.a = value;
+ } else
+ return null;
+
+ value = MessageFieldCodecHelper.parseShort(bits, startIndex + 9, 9, false);
+ if (value != null) {
+ dim.b = value;
+ } else
+ return null;
+
+ value = MessageFieldCodecHelper.parseShort(bits, startIndex + 18, 6, false);
+ if (value != null) {
+ dim.c = value;
+ } else
+ return null;
+
+ value = MessageFieldCodecHelper.parseShort(bits, startIndex + 24, 6, false);
+ if (value != null) {
+ dim.d = value;
+ } else
+ return null;
+
+ try {
+ field.set(obj, dim);
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("unable to set field: " + field.getName(), e);
+ return null;
+ }
+ return 30;
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object val = field.get(obj);
+
+ if (val instanceof Dimension) {
+ Dimension dim = (Dimension)val;
+
+ if (MessageFieldCodecHelper.shortToBits(bits, dim.a, 9, false)) {
+ if (MessageFieldCodecHelper.shortToBits(bits, dim.b, 9, false)) {
+ if (MessageFieldCodecHelper.shortToBits(bits, dim.c, 6, false)) {
+ if (MessageFieldCodecHelper.shortToBits(bits, dim.d, 6, false)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ } else {
+ logger.error("unable field is not of type Dimension: " + field.getName());
+ return false;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("unable to get value from field: " + field.getName(), e);
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class DraughtMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ static private Log logger = LogFactory.getLog(DraughtMessageFieldCodec.class);
+
+ public DraughtMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "draught";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Short value = MessageFieldCodecHelper.parseShort(bits, startIndex, setting.getFieldWidth(), false);
+
+ if (value != null) {
+ try {
+ field.set(obj, value / 10.0);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("unable to set field: " + field.getName(), e);
+ return null;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Double val = field.getDouble(obj);
+
+ if (val != null) {
+ int draught = (int)(val * 10);
+
+ if (MessageFieldCodecHelper.integerToBits(bits, draught, setting.getFieldWidth(), false)) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ logger.error("unable to get value for field: " + field.getName());
+ return false;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("unable to get value from field: " + field.getName(), e);
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public class HeadingMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public HeadingMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "heading";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(setting.getFieldWidth() == 9);
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Short b = MessageFieldCodecHelper.parseShort(bits, startIndex, setting.getFieldWidth(), false);
+
+ if (b == null)
+ return null;
+
+ try {
+ if (b < 0 || b > 359)
+ field.set(obj, AbstractAisSentence.HEADING_NOT_AVAILABLE);
+ else
+ field.set(obj, b);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Short val = field.getShort(obj);
+
+ short b = 511;
+ if (val != null && val >= 0 && val < 360) {
+ b = val;
+ }
+ if (!MessageFieldCodecHelper.shortToBits(bits, b, setting.getFieldWidth(), false)) {
+ return false;
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+public interface IMessageFieldCodec {
+
+ String fieldCodecType();
+
+ Integer decode(List<Byte> bits, int startIndex, Object obj, Field field);
+
+ boolean encode(List<Byte> bits, Object obj, Field field);
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.message.field.codec.ifm.AbstractIfmCodec;
+import com.antu.nmea.message.field.codec.ifm.RawIfmCodec;
+import com.antu.nmea.sentence.ais.ifm.AbstractIfmSegment;
+import com.antu.nmea.sentence.ais.ifm.RawIfmSegment;
+import com.antu.util.GenericFactory;
+
+public class IfmMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ static private Log logger = LogFactory.getLog(IfmMessageFieldCodec.class);
+
+ private GenericFactory<AbstractIfmSegment> segmentFactory = new GenericFactory<AbstractIfmSegment>(
+ "com.antu.nmea.sentence.ais.ifm", "IfmMessage?");
+ private GenericFactory<AbstractIfmCodec> ifmCodecFactory = new GenericFactory<AbstractIfmCodec>(
+ "com.antu.nmea.message.field.codec.ifm", "Ifm?Codec");
+
+ public IfmMessageFieldCodec() {
+ super();
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "ifm";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(bits.size() >= startIndex + 16);
+
+ Short dac = MessageFieldCodecHelper.parseShort(bits, startIndex, 10, false);
+ Short fi = MessageFieldCodecHelper.parseShort(bits, startIndex + 10, 6, false);
+
+ if (dac != null && fi != null) {
+
+ String combined = String.format("%d%d", dac, fi);
+
+ try {
+ AbstractIfmSegment segment = this.segmentFactory.createBySymbol(combined);
+ AbstractIfmCodec codec = this.ifmCodecFactory.createBySymbol(combined);
+
+ if (segment == null || codec == null) {
+ logger.error("unable to create ifm object/codec: " + combined + ", object returned null");
+
+ codec = new RawIfmCodec();
+ segment = new RawIfmSegment();
+ }
+
+ segment.dac = dac;
+ segment.functionIdentifier = fi;
+
+ Integer size = codec.decode(segment, bits, startIndex + 16);
+ if (size != null) {
+
+ field.set(obj, segment);
+ return size;
+ }
+ } catch (InstantiationException | IllegalAccessException e) {
+ logger.error("error in decoding: " + combined, e);
+ }
+ }
+ return null;
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object value = field.get(obj);
+
+ if (value != null && value instanceof AbstractIfmSegment) {
+ AbstractIfmSegment segment = (AbstractIfmSegment)value;
+
+ String combined = String.format("%d%d", segment.dac, segment.functionIdentifier);
+ AbstractIfmCodec codec = this.ifmCodecFactory.createBySymbol(combined);
+
+ if (codec == null) {
+ logger.error("unable to create ifm codec: " + combined + ", object returned null");
+
+ if (segment instanceof RawIfmSegment) {
+
+ codec = new RawIfmCodec();
+ } else
+ return false;
+ }
+
+ if (codec.encode(segment, bits)) {
+ return true;
+ }
+ } else {
+ if (value == null)
+ logger.error("ifm part is null");
+ else
+ logger.error("value object is not AbstractIfmSegment: " + value.getClass().getName());
+
+ return false;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {
+ logger.error("error in encoding", e);
+ }
+ return false;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class IntegerMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public IntegerMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "integer";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Integer value = MessageFieldCodecHelper.parseInteger(bits, startIndex, setting.getFieldWidth(), false);
+
+ if (value == null)
+ return null;
+
+ try {
+ field.set(obj, value);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ if (!MessageFieldCodecHelper.integerToBits(bits, field.getInt(obj), setting.getFieldWidth(), false)) {
+ return false;
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public class LatitudeMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public LatitudeMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "latitude";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(setting.getFieldWidth() == 27);
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Integer val = MessageFieldCodecHelper.parseInteger(bits, startIndex, setting.getFieldWidth(), true);
+
+ if (val == null)
+ return null;
+
+ try {
+ if (val == 0x3412140)
+ field.set(obj, AbstractAisSentence.LATITUDE_NOT_AVAILABLE);
+ else
+ field.set(obj, val / 600000.0);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Double val = field.getDouble(obj);
+
+ int b = 0x3412140;
+ if (val != null && val >= -90 && val <= 90) {
+ b = (int) (val * 60 * 10000);
+ }
+ if (!MessageFieldCodecHelper.integerToBits(bits, b, setting.getFieldWidth(), true)) {
+ return false;
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.annotation.GroupItem;
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.codec.AbstractNmeaSentenceCodec;
+import com.antu.util.GenericFactory;
+import com.antu.util.PrintableList;
+
+public class ListMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ static private Log logger = LogFactory.getLog(ListMessageFieldCodec.class);
+
+ private GenericFactory<Object> groupItemFactory = new GenericFactory<Object>("", "");
+ private GenericFactory<IMessageFieldCodec> messageFieldCodecFactory =
+ new GenericFactory<IMessageFieldCodec>("com.antu.nmea.message.field.codec", "?MessageFieldCodec");
+
+ public ListMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "list";
+ }
+
+ protected int bitsAfterGroupItem(Object obj, Field groupItem) {
+
+ int bits = 0;
+ List<Field> fields = AbstractNmeaSentenceCodec.getMessageFields(obj);
+
+ boolean found = false;
+ for (int i = 0; i < fields.size(); i++) {
+ MessageField annotation = fields.get(i).getAnnotation(MessageField.class);
+
+ if (fields.get(i).getName().equals(groupItem.getName())) {
+ if (annotation.isGroup()) {
+ found = true;
+ }
+ } else if (found) {
+ bits += annotation.requiredBits();
+ }
+ }
+ return bits;
+ }
+
+ protected int bitsPerGroupItem(Object groupItem) {
+ int bits = 0;
+
+ List<Field> fields = AbstractNmeaSentenceCodec.getGroupItems(groupItem);
+
+ for (Field field : fields) {
+ GroupItem annotation = field.getAnnotation(GroupItem.class);
+ bits += annotation.fieldWidth();
+ }
+ return bits;
+ }
+
+ protected boolean decodeItem(List<Byte> bits, int startIndex, Object groupItem) {
+
+ List<Field> fields = AbstractNmeaSentenceCodec.getGroupItems(groupItem);
+
+ for (Field field : fields) {
+ GroupItem annotation = field.getAnnotation(GroupItem.class);
+
+ try {
+ IMessageFieldCodec codec = this.messageFieldCodecFactory.createBySymbol(annotation.itemType());
+
+ if (codec != null) {
+ if (codec.decode(bits, startIndex, groupItem, field) == null) {
+ logger.error("error decoding group item field: " + field.getName());
+ return false;
+ }
+ } else {
+ logger.error("no codec for group item field: " + field.getName());
+ return false;
+ }
+ } catch (InstantiationException | IllegalAccessException e) {
+ logger.error("error decoding item", e);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ int bitsAfterGroupItem = this.bitsAfterGroupItem(obj, field);
+ try {
+ List list = new PrintableList();
+ Object groupItem = this.groupItemFactory.createByFullName(setting.groupItemClass());
+
+ int bitsAvailable = bits.size() - startIndex - bitsAfterGroupItem;
+ int bitsPerItem = this.bitsPerGroupItem(groupItem);
+
+ if (bitsAvailable % bitsPerItem != 0) {
+ logger.error("cannot for integral items for group.");
+ return null;
+ }
+
+ int items = bitsAvailable / bitsPerItem;
+ for (int i = 0; i < items; i++) {
+
+ if (!decodeItem(bits, startIndex + i * bitsPerItem, groupItem)) {
+ return null;
+ }
+ list.add(groupItem);
+ groupItem = this.groupItemFactory.createByFullName(setting.groupItemClass());
+ }
+
+ field.set(obj, list);
+ return bitsPerItem * items;
+ } catch (InstantiationException | IllegalAccessException e) {
+ logger.error("exception during decoding", e);
+ return null;
+ }
+ }
+
+ protected boolean encodeItem(List<Byte> bits, Object item) {
+
+ List<Field> fields = AbstractNmeaSentenceCodec.getGroupItems(item);
+
+ for (Field field : fields) {
+ GroupItem annotation = field.getAnnotation(GroupItem.class);
+ try {
+ IMessageFieldCodec codec = this.messageFieldCodecFactory.createBySymbol(annotation.itemType());
+
+ if (codec != null) {
+ if (!codec.encode(bits, item, field)) {
+ logger.error("error encoding group item field: " + field.getName());
+ return false;
+ }
+ } else {
+ logger.error("no codec for group item field: " + field.getName());
+ return false;
+ }
+ } catch (InstantiationException | IllegalAccessException e) {
+ logger.error("error encoding item", e);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @SuppressWarnings({ "rawtypes" })
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object valueObj = field.get(obj);
+
+ if (valueObj == null || !(valueObj instanceof List)) {
+ logger.error("error, value null or not of type list");
+ return false;
+ }
+
+ List value = (List)valueObj;
+ for (Object item : value) {
+ if (!encodeItem(bits, item)) {
+ return false;
+ }
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("error during encoding", e);
+ }
+ return false;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public class LongitudeMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public LongitudeMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "longitude";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(setting.getFieldWidth() == 28);
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Integer val = MessageFieldCodecHelper.parseInteger(bits, startIndex, setting.getFieldWidth(), true);
+
+ if (val == null)
+ return null;
+
+ try {
+ if (val == 0x6791AC0)
+ field.set(obj, AbstractAisSentence.LONGITUDE_NOT_AVAILABLE);
+ else
+ field.set(obj, val / 600000.0);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Double val = field.getDouble(obj);
+
+ int b = 0x6791AC0;
+ if (val != null && val >= -90 && val <= 90) {
+ b = (int) (val * 60 * 10000);
+ }
+ if (!MessageFieldCodecHelper.integerToBits(bits, b, setting.getFieldWidth(), true)) {
+ return false;
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.BitSet;
+import java.util.List;
+
+import com.antu.nmea.util.StringHelper;
+
+public class MessageFieldCodecHelper {
+
+ static final Character MAPPING[] =
+ {
+ '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
+ 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
+ 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
+ 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
+ ' ', '!', 0x22, '#', '$', '%', '&', '`',
+ '(', ')', '*', '+',',', '-', '.', '/',
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', ':', ';', '<', '=', '>', '?'
+ };
+
+ static final List<Character> MappingList = Arrays.asList(MAPPING);
+
+ private MessageFieldCodecHelper() {
+ }
+
+ static public Byte parseByte(List<Byte> bits, int startIndex, int length, boolean keepSign) {
+
+ if (length > 8 || bits.size() < startIndex + length)
+ return null;
+
+ byte result = 0;
+
+ boolean isNegative = false;
+ if (keepSign && bits.get(startIndex) == 1)
+ isNegative = true;
+ List<Byte> newBits = new ArrayList<Byte>();
+
+ if (isNegative) {
+ for (int i = 0; i < 8 - length; i++) {
+ newBits.add((byte) 1);
+ }
+ } else {
+ for (int i = 0; i < 8 - length; i++) {
+ newBits.add((byte) 0);
+ }
+ }
+
+ for (int i = 8 - length; i < 8; i++) {
+ newBits.add(bits.get(startIndex + i - (8 - length)));
+ }
+
+ for (int i = 0; i < newBits.size(); i++) {
+ result = (byte) (result << 1);
+ result |= newBits.get(i);
+ }
+
+ return result;
+ }
+
+ static public Short parseShort(List<Byte> bits, int startIndex, int length, boolean keepSign) {
+
+ if (length > 16 || bits.size() < startIndex + length)
+ return null;
+
+ short result = 0;
+
+ boolean isNegative = false;
+ if (keepSign && bits.get(startIndex) == 1)
+ isNegative = true;
+ List<Byte> newBits = new ArrayList<Byte>();
+
+ if (isNegative) {
+ for (int i = 0; i < 16 - length; i++) {
+ newBits.add((byte) 1);
+ }
+ } else {
+ for (int i = 0; i < 16 - length; i++) {
+ newBits.add((byte) 0);
+ }
+ }
+
+ for (int i = 16 - length; i < 16; i++) {
+ newBits.add(bits.get(startIndex + i - (16 - length)));
+ }
+
+ for (int i = 0; i < newBits.size(); i++) {
+ result = (short) (result << 1);
+ result |= newBits.get(i);
+ }
+
+ return result;
+ }
+
+ static public Integer parseInteger(List<Byte> bits, int startIndex, int length, boolean keepSign) {
+
+ if (length > 32 || bits.size() < startIndex + length)
+ return null;
+
+ int result = 0;
+
+ boolean isNegative = false;
+ if (keepSign && bits.get(startIndex) == 1)
+ isNegative = true;
+ List<Byte> newBits = new ArrayList<Byte>();
+
+ if (isNegative) {
+ for (int i = 0; i < 32 - length; i++) {
+ newBits.add((byte) 1);
+ }
+ } else {
+ for (int i = 0; i < 32 - length; i++) {
+ newBits.add((byte) 0);
+ }
+ }
+
+ for (int i = 32 - length; i < 32; i++) {
+ newBits.add(bits.get(startIndex + i - (32 - length)));
+ }
+
+ for (int i = 0; i < newBits.size(); i++) {
+ result = (int) (result << 1);
+ result |= newBits.get(i);
+ }
+
+ return result;
+ }
+
+ static public Long parseLong(List<Byte> bits, int startIndex, int length, boolean keepSign) {
+
+ if (length > 64 || bits.size() < startIndex + length)
+ return null;
+
+ long result = 0;
+
+ boolean isNegative = false;
+ if (keepSign && bits.get(startIndex) == 1)
+ isNegative = true;
+ List<Byte> newBits = new ArrayList<Byte>();
+
+ if (isNegative) {
+ for (int i = 0; i < 64 - length; i++) {
+ newBits.add((byte) 1);
+ }
+ } else {
+ for (int i = 0; i < 64 - length; i++) {
+ newBits.add((byte) 0);
+ }
+ }
+
+ for (int i = 64 - length; i < 64; i++) {
+ newBits.add(bits.get(startIndex + i - (64 - length)));
+ }
+
+ for (int i = 0; i < newBits.size(); i++) {
+ result = (long) (result << 1);
+ result |= newBits.get(i);
+ }
+
+ return result;
+ }
+
+ static public Character parseChar(List<Byte> bits, int startIndex) {
+
+ if (bits.size() < startIndex + 6)
+ return null;
+
+ char result = 0;
+ for (int i = startIndex; i < startIndex + 6; i++){
+ result = (char) (result << 1);
+ result |= bits.get(i);
+ }
+
+
+ if (result >= 0 && result < 64){
+ return MAPPING[result];
+ }
+ else {
+ return null;
+ }
+ }
+
+ static public String parseString(List<Byte> bits, int startIndex, int length, boolean removeAtSigns) {
+
+ if (length <= 0 || bits.size() < startIndex + 6 * length) {
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < length; i += 6) {
+ Character c = MessageFieldCodecHelper.parseChar(bits, startIndex + i);
+
+ if (c == null)
+ return null;
+ else
+ sb.append(c);
+ }
+
+ if (removeAtSigns) {
+ return sb.toString().replace('@', ' ').trim();
+ }
+ return sb.toString();
+ }
+
+ static public String removeAtSigns(String str) {
+ return str.replace('@', ' ').trim();
+ }
+
+ static public String convertReservedChars(String str) {
+
+ char[] content = str.toCharArray();
+ StringBuilder sb = new StringBuilder();
+
+ for (int i = 0; i < content.length;) {
+ if (content[i] == '^') {
+ char a = content[i + 1];
+ char b = content[i + 2];
+
+ char c = (char) StringHelper.toByte(a, b);
+ sb.append(c);
+ i += 3;
+ } else {
+ sb.append(content[i]);
+ i++;
+ }
+ }
+ return sb.toString();
+ }
+
+ static public boolean byteToBits(List<Byte> bits, byte value, int numberOfBits, boolean keepSign) {
+
+ if (numberOfBits > 8)
+ return false;
+
+ BitSet bs = BitSet.valueOf(new long[] { value });
+ for (int i = numberOfBits - 1; i >= 0; i--) {
+ if (bs.get(i))
+ bits.add((byte) 0x01);
+ else
+ bits.add((byte) 0x00);
+ }
+ return true;
+ }
+
+ static public boolean shortToBits(List<Byte> bits, short value, int numberOfBits, boolean keepSign) {
+
+ if (numberOfBits > 16)
+ return false;
+
+ BitSet bs = BitSet.valueOf(new long[] { value });
+ for (int i = numberOfBits - 1; i >= 0; i--) {
+ if (bs.get(i))
+ bits.add((byte) 0x01);
+ else
+ bits.add((byte) 0x00);
+ }
+ return true;
+ }
+
+ static public boolean integerToBits(List<Byte> bits, int value, int numberOfBits, boolean keepSign) {
+
+ if (numberOfBits > 32)
+ return false;
+
+ BitSet bs = BitSet.valueOf(new long[] { value });
+ for (int i = numberOfBits - 1; i >= 0; i--) {
+ if (bs.get(i))
+ bits.add((byte) 0x01);
+ else
+ bits.add((byte) 0x00);
+ }
+ return true;
+ }
+
+ static public boolean longToBits(List<Byte> bits, long value, int numberOfBits, boolean keepSign) {
+
+ if (numberOfBits > 64)
+ return false;
+
+ BitSet bs = BitSet.valueOf(new long[] { value });
+ for (int i = numberOfBits - 1; i >= 0; i--) {
+ if (bs.get(i))
+ bits.add((byte) 0x01);
+ else
+ bits.add((byte) 0x00);
+ }
+ return true;
+ }
+
+ static public boolean asciiCharToBits(List<Byte> bits, char c, int numberOfBits) {
+
+ int index = MessageFieldCodecHelper.MappingList.indexOf(c);
+
+ if ( index >= 0 ) {
+
+ if (!MessageFieldCodecHelper.integerToBits(bits, index, 6, false))
+ return false;
+ }
+ return true;
+ }
+
+ static public boolean stringToBits(List<Byte> bits, String value, int length) {
+
+ if (value == null)
+ value = "";
+
+ List<Byte> tempBits = new ArrayList<Byte>();
+
+ boolean success = true;
+ for (int i = 0; i < ((length != 0) ? length : value.length()); i++) {
+ char c = (i >= value.length()) ? '@' : value.charAt(i);
+
+ int index = MessageFieldCodecHelper.MappingList.indexOf(c);
+ if (index >= 0) {
+ MessageFieldCodecHelper.asciiCharToBits(tempBits, c, 6);
+ } else {
+ MessageFieldCodecHelper.asciiCharToBits(tempBits, '^', 6);
+ char a = (char) ((c & 0xF0) >> 4);
+ char b = (char) (c & 0x0F);
+
+ char ac = StringHelper.fromHex(a);
+ char bc = StringHelper.fromHex(b);
+ MessageFieldCodecHelper.asciiCharToBits(tempBits, ac, 6);
+ MessageFieldCodecHelper.asciiCharToBits(tempBits, bc, 6);
+ }
+ }
+
+ bits.addAll(tempBits);
+ return success;
+ }
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public class RateOfTurnMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public RateOfTurnMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "rateOfTurn";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(setting.getFieldWidth() == 8);
+
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Byte b = MessageFieldCodecHelper.parseByte(bits, startIndex, setting.getFieldWidth(), true);
+
+ if (b == null)
+ return null;
+
+ try {
+ if (b == -128)
+ field.set(obj, AbstractAisSentence.RATE_OF_TURN_NOT_AVAILABLE);
+ else if (b == -127 || b == 127)
+ field.set(obj, AbstractAisSentence.RATE_OF_TURN_EXCEED_LIMIT);
+ else
+ field.set(obj, (b / 4.733) * (b / 4.733));
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Double val = field.getDouble(obj);
+
+ byte b = -128;
+ if (val != null) {
+ if (val == AbstractAisSentence.RATE_OF_TURN_EXCEED_LIMIT)
+ b = (byte) ((val > 0) ? 127 : -127);
+ else {
+ boolean negative = val < 0;
+ if (val < 0)
+ val = -val;
+ b = (byte) (Math.sqrt(val) * 4.733);
+
+ if (negative) b = (byte) -b;
+ }
+ }
+ if (!MessageFieldCodecHelper.byteToBits(bits, b, setting.getFieldWidth(), true)) {
+ return false;
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class ShortLatitudeMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ static private Log logger = LogFactory.getLog(ShortLatitudeMessageFieldCodec.class);
+
+ public ShortLatitudeMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "shortLatitude";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert (setting.getFieldWidth() == 17);
+
+ Short val = MessageFieldCodecHelper.parseShort(bits, startIndex, setting.getFieldWidth(), true);
+
+ if (val != null) {
+
+ try {
+ field.setDouble(obj, val / 60.0 / 10);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ ShortLatitudeMessageFieldCodec.logger.error("error parsing value", e);
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Double val = field.getDouble(obj);
+
+ if (val == null)
+ val = (double) 91;
+
+ return MessageFieldCodecHelper.shortToBits(bits, (short) (val * 60 * 10), setting.getFieldWidth(), true);
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ ShortLatitudeMessageFieldCodec.logger.error("error encode value", e);
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class ShortLongitudeMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ static private Log logger = LogFactory.getLog(ShortLongitudeMessageFieldCodec.class);
+
+ public ShortLongitudeMessageFieldCodec() {
+ super();
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "shortLongitude";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert (setting.getFieldWidth() == 18);
+
+ Short val = MessageFieldCodecHelper.parseShort(bits, startIndex, setting.getFieldWidth(), true);
+
+ if (val != null) {
+
+ try {
+ field.setDouble(obj, val / 60.0 / 10);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ ShortLongitudeMessageFieldCodec.logger.error("error parsing value", e);
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Double val = field.getDouble(obj);
+
+ if (val == null)
+ val = (double) 181;
+
+ return MessageFieldCodecHelper.shortToBits(bits, (short) (val * 60 * 10), setting.getFieldWidth(), true);
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ ShortLongitudeMessageFieldCodec.logger.error("error encode value", e);
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class ShortMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public ShortMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "short";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ if (bits.size() < startIndex + setting.getFieldWidth())
+ return null;
+
+ Short value = MessageFieldCodecHelper.parseShort(bits, startIndex, setting.getFieldWidth(), false);
+
+ if (value != null) {
+ try {
+ field.setShort(obj, value);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Short value = field.getShort(obj);
+
+ if (value != null) {
+ if (!MessageFieldCodecHelper.shortToBits(bits, value, setting.getFieldWidth(), false)) {
+ return false;
+ }
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public class SpeedMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ public SpeedMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "speed";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ assert(setting.getFieldWidth() == 10);
+ if (bits.size() - startIndex < setting.getFieldWidth())
+ return null;
+
+ Short b = MessageFieldCodecHelper.parseShort(bits, startIndex, setting.getFieldWidth(), false);
+
+ if (b == null || b < 0)
+ return null;
+
+ try {
+ if (b == 1023)
+ field.set(obj, AbstractAisSentence.SPEED_NOT_AVAILABLE);
+ else if (b == 1022)
+ field.set(obj, AbstractAisSentence.SPEED_EXCEED_LIMIT);
+ else
+ field.set(obj, b / 10.0);
+ return setting.getFieldWidth();
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Double val = field.getDouble(obj);
+
+ short b = 1023;
+ if (val != null && val >= 0) {
+ if (val == AbstractAisSentence.SPEED_EXCEED_LIMIT)
+ b = 1022;
+ else {
+ b = (short) (val * 10);
+ }
+ }
+ if (!MessageFieldCodecHelper.shortToBits(bits, b, setting.getFieldWidth(), false)) {
+ return false;
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class StringMessageFieldCodec extends AbstractMessageFieldCodec {
+
+ static private Log logger = LogFactory.getLog(StringMessageFieldCodec.class);
+
+ public StringMessageFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "string";
+ }
+
+ @Override
+ protected Integer doDecode(List<Byte> bits, int startIndex, Object obj,
+ Field field, FieldSetting setting) {
+
+ int length = setting.getFieldWidth();
+
+ if (length == 0) {
+ int remainder = bits.size() - startIndex;
+ length = (remainder / 6) * 6;
+ }
+
+ String value = MessageFieldCodecHelper.parseString(bits, startIndex, length, false);
+ value = MessageFieldCodecHelper.convertReservedChars(value);
+ value = MessageFieldCodecHelper.removeAtSigns(value);
+
+ if (value != null) {
+ try {
+ field.set(obj, value);
+ return length;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("unable to set field: " + field.getName(), e);
+ return null;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ protected boolean doEncode(List<Byte> bits, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object val = field.get(obj);
+
+ if (val != null && val instanceof String) {
+
+ if (MessageFieldCodecHelper.stringToBits(bits, (String)val, setting.getFieldWidth())) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ logger.error("unable to get value for field: " + field.getName());
+ return false;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("unable to get value from field: " + field.getName(), e);
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec.ifm;
+
+import java.util.List;
+
+import com.antu.nmea.sentence.ais.ifm.AbstractIfmSegment;
+
+public abstract class AbstractIfmCodec {
+
+ public AbstractIfmCodec() {
+ }
+
+ abstract public Integer decode(AbstractIfmSegment segment, List<Byte> bits, int startIndex);
+
+ abstract public boolean encode(AbstractIfmSegment segment, List<Byte> bits);
+}
--- /dev/null
+package com.antu.nmea.message.field.codec.ifm;
+
+import java.util.List;
+
+import com.antu.nmea.message.field.codec.MessageFieldCodecHelper;
+import com.antu.nmea.sentence.ais.ifm.AbstractIfmSegment;
+import com.antu.nmea.sentence.ais.ifm.IfmMessage01;
+
+public class Ifm01Codec extends AbstractIfmCodec {
+
+ public Ifm01Codec() {
+ }
+
+ @Override
+ public Integer decode(AbstractIfmSegment segment, List<Byte> bits,
+ int startIndex) {
+
+ assert(segment instanceof IfmMessage01);
+
+ IfmMessage01 msg = (IfmMessage01)segment;
+ msg.message = MessageFieldCodecHelper.parseString(bits, startIndex, bits.size() - startIndex, false);
+
+ if (msg.message == null)
+ return null;
+ return bits.size() - startIndex;
+ }
+
+ @Override
+ public boolean encode(AbstractIfmSegment segment, List<Byte> bits) {
+
+ assert(segment instanceof IfmMessage01);
+
+ IfmMessage01 msg = (IfmMessage01)segment;
+ assert(msg.message != null);
+
+ if (MessageFieldCodecHelper.stringToBits(bits, msg.message, msg.message.length())) {
+ return true;
+ }
+ return false;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.message.field.codec.ifm;
+
+import java.util.List;
+
+import com.antu.nmea.sentence.ais.ifm.AbstractIfmSegment;
+import com.antu.nmea.sentence.ais.ifm.RawIfmSegment;
+import com.antu.util.PrintableList;
+
+public class RawIfmCodec extends AbstractIfmCodec {
+
+ public RawIfmCodec() {
+ }
+
+ @Override
+ public Integer decode(AbstractIfmSegment segment, List<Byte> bits,
+ int startIndex) {
+
+ assert(segment instanceof RawIfmSegment);
+
+ RawIfmSegment seg = (RawIfmSegment)segment;
+ seg.dataBits = new PrintableList<Byte>();
+
+ for (int i = startIndex; i < bits.size(); i++) {
+ seg.dataBits.add(bits.get(i));
+ }
+
+ return bits.size() - startIndex;
+ }
+
+ @Override
+ public boolean encode(AbstractIfmSegment segment, List<Byte> bits) {
+ assert(segment instanceof RawIfmSegment);
+
+ RawIfmSegment seg = (RawIfmSegment)segment;
+ for (int i = 0; i < seg.dataBits.size(); i++) {
+ bits.add(seg.dataBits.get(i));
+ }
+ return true;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.*;
+
+public class AamSentence extends ParametricSentence {
+
+ public AamSentence() {
+ super();
+ }
+
+ public AamSentence(Date date) {
+ super(date);
+ }
+
+ public AamSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "aam";
+ }
+
+ @SentenceField(order = 1, fieldType="boolean")
+ public boolean arrivalCircleEntered = false;
+
+ @SentenceField(order = 2, fieldType="boolean")
+ public boolean perpendicularPassedAtWaypoint = false;
+
+ @SentenceField(order = 3, fieldType="double", precision=2)
+ public double arrivalCircleRadius = 0.0;
+
+ @SentenceField(order = 4, fieldType="char")
+ public char unitOfRadius = 'N';
+
+ @SentenceField(order = 5, fieldType="string")
+ public String waypointId = "";
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+
+public class AbkSentence extends ParametricSentence {
+
+ public AbkSentence() {
+ super();
+ }
+
+ public AbkSentence(Date date) {
+ super(date);
+ }
+
+ public AbkSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "abk";
+ }
+
+ @SentenceField(order = 1, fieldType = "integer", isRequired = false, fieldWidth = 9)
+ public Integer mmsi = null;
+
+ @SentenceField(order = 2, fieldType = "char", isRequired = false)
+ public Character channel = null;
+
+ @SentenceField(order = 3, fieldType = "integer")
+ public int messageId;
+
+ @SentenceField(order = 4, fieldType = "integer")
+ public int messageSequenceNumber;
+
+ @SentenceField(order = 5, fieldType = "integer")
+ public int typeOfAcknowledgement;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+//import java.util.ArrayList;
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public class AbmSentence extends AbstractAisSentence {
+
+ //private ArrayList<Byte> content = new ArrayList<Byte>();
+
+ public AbmSentence() {
+ super();
+ }
+
+ public AbmSentence(Date date) {
+ super(date);
+ }
+
+ public AbmSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public int getSequentialMessageId() {
+ return sequentialMessageId;
+ }
+
+ @Override
+ public int getTotalNumberOfSentences() {
+ return totalNumberOfSentences;
+ }
+
+ @Override
+ public int getSentenceNumber() {
+ return sentenceNumber;
+ }
+
+ @Override
+ public String sentenceType() {
+ return "abm";
+ }
+
+ @SentenceField(order = 1, fieldType = "integer")
+ public int totalNumberOfSentences;
+
+ @SentenceField(order = 2, fieldType = "integer")
+ public int sentenceNumber;
+
+ @SentenceField(order = 3, fieldType = "integer")
+ public int sequentialMessageId;
+
+ @SentenceField(order = 4, fieldType = "integer", fieldWidth = 9, isRequired = false)
+ public Integer destinationMMSI;
+
+ @SentenceField(order = 5, fieldType = "integer", isRequired = false)
+ public Integer aisChannelForBroadcast;
+
+ @SentenceField(order = 5, fieldType = "integer", isRequired = false, fieldWidth = 9)
+ public Integer messageId;
+
+ @SentenceField(order = 6, fieldType = "string", isIgnoredInReconstruction = true)
+ public String encapsulatedData;
+
+ @SentenceField(order = 7, fieldType = "integer", isIgnoredInReconstruction = true)
+ public int fillBits;
+
+ @Override
+ public String getEncapsulatedData() {
+ return this.encapsulatedData;
+ }
+
+ @Override
+ public int getFillBits() {
+ return this.fillBits;
+ }
+
+ @Override
+ public void increaseSentenceNumber() {
+
+ this.sentenceNumber++;
+
+ }
+
+ @Override
+ public void setEncapsulatedData(String content) {
+
+ this.encapsulatedData = content;
+ }
+
+ @Override
+ public void setFillBits(int fillBits) {
+
+ this.fillBits = fillBits;
+ }
+
+ @Override
+ public void setTotalSentenceCount(int total) {
+
+ this.totalNumberOfSentences = total;
+ }
+
+ @Override
+ public void setSentenceNumber(int number) {
+
+ this.sentenceNumber = number;
+ }
+
+ @Override
+ public void setSequenceId(Integer sequence) {
+
+ this.setSequenceId(sequence);
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public abstract class AbstractAisVesselSentence extends AbstractAisSentence {
+
+ public AbstractAisVesselSentence() {
+ super();
+ }
+
+ public AbstractAisVesselSentence(Date date) {
+ super(date);
+ }
+
+ public AbstractAisVesselSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @SentenceField(order = 1, fieldType = "integer")
+ public int totalNumberOfSentences = 1;
+
+ @SentenceField(order = 2, fieldType = "integer")
+ public int sentenceNumber = 1;
+
+ @SentenceField(order = 3, fieldType = "integer", isRequired = false)
+ public Integer sequentialMessageIdentifier = null;
+
+ @SentenceField(order = 4, fieldType = "char")
+ public char aisChannel;
+
+ @SentenceField(order = 5, fieldType = "string", isIgnoredInReconstruction = true)
+ public String encapsulatedContent;
+
+ @SentenceField(order = 6, fieldType = "integer", isIgnoredInReconstruction = true)
+ public int fillBits;
+
+ @Override
+ public String getEncapsulatedData() {
+ return this.encapsulatedContent;
+ }
+
+ @Override
+ public void setEncapsulatedData(String content) {
+ this.encapsulatedContent = content;
+ }
+
+ @Override
+ public int getFillBits() {
+ return this.fillBits;
+ }
+
+ @Override
+ public void setFillBits(int fillBits) {
+ this.fillBits = fillBits;
+ }
+
+ @Override
+ public void increaseSentenceNumber() {
+ this.sentenceNumber++;
+ }
+
+ @Override
+ public void setTotalSentenceCount(int total) {
+ this.totalNumberOfSentences = total;
+ }
+
+ @Override
+ public void setSentenceNumber(int number) {
+ this.sentenceNumber = number;
+ }
+
+ @Override
+ public void setSequenceId(Integer sequence) {
+ this.sequentialMessageIdentifier = sequence;
+ }
+
+ @Override
+ public int getSequentialMessageId() {
+ return this.sequentialMessageIdentifier;
+ }
+
+ @Override
+ public int getTotalNumberOfSentences() {
+ return this.totalNumberOfSentences;
+ }
+
+ @Override
+ public int getSentenceNumber() {
+ return this.sentenceNumber;
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.util.UtcTime;
+
+public class AcaSentence extends ParametricSentence {
+
+ public AcaSentence() {
+ super();
+ }
+
+ public AcaSentence(Date date) {
+ super(date);
+ }
+
+ public AcaSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "aca";
+ }
+
+ @SentenceField(order = 1, fieldType = "integer")
+ public int sequenceNumber;
+
+ @SentenceField(order = 2, fieldType = "latitude")
+ public double northEastCornerLatitude;
+
+ @SentenceField(order = 3, fieldType = "longitude")
+ public double northEastCornerLongitude;
+
+ @SentenceField(order = 4, fieldType = "latitude")
+ public double southWestCornerLatitude;
+
+ @SentenceField(order = 5, fieldType = "longitude")
+ public double southWestCornerLongitude;
+
+ @SentenceField(order = 6, fieldType = "integer")
+ public int transitionZoneSize;
+
+ @SentenceField(order = 7, fieldType = "integer")
+ public int channelANumber;
+
+ @SentenceField(order = 8, fieldType = "integer")
+ public int channelABandWidth;
+
+ @SentenceField(order = 9, fieldType = "integer")
+ public int channelBNumber;
+
+ @SentenceField(order = 10, fieldType = "integer")
+ public int channelBBandWidth;
+
+ @SentenceField(order = 11, fieldType = "integer")
+ public int tranceivingModeControl;
+
+ @SentenceField(order = 12, fieldType = "integer")
+ public int powerLevelControl;
+
+ @SentenceField(order = 13, fieldType = "char")
+ public char informationSource;
+
+ @SentenceField(order = 14, fieldType = "integer", isRequired = false)
+ public Integer inUseFlag;
+
+ @SentenceField(order = 15, fieldType = "time", isRequired = false)
+ public UtcTime timeOfInUseChange;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+
+public class AckSentence extends ParametricSentence {
+
+ public AckSentence() {
+ super();
+ }
+
+ public AckSentence(Date date) {
+ super(date);
+ }
+
+ public AckSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "ack";
+ }
+
+ @SentenceField(order = 1, fieldType = "integer")
+ public int alarmNumberAtSource;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.util.UtcTime;
+
+public class AcsSentence extends ParametricSentence {
+
+ public AcsSentence() {
+ }
+
+ public AcsSentence(Date date) {
+ super(date);
+ }
+
+ public AcsSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "acs";
+ }
+
+ @SentenceField(order = 1, fieldType = "integer", isRequired = false)
+ public Integer sequenceNumber;
+
+ @SentenceField(order = 2, fieldType = "integer")
+ public int originatorMMSI;
+
+ @SentenceField(order = 3, fieldType = "time")
+ public UtcTime timeOfReceipt;
+
+ @SentenceField(order = 4, fieldType = "integer", fieldWidth = 2)
+ public int day;
+
+ @SentenceField(order = 5, fieldType = "integer", fieldWidth = 2)
+ public int month;
+
+ @SentenceField(order = 6, fieldType = "integer")
+ public int year;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+
+public class AirSentence extends ParametricSentence {
+
+ public AirSentence() {
+ super();
+ }
+
+ public AirSentence(Date date) {
+ super(date);
+ }
+
+ public AirSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "air";
+ }
+
+ @SentenceField(order = 1, fieldType="integer", fieldWidth = 9)
+ public int mmsiOfInterrogatedStation1;
+
+ @SentenceField(order = 2, fieldType="integer")
+ public int messageRequestedFromStation1;
+
+ @SentenceField(order = 3, fieldType="integer", isRequired = false)
+ public Integer messageSubSection1ForStation1;
+
+ @SentenceField(order = 4, fieldType="integer")
+ public int numberOfSecondMessageRequestedFromStation1 = -1;
+
+ @SentenceField(order = 5, fieldType="integer", isRequired = false)
+ public Integer messageSubSection2ForStation1;
+
+ @SentenceField(order = 6, fieldType="integer", fieldWidth = 9)
+ public int mmsiOfInterrogatedStation2 = -1;
+
+ @SentenceField(order = 7, fieldType="integer")
+ public int numberOfMessageRequestedFromStation2 = -1;
+
+ @SentenceField(order = 8, fieldType="integer")
+ public int messageSubSection1ForStation2 = -1;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+
+public class AlmSentence extends ParametricSentence {
+
+ public AlmSentence() {
+ super();
+ }
+
+ public AlmSentence(Date date) {
+ super(date);
+ }
+
+ public AlmSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "alm";
+ }
+
+ @SentenceField(order = 1, fieldType="integer")
+ public int totalNumberOfSentences;
+
+ @SentenceField(order = 2, fieldType="integer")
+ public int sentenceNumber;
+
+ @SentenceField(order = 3, fieldType="integer", fieldWidth = 2)
+ public int satellitePRNNumber;
+
+ @SentenceField(order = 4, fieldType="integer")
+ public int gpsWeekNumber;
+
+ @SentenceField(order = 5, fieldType="hex", fieldWidth = 2)
+ public int svHealth;
+
+ @SentenceField(order = 6, fieldType="hex", fieldWidth = 4)
+ public int eccentricity;
+
+ @SentenceField(order = 7, fieldType="hex", fieldWidth = 2)
+ public int almanacReferenceTime;
+
+ @SentenceField(order = 8, fieldType="hex", fieldWidth = 4)
+ public int inclinationAngle;
+
+ @SentenceField(order = 9, fieldType="hex", fieldWidth = 4)
+ public int rateOfRightAscension;
+
+ @SentenceField(order = 10, fieldType="hex", fieldWidth = 6)
+ public int rootOfSemiMajorAxis;
+
+ @SentenceField(order = 11, fieldType="hex", fieldWidth = 6)
+ public int argumentOfPerigee;
+
+ @SentenceField(order = 12, fieldType="hex", fieldWidth = 6)
+ public int longtitudeOfAscensionNode;
+
+ @SentenceField(order = 13, fieldType="hex", fieldWidth = 6)
+ public int meanAnomaly;
+
+ @SentenceField(order = 14, fieldType="hex", fieldWidth = 3)
+ public int clockParameter1;
+
+ @SentenceField(order = 15, fieldType="hex", fieldWidth = 3)
+ public int clockParameter2;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.util.UtcTime;
+
+public class AlrSentence extends ParametricSentence {
+
+ public AlrSentence() {
+ super();
+ }
+
+ public AlrSentence(Date date) {
+ super(date);
+ }
+
+ public AlrSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "alr";
+ }
+
+ @SentenceField(order = 1, fieldType = "time")
+ public UtcTime timeOfAlarmConditionChange;
+
+ @SentenceField(order = 2, fieldType = "integer")
+ public int uniqueAlarmNumberAtAlarmSource;
+
+ @SentenceField(order = 3, fieldType = "boolean")
+ public boolean thresholdExceeded;
+
+ @SentenceField(order = 4, fieldType = "boolean")
+ public boolean alarmStateAcknowledged;
+
+ @SentenceField(order = 5, fieldType = "string")
+ public String alarmDescription;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+
+public class ApbSentence extends ParametricSentence {
+
+ public ApbSentence() {
+ super();
+ }
+
+ public ApbSentence(Date date) {
+ super(date);
+ }
+
+ public ApbSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "apb";
+ }
+
+ @SentenceField(order = 1, fieldType = "boolean")
+ public boolean isDataValid;
+
+ @SentenceField(order = 2, fieldType = "boolean")
+ public boolean isDataValid2;
+
+ @SentenceField(order = 3, fieldType = "double")
+ public double magnitudeOfXTE;
+
+ @SentenceField(order = 4, fieldType = "char")
+ public char directionToSteer;
+
+ @SentenceField(order = 5, fieldType = "char")
+ public char XTEUnits;
+
+ @SentenceField(order = 6, fieldType = "boolean")
+ public boolean isArrivalCircleEntered;
+
+ @SentenceField(order = 7, fieldType = "boolean")
+ public boolean isPerpendicularPassedAtWaypoint;
+
+ @SentenceField(order = 8, fieldType = "double")
+ public double bearingOriginToDestination;
+
+ @SentenceField(order = 9, fieldType = "char")
+ public char bearingTypeMagneticOrTrue;
+
+ @SentenceField(order = 10, fieldType = "string")
+ public String destinationWaypointId;
+
+ @SentenceField(order = 11, fieldType = "double")
+ public double bearingPresentToDestination;
+
+ @SentenceField(order = 12, fieldType = "char")
+ public char presentBearingTypeMagneticOrTrue;
+
+ @SentenceField(order = 13, fieldType = "double")
+ public double headingToSteerToDestination;
+
+ @SentenceField(order = 14, fieldType = "char")
+ public char headingToSteerToDestinationTypeMagneticOrTrue;
+
+ @SentenceField(order = 15, fieldType = "char")
+ public char modeIndicator;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.sentence.ais.AbstractAisSentence;
+
+public class BbmSentence extends AbstractAisSentence {
+
+ public BbmSentence() {
+ super();
+ }
+
+ public BbmSentence(Date date) {
+ super(date);
+ }
+
+ public BbmSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public int getSequentialMessageId() {
+ return sequentialMessageId;
+ }
+
+ @Override
+ public int getTotalNumberOfSentences() {
+ return totalNumberOfSentences;
+ }
+
+ @Override
+ public int getSentenceNumber() {
+ return sentenceNumber;
+ }
+
+ @Override
+ public String sentenceType() {
+ return "bbm";
+ }
+
+ @SentenceField(order = 1, fieldType = "integer")
+ public int totalNumberOfSentences;
+
+ @SentenceField(order = 2, fieldType = "integer")
+ public int sentenceNumber;
+
+ @SentenceField(order = 3, fieldType = "integer")
+ public int sequentialMessageId;
+
+ @SentenceField(order = 4, fieldType = "integer", fieldWidth = 9)
+ public int destinationMMSI;
+
+ @SentenceField(order = 5, fieldType = "integer")
+ public int aisChannelForBroadcast;
+
+ @SentenceField(order = 5, fieldType = "integer", fieldWidth = 2)
+ public int messageId;
+
+ @SentenceField(order = 6, fieldType = "string", isIgnoredInReconstruction = true)
+ public String encapsulatedData;
+
+ @SentenceField(order = 7, fieldType = "integer", isIgnoredInReconstruction = true)
+ public int fillBits;
+
+ @Override
+ public String getEncapsulatedData() {
+ return this.encapsulatedData;
+ }
+
+ @Override
+ public int getFillBits() {
+ return this.fillBits;
+ }
+
+ @Override
+ public void increaseSentenceNumber() {
+
+ this.sentenceNumber++;
+
+ }
+
+ @Override
+ public void setEncapsulatedData(String content) {
+
+ this.encapsulatedData = content;
+ }
+
+ @Override
+ public void setFillBits(int fillBits) {
+
+ this.fillBits = fillBits;
+ }
+
+ @Override
+ public void setTotalSentenceCount(int total) {
+
+ this.totalNumberOfSentences = total;
+ }
+
+ @Override
+ public void setSentenceNumber(int number) {
+
+ this.sentenceNumber = number;
+ }
+
+ @Override
+ public void setSequenceId(Integer sequence) {
+
+ this.setSequenceId(sequence);
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.util.UtcTime;
+
+public class BecSentence extends ParametricSentence {
+
+ public BecSentence() {
+ super();
+ }
+
+ public BecSentence(Date date) {
+ super(date);
+ }
+
+ public BecSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "bec";
+ }
+
+ @SentenceField(order = 1, fieldType = "time")
+ public UtcTime utcOfObservation;
+
+ @SentenceField(order = 2, fieldType = "latitude")
+ public double waypointLatitude;
+
+ @SentenceField(order = 3, fieldType = "longitude")
+ public double waypointLongitude;
+
+ @SentenceField(order = 4, fieldType = "double")
+ public double trueBearing;
+
+ @SentenceField(order = 5, fieldType = "char")
+ public char bearingTypeTrue;
+
+ @SentenceField(order = 6, fieldType = "double")
+ public double magneticBearing;
+
+ @SentenceField(order = 7, fieldType = "char")
+ public char bearingTypeMagnetic;
+
+ @SentenceField(order = 8, fieldType = "double")
+ public double distance;
+
+ @SentenceField(order = 9, fieldType = "char")
+ public char distanceUnitNauticleMiles;
+
+ @SentenceField(order = 10, fieldType = "string")
+ public String waypointId;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+
+public class BodSentence extends ParametricSentence {
+
+ public BodSentence() {
+ super();
+ }
+
+ public BodSentence(Date date) {
+ super(date);
+ }
+
+ public BodSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "bod";
+ }
+
+ @SentenceField(order = 1, fieldType = "double")
+ public double bearingDegreesTrue;
+
+ @SentenceField(order = 2, fieldType = "char")
+ public char bearingTypeTrue;
+
+ @SentenceField(order = 3, fieldType = "double")
+ public double bearingDegreesMagnetic;
+
+ @SentenceField(order = 4, fieldType = "char")
+ public char bearingTypeMagnetic;
+
+ @SentenceField(order = 5, fieldType = "string")
+ public String destinationWaypointId;
+
+ @SentenceField(order = 6, fieldType = "string")
+ public String originWaypointId;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.util.UtcTime;
+
+public class BwcSentence extends ParametricSentence {
+
+ public BwcSentence() {
+ super();
+ }
+
+ public BwcSentence(Date date) {
+ super(date);
+ }
+
+ public BwcSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "bwc";
+ }
+
+ @SentenceField(order = 1, fieldType = "time")
+ public UtcTime observationTime;
+
+ @SentenceField(order = 2, fieldType = "latitude")
+ public double waypointLatitude;
+
+ @SentenceField(order = 3, fieldType = "longitude")
+ public double waypointLongitude;
+
+ @SentenceField(order = 4, fieldType = "double")
+ public double bearingDegreesTrue;
+
+ @SentenceField(order = 5, fieldType = "char")
+ public char bearingTypeTrue;
+
+ @SentenceField(order = 6, fieldType = "double")
+ public double bearingDegreesMagnetic;
+
+ @SentenceField(order = 7, fieldType = "char")
+ public char bearingTypeMagnetic;
+
+ @SentenceField(order = 8, fieldType = "double")
+ public double distanceToWaypoint;
+
+ @SentenceField(order = 9, fieldType = "char")
+ public char distanceUnitNauticleMiles;
+
+ @SentenceField(order = 10, fieldType = "string")
+ public String waypointId;
+
+ @SentenceField(order = 11, fieldType = "char")
+ public char modeIndicator;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.util.UtcTime;
+
+public class BwrSentence extends ParametricSentence {
+
+ public BwrSentence() {
+ super();
+ }
+
+ public BwrSentence(Date date) {
+ super(date);
+ }
+
+ public BwrSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "bwr";
+ }
+
+ @SentenceField(order = 1, fieldType = "time")
+ public UtcTime observationTime;
+
+ @SentenceField(order = 2, fieldType = "latitude")
+ public double waypointLatitude;
+
+ @SentenceField(order = 3, fieldType = "longitude")
+ public double waypointLongitude;
+
+ @SentenceField(order = 4, fieldType = "double")
+ public double bearingDegreesTrue;
+
+ @SentenceField(order = 5, fieldType = "char")
+ public char bearingTypeTrue;
+
+ @SentenceField(order = 6, fieldType = "double")
+ public double bearingDegreesMagnetic;
+
+ @SentenceField(order = 7, fieldType = "char")
+ public char bearingTypeMagnetic;
+
+ @SentenceField(order = 8, fieldType = "double")
+ public double distanceToWaypoint;
+
+ @SentenceField(order = 9, fieldType = "char")
+ public char distanceUnitNauticleMiles;
+
+ @SentenceField(order = 10, fieldType = "string")
+ public String waypointId;
+
+ @SentenceField(order = 11, fieldType = "char")
+ public char modeIndicator;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.List;
+
+public interface EncapsulationItem extends IGroupedSentence {
+
+ boolean addEncapsulatedData(String content, int fillBits);
+
+ void cleanup();
+
+ List<Byte> getRawData();
+
+ void setEncapsulatedData(String content);
+
+ String getEncapsulatedData();
+
+ int getFillBits();
+
+ void setFillBits(int fillBits);
+
+ void increaseSentenceNumber();
+
+ void setTotalSentenceCount(int total);
+
+ void setSentenceNumber(int number);
+
+ void setSequenceId(Integer sequence);
+
+ IEncapsulatedSentence getEncapsulatedSentence();
+
+ void setEncapsulatedSentence(IEncapsulatedSentence sentence);
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+public abstract class EncapsulationSentence extends NmeaSentence implements EncapsulationItem {
+
+ private ArrayList<Byte> rawData = new ArrayList<Byte>();
+
+ public EncapsulationSentence() {
+ super();
+ }
+
+ public EncapsulationSentence(Date date) {
+ super(date);
+ }
+
+ public EncapsulationSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public void concatenate(IGroupedSentence sentence) {
+
+ if (sentence instanceof EncapsulationSentence) {
+
+ EncapsulationSentence newSen = (EncapsulationSentence)sentence;
+
+ this.increaseSentenceNumber();
+ this.rawData.addAll(newSen.rawData);
+ }
+ }
+
+ @Override
+ public boolean addEncapsulatedData(String content, int fillBits) {
+
+ Byte[] sixBytes = EncapsulationSentence.convertStringToBits(content);
+
+ if (sixBytes != null &&
+ this.rawData.addAll(EncapsulationSentence.getBits(sixBytes, fillBits))) {
+ this.increaseSentenceNumber();
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean decodeStringData(String content) {
+ Byte[] sixBytes = EncapsulationSentence.convertStringToBits(content);
+
+ if (sixBytes != null &&
+ this.rawData.addAll(EncapsulationSentence.getBits(sixBytes, this.getFillBits()))) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean isComplete() {
+ return this.getTotalNumberOfSentences() == this.getSentenceNumber();
+ }
+
+ @Override
+ public void cleanup() {
+ this.rawData.clear();
+ }
+
+ @Override
+ public List<Byte> getRawData() {
+ return this.rawData;
+ }
+
+ static public Byte sixBitToByte(byte sixBit) {
+
+ if (sixBit < 0 || sixBit - (sixBit & 0x3F) != 0)
+ return null;
+
+ byte value = sixBit;
+ if (sixBit < 0x28) {
+ value += 0x30;
+ } else {
+ value += 0x38;
+ }
+ return value;
+ }
+
+ static public Byte byteToSixBit(byte value) {
+
+ if ((value >= 0x30 && value <= 0x57) || (value >= 0x60 && value <= 0x77)) {
+
+ short result = value;
+ result += 0x28;
+
+ if (result > 0x80) {
+ result += 0x20;
+ } else {
+ result += 0x28;
+ }
+
+ return (byte) (result & 0x3F);
+ }
+ else
+ return null;
+ }
+
+ static public String convertSixBitsToString(Byte[] sixBits) {
+
+ int length = sixBits.length;
+
+ int remainder = length % 6;
+ int paddingLength = remainder == 0 ? 0 : 6 - remainder;
+
+ Byte[] paddedBits = new Byte[length + paddingLength];
+
+ for (int i = 0; i < length; i++) {
+ paddedBits[i] = sixBits[i];
+ }
+
+ Byte[] content = new Byte[(length + paddingLength) / 6];
+
+ for (int i = 0; i < content.length; i++) {
+
+ int pos = i * 6;
+ content[i] = 0;
+ content[i] = (byte) (content[i] | (sixBits[pos] << 5));
+ content[i] = (byte) (content[i] | (sixBits[pos + 1] << 4));
+ content[i] = (byte) (content[i] | (sixBits[pos + 2] << 3));
+ content[i] = (byte) (content[i] | (sixBits[pos + 3] << 2));
+ content[i] = (byte) (content[i] | (sixBits[pos + 4] << 1));
+ content[i] = (byte) (content[i] | (sixBits[pos + 5]));
+ }
+
+ byte[] byteContent = new byte[content.length];
+ for (int i = 0; i < content.length; i++)
+ byteContent[i] = EncapsulationSentence.sixBitToByte(content[i]);
+
+ try {
+ String result = new String(byteContent, "ASCII");
+ return result;
+ } catch (UnsupportedEncodingException e) {
+ return null;
+ }
+ }
+
+ static public Byte[] convertStringToBits(String content) {
+
+ try {
+ byte[] byteContent = content.getBytes("ASCII");
+
+ Byte[] result = new Byte[byteContent.length * 6];
+
+ for (int i = 0; i < byteContent.length; i++) {
+ Byte temp = EncapsulationSentence.byteToSixBit(byteContent[i]);
+
+ if (temp == null)
+ return null;
+
+ result[i * 6] = (byte) ((temp & 0x20) >> 5);
+ result[i * 6 + 1] = (byte) ((temp & 0x10) >> 4);
+ result[i * 6 + 2] = (byte) ((temp & 0x08) >> 3);
+ result[i * 6 + 3] = (byte) ((temp & 0x04) >> 2);
+ result[i * 6 + 4] = (byte) ((temp & 0x02) >> 1);
+ result[i * 6 + 5] = (byte) (temp & 0x01);
+ }
+ return result;
+ } catch (UnsupportedEncodingException e) {
+
+ return null;
+ }
+ }
+
+ static public Byte[] convertBitsToSixBits(List<Byte> bits) {
+
+ int length = (int) Math.ceil(bits.size() / 6);
+
+ Byte[] bytes = new Byte[length];
+ for (int i = 0; i < length; i++) {
+
+ if (i == length - 1) {
+ int fillBits = bits.size() % 6;
+
+ byte b = 0;
+ for (int j = 0; j < fillBits; j++) {
+ b |= (bits.get(i * 6 + fillBits) << (fillBits - j - 1));
+ }
+
+ bytes[i] = b;
+ } else {
+ byte b = 0;
+ b |= (bits.get(i * 6) << 5);
+ b |= (bits.get(i * 6 + 1) << 4);
+ b |= (bits.get(i * 6 + 2) << 3);
+ b |= (bits.get(i * 6 + 3) << 2);
+ b |= (bits.get(i * 6 + 4) << 1);
+ b |= bits.get(i * 6 + 5);
+
+ bytes[i] = b;
+ }
+ }
+
+ return bytes;
+ }
+
+ static public List<Byte> getBits(Byte[] sixBytes, int fillBits) {
+ List<Byte> result = new ArrayList<Byte>();
+
+ int padding = (fillBits == 0) ? 0 : fillBits;
+
+ for (int i = 0; i < sixBytes.length - padding; i++) {
+ result.add(sixBytes[i]);
+ }
+
+ return result;
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
+
+import com.antu.nmea.sentence.exception.SentenceCreationException;
+import com.antu.nmea.util.StringHelper;
+
+public class GenericSentenceFactory {
+
+ private HashMap<String, Class<INmeaSentence>> sentenceClasses = new HashMap<String, Class<INmeaSentence>>();
+
+ private INmeaSentence createSentence(java.util.Date timestamp, Class<INmeaSentence> clz)
+ throws SentenceCreationException {
+
+ try {
+ Constructor<INmeaSentence> constructor = clz.getConstructor(java.util.Date.class);
+
+ INmeaSentence obj = constructor.newInstance(timestamp);
+
+ return obj;
+ } catch (NoSuchMethodException | SecurityException |
+ IllegalArgumentException | InvocationTargetException |
+ InstantiationException | IllegalAccessException |
+ NullPointerException e) {
+ throw new SentenceCreationException(e);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public INmeaSentence createSentence(java.util.Date timestamp, String sentenceType)
+ throws SentenceCreationException {
+ if (sentenceClasses.containsKey(sentenceType)) {
+ return this.createSentence(timestamp, sentenceClasses.get(sentenceType));
+ } else {
+
+ StringBuilder sb = new StringBuilder(this.getClass().getPackage().getName());
+ sb.append('.').append(StringHelper.capitalizeFirstChar(sentenceType)).append("Sentence");
+
+ try {
+ Class<INmeaSentence> clz = (Class<INmeaSentence>) Class.forName(sb.toString());
+ sentenceClasses.put(sentenceType, clz);
+
+ return this.createSentence(timestamp, clz);
+ } catch (ClassNotFoundException e) {
+ throw new SentenceCreationException(e);
+ }
+ }
+ }
+
+ static public GenericSentenceFactory Instance = new GenericSentenceFactory();
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+/**
+ * Marker interface.
+ *
+ * @author yining
+ *
+ */
+public interface IEncapsulatedSentence {
+
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+/**
+ *
+ * @author yining
+ *
+ * A grouped sentence provides the interface for multi-sentence sentences
+ * as well as encapsulation sentences
+ */
+public interface IGroupedSentence extends INmeaSentence {
+
+ int getSequentialMessageId();
+
+ int getTotalNumberOfSentences();
+
+ int getSentenceNumber();
+
+ boolean isComplete();
+
+ void concatenate(IGroupedSentence sentence);
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+/**
+ * @author yining
+ *
+ * This is the base of all NmeaSentence objects
+ *
+ * NmeaSentence objects are divided into 5 groups:
+ * 1. Parametric sentences
+ * 2. Multi-sentence sentences
+ * 3. Proprietary sentences
+ * 4. Encapsulation sentences
+ * 5. Query sentences
+ *
+ * A parametric sentence is a simple form of NMEA sentence, with no embedded data. A parametric
+ * sentence may be consisted of several sentences, but each sentence is independent of each other,
+ * and hence the encoding and decoding of a particular sentence is not related to other sentences,
+ * even if they are in the same group. A typical parametric sentence is RMC. Parametric sentences
+ * should extend ParametricSentence, as this information is used when decoding and encoding takes place.
+ *
+ * A multi-sentence sentence is a parametric sentence that would require several sentences together to
+ * form a complete sentence. A typical multi-sentence sentence is TUT, TUT could require up to 255 TUT
+ * sentences to form a complete sentence. Missing a sentence could cause loss of information.
+ *
+ * A multi-sentence object should be first registered with the MultiSentenceTable, which is a singleton.
+ *
+ * e.g.:
+ * MultiSentenceTable.instance().registerType("VDN");
+ *
+ * TUT sentence is pre-registered.
+ *
+ * A proprietary sentence is exactly as defined in the NMEA standards. Any sentence that begins with "$P"
+ * or "!P" is treated as a proprietary sentence.
+ *
+ * Encapsulation sentences and query sentences are defined exactly as in the standards. Encapsulation sentences
+ * must extend the EncapsulationSentence class and query sentences are produced as a QuerySentence object.
+ */
+public interface INmeaSentence {
+
+ String sentenceType();
+
+ Date getReceiveDate();
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.HashMap;
+
+public class MultiSentenceTable {
+
+ static private MultiSentenceTable Instance = new MultiSentenceTable();
+
+ private HashMap<String, Boolean> table = new HashMap<String, Boolean>();
+
+ private MultiSentenceTable() {
+
+ table.put("TUT", true);
+ }
+
+ static public MultiSentenceTable instance() {
+ return MultiSentenceTable.Instance;
+ }
+
+ public boolean isMultiSentenceType(String sentenceType) {
+ return this.table.containsKey(sentenceType.toUpperCase());
+ }
+
+ public void registerType(String sentenceType) {
+ this.table.put(sentenceType.toUpperCase(), true);
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.lang.reflect.Field;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.codec.AbstractNmeaSentenceCodec;
+
+public abstract class NmeaSentence implements INmeaSentence {
+
+ private Date receiveDate;
+
+ public NmeaSentence() {
+ this.receiveDate = Calendar.getInstance().getTime();
+ }
+
+ public NmeaSentence(Date date) {
+ this.receiveDate = date;
+
+ if (this.receiveDate == null)
+ this.receiveDate = Calendar.getInstance().getTime();
+ }
+
+ public NmeaSentence(long currentTimeSinceEpochInSeconds) {
+
+ Calendar cal = Calendar.getInstance();
+ cal.setTimeInMillis(currentTimeSinceEpochInSeconds * 1000);
+
+ this.receiveDate = cal.getTime();
+ }
+
+ abstract public String sentenceType();
+
+ @Override
+ public Date getReceiveDate() {
+ return receiveDate;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder(this.sentenceType()).append("\n");
+
+ List<Field> sentenceFields = AbstractNmeaSentenceCodec.getSentenceFields(this);
+
+ try {
+ for (Field field : sentenceFields) {
+ SentenceField annotation = (SentenceField)field.getAnnotation(SentenceField.class);
+
+ if (!annotation.isIgnoredInReconstruction()) {
+ sb.append(field.getName()).append(": ");
+
+ if (field.get(this) == null) {
+ sb.append("null");
+ } else {
+ sb.append(field.get(this).toString());
+ }
+ sb.append("\n");
+ }
+ }
+
+ List<Field> messageFields = AbstractNmeaSentenceCodec.getMessageFields(this);
+ for (Field field : messageFields) {
+ sb.append(field.getName()).append(": ");
+ sb.append(field.get(this).toString());
+ sb.append("\n");
+ }
+
+ if (this instanceof EncapsulationSentence) {
+ IEncapsulatedSentence encapsulated = ((EncapsulationSentence)this).getEncapsulatedSentence();
+
+ if (encapsulated != null) {
+ List<Field> embeddedFields = AbstractNmeaSentenceCodec.getMessageFields(encapsulated);
+
+ for (Field eField : embeddedFields) {
+ sb.append(eField.getName()).append(": ");
+ sb.append(eField.get(encapsulated).toString());
+ sb.append("\n");
+ }
+ }
+ }
+
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ }
+
+ return sb.toString();
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+public abstract class ParametricSentence extends NmeaSentence {
+
+ public ParametricSentence() {
+ super();
+ }
+
+ public ParametricSentence(Date date) {
+ super(date);
+ }
+
+ public ParametricSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
+
+import com.antu.nmea.util.StringHelper;
+
+public class ParametricSentenceFactory {
+
+ private HashMap<String, Class<ParametricSentence>> sentences = new HashMap<String, Class<ParametricSentence>>();
+
+ private ParametricSentence createSentence(java.util.Date timestamp, Class<ParametricSentence> clz) {
+
+ try {
+ Constructor<ParametricSentence> constructor = clz.getConstructor(java.util.Date.class);
+
+ Object obj = constructor.newInstance(timestamp);
+
+ if (obj instanceof ParametricSentence) {
+ return (ParametricSentence)obj;
+ } else {
+ return null;
+ }
+ } catch (NoSuchMethodException | SecurityException |
+ IllegalArgumentException | InvocationTargetException |
+ InstantiationException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ public ParametricSentence createSentence(java.util.Date timestamp, String sentenceType) {
+ if (sentences.containsKey(sentenceType)) {
+ return this.createSentence(timestamp, sentences.get(sentenceType));
+ } else {
+
+ StringBuilder sb = new StringBuilder(this.getClass().getPackage().getName());
+ sb.append('.').append(StringHelper.capitalizeFirstChar(sentenceType)).append("Sentence");
+
+ try {
+ @SuppressWarnings("unchecked")
+ Class<ParametricSentence> clz = (Class<ParametricSentence>) Class.forName(sb.toString());
+ sentences.put(sentenceType, clz);
+
+ return this.createSentence(timestamp, clz);
+ } catch (ClassNotFoundException e) {
+ return null;
+ }
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+public class QuerySentence extends NmeaSentence {
+
+ public QuerySentence() {
+ super();
+ }
+
+ public QuerySentence(Date date) {
+ super(date);
+ }
+
+ public QuerySentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "query";
+ }
+
+ public String requestTalker = "";
+
+ public String requestedTalker = "";
+
+ public String query = "";
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+import com.antu.nmea.annotation.SentenceField;
+
+public class TutSentence extends NmeaSentence {
+
+ public TutSentence() {
+ super();
+ }
+
+ public TutSentence(Date date) {
+ super(date);
+ }
+
+ public TutSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "tut";
+ }
+
+ @SentenceField(order = 1, fieldType = "string")
+ public String sourceIdentifier;
+
+ @SentenceField(order = 2, fieldType = "string")
+ public String translationCode;
+
+ @SentenceField(order = 3, fieldType = "string")
+ public String textBody;
+
+ public boolean isComplete = true;
+
+ public boolean isTranslated = true;
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+public class VdmSentence extends AbstractAisVesselSentence {
+
+ public VdmSentence() {
+ super();
+ }
+
+ public VdmSentence(Date date) {
+ super(date);
+ }
+
+ public VdmSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "vdm";
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence;
+
+import java.util.Date;
+
+public class VdoSentence extends AbstractAisVesselSentence {
+
+ public VdoSentence() {
+ super();
+ }
+
+ public VdoSentence(Date date) {
+ super(date);
+ }
+
+ public VdoSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public String sentenceType() {
+ return "vdo";
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+
+abstract public class AbstractAisMessage implements IEncapsulatedAisMessage {
+
+ public AbstractAisMessage() {
+ }
+
+ @Override
+ public int messageType() {
+ return this.messageId;
+ }
+
+ @MessageField(order = 1, requiredBits = 6, fieldType = "short")
+ public short messageId;
+
+ @MessageField(order = 2, requiredBits = 2, fieldType = "short")
+ public short repeatIndicator;
+
+ @MessageField(order = 3, requiredBits = 30, fieldType = "integer")
+ public int mmsi;
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import java.util.Date;
+
+import com.antu.nmea.sentence.EncapsulationSentence;
+import com.antu.nmea.sentence.IEncapsulatedSentence;
+
+public abstract class AbstractAisSentence extends EncapsulationSentence {
+
+ public static final double RATE_OF_TURN_NOT_AVAILABLE = 10000;
+ public static final double RATE_OF_TURN_EXCEED_LIMIT = 800;
+
+ public static final double SPEED_EXCEED_LIMIT = 102.2;
+ public static final double SPEED_NOT_AVAILABLE = 200;
+
+ public static final double COURSE_NOT_AVAILABLE = 360;
+ public static final double LATITUDE_NOT_AVAILABLE = 91;
+ public static final double LONGITUDE_NOT_AVAILABLE = 181;
+ public static final short HEADING_NOT_AVAILABLE = 511;
+
+ public IEncapsulatedAisMessage aisMessage;
+
+ public AbstractAisSentence() {
+ super();
+ }
+
+ public AbstractAisSentence(Date date) {
+ super(date);
+ }
+
+ public AbstractAisSentence(long currentTimeSinceEpochInSeconds) {
+ super(currentTimeSinceEpochInSeconds);
+ }
+
+ @Override
+ public IEncapsulatedSentence getEncapsulatedSentence() {
+ return aisMessage;
+ }
+
+ @Override
+ public void setEncapsulatedSentence(IEncapsulatedSentence sentence) {
+ this.aisMessage = (IEncapsulatedAisMessage) sentence;
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.util.PrintableList;
+
+public class AisMessage1 extends AbstractAisMessage {
+
+ public AisMessage1() {
+ this.messageId = 1;
+ }
+
+ @MessageField(order = 4, requiredBits = 4, fieldType = "short")
+ public short navigationalStatus;
+
+ @MessageField(order = 5, requiredBits = 8, fieldType = "rateOfTurn")
+ public double rateOfTurn = AbstractAisSentence.RATE_OF_TURN_NOT_AVAILABLE;
+
+ @MessageField(order = 6, requiredBits = 10, fieldType = "speed")
+ public double speedOverGround = 102.3;
+
+ @MessageField(order = 7, requiredBits = 1, fieldType = "short")
+ public short positionAccuracy;
+
+ @MessageField(order = 8, requiredBits = 28, fieldType = "longitude")
+ public double longitude = 181;
+
+ @MessageField(order = 9, requiredBits = 27, fieldType = "latitude")
+ public double latitude = 91;
+
+ @MessageField(order = 10, requiredBits = 12, fieldType = "course")
+ public double courseOverGround = 360;
+
+ @MessageField(order = 11, requiredBits = 9, fieldType = "heading")
+ public short trueHeading = 511;
+
+ @MessageField(order = 12, requiredBits = 6, fieldType = "short")
+ public short timestamp = 60;
+
+ @MessageField(order = 13, requiredBits = 2, fieldType = "short")
+ public short specialManoeuvreIndicator = 0;
+
+ @MessageField(order = 14, requiredBits = 3, fieldType = "short")
+ public short spare = 0;
+
+ @MessageField(order = 15, requiredBits = 1, fieldType = "short")
+ public short raimFlag = 0;
+
+ @MessageField(order = 16, requiredBits = 19, fieldType = "bits")
+ public PrintableList<Byte> communicationState;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+
+public class AisMessage10 extends AbstractAisMessage {
+
+ public AisMessage10() {
+ this.messageId = 10;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short spare1;
+
+ @MessageField(order = 5, requiredBits = 30, fieldType = "integer")
+ public int destinationId;
+
+ @MessageField(order = 6, requiredBits = 2, fieldType = "short")
+ public short spare2;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage11 extends AisMessage4 {
+
+ public AisMessage11() {
+ this.messageId = 11;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage12 extends AisMessage6 {
+
+ public AisMessage12() {
+ this.messageId = 12;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage13 extends AisMessage7 {
+
+ public AisMessage13() {
+ this.messageId = 13;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage14 extends AisMessage8 {
+
+ public AisMessage14() {
+ this.messageId = 14;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+
+public class AisMessage15 extends AbstractAisMessage {
+
+ public AisMessage15() {
+ this.messageId = 15;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short spare;
+
+ @MessageField(order = 5, requiredBits = 30, fieldType = "integer")
+ public int destinationId1;
+
+ @MessageField(order = 6, requiredBits = 6, fieldType = "short")
+ public short messageId11;
+
+ @MessageField(order = 7, requiredBits = 12, fieldType = "short")
+ public short slotOffset11;
+
+ @MessageField(order = 8, requiredBits = 2, fieldType = "short")
+ public short spare2;
+
+ @MessageField(order = 7, requiredBits = 6, fieldType = "short")
+ public short messageId12;
+
+ @MessageField(order = 8, requiredBits = 12, fieldType = "short")
+ public short slotOffset12;
+
+ @MessageField(order = 9, requiredBits = 2, fieldType = "short")
+ public short spare3;
+
+ @MessageField(order = 10, requiredBits = 30, fieldType = "integer")
+ public int destinationId2;
+
+ @MessageField(order = 11, requiredBits = 6, fieldType = "short")
+ public short messageId21;
+
+ @MessageField(order = 12, requiredBits = 12, fieldType = "short")
+ public short slotOffset21;
+
+ @MessageField(order = 13, requiredBits = 2, fieldType = "short")
+ public short spare4;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import java.util.List;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.util.TransmissionSchedule;
+import com.antu.util.PrintableList;
+
+public class AisMessage16 extends AbstractAisMessage {
+
+ public AisMessage16() {
+ this.messageId = 16;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short spare;
+
+ @MessageField(order = 5, isGroup = true, fieldType = "list", groupItemClass = "com.antu.nmea.util.TransmissionSchedule")
+ public List<TransmissionSchedule> schedules;
+
+ @MessageField(order = 6, fieldType = "bits")
+ public List<Byte> spare2 = new PrintableList<Byte>();
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import java.util.List;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.util.DGNSSData;
+
+public class AisMessage17 extends AbstractAisMessage {
+
+ public AisMessage17() {
+ this.messageId = 17;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short spare;
+
+ @MessageField(order = 5, requiredBits = 18, fieldType = "shortLongitude")
+ public double longitude;
+
+ @MessageField(order = 6, requiredBits = 17, fieldType = "shortLatitude")
+ public double latitude;
+
+ @MessageField(order = 7, requiredBits = 5, fieldType = "short")
+ public short spare2;
+
+ @MessageField(order = 8, requiredBits = 6, fieldType = "short")
+ public Short messageType;
+
+ @MessageField(order = 9, requiredBits = 10, fieldType = "short")
+ public Short stationId;
+
+ @MessageField(order = 10, requiredBits = 13, fieldType = "short")
+ public Short zCount;
+
+ @MessageField(order = 11, requiredBits = 3, fieldType = "short")
+ public Short sequenceNumber;
+
+ @MessageField(order = 12, requiredBits = 5, fieldType = "short")
+ public Short N;
+
+ @MessageField(order = 13, requiredBits = 3, fieldType = "short")
+ public Short health;
+
+ @MessageField(order = 14, fieldType = "list", isGroup = true, groupItemClass = "com.antu.nmea.util.DGNSSData")
+ public List<DGNSSData> dgnssData;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import java.util.List;
+
+import com.antu.nmea.annotation.MessageField;
+
+public class AisMessage18 extends AbstractAisMessage {
+
+ public AisMessage18() {
+ this.messageId = 18;
+ }
+
+ @MessageField(order = 4, requiredBits = 8, fieldType = "short")
+ public short spare;
+
+ @MessageField(order = 5, requiredBits = 10, fieldType = "speed")
+ public double speedOverGround = AbstractAisSentence.SPEED_NOT_AVAILABLE;
+
+ @MessageField(order = 6, requiredBits = 1, fieldType = "short")
+ public short positionAccuracy;
+
+ @MessageField(order = 7, requiredBits = 28, fieldType = "longitude")
+ public double longitude = AbstractAisSentence.LONGITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 8, requiredBits = 27, fieldType = "laitutde")
+ public double latitude = AbstractAisSentence.LATITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 9, requiredBits = 12, fieldType = "course")
+ public double courseOverGround = AbstractAisSentence.COURSE_NOT_AVAILABLE;
+
+ @MessageField(order = 10, requiredBits = 9, fieldType = "heading")
+ public short trueHeading = AbstractAisSentence.HEADING_NOT_AVAILABLE;
+
+ @MessageField(order = 11, requiredBits = 6, fieldType = "short")
+ public short timestamp = 60;
+
+ @MessageField(order = 12, requiredBits = 2, fieldType = "short")
+ public short spare2;
+
+ @MessageField(order = 13, requiredBits = 1, fieldType = "short")
+ public short classBUnitFlag;
+
+ @MessageField(order = 14, requiredBits = 1, fieldType = "short")
+ public short classBDisplayFlag;
+
+ @MessageField(order = 15, requiredBits = 1, fieldType = "short")
+ public short classBDSCFlag;
+
+ @MessageField(order = 16, requiredBits = 1, fieldType = "short")
+ public short classBBandFlag;
+
+ @MessageField(order = 17, requiredBits = 1, fieldType = "short")
+ public short classBMessage22Flag;
+
+ @MessageField(order = 18, requiredBits = 1, fieldType = "short")
+ public short modeFlag;
+
+ @MessageField(order = 19, requiredBits = 1, fieldType = "short")
+ public short raimFlag;
+
+ @MessageField(order = 20, requiredBits = 1, fieldType = "short")
+ public short communicationStateSelectorFlag;
+
+ @MessageField(order = 21, requiredBits = 19, fieldType = "bits")
+ public List<Byte> communicationState;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.util.Dimension;
+
+public class AisMessage19 extends AbstractAisMessage {
+
+ public AisMessage19() {
+ this.messageId = 19;
+ }
+
+ @MessageField(order = 4, requiredBits = 8, fieldType = "short")
+ public short spare;
+
+ @MessageField(order = 5, requiredBits = 10, fieldType = "speed")
+ public double speedOverGround = AbstractAisSentence.SPEED_NOT_AVAILABLE;
+
+ @MessageField(order = 6, requiredBits = 1, fieldType = "short")
+ public short positionAccuracy;
+
+ @MessageField(order = 7, requiredBits = 28, fieldType = "longitude")
+ public double longitude = AbstractAisSentence.LONGITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 8, requiredBits = 27, fieldType = "laitutde")
+ public double latitude = AbstractAisSentence.LATITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 9, requiredBits = 12, fieldType = "course")
+ public double courseOverGround = AbstractAisSentence.COURSE_NOT_AVAILABLE;
+
+ @MessageField(order = 10, requiredBits = 9, fieldType = "heading")
+ public short trueHeading = AbstractAisSentence.HEADING_NOT_AVAILABLE;
+
+ @MessageField(order = 11, requiredBits = 6, fieldType = "short")
+ public short timestamp = 60;
+
+ @MessageField(order = 12, requiredBits = 4, fieldType = "short")
+ public short spare2;
+
+ @MessageField(order = 13, requiredBits = 120, fieldType = "string")
+ public String name;
+
+ @MessageField(order = 14, requiredBits = 8, fieldType = "short")
+ public short typeOfShipAndCargoType;
+
+ @MessageField(order = 15, requiredBits = 30, fieldType = "short")
+ public Dimension dimension;
+
+ @MessageField(order = 16, requiredBits = 4, fieldType = "short")
+ public short typeOfPositionFixingDevice;
+
+ @MessageField(order = 17, requiredBits = 1, fieldType = "short")
+ public short raimFlag;
+
+ @MessageField(order = 18, requiredBits = 1, fieldType = "short")
+ public short dte;
+
+ @MessageField(order = 19, requiredBits = 1, fieldType = "short")
+ public short assignedModeFlag;
+
+ @MessageField(order = 20, requiredBits = 4, fieldType = "short")
+ public short spare3;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage2 extends AisMessage1 {
+
+ public AisMessage2() {
+ this.messageId = 2;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import java.util.List;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.annotation.SentenceMessage;
+import com.antu.nmea.util.DataLink;
+import com.antu.util.PrintableList;
+
+@SentenceMessage(alignBytes = true)
+public class AisMessage20 extends AbstractAisMessage {
+
+ public AisMessage20() {
+ this.messageId = 20;
+ }
+
+ @MessageField(order = 4, fieldType = "short", requiredBits = 2)
+ public short spare;
+
+ @MessageField(order = 5, fieldType = "list", isGroup = true, groupItemClass = "com.antu.nmea.util.DataLink")
+ public List<DataLink> dataLink;
+
+ @MessageField(order = 6, fieldType = "bits")
+ public List<Byte> spare2 = new PrintableList<Byte>();
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import java.util.List;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.util.Dimension;
+import com.antu.util.PrintableList;
+
+public class AisMessage21 extends AbstractAisMessage {
+
+ public AisMessage21() {
+ this.messageId = 21;
+ }
+
+ @MessageField(order = 4, requiredBits = 5, fieldType = "short")
+ public short typeOfAidsToNavigation;
+
+ @MessageField(order = 5, requiredBits = 120, fieldType = "string")
+ public String nameOfAidsToNavigation;
+
+ @MessageField(order = 6, requiredBits = 1, fieldType = "short")
+ public short positionAccuracy;
+
+ @MessageField(order = 7, requiredBits = 28, fieldType = "longitude")
+ public double longitude = AbstractAisSentence.LONGITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 8, requiredBits = 27, fieldType = "latitude")
+ public double latitude = AbstractAisSentence.LATITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 9, requiredBits = 30, fieldType = "short")
+ public Dimension dimension;
+
+ @MessageField(order = 10, requiredBits = 4, fieldType = "short")
+ public short typeOfPositionFixingDevice;
+
+ @MessageField(order = 11, requiredBits = 6, fieldType = "short")
+ public short timestamp;
+
+ @MessageField(order = 12, requiredBits = 1, fieldType = "short")
+ public short offPositionIndicator;
+
+ @MessageField(order = 13, requiredBits = 8, fieldType = "short")
+ public short atonStatus;
+
+ @MessageField(order = 14, requiredBits = 1, fieldType = "short")
+ public short raimFlag;
+
+ @MessageField(order = 15, requiredBits = 1, fieldType = "short")
+ public short virtualAtonFlag;
+
+ @MessageField(order = 16, requiredBits = 1, fieldType = "short")
+ public short assignedModeFlag;
+
+ @MessageField(order = 17, requiredBits = 1, fieldType = "short")
+ public short spare;
+
+ // 0, 6, ... 84
+ @MessageField(order = 18, requiredBits = 0, fieldType = "string")
+ public String nameOfAidsToNavigationExtension;
+
+ // 0, 2, 4, 6
+ @MessageField(order = 19, requiredBits = 0, fieldType = "bits")
+ public List<Byte> spare2 = new PrintableList<Byte>();
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage22 extends AbstractAisMessage {
+
+ public AisMessage22() {
+ this.messageId = 22;
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+
+public class AisMessage23 extends AbstractAisMessage {
+
+ public AisMessage23() {
+ this.messageId = 23;
+ }
+
+ @MessageField(order = 1, requiredBits = 2, fieldType = "short")
+ public short spare;
+
+ @MessageField(order = 2, requiredBits = 18, fieldType = "shortLongitude")
+ public double longitude1;
+
+ @MessageField(order = 3, requiredBits = 17, fieldType = "shortLatitude")
+ public double latitude1;
+
+ @MessageField(order = 4, requiredBits = 18, fieldType = "shortLongitude")
+ public double longitude2;
+
+ @MessageField(order = 5, requiredBits = 17, fieldType = "shortLatitude")
+ public double latitude2;
+
+ @MessageField(order = 6, requiredBits = 4, fieldType = "short")
+ public short stationType;
+
+ @MessageField(order = 7, requiredBits = 8, fieldType = "short")
+ public short typeOfShipAndCargoType;
+
+ @MessageField(order = 8, requiredBits = 22, fieldType = "integer")
+ public int spare2;
+
+ @MessageField(order = 9, requiredBits = 2, fieldType = "short")
+ public short tranceivingMode;
+
+ @MessageField(order = 10, requiredBits = 4, fieldType = "short")
+ public short reportingInterval;
+
+ @MessageField(order = 11, requiredBits = 4, fieldType = "short")
+ public short quietTime;
+
+ @MessageField(order = 12, requiredBits = 6, fieldType = "short")
+ public short spare3;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+
+public class AisMessage24A extends AbstractAisMessage {
+
+ public AisMessage24A() {
+ this.messageId = 24;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short partNumber;
+
+ @MessageField(order = 5, requiredBits = 120, fieldType = "string")
+ public String name;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.util.Dimension;
+
+public class AisMessage24B extends AbstractAisMessage {
+
+ public AisMessage24B() {
+ this.messageId = 24;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short partNumber;
+
+ @MessageField(order = 5, requiredBits = 8, fieldType = "short")
+ public short typeOfShipAndCargoType;
+
+ @MessageField(order = 6, requiredBits = 42, fieldType = "string")
+ public String vendorId;
+
+ @MessageField(order = 7, requiredBits = 42, fieldType = "string")
+ public String callSign;
+
+ @MessageField(order = 8, requiredBits = 30, fieldType = "dimension")
+ public Dimension dimension;
+
+ @MessageField(order = 9, requiredBits = 6, fieldType = "short")
+ public short spare;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage25 extends AbstractAisMessage {
+
+ public AisMessage25() {
+ this.messageId = 25;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage26 extends AbstractAisMessage {
+
+ public AisMessage26() {
+ this.messageId = 26;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage27 extends AbstractAisMessage {
+
+ public AisMessage27() {
+ this.messageId = 27;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+public class AisMessage3 extends AisMessage1 {
+
+ public AisMessage3() {
+ this.messageId = 3;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.util.PrintableList;
+
+public class AisMessage4 extends AbstractAisMessage {
+
+ public AisMessage4() {
+ this.messageId = 4;
+ }
+
+ @MessageField(order = 4, requiredBits = 14, fieldType = "short")
+ public short utcYear = 0;
+
+ @MessageField(order = 5, requiredBits = 4, fieldType = "short")
+ public short utcMonth = 0;
+
+ @MessageField(order = 6, requiredBits = 5, fieldType = "short")
+ public short utcDay = 0;
+
+ @MessageField(order = 7, requiredBits = 5, fieldType = "short")
+ public short utcHour = 24;
+
+ @MessageField(order = 8, requiredBits = 6, fieldType = "short")
+ public short utcMinute = 60;
+
+ @MessageField(order = 9, requiredBits = 6, fieldType = "short")
+ public short utcSecond = 60;
+
+ @MessageField(order = 10, requiredBits = 1, fieldType = "short")
+ public short positionAccuracy = 0;
+
+ @MessageField(order = 11, requiredBits = 28, fieldType = "longitude")
+ public double longitude = AbstractAisSentence.LONGITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 12, requiredBits = 27, fieldType = "latitude")
+ public double latitude = AbstractAisSentence.LATITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 13, requiredBits = 4, fieldType = "short")
+ public short typeOfElectronicPositionFixingDevice = 0;
+
+ @MessageField(order = 14, requiredBits = 10, fieldType = "short")
+ public short spare = 0;
+
+ @MessageField(order = 15, requiredBits = 1, fieldType = "short")
+ public short raimFlag = 0;
+
+ @MessageField(order = 16, requiredBits = 19, fieldType = "bits")
+ public PrintableList<Byte> communicationState;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.util.DateTime;
+import com.antu.nmea.util.Dimension;
+
+public class AisMessage5 extends AbstractAisMessage {
+
+ public AisMessage5() {
+ this.messageId = 5;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short aisVersionIndicator;
+
+ @MessageField(order = 5, requiredBits = 30, fieldType = "integer")
+ public int imoNumber;
+
+ @MessageField(order = 6, requiredBits = 42, fieldType = "string")
+ public String callSign = "";
+
+ @MessageField(order = 7, requiredBits = 120, fieldType = "string")
+ public String name = "";
+
+ @MessageField(order = 8, requiredBits = 8, fieldType = "short")
+ public short typeOfShipAndCargoType;
+
+ @MessageField(order = 9, requiredBits = 30, fieldType = "dimension")
+ public Dimension overallDimension;
+
+ @MessageField(order = 10, requiredBits = 4, fieldType = "short")
+ public short typeOfElectronicPostionFixingDevice;
+
+ @MessageField(order = 11, requiredBits = 20, fieldType = "dateTime")
+ public DateTime eta;
+
+ @MessageField(order = 12, requiredBits = 8, fieldType = "draught")
+ public double maximumPresentStaticDraught;
+
+ @MessageField(order = 13, requiredBits = 120, fieldType = "string")
+ public String destination = "";
+
+ @MessageField(order = 14, requiredBits = 1, fieldType = "short")
+ public short dte = 1;
+
+ @MessageField(order = 15, requiredBits = 1, fieldType = "short")
+ public short spare;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.sentence.ais.ifm.AbstractIfmSegment;
+
+public class AisMessage6 extends AbstractAisMessage {
+
+ public AisMessage6() {
+ this.messageId = 6;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short sequenceNumber;
+
+ @MessageField(order = 5, requiredBits = 30, fieldType = "integer")
+ public int destinationId;
+
+ @MessageField(order = 6, requiredBits = 1, fieldType = "byte")
+ public byte retransmitFlag;
+
+ @MessageField(order = 7, requiredBits = 1, fieldType = "byte")
+ public byte spare;
+
+ @MessageField(order = 8, requiredBits = 936, fieldType = "ifm")
+ public AbstractIfmSegment ifm;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import java.util.List;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.util.Message6Acknowledgement;
+
+public class AisMessage7 extends AbstractAisMessage {
+
+ public AisMessage7() {
+ this.messageId = 7;
+ }
+
+ @MessageField(order = 4, requiredBits = 2, fieldType = "short")
+ public short spare;
+
+ @MessageField(order = 5, isGroup = true, fieldType = "list", groupItemClass = "com.antu.nmea.util.Message6Acknowledgement", requiredBits = 0)
+ public List<Message6Acknowledgement> acknowledgements;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.annotation.MessageField;
+import com.antu.nmea.sentence.ais.ifm.AbstractIfmSegment;
+
+public class AisMessage8 extends AbstractAisMessage {
+
+ public AisMessage8() {
+ this.messageId = 8;
+ }
+
+ @MessageField(order = 4, requiredBits = 1, fieldType = "byte")
+ public byte spare;
+
+ @MessageField(order = 5, requiredBits = 968, fieldType = "ifm")
+ public AbstractIfmSegment ifm;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import java.util.List;
+
+import com.antu.nmea.annotation.MessageField;
+
+public class AisMessage9 extends AbstractAisMessage {
+
+ public AisMessage9() {
+ this.messageId = 9;
+ }
+
+ @MessageField(order = 4, requiredBits = 12, fieldType = "short")
+ public short altitude;
+
+ @MessageField(order = 5, requiredBits = 10, fieldType = "speed")
+ public double speedOverGroud = AbstractAisSentence.SPEED_NOT_AVAILABLE;
+
+ @MessageField(order = 6, requiredBits = 1, fieldType = "short")
+ public short positionAccuracy;
+
+ @MessageField(order = 7, requiredBits = 28, fieldType = "longitude")
+ public double longitude = AbstractAisSentence.LONGITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 8, requiredBits = 27, fieldType = "latitude")
+ public double latitude = AbstractAisSentence.LATITUDE_NOT_AVAILABLE;
+
+ @MessageField(order = 9, requiredBits = 12, fieldType = "course")
+ public double courseOverGround = AbstractAisSentence.COURSE_NOT_AVAILABLE;
+
+ @MessageField(order = 10, requiredBits = 6, fieldType = "short")
+ public short timestamp;
+
+ @MessageField(order = 11, requiredBits = 1, fieldType = "short")
+ public short altitudeSensor;
+
+ @MessageField(order = 12, requiredBits = 7, fieldType = "short")
+ public short spare;
+
+ @MessageField(order = 13, requiredBits = 1, fieldType = "short")
+ public short dte;
+
+ @MessageField(order = 14, requiredBits = 3, fieldType = "short")
+ public short spare2;
+
+ @MessageField(order = 15, requiredBits = 1, fieldType = "short")
+ public short assignedModeFlag;
+
+ @MessageField(order = 16, requiredBits = 1, fieldType = "short")
+ public short raimFlag;
+
+ @MessageField(order = 17, requiredBits = 1, fieldType = "short")
+ public short communicationStateSelectorFlag;
+
+ @MessageField(order = 18, requiredBits = 19, fieldType = "bits")
+ public List<Byte> communicationState;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais;
+
+import com.antu.nmea.sentence.IEncapsulatedSentence;
+
+public interface IEncapsulatedAisMessage extends IEncapsulatedSentence {
+
+ public int messageType();
+}
--- /dev/null
+package com.antu.nmea.sentence.ais.ifm;
+
+public class AbstractIfmSegment {
+
+ protected AbstractIfmSegment() {
+ }
+
+ public short dac;
+ public short functionIdentifier;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais.ifm;
+
+public class IfmMessage01 extends AbstractIfmSegment {
+
+ public IfmMessage01() {
+ }
+
+ public String message;
+}
--- /dev/null
+package com.antu.nmea.sentence.ais.ifm;
+
+import java.util.List;
+
+import com.antu.util.PrintableList;
+
+public class RawIfmSegment extends AbstractIfmSegment {
+
+ public RawIfmSegment() {
+ }
+
+ public List<Byte> dataBits = new PrintableList<Byte>();
+}
--- /dev/null
+package com.antu.nmea.sentence.exception;
+
+public class SentenceCreationException extends Exception {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8503051206403879754L;
+
+ public SentenceCreationException() {
+ super();
+ }
+
+ public SentenceCreationException(String message) {
+ super(message);
+ }
+
+ public SentenceCreationException(Throwable cause) {
+ super(cause);
+ }
+
+ public SentenceCreationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public SentenceCreationException(String message, Throwable cause,
+ boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.annotation.GroupItem;
+import com.antu.nmea.annotation.SentenceField;
+
+public abstract class AbstractSentenceFieldCodec implements ISentenceFieldCodec {
+
+ static private Log logger = LogFactory.getLog(AbstractSentenceFieldCodec.class);
+
+ @Override
+ public boolean decode(String[] segments, Object obj, Field field, int startIndex) {
+
+ if (segments.length < startIndex + this.requiredSegments())
+ return false;
+
+ if (field.isAnnotationPresent(SentenceField.class)) {
+ SentenceField annotation = (SentenceField)field.getAnnotation(SentenceField.class);
+
+ if (segments[startIndex].isEmpty()) {
+ if (!annotation.isRequired()) {
+ try {
+ field.set(obj, null);
+ return true;
+ } catch (IllegalArgumentException |
+ IllegalAccessException e) {
+ AbstractSentenceFieldCodec.logger.error("unable to set value for not required field: " + field.getName());
+ return false;
+ }
+ }
+ return false;
+ }
+
+ return this.doDecode(segments, obj, field, new FieldSetting(annotation), startIndex);
+ } else if (field.isAnnotationPresent(GroupItem.class)) {
+ GroupItem annotation = (GroupItem)field.getAnnotation(GroupItem.class);
+
+ return this.doDecode(segments, obj, field, new FieldSetting(annotation), startIndex);
+ }
+
+ return false;
+ }
+
+ abstract protected boolean doDecode(String[] segments, Object obj,
+ Field field, FieldSetting setting,
+ int startIndex);
+
+ @Override
+ public boolean encode(StringBuilder builder, Object obj, Field field) {
+
+ if (field.isAnnotationPresent(SentenceField.class)) {
+ return this.doEncode(builder, obj, field, new FieldSetting((SentenceField)field.getAnnotation(SentenceField.class)));
+ } else if (field.isAnnotationPresent(GroupItem.class)) {
+ return this.doEncode(builder, obj, field, new FieldSetting((GroupItem)field.getAnnotation(GroupItem.class)));
+ }
+ return false;
+ }
+
+ abstract protected boolean doEncode(StringBuilder builder,
+ Object obj, Field field, FieldSetting setting);
+
+ protected boolean isNeededSegmentsEmpty(String[] segments, int startIndex) {
+
+ for (int i = startIndex; i < startIndex + this.requiredSegments(); i++) {
+
+ if (segments[i].isEmpty()) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class BooleanSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ @Override
+ public String fieldCodecType() {
+ return "boolean";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 1;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ if (segments[startIndex].isEmpty()) {
+
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ try {
+ field.set(obj, Boolean.getBoolean(setting.getDefaultValue()));
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ return true;
+ }
+ };
+
+ if (segments[startIndex].equals("A") || segments[startIndex].equals("a")) {
+
+ try {
+ field.set(obj, true);
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+
+ } else if (segments[startIndex].equals("V") || segments[startIndex].equals("v")) {
+
+ try {
+ field.set(obj, false);
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object value = field.get(obj);
+
+ if (value == null) {
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ builder.append(",");
+ return true;
+ }
+ }
+ if (value instanceof Boolean) {
+ if ((Boolean)value) {
+ builder.append(",A");
+ } else {
+ builder.append(",V");
+ }
+ return true;
+ }
+ return false;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class CharSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ @Override
+ public String fieldCodecType() {
+ return "char";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 1;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ if (segments[startIndex].length() > 1)
+ return false;
+
+ try {
+ if (segments[startIndex].isEmpty()) {
+ if (!setting.isRequired()) {
+ field.set(obj, setting.getDefaultValue().charAt(0));
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ field.set(obj, segments[startIndex].charAt(0));
+ }
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object value = field.get(obj);
+ if (value != null && value instanceof Character) {
+ builder.append(',').append(value);
+ return true;
+ } else if (value == null) {
+
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ builder.append(",");
+ return true;
+ }
+ }
+ return false;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class DoubleSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ @Override
+ public String fieldCodecType() {
+ return "double";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 1;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ if (segments[startIndex].isEmpty()) {
+ if (setting.isRequired()) {
+ return false;
+ }
+ try {
+ field.set(obj, Double.parseDouble(setting.getDefaultValue()));
+ } catch (IllegalArgumentException
+ | IllegalAccessException e) {
+ return false;
+ }
+ return true;
+ }
+
+ Double value = FieldCodecHelper.parseDouble(segments[startIndex], 0, 0);
+ if (value != null) {
+
+ try {
+ field.set(obj, value);
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+
+ }
+ return false;
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+ try {
+ Object value = field.get(obj);
+
+ if (value == null && setting.isRequired()) {
+ return false;
+ } else if (value == null) {
+ builder.append(",");
+ return true;
+ } if (value instanceof Double) {
+ int width = (setting.getFieldWidth() != 0) ? setting.getFieldWidth() : setting.getPrecision() + 2;
+ String format = String.format("%%1$%d.%df", width, setting.getPrecision());
+ builder.append(",").append(String.format(format, (Double)value));
+ return true;
+ }
+ return false;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+public class FieldCodecHelper {
+
+ public static Short parseShort(String segment, int startIndex, int length) {
+
+ short result = 0;
+ int end = length > 0 ? startIndex + length - 1 : segment.length() - 1;
+
+ if (length > segment.length() - startIndex)
+ return null;
+
+ String str = segment.substring(startIndex, end);
+
+ try {
+ result = Short.parseShort(str);
+ return new Short(result);
+ } catch (NumberFormatException e) {
+ return null;
+ }
+
+ /*int i = startIndex;
+ boolean isNegative = false;
+ if (segment.charAt(startIndex + 0) == '-') {
+ i = 1;
+ isNegative = true;
+ } else if (segment.charAt(startIndex + 0) == '+') {
+ i = 1;
+ }
+
+ for (; i < end; i++) {
+ short digit = (short)(segment.charAt(i) - '0');
+
+ if (digit >= 0 && digit <= 9) {
+ result = (short)(result * 10 + digit);
+ } else {
+ return null;
+ }
+ }
+
+ if (!isNegative) {
+ return new Short(result);
+ } else {
+ return new Short((short) -result);
+ }*/
+ }
+
+ public static Integer parseInt(String segment, int startIndex, int length) {
+
+ int result = 0;
+ int end = length > 0 ? startIndex + length - 1 : segment.length() - 1;
+
+ if (length > segment.length() - startIndex)
+ return null;
+
+ String str = segment.substring(startIndex, end);
+
+ try {
+ result = Integer.parseInt(str);
+ return new Integer(result);
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ }
+
+ public static Double parseDouble(String segment, int startIndex, int length) {
+
+ double result = 0;
+
+ int end = length > 0? startIndex + length - 1 : segment.length() - 1;
+
+ if (length > segment.length() - startIndex)
+ return null;
+
+ String str = segment.substring(startIndex, end);
+ try {
+ result = Double.parseDouble(str);
+ return new Double(result);
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class HexSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ public HexSentenceFieldCodec() {
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "hex";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 1;
+ }
+
+ public static Integer toInteger(String hexString) {
+ if (hexString == null || hexString.isEmpty())
+ return null;
+
+ int result = 0;
+ hexString = hexString.toLowerCase();
+ for (int i = 0; i < hexString.length(); i += 2) {
+ byte high = (byte) (Character.digit(hexString.charAt(i), 16) & 0xff);
+ byte low = (byte) (Character.digit(hexString.charAt(i + 1), 16) & 0xff);
+ result = result << 8 | (byte) (high << 4 | low);
+ }
+ return new Integer(result);
+ }
+
+ /**
+ *
+ * @param integer
+ * @param width number of half bytes
+ * @return
+ */
+ public static String toHexString(int integer, int width) {
+
+ final StringBuilder hexString = new StringBuilder();
+
+ byte b0 = (byte) ((integer & 0xFF000000) >> 24);
+ byte b1 = (byte) ((integer & 0x00FF0000) >> 16);
+ byte b2 = (byte) ((integer & 0x0000FF00) >> 8);
+ byte b3 = (byte) (integer & 0x000000FF);
+
+ byte[] byteArray = new byte[4];
+ byteArray[0] = b0;
+ byteArray[1] = b1;
+ byteArray[2] = b2;
+ byteArray[3] = b3;
+
+ for (int i = 0; i < byteArray.length; i++) {
+ if ((byteArray[i] & 0xff) < 0x10)//0~F can not be zero
+ hexString.append("0");
+ hexString.append(Integer.toHexString(0xFF & byteArray[i]));
+ }
+ String hex = hexString.toString().toUpperCase();
+
+ if (width == 0) {
+ return hex;
+ } else {
+ return hex.substring(8 - width);
+ }
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ try {
+
+ if (segments[startIndex].isEmpty()) {
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ field.set(obj, Integer.parseInt(setting.getDefaultValue()));
+ return true;
+ }
+ }
+
+ Integer value = HexSentenceFieldCodec.toInteger(segments[startIndex]);
+ if (value != null)
+ field.set(obj, value);
+ else
+ return false;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object value = field.get(obj);
+
+ if (value == null) {
+ if (setting.isRequired())
+ return false;
+ else {
+ builder.append(",");
+ return true;
+ }
+ }
+
+ if (value instanceof Integer) {
+
+ builder.append(',').append(HexSentenceFieldCodec.toHexString((int) value,
+ setting.getFieldWidth()));
+ } else {
+ return false;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+
+ return true;
+ }
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import com.antu.nmea.annotation.SentenceField;
+
+/**
+ *
+ * @author yining
+ *
+ */
+public interface IGroupSentenceFieldCodec extends ISentenceFieldCodec {
+
+ Object createGroupItem(String fullName);
+
+ int segmentsPerItem(Object groupItem);
+
+ int totalItems(SentenceField annotation, int startIndex, int segmentsLength, int segmentsPerItem);
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+public interface ISentenceFieldCodec {
+
+ boolean decode(String[] segments, Object obj, Field field, int startIndex);
+
+ boolean encode(StringBuilder builder, Object obj, Field field);
+
+ String fieldCodecType();
+
+ int requiredSegments();
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class IntegerSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ @Override
+ public String fieldCodecType() {
+ return "integer";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 1;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ try {
+ if (segments[startIndex].isEmpty()) {
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ field.set(obj, Integer.parseInt(setting.getDefaultValue()));
+ return true;
+ }
+ }
+
+ field.set(obj, Integer.parseInt(segments[startIndex]));
+ return true;
+ } catch (IllegalArgumentException
+ | IllegalAccessException e) {
+
+ return false;
+ }
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+
+ Object value;
+ try {
+ value = field.get(obj);
+
+ if (value == null) {
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ builder.append(",");
+ return true;
+ }
+ } else if (value instanceof Integer) {
+ if (setting.getFieldWidth() == 0)
+ builder.append(',').append(((Integer)value).toString());
+ else {
+ String format = String.format("%%0%dd", setting.getFieldWidth());
+ builder.append(',').append(String.format(format, (Integer)value));
+ }
+ return true;
+ } else {
+ return false;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class LatitudeSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ @Override
+ public String fieldCodecType() {
+ return "latitude";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 2;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ if (this.isNeededSegmentsEmpty(segments, startIndex)) {
+
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ try {
+ field.set(obj, Double.parseDouble(setting.getDefaultValue()));
+ return true;
+ } catch (IllegalArgumentException
+ | IllegalAccessException e) {
+ return false;
+ }
+ }
+ }
+
+ Integer degree = FieldCodecHelper.parseInt(segments[startIndex], 0, 2);
+
+ if (degree != null) {
+
+ Double minute = FieldCodecHelper.parseDouble(segments[startIndex], 2, 0);
+ double total = degree + minute;
+
+ if (segments[startIndex + 1].equals("S") || segments[startIndex + 1].equals("s")) {
+ total = -total;
+ } else if (!segments[startIndex + 1].equals("N") && !segments[startIndex + 1].equals("n")) {
+ return false;
+ }
+
+ try {
+ field.set(obj, new Double(total));
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object value = field.get(obj);
+
+ if (value == null) {
+ if (setting.isRequired())
+ return false;
+ else {
+ builder.append(",,");
+ return true;
+ }
+ }
+
+ if (value instanceof Double) {
+ double total = (Double)value;
+
+ boolean isNegative = total < 0;
+
+ if (isNegative) total = -total;
+ int degree = (int)(total / 100);
+
+ double minute = total - degree * 100;
+
+ String result = String.format("%02d%5.2f", degree, minute);
+ if (isNegative) result += ",S";
+ else result += ",N";
+
+ builder.append(result);
+ return true;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ return false;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.annotation.GroupItem;
+import com.antu.nmea.annotation.GroupItemAnnotationSorter;
+import com.antu.nmea.annotation.SentenceField;
+import com.antu.nmea.util.StringHelper;
+import com.antu.util.GenericFactory;
+import com.antu.util.PrintableList;
+
+public class ListSentenceFieldCodec extends AbstractSentenceFieldCodec
+ implements IGroupSentenceFieldCodec {
+
+ private GenericFactory<Object> groupItemFactory;
+
+ private GenericFactory<AbstractSentenceFieldCodec> codecFactory;
+
+ static private Log logger = LogFactory.getLog(ListSentenceFieldCodec.class);
+
+ public ListSentenceFieldCodec() {
+ super();
+ this.groupItemFactory = new GenericFactory<Object>("");
+ this.codecFactory = new GenericFactory<AbstractSentenceFieldCodec>("com.antu.nmea.sentence.field.codec", "?SentenceFieldCodec");
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "list";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 0;
+ }
+
+ @Override
+ public Object createGroupItem(String fullName) {
+
+ try {
+ return this.groupItemFactory.createByFullName(fullName);
+ } catch (InstantiationException | IllegalAccessException e) {
+ ListSentenceFieldCodec.logger.error("unable to init object: " + fullName, e);
+ return null;
+ }
+ }
+
+ protected List<Field> getGroupItems(Object item) {
+
+ List<Field> result = new ArrayList<Field>();
+
+ for (Field field : item.getClass().getFields()) {
+
+ if (field.isAnnotationPresent(GroupItem.class)) {
+ result.add(field);
+ }
+ }
+
+ Collections.sort(result, new GroupItemAnnotationSorter());
+ return result;
+ }
+
+ /**
+ * Works out number of segments required for 1 item in the group.
+ * @param item
+ * @return
+ */
+ @Override
+ public int segmentsPerItem(Object item) {
+
+ List<Field> fields = this.getGroupItems(item);
+
+ int segments = 0;
+ for (Field field : fields) {
+ GroupItem annotation = field.getAnnotation(GroupItem.class);
+ segments += annotation.fieldWidth();
+ }
+
+ return segments;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ protected boolean decodeItem(PrintableList listItem, String[] segments,
+ int startIndex, String groupItemClass) {
+
+ Object groupItem = this.createGroupItem(groupItemClass);
+
+ if (groupItem == null)
+ return false;
+
+ List<Field> fields = this.getGroupItems(groupItem);
+
+ int index = startIndex;
+ for (Field field : fields) {
+ GroupItem annotation = field.getAnnotation(GroupItem.class);
+ try {
+ AbstractSentenceFieldCodec codec = this.codecFactory.getBySymbol(annotation.itemType());
+
+ if (codec.decode(segments, groupItem, field, index)) {
+ index += annotation.fieldWidth();
+ } else {
+ ListSentenceFieldCodec.logger.error("unable to decode group item: " + field.getName());
+ return false;
+ }
+ } catch (InstantiationException | IllegalAccessException e) {
+ ListSentenceFieldCodec.logger.error("cannot create codec for group item: " + annotation.itemType());
+ return false;
+ }
+ }
+
+ listItem.add(groupItem);
+ return true;
+ }
+
+ @Override
+ public int totalItems(SentenceField annotation, int startIndex,
+ int segmentsLength, int segmentsPerItem) {
+
+ int totalSegmentsAvailable = segmentsLength - startIndex - annotation.reservedSegments();
+
+ return totalSegmentsAvailable / segmentsPerItem;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ SentenceField annotation = field.getAnnotation(SentenceField.class);
+
+ @SuppressWarnings("rawtypes")
+ PrintableList result = new PrintableList();
+
+ int reservedSegmentsForOtherFields = annotation.reservedSegments();
+ int totalFieldForGroup = segments.length - startIndex - reservedSegmentsForOtherFields;
+ Object item = this.createGroupItem(annotation.groupItemClass());
+
+ int fieldsForOneItem = this.segmentsPerItem(item);
+ int totalItems = totalFieldForGroup / fieldsForOneItem;
+ int remainder = totalFieldForGroup % fieldsForOneItem;
+
+ if (remainder != 0) {
+ ListSentenceFieldCodec.logger.error("cannot use all fields");
+ return false;
+ }
+
+ if (item != null) {
+ for (int i = 0; i < totalItems; i++) {
+ if (!this.decodeItem(result, segments,
+ startIndex + i * fieldsForOneItem, annotation.groupItemClass())) {
+ ListSentenceFieldCodec.logger.error("unable to decode group item.");
+ return false;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ List items = (List)field.get(obj);
+
+ for (Object item : items) {
+
+ List<Field> fields = this.getGroupItems(item);
+
+ for (Field itemField : fields) {
+
+ GroupItem itemAnnotation = itemField.getAnnotation(GroupItem.class);
+
+ AbstractSentenceFieldCodec codec = codecFactory.getBySymbol(StringHelper.capitalizeFirstChar(itemAnnotation.itemType()));
+
+ if (codec != null) {
+ codec.encode(builder, item, itemField);
+ } else {
+ ListSentenceFieldCodec.logger.error("unable to retrieve codec for item: " + itemAnnotation.itemType());
+ return false;
+ }
+ }
+ }
+
+ } catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {
+ ListSentenceFieldCodec.logger.error("unable to retrieve list object", e);
+ return false;
+ }
+ return false;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class LongitudeSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ @Override
+ public String fieldCodecType() {
+ return "longitude";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 2;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ if (this.isNeededSegmentsEmpty(segments, startIndex)) {
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ try {
+ field.set(obj, Double.parseDouble(setting.getDefaultValue()));
+ return true;
+ } catch (IllegalArgumentException
+ | IllegalAccessException e) {
+ return false;
+ }
+ }
+ }
+
+ Integer degree = FieldCodecHelper.parseInt(segments[startIndex], 0, 3);
+
+ if (degree != null) {
+
+ Double minute = FieldCodecHelper.parseDouble(segments[startIndex], 2, 0);
+ double total = degree + minute;
+
+ if (segments[startIndex + 1].equals("W") || segments[startIndex + 1].equals("w")) {
+ total = -total;
+ } else if (!segments[startIndex + 1].equals("E") && !segments[startIndex + 1].equals("e")) {
+ return false;
+ }
+
+ try {
+ field.set(obj, new Double(total));
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object value = field.get(obj);
+
+ if (value == null) {
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ builder.append(",,");
+ }
+ }
+
+ if (value instanceof Double) {
+ double total = (Double)value;
+
+ boolean isNegative = total < 0;
+
+ if (isNegative) total = -total;
+ int degree = (int)(total / 100);
+
+ double minute = total - degree * 100;
+
+ String result = String.format("%03d%5.2f", degree, minute);
+ if (isNegative) result += ",W";
+ else result += ",E";
+
+ builder.append(result);
+ return true;
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ return false;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+
+public class StringSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ @Override
+ public String fieldCodecType() {
+ return "string";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 1;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ try {
+ if (this.isNeededSegmentsEmpty(segments, startIndex)) {
+ if (setting.isRequired())
+ return false;
+ else {
+ field.set(obj, setting.getDefaultValue());
+ return true;
+ }
+ }
+ field.set(obj, segments[startIndex]);
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+
+ try {
+ Object value = field.get(obj);
+
+ if (value == null) {
+ if (setting.isRequired())
+ return false;
+ else {
+ builder.append(",");
+ return true;
+ }
+ }
+ builder.append(',').append(value.toString());
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+
+ return false;
+ }
+
+ return true;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.sentence.field.codec;
+
+import java.lang.reflect.Field;
+
+import com.antu.nmea.annotation.FieldSetting;
+import com.antu.nmea.util.UtcTime;
+
+public class TimeSentenceFieldCodec extends AbstractSentenceFieldCodec {
+
+ public TimeSentenceFieldCodec() {
+ super();
+ }
+
+ @Override
+ public String fieldCodecType() {
+ return "time";
+ }
+
+ @Override
+ public int requiredSegments() {
+ return 1;
+ }
+
+ @Override
+ protected boolean doDecode(String[] segments, Object obj, Field field,
+ FieldSetting setting, int startIndex) {
+
+ if (this.isNeededSegmentsEmpty(segments, startIndex)) {
+ if (setting.isRequired()) {
+ return false;
+ } else {
+ segments[startIndex] = setting.getDefaultValue();
+ }
+ }
+
+ Integer hour = FieldCodecHelper.parseInt(segments[startIndex], 0, 2);
+ Integer minute = FieldCodecHelper.parseInt(segments[startIndex], 2, 2);
+ Double second = FieldCodecHelper.parseDouble(segments[startIndex], 4, 0);
+
+ if (hour != null && minute != null && second != null) {
+
+ UtcTime value = new UtcTime();
+ value.hour = hour;
+ value.minute = minute;
+ value.second = second;
+
+ if (value.isValid()) {
+
+ try {
+ field.set(obj, value);
+ return true;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ } else
+ return false;
+
+ }
+ return false;
+ }
+
+ @Override
+ protected boolean doEncode(StringBuilder builder, Object obj, Field field,
+ FieldSetting setting) {
+ try {
+ Object value = field.get(obj);
+
+ if (value == null) {
+ if (setting.isRequired())
+ return false;
+ else {
+ builder.append(",");
+ return true;
+ }
+ }
+
+ if (value instanceof UtcTime) {
+ UtcTime time = (UtcTime)value;
+ builder.append(',').append(String.format("%02d%02d%5.2f", time.hour, time.minute, time.second));
+ }
+ return false;
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ return false;
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source;
+
+import java.util.Observable;
+import java.util.Observer;
+
+import com.antu.nmea.codec.CodecManager;
+
+abstract public class AbstractNmeaDataSource implements INmeaDataSource, Observer {
+
+ protected AcceptanceSetting acceptanceSetting;
+
+ protected CodecManager manager;
+
+ protected String talker;
+
+ public AbstractNmeaDataSource(String talker, AcceptanceSetting accSetting) {
+
+ assert(accSetting != null);
+ manager = new CodecManager();
+
+ this.acceptanceSetting = accSetting;
+
+ manager.addObserver(this);
+ AbstractNmeaDataSource.updateAcceptanceList(manager, acceptanceSetting);
+ }
+
+ static public void updateAcceptanceList(CodecManager manager, AcceptanceSetting setting) {
+
+ for (String type : setting.getParametricSettings()) {
+ manager.acceptanceList().addPublicSentence(type);
+ }
+
+ for (String type : setting.getProprietarySettings()) {
+ manager.acceptanceList().addProprietarySentence(type);
+ }
+
+ for (MessageSetting msgSetting : setting.getMessageSettings()) {
+
+ for (int msgId : msgSetting.getMessages()) {
+ manager.acceptanceList().addMessage(msgSetting.getSentenceType(), msgId);
+ }
+ }
+ }
+
+ public AcceptanceSetting getAcceptanceSetting() {
+ return acceptanceSetting;
+ }
+
+ @Override
+ public void update(Observable o, Object arg) {
+ //TODO
+ }
+}
--- /dev/null
+package com.antu.nmea.source;
+
+import java.util.List;
+
+public class AcceptanceSetting {
+
+ private List<MessageSetting> messageSettings;
+
+ private List<String> proprietarySettings;
+
+ private List<String> parametricSettings;
+
+ public AcceptanceSetting() {
+ }
+
+ public List<MessageSetting> getMessageSettings() {
+ return messageSettings;
+ }
+
+ public void setMessageSettings(List<MessageSetting> messageSettings) {
+ this.messageSettings = messageSettings;
+ }
+
+ public List<String> getProprietarySettings() {
+ return proprietarySettings;
+ }
+
+ public void setProprietarySettings(List<String> proprietarySettings) {
+ this.proprietarySettings = proprietarySettings;
+ }
+
+ public List<String> getParametricSettings() {
+ return parametricSettings;
+ }
+
+ public void setParametricSettings(List<String> parametricSettings) {
+ this.parametricSettings = parametricSettings;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source;
+
+public interface IDataSourceSetting {
+
+ boolean getAutoRecover();
+
+ String getName();
+}
--- /dev/null
+package com.antu.nmea.source;
+
+import com.antu.nmea.sentence.INmeaSentence;
+
+public interface INmeaDataSource extends Runnable {
+
+ String getName();
+ void stop();
+ void send(INmeaSentence sentence);
+}
--- /dev/null
+package com.antu.nmea.source;
+
+import java.util.List;
+
+public class MessageSetting {
+
+ private String sentenceType;
+
+ private List<Integer> messages;
+
+ public MessageSetting() {
+ }
+
+ public String getSentenceType() {
+ return sentenceType;
+ }
+
+ public void setSentenceType(String sentenceType) {
+ this.sentenceType = sentenceType;
+ }
+
+ public List<Integer> getMessages() {
+ return messages;
+ }
+
+ public void setMessages(List<Integer> messages) {
+ this.messages = messages;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.file;
+
+import java.util.Date;
+
+public abstract class AbstractDateConverter {
+
+ public AbstractDateConverter() {
+ }
+
+ abstract public Date convert(String value);
+}
--- /dev/null
+package com.antu.nmea.source.file;
+
+import java.util.Date;
+
+public class DateTimeDateConverter extends AbstractDateConverter {
+
+ public DateTimeDateConverter() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public Date convert(String value) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.file;
+
+import java.util.Date;
+
+public class EpochDateConverter extends AbstractDateConverter {
+
+ public EpochDateConverter() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public Date convert(String value) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.file;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Calendar;
+import java.util.Date;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.codec.exception.SentenceCodecNotFoundException;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.source.AbstractNmeaDataSource;
+import com.antu.nmea.source.AcceptanceSetting;
+import com.antu.util.GenericFactory;
+
+public class FileDataSource extends AbstractNmeaDataSource {
+
+ static private Log logger = LogFactory.getLog(FileDataSource.class);
+
+ private FileDataSourceSetting setting;
+
+ private boolean stopRequested = false;
+
+ private GenericFactory<AbstractDateConverter> converterFactory;
+
+ public FileDataSource(String talker, FileDataSourceSetting setting,
+ AcceptanceSetting accSetting) {
+ super(talker, accSetting);
+
+ assert(setting != null);
+ this.setting = setting;
+
+ this.converterFactory = new GenericFactory<AbstractDateConverter>("com.antu.nmea.source.file", "?DateConverter");
+ }
+
+ @Override
+ public void stop() {
+ this.stopRequested = true;
+ }
+
+ @Override
+ public void run() {
+
+ stopRequested = false;
+ String fileName = this.setting.getFileName();
+
+ while (!stopRequested) {
+ try (BufferedReader reader =
+ new BufferedReader(
+ new InputStreamReader(
+ new FileInputStream(fileName),
+ "ASCII"))){
+
+ do {
+ String line = null;
+ int lineIndex = 1;
+
+ // read line
+ while ((line = reader.readLine()) != null) {
+
+ if (line.endsWith("\r\n")) {
+
+ } else if (line.endsWith("\r")) {
+ line += "\n";
+ } else if (line.endsWith("\n")) {
+ line.replace("\n", "\r\n");
+ } else {
+ line += "\r\n";
+ }
+
+ int index = line.indexOf(this.setting.getDelimiter());
+ try {
+ if (index >= 0) {
+ Date time = Calendar.getInstance().getTime();
+ String timeline = line.substring(0, index);
+
+ AbstractDateConverter converter = this.converterFactory.getBySymbol(this.setting.getConverter());
+
+ if (converter == null) {
+ converter = this.converterFactory.getByFullName(this.setting.getConverter());
+ }
+
+ if (converter != null) {
+
+ time = converter.convert(timeline);
+ line = line.substring(index + 1);
+ this.manager.decode(time, line);
+ } else {
+ FileDataSource.logger.error("unable to find converter for " + this.setting.getConverter() + ", timeline is: " + timeline);
+ }
+
+ } else {
+ manager.decode(line);
+ }
+ } catch (ClassNotFoundException
+ | InstantiationException
+ | IllegalAccessException
+ | SentenceFieldCodecNotFoundException
+ | SentenceCodecNotFoundException e) {
+ FileDataSource.logger.error("error parsing file: " + fileName + ", line: " + new Integer(lineIndex).toString(), e);
+ }
+ lineIndex++;
+ Thread.sleep(((FileDataSourceSetting)setting).getReadIntervalInMillis());
+ }
+ } while (this.setting.getAutoRecover());
+ // if not auto recover, terminate after file reaches end.
+ } catch (IOException | InterruptedException e) {
+ FileDataSource.logger.error("error reading file: " + fileName, e);
+ break;
+ }
+ }
+ }
+
+ @Override
+ public String getName() {
+ return this.setting.getName();
+ }
+
+ @Override
+ public void send(INmeaSentence sentence) {
+ // do nothing
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.file;
+
+import com.antu.nmea.source.IDataSourceSetting;
+
+public class FileDataSourceSetting implements IDataSourceSetting {
+
+ private String name;
+ private String fileName;
+ private boolean isAutoRecover;
+ private int readIntervalInMillis;
+ private char delimiter = ';';
+ private String converter = "date";
+
+ public FileDataSourceSetting() {
+ }
+
+ @Override
+ public boolean getAutoRecover() {
+ return this.isAutoRecover;
+ }
+
+ public void setAutoRecover(boolean autoRecover) {
+ this.isAutoRecover = autoRecover;
+ }
+
+ @Override
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public int getReadIntervalInMillis() {
+ return readIntervalInMillis;
+ }
+
+ public void setReadIntervalInMillis(int readIntervalInMillis) {
+ this.readIntervalInMillis = readIntervalInMillis;
+ }
+
+ public char getDelimiter() {
+ return delimiter;
+ }
+
+ public void setDelimiter(char delimiter) {
+ this.delimiter = delimiter;
+ }
+
+ public String getConverter() {
+ return converter;
+ }
+
+ public void setConverter(String converter) {
+ this.converter = converter;
+ }
+}
--- /dev/null
+package com.antu.nmea.source.file;
+
+import java.util.Date;
+
+public class TimeDateConverter extends AbstractDateConverter {
+
+ public TimeDateConverter() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public Date convert(String value) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.serial;
+
+import javax.comm.SerialPort;
+import javax.comm.SerialPortEvent;
+import javax.comm.SerialPortEventListener;
+
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.source.AbstractNmeaDataSource;
+import com.antu.nmea.source.AcceptanceSetting;
+
+public class SerialDataSource extends AbstractNmeaDataSource implements SerialPortEventListener {
+
+ private SerialDataSourceSetting setting;
+
+ private SerialPort port;
+
+ private boolean stopRequested = false;
+
+ public SerialDataSource(String talker, AcceptanceSetting accSetting, SerialDataSourceSetting setting) {
+ super(talker, accSetting);
+
+ assert(setting != null);
+ this.setting = setting;
+ }
+
+ @Override
+ public String getName() {
+ return this.setting.getName();
+ }
+
+ @Override
+ public void stop() {
+ this.stopRequested = true;
+ }
+
+ @Override
+ public void send(INmeaSentence sentence) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void run() {
+
+ this.stopRequested = false;
+ while (!this.stopRequested) {
+
+
+ }
+
+ this.port.close();
+ }
+
+ @Override
+ public void serialEvent(SerialPortEvent evt) {
+ // TODO Auto-generated method stub
+
+ switch (evt.getEventType()) {
+
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.serial;
+
+import com.antu.nmea.source.IDataSourceSetting;
+
+public class SerialDataSourceSetting implements IDataSourceSetting {
+
+ public SerialDataSourceSetting() {
+ }
+
+ @Override
+ public boolean getAutoRecover() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public String getName() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+
+}
--- /dev/null
+package com.antu.nmea.source.tcp.client;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.source.AbstractNmeaDataSource;
+import com.antu.nmea.source.AcceptanceSetting;
+
+public class TcpClientDataSource extends AbstractNmeaDataSource {
+
+ static private Log logger = LogFactory.getLog(TcpClientDataSource.class);
+
+ private TcpClientDataSourceSetting setting;
+
+ private List<TcpClientHandler> handlers = new ArrayList<TcpClientHandler>();
+
+ public TcpClientDataSource(String talker, AcceptanceSetting accSetting, TcpClientDataSourceSetting setting) {
+ super(talker, accSetting);
+
+ assert(setting != null);
+ this.setting = setting;
+ }
+
+ void addHandler(TcpClientHandler handler) {
+ synchronized(this) {
+ this.handlers.add(handler);
+ }
+ }
+
+ void removeHandler(TcpClientHandler handler) {
+ synchronized(this) {
+ this.handlers.remove(handler);
+ }
+ }
+
+ @Override
+ public String getName() {
+ return setting.getName();
+ }
+
+ @Override
+ public void stop() {
+ }
+
+ @Override
+ public void send(INmeaSentence sentence) {
+
+ List<String> strings = this.manager.encode(talker, sentence);
+
+ List<TcpClientHandler> hs = null;
+ synchronized(this) {
+ hs = new ArrayList<TcpClientHandler>(this.handlers);
+ }
+ for (TcpClientHandler h : hs) {
+ h.send(strings);
+ }
+ }
+
+ @Override
+ public void run() {
+
+ EventLoopGroup bossGroup = new NioEventLoopGroup();
+ EventLoopGroup workerGroup = new NioEventLoopGroup();
+ try {
+
+ ServerBootstrap sb = new ServerBootstrap();
+ sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
+
+ sb.option(ChannelOption.SO_BACKLOG, 1024);
+ sb.childHandler(new TcpConnectionHandler(this, this.acceptanceSetting));
+ TcpClientDataSource.logger.info("starting server...");
+
+ ChannelFuture f = sb.bind(setting.getPort()).sync();
+ TcpClientDataSource.logger.info("server started at port " + this.setting.getPort() + "...");
+ f.channel().closeFuture().sync();
+ TcpClientDataSource.logger.info("Server shutdown");
+ } catch (Exception e) {
+ TcpClientDataSource.logger.error("unrecoverable error", e);
+ } finally {
+ bossGroup.shutdownGracefully();
+ workerGroup.shutdownGracefully();
+ }
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.tcp.client;
+
+import com.antu.nmea.source.IDataSourceSetting;
+
+public class TcpClientDataSourceSetting implements IDataSourceSetting {
+
+ private String name;
+
+ private boolean isAutoRecover = true;
+
+ private int port = 8904;
+
+ public TcpClientDataSourceSetting() {
+ }
+
+ @Override
+ public boolean getAutoRecover() {
+ return this.isAutoRecover;
+ }
+
+ public void setAutoRecover(boolean isAutoRecover) {
+ this.isAutoRecover = isAutoRecover;
+ }
+
+ @Override
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void setPort(int port) {
+ this.port = port;
+ }
+}
--- /dev/null
+package com.antu.nmea.source.tcp.client;
+
+import java.io.UnsupportedEncodingException;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.codec.CodecManager;
+import com.antu.nmea.source.AbstractNmeaDataSource;
+import com.antu.nmea.source.AcceptanceSetting;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+
+public class TcpClientHandler extends ChannelInboundHandlerAdapter {
+
+ static private Log logger = LogFactory.getLog(TcpClientHandler.class);
+
+ private ChannelHandlerContext handler;
+
+ private CodecManager manager;
+
+ private TcpClientDataSource dataSource;
+
+ public TcpClientHandler(TcpClientDataSource dataSource, AcceptanceSetting setting) {
+
+ manager = new CodecManager();
+ AbstractNmeaDataSource.updateAcceptanceList(manager, setting);
+ this.dataSource = dataSource;
+ }
+
+ public void send(List<String> strings) {
+
+ if (handler != null) {
+ try {
+ for (String str : strings) {
+
+ byte[] bytes = str.getBytes("ASCII");
+ ByteBuf buffer = Unpooled.buffer(bytes.length);
+ buffer.writeBytes(bytes);
+ this.handler.writeAndFlush(buffer);
+ }
+ } catch (UnsupportedEncodingException e) {
+ TcpClientHandler.logger.error("exception in netty handler send", e);
+ }
+ }
+ }
+
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
+
+ this.handler = ctx;
+
+ TcpClientHandler.logger.info("connection established: " + ctx.channel());
+ }
+
+ @Override
+ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+
+ TcpClientHandler.logger.info("string received from" + ctx.channel() + ", content: " + (String)msg);
+ this.manager.decode((String) msg);
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
+ throws Exception {
+ TcpClientHandler.logger.error("exception in netty handler receive", cause);
+ ctx.fireExceptionCaught(cause);
+ TcpClientHandler.logger.info("closing connection" + ctx.channel());
+ ctx.close();
+ TcpClientHandler.logger.info("connection closed");
+ this.handler = null;
+ this.dataSource.removeHandler(this);
+ }
+}
--- /dev/null
+package com.antu.nmea.source.tcp.client;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.source.AcceptanceSetting;
+
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.handler.codec.string.StringDecoder;
+
+public class TcpConnectionHandler extends ChannelInitializer<SocketChannel> {
+
+ static private Log logger = LogFactory.getLog(TcpConnectionHandler.class);
+
+ private TcpClientDataSource observer;
+
+ private AcceptanceSetting acceptanceSetting;
+
+ public TcpConnectionHandler(TcpClientDataSource observer, AcceptanceSetting accSetting) {
+ assert(observer != null);
+ this.observer = observer;
+ }
+
+ @Override
+ protected void initChannel(SocketChannel channel) throws Exception {
+
+ TcpClientHandler handler = new TcpClientHandler(this.observer, this.acceptanceSetting);
+
+ TcpConnectionHandler.logger.info("Incoming connection at: " + channel.toString());
+ channel.pipeline().addLast(new StringDecoder());
+ channel.pipeline().addLast(handler);
+ this.observer.addHandler(handler);
+ }
+}
--- /dev/null
+package com.antu.nmea.source.tcp.server;
+
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.sentence.INmeaSentence;
+import com.antu.nmea.source.AbstractNmeaDataSource;
+import com.antu.nmea.source.AcceptanceSetting;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+import io.netty.handler.codec.string.StringDecoder;
+
+public class TcpServerDataSource extends AbstractNmeaDataSource {
+
+ static private Log logger = LogFactory.getLog(TcpServerDataSource.class);
+
+ private TcpServerDataSourceSetting setting;
+
+ private TcpServerHandler handler;
+
+ public TcpServerDataSource(String talker, TcpServerDataSourceSetting setting, AcceptanceSetting accSetting) {
+ super(talker, accSetting);
+
+ assert(setting != null);
+ this.setting = setting;
+
+ this.handler = new TcpServerHandler(setting, manager);
+ }
+
+ @Override
+ public String getName() {
+ return this.setting.getName();
+ }
+
+ @Override
+ public void stop() {
+ }
+
+ @Override
+ public void run() {
+
+ do {
+ EventLoopGroup g = new NioEventLoopGroup();
+
+ try {
+ Bootstrap bs = new Bootstrap().group(g).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
+ bs.handler(new ChannelInitializer<SocketChannel>(){
+
+ @Override
+ protected void initChannel(SocketChannel ch) throws Exception {
+
+ ch.pipeline().addLast(new StringDecoder());
+ ch.pipeline().addLast(handler);
+ }
+
+ });
+
+ ChannelFuture f = bs.connect(this.setting.getHost(), this.setting.getPort()).sync();
+ TcpServerDataSource.logger.info("connected to " + this.setting.getHost() + ":" + this.setting.getPort());
+ f.channel().closeFuture().sync();
+ } catch (InterruptedException e) {
+ TcpServerDataSource.logger.error("exception during connected to " + this.setting.getHost() + ":" + this.setting.getPort(), e);
+ } finally {
+ g.shutdownGracefully();
+ TcpServerDataSource.logger.info("client shutdown");
+ }
+ } while (this.setting.getAutoRecover());
+ }
+
+ @Override
+ public void send(INmeaSentence sentence) {
+
+ List<String> strings = this.manager.encode(talker, sentence);
+
+ this.handler.send(strings);
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.tcp.server;
+
+import com.antu.nmea.source.IDataSourceSetting;
+
+public class TcpServerDataSourceSetting implements IDataSourceSetting {
+
+ private boolean isAutoRecover;
+
+ private String name;
+
+ private String host;
+
+ private int port;
+
+ private String username;
+
+ private String password;
+
+ public TcpServerDataSourceSetting() {
+ }
+
+ public void setAutoRecover(boolean isAutoRecover) {
+ this.isAutoRecover = isAutoRecover;
+ }
+
+ @Override
+ public boolean getAutoRecover() {
+ return this.isAutoRecover;
+ }
+
+ @Override
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+}
--- /dev/null
+package com.antu.nmea.source.tcp.server;
+
+import java.io.UnsupportedEncodingException;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.antu.nmea.codec.CodecManager;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+
+public class TcpServerHandler extends ChannelInboundHandlerAdapter {
+
+ static private Log logger = LogFactory.getLog(TcpServerHandler.class);
+
+ private TcpServerDataSourceSetting setting;
+
+ private CodecManager manager;
+
+ private ChannelHandlerContext context;
+
+ public TcpServerHandler(TcpServerDataSourceSetting setting, CodecManager manager) {
+ assert(setting != null);
+
+ this.setting = setting;
+ this.manager = manager;
+ }
+
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
+
+ this.context = ctx;
+
+ TcpServerHandler.logger.info("connection established: " + ctx.channel());
+
+ byte[] username = this.setting.getUsername().getBytes("ASCII");
+ byte[] password = this.setting.getPassword().getBytes("ASCII");
+
+ byte[] logon = new byte[username.length + password.length + 3];
+ logon[0] = 1;
+
+ System.arraycopy(username, 0, logon, 1, username.length);
+ logon[1 + username.length] = 0;
+ System.arraycopy(password, 0, logon, 2 + username.length, password.length);
+ logon[logon.length - 1] = 0;
+
+ ByteBuf buffer = Unpooled.buffer(logon.length);
+ buffer.writeBytes(logon);
+
+ ctx.channel().writeAndFlush(buffer);
+ TcpServerHandler.logger.info("logon information sent, username: " + this.setting.getUsername() + ", password: " + this.setting.getPassword());
+ }
+
+ @Override
+ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+
+ this.manager.decode((String) msg);
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
+ throws Exception {
+ TcpServerHandler.logger.error("exception in netty handler receive", cause);
+ ctx.fireExceptionCaught(cause);
+ ctx.close();
+ this.context = null;
+ }
+
+ public void send(List<String> strings) {
+
+ if (this.context == null)
+ return;
+
+ try {
+ for (String str : strings) {
+
+ byte[] bytes = str.getBytes("ASCII");
+ ByteBuf buffer = Unpooled.buffer(bytes.length);
+ buffer.writeBytes(bytes);
+ this.context.writeAndFlush(buffer);
+ }
+ } catch (UnsupportedEncodingException e) {
+ TcpServerHandler.logger.error("exception in netty handler send", e);
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.util;
+
+import java.util.ArrayList;
+
+public class Buffer {
+ private final int BUFFER_SIZE = 500;
+ private char[] buffer;
+ private int capacity;
+ private int length;
+
+ public Buffer() {
+ buffer = new char[BUFFER_SIZE];
+ capacity = BUFFER_SIZE;
+ length = 0;
+ }
+
+ public Buffer(int size) {
+ buffer = new char[size];
+ this.capacity = size;
+ length = 0;
+ }
+
+ static public void copy(char[] from, int fromIndex, int length, char[] to, int startIndex) {
+ for (int i = fromIndex, j = startIndex; i < length && j < to.length; i++, j++) {
+ to[j] = from[i];
+ }
+ }
+
+ public ArrayList<String> append(char[] content) {
+
+ char[] newContent = new char[this.length + content.length];
+
+ Buffer.copy(this.buffer, 0, this.length, newContent, 0);
+ Buffer.copy(content, 0, content.length, newContent, this.length);
+
+ int begin = -1, end = -1, searchIndex = 0;
+
+ ArrayList<String> result = new ArrayList<String>();
+ do {
+ begin = this.findBeginMark(newContent, searchIndex);
+
+ if (begin >= searchIndex) {
+ end = this.findEndMark(newContent, begin + 1);
+ }
+
+ if (begin >= searchIndex && end > begin) {
+ String sentence = new String(newContent, begin, end - begin);
+ result.add(sentence);
+ searchIndex = end;
+ }
+ } while (begin >= 0 && end > 0);
+
+ if (searchIndex < newContent.length) {
+
+ int len = newContent.length - searchIndex;
+
+ if (len < this.capacity) {
+ Buffer.copy(newContent, searchIndex, len, this.buffer, 0);
+ this.length = len;
+ } else {
+ this.length = 0;
+ }
+ } else {
+ this.length = 0;
+ }
+
+ return result;
+ }
+
+ public ArrayList<String> append(String content) {
+ return this.append(content.toCharArray());
+ }
+
+ public int capacity() {
+ return this.capacity;
+ }
+
+ public int length() {
+ return this.length;
+ }
+
+ public boolean isEmpty() {
+ return this.length == 0;
+ }
+
+ /**
+ * Finds the beginning of an nmea sentence, a sentence begins with '!' or '$'
+ * @param p the char string to search the beginning of the sentence
+ * @param startIndex search from the startIndex position
+ * @return returns the index of the beginning, or -1 if not found.
+ */
+ private int findBeginMark(char[] p, int startIndex) {
+
+ for (int index = startIndex; index < p.length; index++) {
+
+ char c = p[index];
+ if (c == '!' || c == '$')
+ return index;
+ }
+ return -1;
+ }
+
+ /**
+ * Finds the end of an nmea sentence, the end of a sentence is "\r\n",
+ * if only '\n' or '\r' found, it is also treated as the end of a sentence
+ * if none of the above found, but the beginning of a sentence is found, sentence end is also found.
+ * @param p the character string to search for
+ * @param startIndex search from the startIndex position
+ * @return the index of the beginning of the next sentence, or -1 if not found
+ */
+ private int findEndMark(char[] p, int startIndex) {
+
+ for (int index = startIndex; index < p.length; index++) {
+
+ char c = p[index];
+ if (c == '\n' || c == '\r') {
+ if (c == '\r') {
+ if (index < p.length - 1 && p[index + 1] == '\n') {
+ return index + 2;
+ }
+ }
+ return index + 1;
+ } else if (c == '!' || c == '$') {
+ return index;
+ }
+ }
+
+ return -1;
+ }
+}
--- /dev/null
+package com.antu.nmea.util;
+
+import java.util.List;
+
+import com.antu.nmea.annotation.GroupItem;
+
+public class DGNSSData {
+
+ public DGNSSData() {
+ }
+
+ @GroupItem(order = 1, itemType = "bits", fieldWidth = 24)
+ public List<Byte> data;
+}
--- /dev/null
+package com.antu.nmea.util;
+
+import com.antu.nmea.annotation.GroupItem;
+
+public class DataLink {
+
+ public DataLink() {
+ }
+
+ @GroupItem(order = 1, fieldWidth = 12, itemType = "short")
+ public short offsetNumber;
+
+ @GroupItem(order = 2, fieldWidth = 4, itemType = "short")
+ public short numberOfSlots;
+
+ @GroupItem(order = 3, fieldWidth = 3, itemType = "short")
+ public short timeout;
+
+ @GroupItem(order = 4, fieldWidth = 11, itemType = "short")
+ public short increment;
+}
--- /dev/null
+package com.antu.nmea.util;
+
+public class DateTime {
+
+ public DateTime() {
+ }
+
+ public short month;
+ public short day;
+ public short hour;
+ public short minute;
+}
--- /dev/null
+package com.antu.nmea.util;
+
+public class Dimension {
+
+ public Dimension() {
+ }
+
+ public short a;
+ public short b;
+ public short c;
+ public short d;
+}
--- /dev/null
+package com.antu.nmea.util;
+
+import com.antu.nmea.annotation.GroupItem;
+
+public class Message6Acknowledgement {
+
+ public Message6Acknowledgement() {
+ }
+
+ @GroupItem(order = 1, itemType = "integer", fieldWidth = 30)
+ public int destinationId;
+
+ @GroupItem(order = 2, itemType = "short", fieldWidth = 2)
+ public short sequenceNumber;
+}
--- /dev/null
+package com.antu.nmea.util;
+
+public class Pair<A, B> {
+ private final A first;
+ private final B second;
+
+ public Pair(A first, B second) {
+ super();
+ this.first = first;
+ this.second = second;
+ }
+
+ public int hashCode() {
+ int hashFirst = first != null ? first.hashCode() : 0;
+ int hashSecond = second != null ? second.hashCode() : 0;
+
+ return (hashFirst + hashSecond) * hashSecond + hashFirst;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public boolean equals(Object other) {
+ if (other instanceof Pair) {
+ Pair otherPair = (Pair) other;
+ return
+ (( this.first == otherPair.first ||
+ ( this.first != null && otherPair.first != null &&
+ this.first.equals(otherPair.first))) &&
+ ( this.second == otherPair.second ||
+ ( this.second != null && otherPair.second != null &&
+ this.second.equals(otherPair.second))) );
+ }
+
+ return false;
+ }
+
+ public String toString()
+ {
+ return "(" + first + ", " + second + ")";
+ }
+
+ public A getFirst() {
+ return first;
+ }
+
+ public B getSecond() {
+ return second;
+ }
+}
--- /dev/null
+package com.antu.nmea.util;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+
+import com.antu.nmea.sentence.IGroupedSentence;
+
+public class SentenceStore<K, V extends IGroupedSentence> {
+
+ private HashMap<K, V> storedSentences = new HashMap<K, V>();
+
+ public SentenceStore() {
+ }
+
+ public List<V> getExpiredItems(Date checkTime, int milliSeconds) {
+
+ List<V> result = new ArrayList<V>();
+ List<K> keys = new ArrayList<K>();
+
+ if (checkTime == null || milliSeconds < 0)
+ return result;
+
+ long time = checkTime.getTime() - milliSeconds;
+
+ synchronized (this) {
+
+ for (K key : this.storedSentences.keySet()) {
+
+ if (this.storedSentences.get(key).getReceiveDate().getTime() < time) {
+ keys.add(key);
+ result.add(this.storedSentences.get(key));
+ }
+ }
+
+ for (K key : keys) {
+ this.storedSentences.remove(key);
+ }
+ }
+ keys.clear();
+
+ return result;
+ }
+
+ public V addItem(K key, V value) {
+
+ if (value.getTotalNumberOfSentences() == 1) {
+ return value;
+ }
+
+ synchronized (this) {
+
+ if (this.storedSentences.containsKey(key)) {
+
+ V oldValue = this.storedSentences.get(key);
+
+ if (oldValue.getSentenceNumber() + 1 == value.getSentenceNumber()) {
+
+ if (value.getSentenceNumber() == value.getTotalNumberOfSentences()) {
+
+ oldValue.concatenate(value);
+ this.storedSentences.remove(key);
+ return oldValue;
+ } else {
+ oldValue.concatenate(value);
+ return null;
+ }
+
+ } else {
+ this.storedSentences.remove(key);
+
+ if (value.getSentenceNumber() == 1)
+ this.storedSentences.put(key, value);
+ return oldValue;
+ }
+
+ } else if (value.getSentenceNumber() == 1) {
+ this.storedSentences.put(key, value);
+ return null;
+ } else {
+ return null;
+ }
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.util;
+
+public class StringHelper {
+
+ static public String capitalizeFirstChar(String str) {
+
+ char[] chars = str.toCharArray();
+ chars[0] = Character.toUpperCase(chars[0]);
+
+ return new String(chars);
+ }
+
+ static public byte toByte(char c) {
+ switch (c) {
+ case '1':
+ return (byte)0x01;
+ case '2':
+ return (byte)0x02;
+ case '3':
+ return (byte)0x03;
+ case '4':
+ return (byte)0x04;
+ case '5':
+ return (byte)0x05;
+ case '6':
+ return (byte)0x06;
+ case '7':
+ return (byte)0x07;
+ case '8':
+ return (byte)0x08;
+ case '9':
+ return (byte)0x09;
+ case 'A':
+ return (byte)0x0A;
+ case 'B':
+ return (byte)0x0B;
+ case 'C':
+ return (byte)0x0C;
+ case 'D':
+ return (byte)0x0D;
+ case 'E':
+ return (byte)0x0E;
+ case 'F':
+ return (byte)0x0F;
+ default:
+ return (byte)0;
+ }
+ }
+
+ static public byte toByte(char a, char b) {
+
+ return (byte) ((StringHelper.toByte(a) << 4) | (StringHelper.toByte(b)));
+ }
+
+ static public char fromHex(char c) {
+ switch (c) {
+ case 1:
+ return '1';
+ case 2:
+ return '2';
+ case 3:
+ return '3';
+ case 4:
+ return '4';
+ case 5:
+ return '5';
+ case 6:
+ return '6';
+ case 7:
+ return '7';
+ case 8:
+ return '8';
+ case 9:
+ return '9';
+ case 0x0A:
+ return 'A';
+ case 0x0B:
+ return 'B';
+ case 0x0C:
+ return 'C';
+ case 0x0D:
+ return 'D';
+ case 0x0E:
+ return 'E';
+ case 0x0F:
+ return 'F';
+ default:
+ return '0';
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.util;
+
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+
+public final class TranslationCodeTable {
+
+ static private TranslationCodeTable Instance = new TranslationCodeTable();
+
+ private HashMap<String, String> proprietaryCode = new HashMap<String, String>();
+
+ private TranslationCodeTable() {
+ }
+
+ static public TranslationCodeTable instance() {
+ return TranslationCodeTable.Instance;
+ }
+
+ public void addCode(String code, String encoding) {
+ synchronized(this) {
+ this.proprietaryCode.put(code, encoding);
+ }
+ }
+
+ public boolean isTranslationCodeProprietary(String translationCode) {
+ return translationCode.startsWith("P") && translationCode.length() == 4;
+ }
+
+ public String getEncoding(String translationCode) {
+
+ try {
+ int encoding = Integer.parseInt(translationCode);
+
+ return "ISO8859_" + new Integer(encoding).toString();
+ } catch (NumberFormatException e) {
+
+ if (translationCode.equals("U")) {
+ return "UTF-16";
+ } else if (translationCode .equals("A")) {
+ return "ASCII";
+ } else if (translationCode.startsWith("P")) {
+ String code = translationCode.substring(1);
+
+ if (this.proprietaryCode.containsKey(code)) {
+ return this.proprietaryCode.get(code);
+ } else {
+ return null;
+ }
+ }
+ }
+ return null;
+ }
+
+ public String decode(String translationCode, String textCode) {
+
+ if (translationCode == null || translationCode.isEmpty() ||
+ textCode == null || textCode.isEmpty())
+ return null;
+
+ String encoding = this.getEncoding(translationCode);
+
+ if (encoding != null) {
+
+ byte[] bytes = new byte[textCode.length() / 2];
+ for (int i = 0; i < bytes.length; i++) {
+ char a = textCode.charAt(i * 2);
+ char b = textCode.charAt(i * 2 + 1);
+
+ bytes[i] = StringHelper.toByte(a, b);
+ }
+
+ try {
+ return new String(bytes, encoding);
+ } catch (UnsupportedEncodingException e) {
+ return null;
+ }
+ }
+
+ return null;
+ }
+
+ public String encode(String translationCode, String text) {
+
+ if (translationCode == null || translationCode.isEmpty() ||
+ text == null || text.isEmpty() || text.length() % 2 != 0)
+ return null;
+
+ String encoding = this.getEncoding(translationCode);
+
+ if (encoding != null) {
+
+ try {
+ byte[] bytes = text.getBytes(encoding);
+
+ StringBuilder builder = new StringBuilder();
+ for (byte b : bytes) {
+ char c = (char) ((b & 0xF0) >> 4);
+ char d = (char) (b & 0x0F);
+
+ builder.append(StringHelper.fromHex(c)).append(StringHelper.fromHex(d));
+ }
+ return builder.toString();
+
+ } catch (UnsupportedEncodingException e) {
+ return null;
+ }
+ }
+ return null;
+ }
+}
--- /dev/null
+package com.antu.nmea.util;
+
+import com.antu.nmea.annotation.GroupItem;
+
+public class TransmissionSchedule {
+
+ public TransmissionSchedule() {
+ }
+
+ @GroupItem(order = 1, fieldWidth = 30, itemType = "integer")
+ public int destinationId;
+
+ @GroupItem(order = 2, fieldWidth = 12, itemType = "short")
+ public short offSet1;
+
+ @GroupItem(order = 3, fieldWidth = 10, itemType = "short")
+ public short increment1;
+}
--- /dev/null
+package com.antu.nmea.util;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+
+public class UtcDate {
+
+ public int year;
+ public int month;
+ public int day;
+
+ public boolean isValid() {
+
+ Calendar cal = Calendar.getInstance();
+ cal.set(year, month, day, 0, 0, 0);
+
+ Date date = cal.getTime();
+
+ SimpleDateFormat sdf = new SimpleDateFormat();
+
+ try {
+ sdf.parse(date.toString());
+ return true;
+ } catch (ParseException e) {
+ return false;
+ }
+ }
+}
--- /dev/null
+package com.antu.nmea.util;
+
+public class UtcTime {
+
+ public int hour;
+ public int minute;
+ public double second;
+
+ public boolean isValid() {
+ if (0 <= hour && hour < 24 &&
+ 0 <= minute && minute < 60 &&
+ 0 <= second && second < 60)
+ return true;
+ return false;
+ }
+
+}
--- /dev/null
+package com.antu.util;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class GenericFactory<E> {
+
+ private List<String> registeredPackages;
+ private HashMap<String, String> symbolsToClassNameMapping;
+ @SuppressWarnings("rawtypes")
+ private HashMap<String, Class> initializedClasses;
+ private HashMap<String, E> initializedObjects;
+
+ private String pattern;
+
+ static private Log logger = LogFactory.getLog(GenericFactory.class);
+
+ @SuppressWarnings("rawtypes")
+ public GenericFactory(String pattern) {
+
+ this.registeredPackages = new ArrayList<String>();
+
+ this.pattern = pattern;
+ this.initializedClasses = new HashMap<String, Class>();
+ this.initializedObjects = new HashMap<String, E>();
+ this.symbolsToClassNameMapping = new HashMap<String, String>();
+ }
+
+ @SuppressWarnings("rawtypes")
+ public GenericFactory(String defaultPackage, String pattern) {
+
+ this.registeredPackages = new ArrayList<String>();
+ this.registeredPackages.add(defaultPackage);
+ this.pattern = pattern;
+ this.initializedClasses = new HashMap<String, Class>();
+ this.initializedObjects = new HashMap<String, E>();
+ this.symbolsToClassNameMapping = new HashMap<String, String>();
+ }
+
+ public boolean isPackageRegistered(String packageName) {
+ return this.registeredPackages.contains(packageName);
+ }
+
+ public void registerPackage(String packageName) {
+
+ if (!this.registeredPackages.contains(packageName)) {
+ this.registeredPackages.add(packageName);
+ }
+ }
+
+ /**
+ * Finds a class from full class name.
+ * @param className
+ * @return returns null if class not found.
+ */
+ protected Class<?> findClass(String className) {
+
+ assert(className != null && !className.isEmpty());
+
+ if (this.initializedClasses.containsKey(className)) {
+ return this.initializedClasses.get(className);
+ }
+
+ try {
+ GenericFactory.logger.debug("class found: " + className);
+ Class<?> clz = Class.forName(className);
+ this.initializedClasses.put(className, clz);
+ return clz;
+ } catch (ClassNotFoundException e) {
+ GenericFactory.logger.fatal("class: " + className + " cannot be found", e);
+ return null;
+ }
+ }
+
+ /**
+ * Finds a class from symbol name
+ * @param symbol
+ * @return
+ */
+ protected Class<?> findClassBySymbol(String symbol) {
+
+ assert(symbol != null && !symbol.isEmpty());
+ String actualName = this.pattern.replace("?", symbol);
+
+ for (String packageName : this.registeredPackages) {
+
+ String className = packageName + "." + actualName;
+ Class<?> clz = this.findClass(className);
+ if (clz != null) {
+
+ this.symbolsToClassNameMapping.put(symbol, className);
+ this.initializedClasses.put(className, clz);
+ return clz;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Retrieves an object by full class name, if already created,
+ * use what is cached. Otherwise, creates a new object.
+ * @param className
+ * @return
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ */
+ @SuppressWarnings("unchecked")
+ public E getByFullName(String className)
+ throws InstantiationException, IllegalAccessException {
+
+ if (this.initializedObjects.containsKey(className)) {
+ GenericFactory.logger.info("cached object found");
+ return this.initializedObjects.get(className);
+ } else if (this.initializedClasses.containsKey(className)) {
+ E obj = (E)this.initializedClasses.get(className).newInstance();
+ this.initializedObjects.put(className, obj);
+ GenericFactory.logger.info("object not in cache, initialized");
+ return obj;
+ } else {
+ Class<?> clz = this.findClass(className);
+
+ if (clz != null) {
+ this.initializedClasses.put(className, clz);
+ E obj = (E)this.initializedClasses.get(className).newInstance();
+ this.initializedObjects.put(className, obj);
+ return obj;
+ }
+ }
+ return null;
+ }
+
+ public E getBySymbol(String symbol)
+ throws InstantiationException, IllegalAccessException {
+
+ if (this.symbolsToClassNameMapping.containsKey(symbol)) {
+ return this.getByFullName(this.symbolsToClassNameMapping.get(symbol));
+ } else {
+
+ Class<?> clz = this.findClassBySymbol(symbol);
+ if (clz != null) {
+ this.symbolsToClassNameMapping.put(symbol, clz.getName());
+ E obj = this.getByFullName(clz.getName());
+ return obj;
+ }
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E createBySymbol(String symbol)
+ throws InstantiationException, IllegalAccessException {
+ Class<?> clz = this.findClassBySymbol(symbol);
+
+ return (E)clz.newInstance();
+ }
+
+ @SuppressWarnings("unchecked")
+ public E createByFullName(String className)
+ throws InstantiationException, IllegalAccessException {
+ Class<?> clz = this.findClass(className);
+ return (E)clz.newInstance();
+ }
+}
--- /dev/null
+package com.antu.util;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class PrintableList<T> extends ArrayList<T> {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4551918441044276598L;
+
+ public PrintableList() {
+ super();
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder("(");
+
+ for (T t : this) {
+ sb.append(t.toString()).append(",");
+ }
+
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public PrintableList<Byte> flip() {
+ PrintableList<Byte> result = new PrintableList<Byte>();
+
+ for (T elem : this) {
+ if (elem.equals(0)) {
+ result.add((byte) 1);
+ } else {
+ result.add((byte) 0);
+ }
+ }
+ return result;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public boolean equals(Object obj) {
+
+ if (obj == null || !(obj instanceof List))
+ return false;
+
+ List val = (List)obj;
+
+ if (this.size() != val.size())
+ return false;
+
+ for (int i = 0; i < val.size(); i++) {
+
+ if (!this.get(i).equals(val.get(i)))
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+
+ int hash = 0;
+
+ for (T elem : this) {
+ hash += elem.hashCode();
+ }
+ return hash;
+ }
+}
import android.widget.TextView;
import android.widget.ToggleButton;
+import com.antu.nmea.codec.CodecManager;
+import com.antu.nmea.codec.exception.SentenceCodecNotFoundException;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
+import java.util.TooManyListenersException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Logger;
+import javax.comm.SerialPort;
+import javax.comm.SerialPortEventListener;
+import javax.comm.UnsupportedCommOperationException;
+
public class MainActivity extends AppCompatActivity {
+ private SerialPort serialPortGPS=null;
+ private SerialPort serialPortUSB=null;
+
private final String TAG="ag3335m_Demo";
public final String GPS_SERIAL_DEVICE = "/dev/ttyS2";
public final String USB_SERIAL_DEVICE = "/dev/ttyGS3";
});
}
-
+ private void init_nmea(){
+ CodecManager manager = new CodecManager();
+
+ manager.acceptanceList().addAllMessages("vdm");
+ try {
+ manager.decode("!AIVDM,1,1,,1,1P000Oh1IT1svTP2r:43grwb05q4,0*01\r\n");
+ } catch (SentenceFieldCodecNotFoundException e) {
+ e.printStackTrace();
+ } catch (SentenceCodecNotFoundException e) {
+ e.printStackTrace();
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ } catch (InstantiationException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ }
public static String byte2hex(byte[] var0,int len) {
if (var0 == null) {
throw new IllegalArgumentException("Argument b ( byte array ) is null! ");
LOCAL_ALLOW_UNDEFINED_SYMBOLS := true
LOCAL_SRC_FILES := native-lib.c gps_hardware.c
LOCAL_MODULE_TAGS := optional
-LOCAL_SHARED_LIBRARIES := libcutils \
- liblog \
- libc
-LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib
+
+LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog -lc
LOCAL_C_INCLUDES := bionic/libc/bionic
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/kernel-headers
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/kernel-headers $(LOCAL_PATH)/libag3335m/inc
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include $(LOCAL_PATH)/kernel-headers
+#LOCAL_CFLAGS := -Werror
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libag3335m_dl
+LOCAL_ALLOW_UNDEFINED_SYMBOLS := true
+LOCAL_SRC_FILES := $(LOCAL_PATH)/libag3335m/src/hdl_demo.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_debug.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_channel.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_da_cmd.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_brom_base.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_api.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_ports/hdl_flash_api.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_ports/hdl_i2c.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_ports/hdl_os_util.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_ports/hdl_spi.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_ports/hdl_uart.c \
+ $(LOCAL_PATH)/libag3335m/src/hdl_ports/md5.c
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog -lc
+LOCAL_C_INCLUDES := bionic/libc/bionic
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/kernel-headers $(LOCAL_PATH)/libag3335m/inc $(LOCAL_PATH)/libag3335m/inc/hdl_ports
LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include $(LOCAL_PATH)/kernel-headers
#LOCAL_CFLAGS := -Werror
include $(BUILD_SHARED_LIBRARY)
APP_ALLOW_MISSING_DEPS=true
LOCAL_SRC_FILES := \
test.c
-LOCAL_C_INCLUDES := bionic/libc/bionic
+LOCAL_C_INCLUDES := bionic/libc/bionic $(LOCAL_PATH)/libag3335m/inc
-LOCAL_SHARED_LIBRARIES := \
- libcutils \
- liblog \
- libc
-LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib
+LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog -lc
LOCAL_SHARED_LIBRARIES += libag3335m_jni
LOCAL_MODULE := ag333m_tool
LOCAL_ALLOW_UNDEFINED_SYMBOLS := true
-include $(BUILD_EXECUTABLE)
\ No newline at end of file
+include $(BUILD_EXECUTABLE)
APP_MODULES := libag3335m_jni
-APP_ABI := armeabi-v7a
\ No newline at end of file
+APP_ABI := armeabi-v7a
+APP_PLATFORM=android-19
\ No newline at end of file
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2020 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#define EN_RAW_MSG_PAIRCMD "PAIR830,2\r\n"
+
+#define MAX_PAYLOAD_SIZE (5*1024) // 5 Kbyte
+#define MAX_CH_NUM (78)
+
+#define PREAMBLE1 (0x04)
+#define PREAMBLE2 (0x24)
+#define ENDWORD1 (0xAA)
+#define ENDWORD2 (0x44)
+
+#define MESSAGE_ID_SIZE (2)
+#define LENGTH_SIZE (2)
+
+#define RAW_MEAS_MSGID (4001)
+#define SV_INFO_MSGID (4003)
+#define PVT_MSGID (4005)
+
+enum {
+ GN_GPS = 0,
+ GN_GLO = 1,
+ GN_BDS = 2,
+ GN_GAL = 3,
+ GN_QZS = 4,
+ GN_SBS = 5,
+ GN_NAVIC = 6
+};
+
+enum {
+ SIG_TYPE_L1 = 0,
+ SIG_TYPE_L5 = 1
+};
+
+// ------------------------------------------------------------------------
+// | Preamble | Message ID | Length | Payload | Checksum | End Word |
+// ------------------------------------------------------------------------
+// | 0x04 | 0x24 | 2 Bytes | 2 Bytes| Variable| 1 Byte | 0xAA | 0x44 |
+//
+// Preamble(2-Bytes word): 0x2404
+// Binary payload :
+// - Message ID
+// - Length: lenght of the Data feild in binary payload
+// - Data: Variable length data
+// Checksum range: Message ID + Length + Payload
+typedef struct {
+ unsigned short msg_id;
+ unsigned short len;
+ unsigned char data[MAX_PAYLOAD_SIZE]; // payload
+} binary_payload_t;
+
+typedef struct {
+ double tow;
+ unsigned short wn;
+ unsigned char clk_status;
+ signed char leap_sec;
+ unsigned char nmeas;
+ unsigned char iod;
+ unsigned short reserved2;
+} raw_meas_part1_t;
+
+typedef struct {
+ unsigned char gn_sig; // bit 4~7: GNSS type
+ // 0: GPS, 1: GLO, 2: BDS, 3: GAL, 4: QZS, 5, SBS, 6: NAVIC
+ // bit 0~3: signal type
+ // 0: GPS L1CA, GLO L1CA, BDS B1I, GAL E1 , QZS L1CA
+ // 1: GPS L5 , , BDS B2a, GAL E5a, QZS L5 , NAVIC L5 SPS
+ unsigned char prn_slot; // PRN or GLO slot
+ unsigned char glo_frq; // GLO frequency number, K equal this item minus eight
+ unsigned char cn0; // signal to noise power density (dB-Hz)
+ float doppler; // Doppler (Hz)
+ double pseudorange; // pseudorange (meter)
+ double carrier_phase; // carrier phase (cycle)
+ unsigned char pr_var_ind; // pseudorange variance index
+ unsigned char do_var_ind; // Doppler variance index
+ unsigned short lock_time; // carrier phase lock time
+ unsigned short ch_status; // bit 12~15: tracking status
+ // 0: acquire
+ // 1: code locked
+ // 2: code and carrier frequency locked
+ // 3: code and carrier phase locked
+ // bit 10~11: frame sync status
+ // 0: none
+ // 1: bit sync
+ // 2: subframe
+ // 3: exact framesync
+ // bit 9: pseudorange valid
+ // 0: invalid
+ // 1: valid
+ // bit 8: carrier phase valid
+ // 0: invalid
+ // 1: valid
+ // bit 6~7: half cycle indicator
+ // 0: no half cycle ambiguity
+ // 1: half cycle ambiguity (parity unknown)
+ // bit 0~5: reserved
+ unsigned short reserved; // reserved
+} raw_meas_part2_t;
+
+typedef struct {
+ unsigned char iod; // issue of data
+ unsigned char nsv; // number of satellites
+ unsigned char reserved2; // reserved
+} raw_meas_sv_info_head_t;
+
+typedef struct {
+ unsigned char gn_sig; // bit 4~7: GNSS type
+ // 0: GPS, 1: GLO, 2: BDS, 3: GAL, 4: QZS, 5, SBS, 6: NAVIC
+ // bit 0~3: signal type
+ // 0: GPS L1CA, GLO L1CA, BDS B1I, GAL E1 , QZS L1CA
+ // 1: GPS L5 , , BDS B2a, GAL E5a, QZS L5 , NAVIC L5 SPS
+ unsigned char prn_slot; // PRN or GLO slot
+ unsigned short azim; // Azimuth angle to the satellite (0 to 360 deg)
+ signed char elev; // Elevation angle to the satellite (-90 to +90 deg)
+ unsigned char sv_status; // reserved
+ unsigned short reserved2; // reserved
+ float px; // satellite X coordinate (ECEF,m)
+ float py; // satellite Y coordinate (ECEF,m)
+ float pz; // satellite Z coordinate (ECEF,m)
+ float vx; // satellite X velocity (ECEF,m/s)
+ float vy; // satellite Y velocity (ECEF,m/s)
+ float vz; // satellite X velocity (ECEF,m/s)
+ float clk_bias; // m
+ float clk_drift; // m/s
+ float trop_delay; // trop delay (m)
+ float iono_delay; // iono delay (m)
+} raw_meas_sv_info_body_t;
+
+typedef struct {
+ unsigned char iod; // issue of data
+ unsigned char fix_quality; // number of satellites
+ unsigned short year; // reserved
+ unsigned char month; // UTC year
+ unsigned char day; // UTC day
+ unsigned char hour; // UTC hour
+ unsigned char min; // UTC minute
+ unsigned short ms; // UTC millisecond
+ unsigned char sec; // UTC second
+ unsigned char status; // PVT status
+ signed int lat; // latitude (1e-7 deg)
+ signed int lon; // longitude (1e-7 deg)
+ signed int alt; // altitude above mean sea level (mm)
+ signed int geoid; // height of geoid above WGS84 (mm)
+ unsigned int speed; // ground speed (mm/s)
+ unsigned int heading; // heading (1e-5 deg)
+ float h_acc; // horizontal accuracy (mm)
+ signed int lsq_lat; // LSQ latitude (1e-7 deg)
+ signed int lsq_lon; // LSQ longitude (1e-7 deg)
+ signed int lsq_alt; // LSQ altitude (mm)
+ signed int lsq_vel_n; // LSQ velocity north (mm/s)
+ signed int lsq_vel_e; // LSQ velocity east (mm/s)
+ signed int lsq_vel_d; // LSQ velocity down (mm/s)
+ double lsq_cb; // LSQ clock bias (m)
+ double lsq_cd; // LSQ clock drift (m/s)
+ signed int kf_lat; // KF latitude (1e-7 deg)
+ signed int kf_lon; // KF longitude (1e-7 deg)
+ signed int kf_alt; // KF altitude (mm)
+ signed int kf_vel_n; // KF velocity north (mm/s)
+ signed int kf_vel_e; // KF velocity north (mm/s)
+ signed int kf_vel_d; // KF velocity north (mm/s)
+ double kf_cb; // KF clock bias (m)
+ double kf_cd; // KF clock drift (m/s)
+} raw_meas_pvt_t;
+
+typedef struct {
+ unsigned char obs_valid; // observation valid flag
+ unsigned char sv_valid; // sv position and velocity valid flag
+ unsigned char gn; // GNSS type
+ // 0: GPS, 1: GLO, 2: BDS, 3: GAL, 4: QZS, 5, SBS, 6: NAVIC
+ unsigned char prn; // PRN
+ unsigned char glo_frq; // GLO frequency number, K equal this item minus eight
+ unsigned char snr[2]; // signal to noise power density (dB-Hz)
+ unsigned char loss_lock_ind[2]; // RINEX loss lock indicator
+ // 0 : OK
+ // bit0: cycle slip possible
+ // bit1: half cycle ambiguity possible
+ float doppler[2]; // Doppler (Hz)
+ double pseudorange[2]; // pseudorange (meter)
+ double carrier_phase[2]; // carrier phase (cycle)
+ double pr_quality[2]; // pseudorange quality
+ double do_quality[2]; // Doppler quality
+ double sv_pos[3]; // satellite position in ECEF
+ double sv_vel[3]; // satellite velocity in ECEF
+ double elev; // elevation (deg)
+ double azim; // azimuth (deg)
+} obs_and_sv_info_t;
+
+typedef struct {
+ unsigned char valid;
+ int IOD[3]; // [0]: observation, [1]: sv info, [2] PVT
+ double tow;
+ unsigned short wn;
+ int nsv; // number of valid obs_and_info
+ obs_and_sv_info_t obs_and_svinfo[MAX_CH_NUM];
+} gnss_data_info_t;
+
+static int decode_binary_packet(unsigned char *buffer,binary_payload_t *payload);
+static unsigned char calculate_binary_checksum(const binary_payload_t *payload);
+static void reset_gnss_data(gnss_data_info_t *gnss_data);
+static int decode_binary_message(unsigned char *buffer, unsigned short msg_id, gnss_data_info_t *gnss_data, int *has_ever_fixed);
+static void decode_raw_meas(unsigned char *payload_data_p, gnss_data_info_t *gnss_data);
+static void decode_sv_info(unsigned char *payload_data_p, gnss_data_info_t *gnss_data);
+static void decode_pvt(unsigned char *payload_data_p, gnss_data_info_t *gnss_data, int *has_ever_fixed);
+static double conver_pr_variance(unsigned char index);
+static double conver_do_variance(unsigned char index);
+static int cmp_observation(const void *p1, const void *p2);
+static int sort_observation(obs_and_sv_info_t *obs, int nobs);
+
+//-----------------------------------------------------------------------------------
+int main(int argc, char* argv[]) {
+ FILE *data_input_fp;
+ FILE *data_output_fp;
+ int nbyte = 0;
+ unsigned char buffer[MAX_PAYLOAD_SIZE] = { 0 };
+ unsigned short len = 0;
+ unsigned short msg_id = 0;
+ int has_ever_fixed = 0;
+ gnss_data_info_t gnss_data;
+
+ // open file
+ if (!(data_input_fp = fopen("D:\\NmeaLog.nma", "rb"))) {
+ printf("Error: open input file!\n");
+ return 0;
+ }
+ if (!(data_output_fp = fopen("D:\\observation.csv", "wb"))) {
+ printf("Error: open output file!\n");
+ return 0;
+ }
+
+ // init
+ reset_gnss_data(&gnss_data);
+
+ while (!feof(data_input_fp)) {
+ unsigned char data;
+ fread(&data, 1, 1, data_input_fp);
+
+ // find preamble
+ if (nbyte == 0) {
+ if (data != PREAMBLE1) {
+ continue;
+ }
+ buffer[nbyte] = data;
+ nbyte++;
+ continue;
+ }
+
+ if (nbyte == 1) {
+ if (data != PREAMBLE2) {
+ nbyte = 0;
+ continue;
+ }
+ buffer[nbyte] = data;
+ nbyte++;
+ continue;
+ }
+
+ // put data into buffer
+ assert(nbyte < MAX_PAYLOAD_SIZE);
+ buffer[nbyte] = data;
+ nbyte++;
+
+ // decode msg id and length
+ if (nbyte == 6) {
+ memcpy(&msg_id, buffer + 2, sizeof(unsigned short));
+ memcpy(&len, buffer + 4, sizeof(unsigned short));
+ printf("msg_id=%d, len=%d\n", msg_id, len);
+ }
+
+ // check length
+ if ((nbyte == 6) && ((len == 0) || (len > MAX_PAYLOAD_SIZE))) {
+ printf("Invalid len: msg_id=%d, len=%d\n", msg_id, len);
+ nbyte = 0;
+ len = 0;
+ msg_id = 0;
+ continue;
+ }
+
+ // 9 = header + id + len + checksum + tail
+ // = 2 + 2 + 2 + 1 + 2
+ if (nbyte < (len + 9)) {
+ continue;
+ }
+
+ // decode binary messages
+ if (decode_binary_message(buffer, msg_id, &gnss_data, &has_ever_fixed)) {
+ // sequence: PVT_MSGID -> RAW_MEAS_MSGID -> SV_INFO_MSGID
+ if (msg_id == SV_INFO_MSGID) {
+ int IOD_consistent = 0;
+ if ((gnss_data.IOD[0] >= 0) &&
+ (gnss_data.IOD[0] == gnss_data.IOD[1]) &&
+ (gnss_data.IOD[1] == gnss_data.IOD[2])) {
+ IOD_consistent = 1;
+ }
+
+ if ((data_output_fp != NULL) && (has_ever_fixed == 1) && IOD_consistent) {
+ int i;
+ // sort observation
+ sort_observation(gnss_data.obs_and_svinfo, gnss_data.nsv);
+
+ // write observation to file
+ for (i = 0; i < gnss_data.nsv; i++) {
+ if (gnss_data.obs_and_svinfo[i].obs_valid == 0) {
+ continue;
+ }
+ if (gnss_data.obs_and_svinfo[i].sv_valid == 0) {
+ continue;
+ }
+ // format:
+ // IOD, Week number, TOW, GNSS type, PRN, GLO Frq,
+ // L1 SNR, L1 LLI, L1 Doppler, L1 Pseudorange, L1 Carrier phase,
+ // L5 SNR, L5 LLI, L5 Doppler, L5 Pseudorange, L5 Carrier phase,
+ // SV pos x, SV pos y, SV pos z
+ fprintf(data_output_fp, "%u,%d,%.3f,%u,%u,%u,%u,%u,%.3f,%.3f,%.3f,%u,%u,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f\r\n",
+ gnss_data.IOD[0],
+ gnss_data.wn,
+ gnss_data.tow,
+ gnss_data.obs_and_svinfo[i].gn,
+ gnss_data.obs_and_svinfo[i].prn,
+ gnss_data.obs_and_svinfo[i].glo_frq,
+ gnss_data.obs_and_svinfo[i].snr[0],
+ gnss_data.obs_and_svinfo[i].loss_lock_ind[0],
+ gnss_data.obs_and_svinfo[i].doppler[0],
+ gnss_data.obs_and_svinfo[i].pseudorange[0],
+ gnss_data.obs_and_svinfo[i].carrier_phase[0],
+ gnss_data.obs_and_svinfo[i].snr[1],
+ gnss_data.obs_and_svinfo[i].loss_lock_ind[1],
+ gnss_data.obs_and_svinfo[i].doppler[1],
+ gnss_data.obs_and_svinfo[i].pseudorange[1],
+ gnss_data.obs_and_svinfo[i].carrier_phase[1],
+ gnss_data.obs_and_svinfo[i].sv_pos[0],
+ gnss_data.obs_and_svinfo[i].sv_pos[1],
+ gnss_data.obs_and_svinfo[i].sv_pos[2]);
+ }
+ }
+ // reset GNSS data
+ reset_gnss_data(&gnss_data);
+ }
+ }
+ // reset after decode
+ nbyte = 0;
+ len = 0;
+ msg_id = 0;
+ memset(buffer, 0, sizeof(unsigned char) * MAX_PAYLOAD_SIZE);
+ } // end of while loop
+
+ // close file
+ if (data_input_fp) {
+ fclose(data_input_fp);
+ }
+ return 1;
+}
+int main(int argc, char* argv[]) {
+
+ FILE *data_input_fp;
+ FILE *data_output_fp;
+ int nbyte = 0;
+ unsigned char buffer[MAX_PAYLOAD_SIZE] = { 0 };
+ unsigned short len = 0;
+ unsigned short msg_id = 0;
+ int has_ever_fixed = 0;
+ gnss_data_info_t gnss_data;
+
+ // open file
+ if (!(data_input_fp = fopen("D:\\NmeaLog.nma", "rb"))) {
+ printf("Error: open input file!\n");
+ return 0;
+ }
+ if (!(data_output_fp = fopen("D:\\observation.csv", "wb"))) {
+ printf("Error: open output file!\n");
+ return 0;
+ }
+
+ // init
+ reset_gnss_data(&gnss_data);
+
+ while (!feof(data_input_fp)) {
+ unsigned char data;
+ fread(&data, 1, 1, data_input_fp);
+
+ // find preamble
+ if (nbyte == 0) {
+ if (data != PREAMBLE1) {
+ continue;
+ }
+ buffer[nbyte] = data;
+ nbyte++;
+ continue;
+ }
+
+ if (nbyte == 1) {
+ if (data != PREAMBLE2) {
+ nbyte = 0;
+ continue;
+ }
+ buffer[nbyte] = data;
+ nbyte++;
+ continue;
+ }
+
+ // put data into buffer
+ assert(nbyte < MAX_PAYLOAD_SIZE);
+ buffer[nbyte] = data;
+ nbyte++;
+
+ // decode msg id and length
+ if (nbyte == 6) {
+ memcpy(&msg_id, buffer + 2, sizeof(unsigned short));
+ memcpy(&len, buffer + 4, sizeof(unsigned short));
+ printf("msg_id=%d, len=%d\n", msg_id, len);
+ }
+
+ // check length
+ if ((nbyte == 6) && ((len == 0) || (len > MAX_PAYLOAD_SIZE))) {
+ printf("Invalid len: msg_id=%d, len=%d\n", msg_id, len);
+ nbyte = 0;
+ len = 0;
+ msg_id = 0;
+ continue;
+ }
+
+ // 9 = header + id + len + checksum + tail
+ // = 2 + 2 + 2 + 1 + 2
+ if (nbyte < (len + 9)) {
+ continue;
+ }
+
+ // decode binary messages
+ if (decode_binary_message(buffer, msg_id, &gnss_data, &has_ever_fixed)) {
+ // sequence: PVT_MSGID -> RAW_MEAS_MSGID -> SV_INFO_MSGID
+ if (msg_id == SV_INFO_MSGID) {
+ int IOD_consistent = 0;
+ if ((gnss_data.IOD[0] >= 0) &&
+ (gnss_data.IOD[0] == gnss_data.IOD[1]) &&
+ (gnss_data.IOD[1] == gnss_data.IOD[2])) {
+ IOD_consistent = 1;
+ }
+
+ if ((data_output_fp != NULL) && (has_ever_fixed == 1) && IOD_consistent) {
+ int i;
+ // sort observation
+ sort_observation(gnss_data.obs_and_svinfo, gnss_data.nsv);
+
+ // write observation to file
+ for (i = 0; i < gnss_data.nsv; i++) {
+ if (gnss_data.obs_and_svinfo[i].obs_valid == 0) {
+ continue;
+ }
+ if (gnss_data.obs_and_svinfo[i].sv_valid == 0) {
+ continue;
+ }
+ // format:
+ // IOD, Week number, TOW, GNSS type, PRN, GLO Frq,
+ // L1 SNR, L1 LLI, L1 Doppler, L1 Pseudorange, L1 Carrier phase,
+ // L5 SNR, L5 LLI, L5 Doppler, L5 Pseudorange, L5 Carrier phase,
+ // SV pos x, SV pos y, SV pos z
+ fprintf(data_output_fp, "%u,%d,%.3f,%u,%u,%u,%u,%u,%.3f,%.3f,%.3f,%u,%u,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f\r\n",
+ gnss_data.IOD[0],
+ gnss_data.wn,
+ gnss_data.tow,
+ gnss_data.obs_and_svinfo[i].gn,
+ gnss_data.obs_and_svinfo[i].prn,
+ gnss_data.obs_and_svinfo[i].glo_frq,
+ gnss_data.obs_and_svinfo[i].snr[0],
+ gnss_data.obs_and_svinfo[i].loss_lock_ind[0],
+ gnss_data.obs_and_svinfo[i].doppler[0],
+ gnss_data.obs_and_svinfo[i].pseudorange[0],
+ gnss_data.obs_and_svinfo[i].carrier_phase[0],
+ gnss_data.obs_and_svinfo[i].snr[1],
+ gnss_data.obs_and_svinfo[i].loss_lock_ind[1],
+ gnss_data.obs_and_svinfo[i].doppler[1],
+ gnss_data.obs_and_svinfo[i].pseudorange[1],
+ gnss_data.obs_and_svinfo[i].carrier_phase[1],
+ gnss_data.obs_and_svinfo[i].sv_pos[0],
+ gnss_data.obs_and_svinfo[i].sv_pos[1],
+ gnss_data.obs_and_svinfo[i].sv_pos[2]);
+ }
+ }
+ // reset GNSS data
+ reset_gnss_data(&gnss_data);
+ }
+ }
+ // reset after decode
+ nbyte = 0;
+ len = 0;
+ msg_id = 0;
+ memset(buffer, 0, sizeof(unsigned char) * MAX_PAYLOAD_SIZE);
+ } // end of while loop
+
+ // close file
+ if (data_input_fp) {
+ fclose(data_input_fp);
+ }
+ return 1;
+}
+//-----------------------------------------------------------------------------------
+static int decode_binary_packet(unsigned char *buffer, binary_payload_t *payload) {
+ int i;
+ int has_preamble = 0;
+ int has_endword = 0;
+ unsigned char *pbyte = NULL;
+ const unsigned char *pbuffer = NULL;
+ unsigned char checksum = 0;
+ if (NULL == buffer || NULL == payload) {
+ return 0;
+ }
+ memset(payload, 0, sizeof(binary_payload_t));
+ pbuffer = buffer;
+ /* check preamble */
+ if (PREAMBLE1 == *pbuffer) {
+ pbuffer++;
+
+ if (PREAMBLE2 == *pbuffer) {
+ has_preamble = 1;
+ pbuffer++;
+ }
+ }
+ if (0 == has_preamble) {
+ return 0;
+ }
+ pbyte = (unsigned char*) payload;
+ /* copy 2Bytes message_id and 2Bytes length*/
+ for (i = 0; i < (MESSAGE_ID_SIZE + LENGTH_SIZE); i++) {
+ *pbyte++ = *pbuffer++;
+ }
+ /* copy length Bytes of message data */
+ pbyte = payload->data;
+ for (i = 0; i < payload->len; i++) {
+ *pbyte++ = *pbuffer++;
+ }
+ /* copy 1byte checksum field */
+ checksum = *pbuffer;
+ if (calculate_binary_checksum(payload) != checksum) {
+ return 0;
+ }
+ pbuffer++;
+ if (ENDWORD1 == *pbuffer) {
+ pbuffer++;
+ if (ENDWORD2 == *pbuffer) {
+ has_endword = 1;
+ }
+ }
+ if (0 == has_endword) {
+ return 0;
+ }
+ return 1;
+}
+
+//-----------------------------------------------------------------------------------
+/* The checksum is the 8-bit exclusive OR of (Message ID + Length + Data) */
+static unsigned char calculate_binary_checksum(const binary_payload_t *payload) {
+ unsigned char checksum = 0;
+ unsigned char *pheader = NULL;
+ unsigned char *pdata = NULL;
+ unsigned short i;
+ if (NULL == payload) {
+ return 0;
+ }
+ pheader = (unsigned char*) payload;
+ for (i = 0; i < (MESSAGE_ID_SIZE + LENGTH_SIZE); i++) {
+ checksum ^= *pheader;
+ pheader++;
+ }
+ pdata = (unsigned char*) payload->data;
+ for (i = 0; i < payload->len; i++) {
+ checksum ^= *pdata;
+ pdata++;
+ }
+ return checksum;
+}
+
+//-----------------------------------------------------------------------------------
+static void reset_gnss_data(gnss_data_info_t *gnss_data) {
+ memset(gnss_data, 0, sizeof(gnss_data_info_t));
+ gnss_data->IOD[0] = -1;
+ gnss_data->IOD[1] = -1;
+ gnss_data->IOD[2] = -1;
+}
+
+//-----------------------------------------------------------------------------------
+static int decode_binary_message(unsigned char *buffer, unsigned short msg_id, gnss_data_info_t *gnss_data, int *has_ever_fixed) {
+ binary_payload_t payload;
+ memset(payload.data, 0, sizeof(unsigned char) * MAX_PAYLOAD_SIZE);
+
+ // check checksum and decode message type
+ if (decode_binary_packet(buffer, &payload)) {
+ if (msg_id == RAW_MEAS_MSGID) {
+ decode_raw_meas(payload.data, gnss_data);
+ return 1;
+ } else if (msg_id == SV_INFO_MSGID) {
+ decode_sv_info(payload.data, gnss_data);
+ return 1;
+ } else if (msg_id == PVT_MSGID) {
+ decode_pvt(payload.data, gnss_data, has_ever_fixed);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+//-----------------------------------------------------------------------------------
+static void decode_raw_meas(unsigned char *payload_data_p, gnss_data_info_t *gnss_data) {
+ int i, j;
+ int nobs;
+ raw_meas_part1_t raw_meas_part1;
+
+ // init
+ nobs = 0;
+ memset(&raw_meas_part1, 0, sizeof(raw_meas_part1_t));
+
+ // step 1: extract measurement time info
+ memcpy(&raw_meas_part1, payload_data_p, sizeof(raw_meas_part1_t));
+ payload_data_p += sizeof(raw_meas_part1_t);
+
+ printf("tow=%f, wn=%d, IOD=%u, clk_status=%d, leap_sec=%d, nmeas=%d\n",
+ raw_meas_part1.tow, raw_meas_part1.wn, raw_meas_part1.iod,
+ raw_meas_part1.clk_status, raw_meas_part1.leap_sec,
+ raw_meas_part1.nmeas);
+
+ // step 2: extract measurement content
+ for (i = 0; i < raw_meas_part1.nmeas; i++) {
+ unsigned char gnss;
+ unsigned char sig;
+ unsigned char loss_lock_ind; // 0: OK
+ unsigned char half_cycle; // 0: no half cycle ambiguity
+ int prn;
+ raw_meas_part2_t raw_meas_part2;
+
+ // init
+ memset(&raw_meas_part2, 0, sizeof(raw_meas_part2_t));
+ memcpy(&raw_meas_part2, payload_data_p, sizeof(raw_meas_part2_t));
+ payload_data_p += sizeof(raw_meas_part2_t);
+
+ // extract bits
+ gnss = (raw_meas_part2.gn_sig >> 4) & 0x0f;
+ sig = raw_meas_part2.gn_sig & 0x0f;
+ half_cycle = (raw_meas_part2.ch_status >> 8) & 0x03;
+ prn = (int) raw_meas_part2.prn_slot;
+
+ // convert QZSS PRN from 193 to 1
+ if (gnss == GN_QZS) {
+ if (prn >= 193) {
+ prn -= 192;
+ }
+ }
+
+ // encode RINEX loss lock indicator
+ loss_lock_ind = 0;
+ if (raw_meas_part2.lock_time <= 0) {
+ loss_lock_ind |= 0x01;
+ }
+ if (half_cycle) {
+ loss_lock_ind |= 0x02;
+ }
+
+ printf("gnss=%2u, sig=%2u, prn=%3u, glo_frq=%2u, cn0=%2u, pr=%14.3f, cp=%14.3f, dopp=%9.2f, var=%u, %u, lock_time=%4u, ch_status=%4x\n",
+ gnss, sig, prn, raw_meas_part2.glo_frq, raw_meas_part2.cn0,
+ raw_meas_part2.pseudorange, raw_meas_part2.carrier_phase,
+ raw_meas_part2.doppler, raw_meas_part2.pr_var_ind,
+ raw_meas_part2.do_var_ind, raw_meas_part2.lock_time,
+ raw_meas_part2.ch_status);
+
+ if (raw_meas_part2.cn0 > 0) {
+ int frq;
+ int has_same_prn;
+ int obs_idx;
+
+ obs_idx = nobs;
+
+ // search any same PRN observation in data
+ has_same_prn = 0;
+ for (j = 0; j < nobs; j++) {
+ if (gnss_data->obs_and_svinfo[j].gn != gnss) {
+ continue;
+ }
+ if (gnss_data->obs_and_svinfo[j].prn != prn) {
+ continue;
+ }
+ obs_idx = j;
+ has_same_prn = 1;
+ break;
+ }
+
+ frq = 0; // L1
+ if (sig == SIG_TYPE_L5) {
+ frq = 1; // L5
+ }
+
+ // write measurement
+ gnss_data->obs_and_svinfo[obs_idx].obs_valid = 1;
+ gnss_data->obs_and_svinfo[obs_idx].gn = gnss;
+ gnss_data->obs_and_svinfo[obs_idx].prn = prn;
+ gnss_data->obs_and_svinfo[obs_idx].glo_frq = raw_meas_part2.glo_frq;
+ gnss_data->obs_and_svinfo[obs_idx].snr[frq] = raw_meas_part2.cn0;
+ gnss_data->obs_and_svinfo[obs_idx].loss_lock_ind[frq] = loss_lock_ind;
+ gnss_data->obs_and_svinfo[obs_idx].doppler[frq] = raw_meas_part2.doppler;
+ gnss_data->obs_and_svinfo[obs_idx].pseudorange[frq] = raw_meas_part2.pseudorange;
+ gnss_data->obs_and_svinfo[obs_idx].carrier_phase[frq] = raw_meas_part2.carrier_phase;
+ gnss_data->obs_and_svinfo[obs_idx].pr_quality[frq] = conver_pr_variance(raw_meas_part2.pr_var_ind);
+ gnss_data->obs_and_svinfo[obs_idx].do_quality[frq] = conver_do_variance(raw_meas_part2.do_var_ind);
+
+ // update observation number
+ if (!has_same_prn) {
+ nobs++;
+ }
+ }
+ }
+ printf("\n\n");
+
+ gnss_data->IOD[0] = raw_meas_part1.iod;
+ gnss_data->tow = raw_meas_part1.tow;
+ gnss_data->wn = raw_meas_part1.wn;
+ gnss_data->nsv = nobs;
+}
+
+//-----------------------------------------------------------------------------------
+static void decode_sv_info(unsigned char *payload_data_p, gnss_data_info_t *gnss_data) {
+ int i;
+ raw_meas_sv_info_head_t sv_info_head;
+
+ // step 1: extract measurement time info
+ memset(&sv_info_head, 0, sizeof(raw_meas_sv_info_head_t));
+ memcpy(&sv_info_head, payload_data_p, sizeof(raw_meas_sv_info_head_t));
+ payload_data_p += sizeof(raw_meas_sv_info_head_t);
+
+ gnss_data->IOD[1] = sv_info_head.iod;
+ printf("sv_info: IOD=%u, nsv=%u\n", sv_info_head.iod, sv_info_head.nsv);
+
+ // step 2: extract SV info content
+ for (i = 0; i < sv_info_head.nsv; i++) {
+ unsigned char gnss;
+ unsigned char eph_valid;
+ unsigned char iono_source;
+ int prn;
+ int j;
+ raw_meas_sv_info_body_t sv_info_body;
+
+ memset(&sv_info_body, 0, sizeof(raw_meas_sv_info_body_t));
+ memcpy(&sv_info_body, payload_data_p, sizeof(raw_meas_sv_info_body_t));
+
+ payload_data_p += sizeof(raw_meas_sv_info_body_t);
+
+ // extract bits
+ gnss = (sv_info_body.gn_sig >> 4) & 0x0f;
+ prn = (int) sv_info_body.prn_slot;
+
+ // convert QZSS PRN from 193 to 1
+ if (gnss == GN_QZS) {
+ if (prn >= 193) {
+ prn -= 192;
+ }
+ }
+
+ eph_valid = (sv_info_body.sv_status & 0x01);
+ iono_source = ((sv_info_body.sv_status >> 4) & 0x0f);
+
+ printf("SV_Info: gnss=%2u, prn=%3u, eph=%u, elv=%3d, alz=%3u, pxzy=%.2f, %.2f, %.2f, vxyz=%.2f, %.2f, %.2f, cb=%.2f, cd=%.2e, trop=%.2f, iono=%.2f, src=%u\n",
+ gnss, prn, eph_valid, sv_info_body.elev, sv_info_body.azim,
+ sv_info_body.px, sv_info_body.py, sv_info_body.pz,
+ sv_info_body.vx, sv_info_body.vy, sv_info_body.vz,
+ sv_info_body.clk_bias, sv_info_body.clk_drift,
+ sv_info_body.trop_delay, sv_info_body.iono_delay, iono_source);
+
+ // write sv info
+ // search any same PRN observation in data
+ for (j = 0; j < gnss_data->nsv; j++) {
+ if (gnss_data->obs_and_svinfo[j].gn != gnss) {
+ continue;
+ }
+ if (gnss_data->obs_and_svinfo[j].prn != prn) {
+ continue;
+ }
+ gnss_data->obs_and_svinfo[j].sv_valid = 1;
+ gnss_data->obs_and_svinfo[j].sv_pos[0] = sv_info_body.px;
+ gnss_data->obs_and_svinfo[j].sv_pos[1] = sv_info_body.py;
+ gnss_data->obs_and_svinfo[j].sv_pos[2] = sv_info_body.pz;
+ gnss_data->obs_and_svinfo[j].sv_vel[0] = sv_info_body.vx;
+ gnss_data->obs_and_svinfo[j].sv_vel[1] = sv_info_body.vy;
+ gnss_data->obs_and_svinfo[j].sv_vel[2] = sv_info_body.vz;
+ gnss_data->obs_and_svinfo[j].elev = sv_info_body.elev;
+ gnss_data->obs_and_svinfo[j].azim = sv_info_body.azim;
+ break;
+ }
+ }
+ printf("\n\n");
+}
+
+//-----------------------------------------------------------------------------------
+static void decode_pvt(unsigned char *payload_data_p, gnss_data_info_t *gnss_data, int *has_ever_fixed) {
+ raw_meas_pvt_t pvt;
+ double utc_sec;
+ double lat, lon, alt, geoid;
+ double speed, heading, h_acc;
+ // LSQ
+ double lsq_lat, lsq_lon, lsq_alt;
+ double lsq_vel[3];
+ double lsq_cb, lsq_cd;
+ // KF
+ double kf_lat, kf_lon, kf_alt;
+ double kf_vel[3];
+ double kf_cb, kf_cd;
+
+ memset(&pvt, 0, sizeof(raw_meas_pvt_t));
+ memcpy(&pvt, payload_data_p, sizeof(raw_meas_pvt_t));
+
+ gnss_data->IOD[2] = pvt.iod;
+
+ utc_sec = ((double) pvt.sec) + ((double) pvt.ms) / 1000.0;
+ lat = ((double) pvt.lat) * 1e-7;
+ lon = ((double) pvt.lon) * 1e-7;
+ alt = ((double) pvt.alt) * 1e-3;
+ geoid = ((double) pvt.geoid) * 1e-3;
+
+ speed = ((double) pvt.speed) * 1e-3;
+ heading = ((double) pvt.heading) * 1e-5;
+ h_acc = ((double) pvt.h_acc) * 1e-3;
+
+ printf("PVT_POS: IOD=%u, fixq=%u, UTC=%u %02u %02u %u:%u:%f, LLA=%f,%f,%f, geoid=%f\n",
+ pvt.iod, pvt.fix_quality, pvt.year, pvt.month, pvt.day, pvt.hour,
+ pvt.min, utc_sec, lat, lon, alt, geoid);
+
+ printf("PVT_VEL: speed=%f, heading=%f, h_acc=%f, status=%x\n", speed,
+ heading, h_acc, pvt.status);
+
+ if ((pvt.status & 0x02)) {
+ lsq_lat = ((double) pvt.lsq_lat) * 1e-7;
+ lsq_lon = ((double) pvt.lsq_lon) * 1e-7;
+ lsq_alt = ((double) pvt.lsq_alt) * 1e-3;
+ lsq_vel[0] = ((double) pvt.lsq_vel_n) * 1e-3;
+ lsq_vel[1] = ((double) pvt.lsq_vel_e) * 1e-3;
+ lsq_vel[2] = ((double) pvt.lsq_vel_d) * 1e-3;
+ lsq_cb = pvt.lsq_cb;
+ lsq_cd = pvt.lsq_cd;
+
+ printf("PVT_LSQ: LLA=%f,%f,%f, vel=%f,%f,%f, cb=%f, cd=%f\n", lsq_lat,
+ lsq_lon, lsq_alt, lsq_vel[0], lsq_vel[1], lsq_vel[2], lsq_cb,
+ lsq_cd);
+ }
+
+ if ((pvt.status & 0x04)) {
+ kf_lat = ((double) pvt.kf_lat) * 1e-7;
+ kf_lon = ((double) pvt.kf_lon) * 1e-7;
+ kf_alt = ((double) pvt.kf_alt) * 1e-3;
+ kf_vel[0] = ((double) pvt.kf_vel_n) * 1e-3;
+ kf_vel[1] = ((double) pvt.kf_vel_e) * 1e-3;
+ kf_vel[2] = ((double) pvt.kf_vel_d) * 1e-3;
+ kf_cb = pvt.kf_cb;
+ kf_cd = pvt.kf_cd;
+ printf("PVT_KF: LLA=%f,%f,%f, vel=%f,%f,%f, cb=%f, cd=%f\n", kf_lat,
+ kf_lon, kf_alt, kf_vel[0], kf_vel[1], kf_vel[2], kf_cb, kf_cd);
+ }
+
+ // update PVT ever fixed flag
+ if( (*has_ever_fixed) == 0 ) {
+ if( pvt.fix_quality > 0 ) {
+ *has_ever_fixed = 1;
+ }
+ }
+
+ printf("\n\n");
+}
+
+//-----------------------------------------------------------------------------------
+static double conver_pr_variance(unsigned char index) {
+ double var;
+ if (index == 0)
+ var = 1.0;
+ else if (index == 1)
+ var = 2.0;
+ else if (index == 2)
+ var = 4.0;
+ else if (index == 3)
+ var = 9.0;
+ else if (index == 4)
+ var = 16.0;
+ else if (index == 5)
+ var = 25.0;
+ else if (index == 6)
+ var = 36.0;
+ else if (index == 7)
+ var = 49.0;
+ else if (index == 8)
+ var = 64.0;
+ else if (index == 9)
+ var = 81.0;
+ else if (index == 10)
+ var = 100.0;
+ else if (index == 11)
+ var = 121.0;
+ else if (index == 12)
+ var = 169.0;
+ else if (index == 13)
+ var = 225.0;
+ else if (index == 14)
+ var = 289.0;
+ else if (index == 15)
+ var = 361.0;
+ else if (index == 16)
+ var = 441.0;
+ else if (index == 17)
+ var = 529.0;
+ else if (index == 18)
+ var = 625.0;
+ else if (index == 19)
+ var = 729.0;
+ else if (index == 20)
+ var = 841.0;
+ else if (index == 21)
+ var = 961.0;
+ else if (index == 22)
+ var = 1089.0;
+ else if (index == 23)
+ var = 1444.0;
+ else if (index == 24)
+ var = 1849.0;
+ else if (index == 25)
+ var = 2304.0;
+ else if (index == 26)
+ var = 2809.0;
+ else if (index == 27)
+ var = 3364.0;
+ else if (index == 28)
+ var = 3969.0;
+ else if (index == 29)
+ var = 4624.0;
+ else if (index == 30)
+ var = 5329.0;
+ else if (index == 31)
+ var = 6084.0;
+ else if (index == 32)
+ var = 6084.0;
+ else
+ var = 6084.0;
+ return var;
+}
+
+//-----------------------------------------------------------------------------------
+static double conver_do_variance(unsigned char index) {
+ double var;
+ if (index == 0)
+ var = 0.04;
+ else if (index == 1)
+ var = 0.07;
+ else if (index == 2)
+ var = 0.10;
+ else if (index == 3)
+ var = 0.16;
+ else if (index == 4)
+ var = 0.25;
+ else if (index == 5)
+ var = 0.36;
+ else if (index == 6)
+ var = 0.49;
+ else if (index == 7)
+ var = 0.64;
+ else if (index == 8)
+ var = 0.81;
+ else if (index == 9)
+ var = 1.0;
+ else if (index == 10)
+ var = 1.44;
+ else if (index == 11)
+ var = 1.96;
+ else if (index == 12)
+ var = 2.56;
+ else if (index == 13)
+ var = 3.24;
+ else if (index == 14)
+ var = 4.0;
+ else if (index == 15)
+ var = 5.76;
+ else if (index == 16)
+ var = 7.84;
+ else if (index == 17)
+ var = 10.24;
+ else if (index == 18)
+ var = 12.96;
+ else if (index == 19)
+ var = 16.0;
+ else if (index == 20)
+ var = 19.36;
+ else if (index == 21)
+ var = 23.04;
+ else if (index == 22)
+ var = 25.0;
+ else if (index == 23)
+ var = 25.0;
+ else
+ var = 25.0;
+ return var;
+}
+
+//-----------------------------------------------------------------------------------
+static int cmp_observation(const void *p1, const void *p2) {
+ obs_and_sv_info_t *q1 = (obs_and_sv_info_t *) p1, *q2 = (obs_and_sv_info_t *) p2;
+ if (q1->gn != q2->gn)
+ return (int) q1->gn - (int) q2->gn;
+ return (int) q1->prn - (int) q2->prn;
+}
+
+//-----------------------------------------------------------------------------------
+static int sort_observation(obs_and_sv_info_t *obs, int nobs) {
+ if (nobs <= 0) {
+ return 0;
+ }
+ qsort(obs, nobs, sizeof(obs_and_sv_info_t), cmp_observation);
+ return nobs;
+}
#define GH_IOC_MAGIC 'G'
#define GH_IOCTL_CMD_RESET _IOW(GH_IOC_MAGIC, 0x02, uint32_t)
#define AG3335_DEVICE "/dev/ag3335m"
-int ag3335m_reset(){
+int ag3335m_reset(int enabled){
int dev_fd;
dev_fd = open(AG3335_DEVICE, O_RDWR | O_SYNC);
if (dev_fd < 0) {
return 1;
}
int err = 0;
- int enabled =1;
{// enable step counter
LOGD("ag3335m_reset ioctl");
tcgetattr(fd, &termios);
cfmakeraw(&termios);
- termios.c_oflag &= ~OPOST;
- termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
- termios.c_cflag &= ~(CSIZE | PARENB |CRTSCTS);//CRTSCTS
- //termios.c_cflag |= (CS8 |CRTSCTS );//CRTSCTS
- termios.c_cflag |= (CS8 );//CRTSCTS
+ // termios.c_oflag &= ~OPOST;
+ // termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
+ // termios.c_cflag &= ~(CSIZE | PARENB |CRTSCTS);//CRTSCTS
+ termios.c_cflag |= (CS8 |CRTSCTS );//CRTSCTS
+ //termios.c_cflag |= (CS8 );//CRTSCTS
/* set input/output baudrate */
cfsetospeed(&termios, baud);
cfsetispeed(&termios, baud);
void recvThread(void* arg){
int ret=0;
- char* rebootcmd="$PAIR009*33\r\n";
+ // char* rebootcmd="$PAIR009*33\r\n";
char* getportstat="$PAIR868*3C\r\n";
- write(gps_fd,rebootcmd,13);
+ // write(gps_fd,rebootcmd,13);
//write(gps_fd,getportstat,13);
while(1==1){
ret=read(tty_fd,readbuftty,2047);
int gps_hardware_close(void);
int tty_hardware_open(void);
int tty_hardware_close(void);
-int ag3335m_reset();
+int ag3335m_reset(int enabled);
#endif //AG3335M_DOWNLOAD_DEMO_HARDWARE_H
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_API_H__
+#define __HDL_API_H__
+
+#include "hdl_brom_base.h"
+#include "hdl_da_cmd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef PSRAM_DOWNLOAD
+typedef enum {
+ DISCONNECT_NONE = 0,
+ DISCONNECT_POWER_OFF,
+ DISCONNECT_RESET
+} HDL_DISCONNECT_TYPE;
+
+bool hdl_connect(const hdl_da_info_t *da_info, const hdl_connect_arg_t *connect_arg,
+ hdl_da_report_t *da_report);
+bool hdl_format(const hdl_format_arg_t *format_arg);
+bool hdl_readback(const hdl_readback_arg_t *readback_arg);
+bool hdl_disconnect(HDL_DISCONNECT_TYPE disconnect_type);
+#else
+bool hdl_connect(const hdl_da_info_t *da_info, const hdl_connect_arg_t *connect_arg);
+#endif
+
+bool hdl_download(const hdl_download_arg_t *download_arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_API_H__
+
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_BROM_BASE_H__
+#define __HDL_BROM_BASE_H__
+
+#include "hdl_channel.h"
+#include "hdl_ports/hdl_flash_api.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+ BROM_CMD_READ16 = 0xD0,
+ BROM_CMD_READ32 = 0xD1,
+ BROM_CMD_WRITE16 = 0xD2,
+ BROM_CMD_WRITE32 = 0xD4,
+ BROM_CMD_JUMP_DA = 0xD5,
+ BROM_CMD_SEND_DA = 0xD7
+} HDL_BROM_CMD;
+
+#if defined(CHIP_7686)
+#define HDL_WDT_REG 0xA2090000
+#define HDL_WDT_VAL 0x0011
+#define HDL_DA_RUN_ADDR 0x04009000
+
+#elif defined(CHIP_3335)
+#define HDL_WDT_REG 0xA2080000
+#define HDL_WDT_VAL 0x0010
+#define HDL_DA_RUN_ADDR 0x04204000
+#endif
+
+#define BROM_OK 0x0000
+#define BROM_ERROR 0x1000
+
+bool hdl_brom_start();
+
+bool hdl_brom_disable_wdt();
+
+bool hdl_brom_read16(uint32_t addr, uint16_t *data);
+bool hdl_brom_read32(uint32_t addr, uint32_t *data);
+bool hdl_brom_write16(uint32_t addr, uint16_t data);
+bool hdl_brom_write32(uint32_t addr, uint32_t data);
+
+bool hdl_brom_send_da(const hdl_connect_arg_t *connect_arg,
+ uint32_t da_flash_pos, uint32_t da_start_addr, uint32_t da_len);
+bool hdl_brom_jump_da(uint32_t addr);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_BROM_BASE_H__
+
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_CHANNEL_H__
+#define __HDL_CHANNEL_H__
+
+#include "hdl_ports/hdl_uart.h"
+#include "hdl_ports/hdl_spi.h"
+#include "hdl_ports/hdl_i2c.h"
+
+#include "hdl_data.h"
+#include "hdl_ports/hdl_os_util.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+ CHANNEL_TYPE_UART = 0,
+ CHANNEL_TYPE_SPI,
+ CHANNEL_TYPE_I2C
+} HDL_CHANNEL_TYPE;
+
+typedef struct {
+ bool (*m_com_init) (void);
+ uint8_t (*m_com_get_byte) (void);
+ bool (*m_com_get_byte_status) (uint8_t *data);
+ uint32_t (*m_com_get_byte_buffer) (uint8_t *buf, uint32_t length);
+ void (*m_com_put_byte) (uint8_t data);
+ uint32_t (*m_com_put_byte_buffer) (uint8_t *buf, uint32_t length);
+ void (*m_com_put_byte_complete) (uint8_t data);
+ uint16_t (*m_com_get_data16) (void);
+ void (*m_com_put_data16) (uint16_t data);
+ uint32_t (*m_com_get_data32) (void);
+ void (*m_com_put_data32) (uint32_t data);
+ void (*m_com_purge_fifo) (void);
+ void (*m_com_set_baudrate) (hal_uart_baudrate_t baud_rate);
+ void (*m_com_setup_new_port) (void);
+ bool (*m_com_deinit) (void);
+} g_hdl_channel_t;
+
+extern g_hdl_channel_t g_hdl_channel;
+
+#define HDL_COM_Init g_hdl_channel.m_com_init
+#define HDL_COM_GetByte g_hdl_channel.m_com_get_byte
+#define HDL_COM_GetByteStatus(data) g_hdl_channel.m_com_get_byte_status(data)
+#define HDL_COM_GetByte_Buffer(buf,length) g_hdl_channel.m_com_get_byte_buffer(buf, length)
+#define HDL_COM_PutByte(data) g_hdl_channel.m_com_put_byte(data)
+#define HDL_COM_PutByte_Buffer(buf,length) g_hdl_channel.m_com_put_byte_buffer(buf, length)
+#define HDL_COM_PutByte_Complete(data) g_hdl_channel.m_com_put_byte_complete(data)
+#define HDL_COM_GetData16 g_hdl_channel.m_com_get_data16
+#define HDL_COM_PutData16(data) g_hdl_channel.m_com_put_data16(data)
+#define HDL_COM_GetData32 g_hdl_channel.m_com_get_data32
+#define HDL_COM_PutData32(data) g_hdl_channel.m_com_put_data32(data)
+#define HDL_COM_PurgeFIFO g_hdl_channel.m_com_purge_fifo
+#define HDL_COM_SetBaudRate(baud_rate) g_hdl_channel.m_com_set_baudrate(baud_rate)
+#define HDL_COM_SetupNewPort g_hdl_channel.m_com_setup_new_port
+#define HDL_COM_Deinit g_hdl_channel.m_com_deinit
+
+bool hdl_channel_init(void);
+uint8_t hdl_get_channel_type();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_CHANNEL_H__
+
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_CONFIG_H__
+#define __HDL_CONFIG_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <linux/ioctl.h>
+#include <fcntl.h>
+
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <assert.h>
+
+
+#include <sys/time.h>
+#include <sys/ioctl.h>
+#include <termios.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <string.h>
+#include <linux/kd.h>
+#include <linux/vt.h>
+#include <errno.h>
+#include <pthread.h>
+
+#include <math.h>
+#include <poll.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <sys/select.h>
+
+#include <linux/input.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//#define CHIP_7686 // 7686=7682=5932
+#define CHIP_3335
+
+#if defined(CHIP_7686)
+#define HDL_VIA_UART
+#elif defined(CHIP_3335)
+#define HDL_VIA_UART
+//#define HDL_VIA_SPI
+//#define HDL_VIA_I2C
+#else
+#error "Only support 768x/3335"
+#endif
+
+// ToDo Porting: Please use your platform API to implement them.
+#ifdef HDL_VIA_UART
+#define HDL_UART_NUM 1
+
+#elif defined(HDL_VIA_SPI)
+#define SPIM_TEST_FREQUENCY 500000
+#define SPIM_TEST_PORT HAL_SPI_MASTER_0
+
+#define SPIM_PIN_NUMBER_CS HAL_GPIO_34
+#define SPIM_PIN_FUNC_CS HAL_GPIO_34_SPI_MST0_CS
+#define SPIM_PIN_NUMBER_CLK HAL_GPIO_35
+#define SPIM_PIN_FUNC_CLK HAL_GPIO_35_SPI_MST0_SCK
+#define SPIM_PIN_NUMBER_MOSI HAL_GPIO_32
+#define SPIM_PIN_FUNC_MOSI HAL_GPIO_32_SPI_MST0_MOSI
+#define SPIM_PIN_NUMBER_MISO HAL_GPIO_33
+#define SPIM_PIN_FUNC_MISO HAL_GPIO_33_SPI_MST0_MISO
+
+#elif defined(HDL_VIA_I2C)
+#define I2C_MASTER_NUM HAL_I2C_MASTER_1
+#define I2C_MODE HAL_I2C_IO_OPEN_DRAIN// first:HAL_I2C_IO_PUSH_PULL; second:HAL_I2C_IO_OPEN_DRAIN
+#define I2C_SCL_PIN_USED HAL_GPIO_26
+#define I2C_SCL_MODE_USED HAL_GPIO_26_I2C1_SCL
+#define I2C_SDA_PIN_USED HAL_GPIO_27
+#define I2C_SDA_MODE_USED HAL_GPIO_27_I2C1_SDA
+#endif
+typedef int BOOL;
+#define TRUE 1
+#define FALSE 0
+typedef int hal_uart_baudrate_t ;
+// Turn on HDL Debug Log
+#define HDL_DEBUG
+
+// Choose PSRAM download
+//#define PSRAM_DOWNLOAD
+
+/***
+ * main_region:
+ address_type: physical
+ rom_list:
+ - rom:
+ file: partition_table.bin
+ name: PartitionTable
+ begin_address: 0x08000000
+ - rom:
+ file: ag3335_bootloader.bin
+ name: BootLoader
+ begin_address: 0x08003000
+ - rom:
+ file: gnss_demo.bin
+ name: CM4
+ begin_address: 0x08013000
+ - rom:
+ file: gnss_config.bin
+ name: GNSSConfiguration
+ begin_address: 0x083FF000
+ */
+// DA Flash Position
+#define HDL_DA_FLASH_POS 0x00100000
+#define HDL_DA_SIZE 28672
+
+// Test Images Flash Position in Host & Target Device
+#define HDL_BL_IMAGE_HOST_FLASH_POS 0x00110000
+#define HDL_BL_IMAGE_SLAVE_FLASH_POS 0x08010000
+#define HDL_BL_IMAGE_SIZE 32768
+#define HDL_BL_IMAGE_NAME "BootLoader"
+#define HDL_CM4_IMAGE_HOST_FLASH_POS 0x00120000
+#define HDL_CM4_IMAGE_SLAVE_FLASH_POS 0x08020000
+#define HDL_CM4_IMAGE_SIZE 540672
+#define HDL_CM4_IMAGE_NAME "CM4"
+#define HDL_OTHER_IMAGE_HOST_FLASH_POS 0x001F0000
+#define HDL_OTHER_IMAGE_SLAVE_FLASH_POS 0x080F0000
+#define HDL_OTHER_IMAGE_SIZE 53248
+#define HDL_OTHER_IMAGE_NAME "Other"
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_CONFIG_H__
+
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_DA_CMD_H__
+#define __HDL_DA_CMD_H__
+
+#include "hdl_channel.h"
+#include "hdl_ports/hdl_flash_api.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// DA Return
+#define DA_S_DONE 0x00
+
+#define DA_SYNC_CHAR 0xC0
+#define DA_CONT_CHAR 0x69
+#define DA_STOP_CHAR 0x96
+#define DA_ACK 0x5A
+#define DA_NACK 0xA5
+#define DA_UNKNOWN_CMD 0xBB
+#define DA_FLUSH_CONT 0xE1
+#define DA_FLUSH_DONE 0xE2
+
+#define DA_S_IN_PROGRESS 3021
+#define DA_S_UART_GET_DATA_TIMEOUT 3061
+#define DA_S_UART_GET_CHKSUM_LSB_TIMEOUT 3062
+#define DA_S_UART_GET_CHKSUM_MSB_TIMEOUT 3063
+#define DA_S_UART_DATA_CKSUM_ERROR 3064
+#define DA_S_UART_RX_BUF_FULL 3065
+
+// DA CMD
+#define DA_FORMAT_CMD 0xD4
+#define DA_NOR_WRITE_DATA 0xB2
+#define DA_READ_CMD 0xD6
+#define DA_FINISH_CMD 0xD9
+#define DA_ENABLE_WATCHDOG_CMD 0xDB
+
+#define DA_SEND_PACKET_LEN (4 * 1024)
+#define DA_RECV_PACKET_LEN (4 * 1024)
+
+
+#ifndef PSRAM_DOWNLOAD
+bool hdl_sync_with_da(bool enable_log, hdl_da_report_t *da_report);
+bool hdl_da_format(const hdl_format_arg_t *format_arg);
+bool hdl_da_readback(const hdl_readback_arg_t *readback_arg);
+bool hdl_da_enable_wdt(uint16_t wdt_sec);
+bool hdl_da_finish(bool power_off);
+#else
+bool hdl_sync_with_da(bool enable_log);
+#endif
+
+bool hdl_da_download(hdl_image_t *image, hdl_download_cb download_cb, void *download_cb_arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_DA_CMD_H__
+
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_DATA_H__
+#define __HDL_DATA_H__
+
+#include "hdl_config.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void (*hdl_init_cb)(void *usr_arg);
+typedef void (*hdl_da_send_cb)(void *usr_arg, uint32_t sent_bytes, uint32_t da_total_bytes);
+typedef void (*hdl_download_cb)(void *usr_arg, char *cur_image_name,
+ uint32_t sent_bytes, uint32_t total_bytes);
+typedef void (*hdl_progress_cb)(void *usr_arg, uint8_t percent);
+typedef void (*hdl_readback_cb)(void *usr_arg, uint32_t cur_flash_addr,
+ uint8_t *readback_buf, uint32_t readback_buf_len,
+ uint32_t read_len, uint32_t readback_total_len);
+
+typedef struct {
+ uint32_t da_flash_addr; // Or da_ram_pointer, Or da_file if your host have file system
+ uint32_t da_run_addr;
+ uint32_t da_len;
+} hdl_da_info_t;
+
+typedef struct {
+ hdl_init_cb conn_da_init_cb;
+ void *conn_da_init_cb_arg;
+ hdl_da_send_cb conn_da_send_cb;
+ void *conn_da_send_cb_arg;
+ bool conn_enable_log;
+} hdl_connect_arg_t;
+
+typedef struct {
+ uint16_t hw_code;
+ uint16_t hw_subcode;
+ uint16_t flash_manufacturer_id;
+ uint16_t flash_id1;
+ uint16_t flash_id2;
+ uint32_t flash_base_addr;
+ uint32_t flash_size;
+} hdl_da_report_t;
+
+typedef struct {
+ hdl_init_cb format_init_cb;
+ void *format_init_cb_arg;
+ hdl_progress_cb format_progress_cb;
+ void *format_progress_cb_arg;
+ uint32_t format_addr;
+ uint32_t format_size;
+} hdl_format_arg_t;
+
+typedef struct _hdl_image_t {
+ uint32_t image_host_flash_addr; // Or image_ram_pointer, Or image_file if your host have file system
+ uint32_t image_slave_flash_addr;
+ uint32_t image_len;
+ char *image_name;
+ bool image_is_bootloader;
+ struct _hdl_image_t *next;
+} hdl_image_t;
+
+typedef struct {
+ hdl_init_cb download_init_cb;
+ void *download_init_cb_arg;
+ hdl_download_cb download_cb;
+ void *download_cb_arg;
+ hdl_image_t *download_images;
+} hdl_download_arg_t;
+
+typedef struct {
+ hdl_init_cb readback_init_cb;
+ void *readback_init_cb_arg;
+ hdl_readback_cb readback_cb;
+ void *readback_cb_arg;
+ uint32_t readback_flash_addr;
+ uint32_t readback_total_len;
+} hdl_readback_arg_t;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_DATA_H__
+
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_DEBUG_H__
+#define __HDL_DEBUG_H__
+
+#include "hdl_config.h"
+#include <android/log.h>
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#define DEV_LOG_TAG "ag3335m"
+
+// ToDo Porting: Please use your platform API to implement it.
+// Platform Log API
+#ifdef HDL_DEBUG
+#define HDL_LOGI(...) __android_log_print(ANDROID_LOG_INFO,DEV_LOG_TAG,__VA_ARGS__)
+#define HDL_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,DEV_LOG_TAG,__VA_ARGS__)
+#define HDL_LOGW(...) __android_log_print(ANDROID_LOG_WARN,DEV_LOG_TAG,__VA_ARGS__)
+#define HDL_LOGE(...) __android_log_print(ANDROID_LOG_ERROR,DEV_LOG_TAG,__VA_ARGS__)
+#else
+#define HDL_LOGI(...)
+#define HDL_LOGD(...)
+#define HDL_LOGW(...)
+#define HDL_LOGE(...)
+#endif
+
+#define HDL_SUCCESS_LOG(X) HDL_LOGI("%s %s", X, ((success) ? "success" : "fail"))
+
+/*
+#ifndef HDL_Assert
+#define HDL_Assert(X) \
+ do \
+ { \
+ if(!(X)) \
+ { \
+ HDL_LOGE("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); \
+ HDL_LOGE("HDL_Assert Fail: %s", #X); \
+ HDL_LOGE("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); \
+ vTaskDelay(1000); \
+ while(1) {} \
+ } \
+ } while(0)
+#endif
+*/
+
+#ifndef HDL_Require_Noerr_Action
+#define HDL_Require_Noerr_Action(X, GOTO_LABEL, Fun) \
+ do { \
+ if(!(X)) { \
+ { HDL_LOGI("%s fail", Fun); } \
+ goto GOTO_LABEL; \
+ } else { \
+ { HDL_LOGI("%s success", Fun); } \
+ } \
+ } while(0)
+#endif
+
+#ifndef HDL_Require_Noerr
+#define HDL_Require_Noerr(X, GOTO_LABEL) \
+ do { \
+ if(!(X)) { \
+ goto GOTO_LABEL; \
+ } \
+ } while(0)
+#endif
+
+
+#ifndef HDL_MAIN_LOG
+#define HDL_MAIN_LOG(fmt,arg...) \
+ do \
+ { \
+ HDL_LOGI("##################################################"); \
+ HDL_LOGI(fmt, ##arg); \
+ HDL_LOGI("##################################################"); \
+ } while(0)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_DEMO_H__
+#define __HDL_DEMO_H__
+
+#include "hdl_api.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+void hdl_host_dl_demo();
+
+void hdl_main_entry();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_DEMO_H__
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_FLASH_API_H__
+#define __HDL_FLASH_API_H__
+
+#include "hdl_debug.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// ToDo Porting: Please use your platform API to implement them.
+// Host Flash API
+bool hdl_flash_init();
+bool hdl_flash_read(uint32_t start_address, uint8_t *buffer, uint32_t length);
+bool hdl_flash_deinit();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_FLASH_API_H__
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_I2C_H__
+#define __HDL_I2C_H__
+
+#include "hdl_debug.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// ToDo Porting: Please use your platform API to implement them.
+// I2C API
+bool hdl_i2c_master_init();
+bool hdl_i2c_master_deinit();
+
+uint8_t hdl_i2c_master_get_byte();
+bool hdl_i2c_master_get_byte_status(uint8_t *data);
+uint32_t hdl_i2c_master_get_byte_buffer(uint8_t *buf, uint32_t length);
+
+void hdl_i2c_master_put_byte(uint8_t data);
+uint32_t hdl_i2c_master_put_byte_buffer(uint8_t *buf, uint32_t length);
+void hdl_i2c_master_put_byte_complete(uint8_t data);
+
+uint16_t hdl_i2c_master_get_data16();
+void hdl_i2c_master_put_data16(uint16_t data);
+uint32_t hdl_i2c_master_get_data32();
+void hdl_i2c_master_put_data32(uint32_t data);
+
+void hdl_i2c_master_purge_fifo();
+void hdl_i2c_master_set_baudrate(hal_uart_baudrate_t baud_rate);
+
+void hdl_i2c_enable_check_data_valid();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_I2C_H__
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_UTIL_H__
+#define __HDL_UTIL_H__
+
+#include "hdl_debug.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+void sleep_us(unsigned int nusecs);
+// ToDo Porting: Please use your platform API to implement it.
+#define hdl_delay(X) sleep_us(X*1000)
+
+#define HAL_UART_BAUDRATE_921600 B921600
+
+int ag3335m_reset(int enabled);
+
+#ifndef min
+#define min(a, b) (((a) < (b)) ? (a) : (b))
+#endif
+
+#ifndef max
+#define max(a, b) (((a) > (b)) ? (a) : (b))
+#endif
+
+uint16_t hdl_compute_checksum(uint8_t *buf, uint32_t buf_len);
+
+uint32_t hdl_compute_simple_checksum(uint8_t *buf, uint32_t buf_len);
+
+// ToDo Porting: Please use your platform MD5 API to implement it, or ignore it.
+void hdl_md5(const uint8_t *input, size_t len, uint8_t output[16]);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_SPI_H__
+#define __HDL_SPI_H__
+
+#include "hdl_debug.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// ToDo Porting: Please use your platform API to implement them.
+// I2C API
+bool hdl_spi_master_init();
+bool hdl_spi_master_deinit();
+
+uint8_t hdl_spi_master_get_byte();
+bool hdl_spi_master_get_byte_status(uint8_t *data);
+uint32_t hdl_spi_master_get_byte_buffer(uint8_t *buf, uint32_t length);
+
+void hdl_spi_master_put_byte(uint8_t data);
+uint32_t hdl_spi_master_put_byte_buffer(uint8_t *buf, uint32_t length);
+void hdl_spi_master_put_byte_complete(uint8_t data);
+
+uint16_t hdl_spi_master_get_data16();
+void hdl_spi_master_put_data16(uint16_t data);
+uint32_t hdl_spi_master_get_data32();
+void hdl_spi_master_put_data32(uint32_t data);
+
+void hdl_spi_master_purge_fifo();
+void hdl_spi_master_set_baudrate(hal_uart_baudrate_t baud_rate);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_SPI_H__
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#ifndef __HDL_UART_H__
+#define __HDL_UART_H__
+
+#include "hdl_debug.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// ToDo Porting: Please use your platform API to implement them.
+// UART API
+bool hdl_uart_init();
+bool hdl_uart_deinit();
+
+uint8_t hdl_uart_get_byte();
+bool hdl_uart_get_byte_status(uint8_t *data);
+uint32_t hdl_uart_get_byte_buffer(uint8_t *buf, uint32_t length);
+
+void hdl_uart_put_byte(uint8_t data);
+uint32_t hdl_uart_put_byte_buffer(uint8_t *buf, uint32_t length);
+void hdl_uart_put_byte_complete(uint8_t data);
+
+uint16_t hdl_uart_get_data16();
+void hdl_uart_put_data16(uint16_t data);
+uint32_t hdl_uart_get_data32();
+void hdl_uart_put_data32(uint32_t data);
+
+void hdl_uart_purge_fifo();
+void hdl_uart_set_baudrate(hal_uart_baudrate_t baud_rate);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__HDL_UART_H__
--- /dev/null
+//
+// Created by incar on 2020-12-18.
+//
+
+#ifndef AG3335M_DOWNLOAD_DEMO_MD5_H
+#define AG3335M_DOWNLOAD_DEMO_MD5_H
+/* MD5.H - header file for MD5C.C
+ */
+
+/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+rights reserved.
+License to copy and use this software is granted provided that it
+is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+Algorithm" in all material mentioning or referencing this software
+or this function.
+License is also granted to make and use derivative works provided
+that such works are identified as "derived from the RSA Data
+Security, Inc. MD5 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work.
+RSA Data Security, Inc. makes no representations concerning either
+the merchantability of this software or the suitability of this
+software for any particular purpose. It is provided "as is"
+without express or implied warranty of any kind.
+These notices must be retained in any copies of any part of this
+documentation and/or software.
+ */
+
+/* POINTER defines a generic pointer type */
+typedef unsigned char *POINTER;
+
+/* UINT2 defines a two byte word */
+typedef unsigned short int UINT2;
+
+/* UINT4 defines a four byte word */
+typedef unsigned long int UINT4;
+
+/* PROTO_LIST is defined depending on how PROTOTYPES is defined above.
+If using PROTOTYPES, then PROTO_LIST returns the list, otherwise it
+ returns an empty list.
+ */
+
+/* MD5 context. */
+typedef struct tagMD5_CTX{
+ UINT4 state[4]; /* state (ABCD) */
+ UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */
+ unsigned char buffer[64]; /* input buffer */
+} MD5_CTX;
+#ifdef __cplusplus
+extern "C" {
+#endif
+void MD5Init (MD5_CTX *context);
+void MD5Update (MD5_CTX *context,unsigned char *input,unsigned int inputLen);
+void MD5Final (unsigned char digest[16], MD5_CTX *context);
+
+static void MD5Transform (UINT4 state[4], unsigned char block[64]);
+static void Encode (unsigned char *output, UINT4 *input, unsigned int len);
+static void Decode (UINT4 *output, unsigned char *input, unsigned int len);
+static void MD5_memcpy (POINTER output, POINTER input, unsigned int len);
+static void MD5_memset (POINTER output, int value, unsigned int len);
+
+#ifdef __cplusplus
+}
+#endif
+#endif //AG3335M_DOWNLOAD_DEMO_MD5_H
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_api.h"
+
+#define HDL_HW_CODE_REG 0x80000008
+#define HDL_HW_SUBCODE_REG 0x8000000C
+
+#ifdef PSRAM_DOWNLOAD
+bool hdl_connect(const hdl_da_info_t *da_info, const hdl_connect_arg_t *connect_arg)
+{
+ if (da_info == NULL || connect_arg == NULL) {
+ HDL_LOGE("hdl_connect fail, invalid parameter");
+ return FALSE;
+ }
+
+ // Init Channel & HandShake with Chip BROM via Brom_StartCMD
+ bool success = hdl_channel_init();
+ HDL_Require_Noerr_Action(success, exit, "hdl_channel_init");
+ hdl_brom_start();
+
+ // Read Chip HW_Code/SubCode
+ uint16_t hw_code = 0;
+ uint16_t hw_subcode = 0;
+ hdl_brom_read16(HDL_HW_CODE_REG, &hw_code);
+ hdl_brom_read16(HDL_HW_SUBCODE_REG, &hw_subcode);
+ HDL_LOGI("hdl_connect, hw_code 0x%04X 0x%04X", hw_code, hw_subcode);
+
+ // Brom Disable WDT
+ success = hdl_brom_disable_wdt();
+ HDL_Require_Noerr_Action(success, exit, "hdl_brom_disable_wdt");
+
+ // Brom Send DA
+ success = hdl_brom_send_da(connect_arg, da_info->da_flash_addr, da_info->da_run_addr, da_info->da_len);
+ HDL_Require_Noerr_Action(success, exit, "hdl_brom_send_da");
+
+ // Brom Jump to DA
+ success = hdl_brom_jump_da(da_info->da_run_addr);
+ HDL_Require_Noerr_Action(success, exit, "hdl_brom_jump_da");
+
+ // DA Sync
+ success = hdl_sync_with_da(connect_arg->conn_enable_log);
+
+exit:
+ return success;
+}
+#else
+bool hdl_connect(const hdl_da_info_t *da_info, const hdl_connect_arg_t *connect_arg, hdl_da_report_t *da_report)
+{
+ if (da_info == NULL || connect_arg == NULL || da_report == NULL) {
+ HDL_LOGE("hdl_connect fail, invalid parameter");
+ return FALSE;
+ }
+
+ // Init Channel & HandShake with Chip BROM via Brom_StartCMD
+ bool success = hdl_channel_init();
+ HDL_Require_Noerr_Action(success, exit, "hdl_channel_init");
+ hdl_brom_start();
+
+ // Read Chip HW_Code/SubCode
+ uint16_t hw_code = 0;
+ uint16_t hw_subcode = 0;
+ hdl_brom_read16(HDL_HW_CODE_REG, &hw_code);
+ hdl_brom_read16(HDL_HW_SUBCODE_REG, &hw_subcode);
+ HDL_LOGI("hdl_connect, hw_code 0x%04X 0x%04X", hw_code, hw_subcode);
+ da_report->hw_code = hw_code;
+ da_report->hw_subcode = hw_subcode;
+
+ // Brom Disable WDT
+ success = hdl_brom_disable_wdt();
+ HDL_Require_Noerr_Action(success, exit, "hdl_brom_disable_wdt");
+
+ // Brom Send DA
+ success = hdl_brom_send_da(connect_arg, da_info->da_flash_addr, da_info->da_run_addr, da_info->da_len);
+ HDL_Require_Noerr_Action(success, exit, "hdl_brom_send_da");
+
+ // Brom Jump to DA
+ success = hdl_brom_jump_da(da_info->da_run_addr);
+ HDL_Require_Noerr_Action(success, exit, "hdl_brom_jump_da");
+
+ // DA Sync
+ success = hdl_sync_with_da(connect_arg->conn_enable_log, da_report);
+ HDL_MAIN_LOG("DA_Report HW_Code=0x%04X-0x%04X, Flash ID=0x%04X 0x%04X 0x%04X, Flash Base Addr=0x%08X, Flash Size=0x%08X",
+ da_report->hw_code, da_report->hw_subcode, da_report->flash_manufacturer_id,
+ da_report->flash_id1, da_report->flash_id2, da_report->flash_base_addr,
+ da_report->flash_size);
+
+exit:
+ return success;
+}
+#endif
+
+#ifndef PSRAM_DOWNLOAD
+bool hdl_format(const hdl_format_arg_t *format_arg)
+{
+ if (format_arg == NULL || format_arg->format_size == 0 || format_arg->format_addr < 0x08000000) {
+ HDL_LOGE("hdl_format fail, invalid parameter");
+ return FALSE;
+ }
+ HDL_LOGI("hdl_format Addr=0x%08X Size=0x%08X", format_arg->format_addr, format_arg->format_size);
+ return hdl_da_format(format_arg);
+}
+#endif
+
+bool hdl_download(const hdl_download_arg_t *download_arg)
+{
+ bool success = FALSE;
+ // Check Empty Parameter
+ if (download_arg == NULL || download_arg->download_images == NULL) {
+ HDL_LOGE("hdl_download fail, invalid parameter");
+ return FALSE;
+ }
+
+ // Check Image Flash_Addr & Size
+ hdl_image_t *image = download_arg->download_images;
+ while (image != NULL) {
+ HDL_LOGI("Download Image (%s) BL=%d 0x%08X->0x%08X %d",
+ image->image_name, image->image_is_bootloader, image->image_host_flash_addr,
+ image->image_slave_flash_addr, image->image_len);
+ // image slave_flash_addr and image_len
+ if (image->image_slave_flash_addr == 0 || image->image_len == 0) {
+ HDL_LOGE("hdl_download fail, Image (%s) invalid flash_addr/len", image->image_name);
+ return FALSE;
+ }
+ // image slave_flash_addr must be 4K align
+ if (image->image_slave_flash_addr % 0x1000 != 0) {
+ HDL_LOGE("hdl_download fail, Image (%s) Slave_Flash_Addr not 4K Align", image->image_name);
+ return FALSE;
+ }
+ // image slave_flash_addr + size must < next_image slave_flash_addr
+ hdl_image_t *next = image->next;
+ if (next != NULL && image->image_slave_flash_addr + image->image_len >= next->image_slave_flash_addr) {
+ HDL_LOGE("hdl_download fail, Image (%s) Size is overlap next Image (%s)",
+ image->image_name, next->image_name);
+ return FALSE;
+ }
+ image = image->next;
+ }
+
+ // Download init callback
+ if (download_arg->download_init_cb != NULL) {
+ download_arg->download_init_cb(download_arg->download_init_cb_arg);
+ }
+
+ // Download Every Image
+ image = download_arg->download_images;
+ while (image != NULL) {
+ HDL_LOGI("Start Download Image (%s)", image->image_name);
+ success = hdl_da_download(image, download_arg->download_cb, download_arg->download_cb_arg);
+ HDL_Require_Noerr_Action(success, exit, "hdl_da_download");
+ image = image->next;
+ }
+
+exit:
+ return success;
+}
+
+#ifndef PSRAM_DOWNLOAD
+bool hdl_readback(const hdl_readback_arg_t *readback_arg)
+{
+ // Check Empty Parameter
+ if (readback_arg == NULL || readback_arg->readback_flash_addr < 0x08000000
+ || readback_arg->readback_total_len == 0) {
+ HDL_LOGE("hdl_readback fail, invalid parameter");
+ return FALSE;
+ }
+ return hdl_da_readback(readback_arg);
+}
+
+bool hdl_disconnect(HDL_DISCONNECT_TYPE disconnect_type)
+{
+ bool success = FALSE;
+ HDL_LOGI("hdl_disconnect disconnect_type=%d", disconnect_type);
+ if (disconnect_type == DISCONNECT_RESET) {
+ success = hdl_da_enable_wdt(5);
+ } else {
+ bool power_off = (disconnect_type == DISCONNECT_POWER_OFF);
+ success = hdl_da_finish(power_off);
+ }
+ HDL_COM_Deinit();
+ return success;
+}
+#endif
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_brom_base.h"
+#include "../inc/hdl_ports/hdl_os_util.h"
+#include "../inc/hdl_debug.h"
+#include "../inc/hdl_channel.h"
+
+extern uint8_t g_hdl_data_buf[];
+
+bool g_brom_task_stop = FALSE;
+const unsigned char HDL_START_CMD[4] = {0xA0, 0x0A, 0x50, 0x05};
+const unsigned char HDL_BROM_RSP_CMD[4] = {0x5F, 0xF5, 0xAF, 0xFA};
+
+static void brom_start_task(void *pvParameters)
+{
+ while (!g_brom_task_stop) {
+ HDL_COM_PutByte(HDL_START_CMD[0]);
+ HDL_LOGI("brom_start_task put_char 0xA0");
+ hdl_delay(50);
+ }
+ hdl_delete_task(NULL);
+}
+
+static void brom_write8_echo(uint8_t data)
+{
+ HDL_LOGI("brom_write8_echo 0x%02X", data);
+ HDL_COM_PutByte(data);
+ uint8_t rx_data = HDL_COM_GetByte();
+ HDL_LOGI("brom_write8_echo 0x%02X - 0x%02X", data, rx_data);
+}
+
+static void brom_write16_echo(uint16_t data)
+{
+ HDL_LOGI("brom_write16_echo 0x%04X", data);
+ HDL_COM_PutData16(data);
+ uint16_t rx_data = HDL_COM_GetData16();
+ HDL_LOGI("brom_write16_echo 0x%04X - 0x%04X", data, rx_data);
+}
+
+static void brom_write32_echo(uint32_t data)
+{
+ HDL_LOGI("brom_write32_echo 0x%08X", data);
+ HDL_COM_PutData32(data);
+ uint32_t rx_data = HDL_COM_GetData32();
+ HDL_LOGI("brom_write32_echo 0x%08X - 0x%08X", data, rx_data);
+}
+
+bool hdl_brom_start()
+{
+ char rx_data = 0;
+brom_start_retry:
+
+#if defined (HDL_VIA_UART)
+ // ToDo Note: For our UART, need to create asnyc_task to send START_CMD[0]=0xA0
+ // continuously in UART Polling mode.
+ // For your UART, you could try to use UART DMA mode, or create task like us.
+ g_brom_task_stop = FALSE;
+ hdl_create_brom_start_task(brom_start_task);
+ while (1) {
+ hdl_delay(20);
+ rx_data = HDL_COM_GetByte();
+ if (rx_data == HDL_BROM_RSP_CMD[0]) {
+ g_brom_task_stop = TRUE;
+ HDL_LOGI("hdl_brom_start 0xA0<->0x5F");
+ break;
+ }
+ }
+#elif defined (HDL_VIA_SPI) || defined (HDL_VIA_I2C)
+ HDL_COM_PutByte(HDL_START_CMD[0]);
+ rx_data = HDL_COM_GetByte();
+ if (rx_data == HDL_BROM_RSP_CMD[0]) {
+ HDL_LOGI("hdl_brom_start 0xA0<->0x5F");
+ } else {
+ HDL_LOGE("hdl_brom_start 0x0A ->(error) 0x%02X, retry", rx_data);
+ #if defined (HDL_VIA_SPI)
+ hdl_delay(2000);
+ #else
+ hdl_delay(50);
+ #endif
+ goto brom_start_retry;
+ }
+#endif
+
+ #if defined (HDL_VIA_I2C)
+ hdl_i2c_enable_check_data_valid();
+ #endif
+
+ HDL_COM_PutByte(HDL_START_CMD[1]);
+ rx_data = HDL_COM_GetByte();
+ if (rx_data == HDL_BROM_RSP_CMD[1]) {
+ HDL_LOGI("hdl_brom_start 0x0A<->0xF5");
+ } else {
+ HDL_LOGE("hdl_brom_start 0x0A ->(error) 0x%02X, retry", rx_data);
+ hdl_delay(2000);
+ goto brom_start_retry;
+ }
+
+ HDL_COM_PutByte(HDL_START_CMD[2]);
+ rx_data = HDL_COM_GetByte();
+ if (rx_data == HDL_BROM_RSP_CMD[2]) {
+ HDL_LOGI("hdl_brom_start 0x50<->0xAF");
+ } else {
+ HDL_LOGE("hdl_brom_start 0x50 ->(error) 0x%02X, retry", rx_data);
+ hdl_delay(2000);
+ goto brom_start_retry;
+ }
+
+ HDL_COM_PutByte(HDL_START_CMD[3]);
+ rx_data = HDL_COM_GetByte();
+ if (rx_data == HDL_BROM_RSP_CMD[3]) {
+ HDL_LOGI("hdl_brom_start 0x05<->0xFA");
+ } else {
+ HDL_LOGE("hdl_brom_start 0x05 ->(error) 0x%02X, retry", rx_data);
+ hdl_delay(2000);
+ goto brom_start_retry;
+ }
+
+ HDL_LOGI("hdl_brom_start pass");
+ return TRUE;
+}
+
+bool hdl_brom_disable_wdt()
+{
+ return hdl_brom_write16(HDL_WDT_REG, HDL_WDT_VAL);
+}
+
+bool hdl_brom_read16(uint32_t addr, uint16_t *data)
+{
+ bool success = FALSE;
+ brom_write8_echo(BROM_CMD_READ16);
+ brom_write32_echo(addr);
+ brom_write32_echo(1);
+
+ uint16_t status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_read16");
+ *data = HDL_COM_GetData16();
+ status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_read16");
+ success = TRUE;
+
+exit:
+ return success;
+}
+
+bool hdl_brom_read32(uint32_t addr, uint32_t *data)
+{
+ bool success = FALSE;
+ brom_write8_echo(BROM_CMD_READ32);
+ brom_write32_echo(addr);
+ brom_write32_echo(1);
+
+ uint16_t status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_read32");
+ *data = HDL_COM_GetData16();
+ status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_read32");
+ success = TRUE;
+
+exit:
+ return success;
+}
+
+bool hdl_brom_write16(uint32_t addr, uint16_t data)
+{
+ bool success = FALSE;
+ brom_write8_echo(BROM_CMD_WRITE16);
+ brom_write32_echo(addr);
+ brom_write32_echo(1);
+
+ uint16_t status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_write16");
+ brom_write16_echo(data);
+ status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_write16");
+ success = TRUE;
+
+exit:
+ return success;
+}
+
+bool hdl_brom_write32(uint32_t addr, uint32_t data)
+{
+ bool success = FALSE;
+ brom_write8_echo(BROM_CMD_WRITE32);
+ brom_write32_echo(addr);
+ brom_write32_echo(1);
+
+ uint16_t status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_write32");
+ brom_write32_echo(data);
+ status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_write32");
+ success = TRUE;
+
+exit:
+ return success;
+}
+
+bool hdl_brom_send_da(const hdl_connect_arg_t *connect_arg,
+ uint32_t da_flash_pos, uint32_t da_start_addr, uint32_t da_len)
+{
+ bool success = FALSE;
+ bool ret = hdl_flash_init();
+ HDL_Require_Noerr_Action(ret, exit, "hdl_flash_init");
+ HDL_LOGI("hdl_brom_send_da 0x%08X 0x%08X %d", da_flash_pos, da_start_addr, da_len);
+
+ // DA Init Callback
+ if (connect_arg != NULL && connect_arg->conn_da_init_cb != NULL) {
+ connect_arg->conn_da_init_cb(connect_arg->conn_da_init_cb_arg);
+ }
+
+ brom_write8_echo(BROM_CMD_SEND_DA);
+ brom_write32_echo(da_start_addr);
+ brom_write32_echo(da_len);
+ brom_write32_echo(0); // data_sig_len = 0
+ uint16_t status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_send_da");
+
+ const uint32_t packet_len = 1024;
+ uint32_t total_sent_len = 0;
+ uint32_t local_check_sum = 0;
+ while (total_sent_len < da_len) {
+ unsigned int to_send_len = min(packet_len, da_len - total_sent_len);
+ ret = hdl_flash_read(da_flash_pos + total_sent_len, g_hdl_data_buf, to_send_len);
+ if (ret) {
+ uint32_t sent_len = HDL_COM_PutByte_Buffer(g_hdl_data_buf, to_send_len);
+ total_sent_len += sent_len;
+ HDL_LOGI("hdl_brom_send_da, %d sent %d", to_send_len, sent_len);
+
+ // DA Send Callback
+ if (connect_arg != NULL && connect_arg->conn_da_send_cb != NULL) {
+ connect_arg->conn_da_send_cb(connect_arg->conn_da_send_cb_arg, total_sent_len, da_len);
+ }
+
+ if (sent_len > 0) {
+ local_check_sum ^= hdl_compute_checksum(g_hdl_data_buf, sent_len);
+ }
+ } else {
+ HDL_LOGI("hdl_brom_send_da, flash read fail %d", ret);
+ }
+ }
+ uint16_t brom_check_sum = HDL_COM_GetData16();
+ HDL_LOGI("hdl_brom_send_da, local_check_sum=%d brom_check_sum=%d", local_check_sum, brom_check_sum);
+ HDL_Require_Noerr_Action(local_check_sum == brom_check_sum, exit, "hdl_brom_send_da, checksum");
+ status = HDL_COM_GetData16();
+ HDL_Require_Noerr_Action(status < BROM_ERROR, exit, "hdl_brom_send_da");
+ success = TRUE;
+
+exit:
+ hdl_flash_deinit();
+ return success;
+}
+
+bool hdl_brom_jump_da(uint32_t addr)
+{
+ HDL_LOGI("hdl_brom_jump_da 0x%08X", addr);
+ brom_write8_echo(BROM_CMD_JUMP_DA);
+ brom_write32_echo(addr);
+ uint16_t status = HDL_COM_GetData16();
+ return (status < BROM_ERROR);
+}
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_channel.h"
+
+uint8_t g_hdl_data_buf[4096] = {0};
+
+g_hdl_channel_t g_hdl_channel;
+
+HDL_CHANNEL_TYPE g_hdl_channel_type = CHANNEL_TYPE_UART;
+
+bool hdl_channel_init(void)
+{
+ bool success = TRUE;
+#ifdef HDL_VIA_UART
+ g_hdl_channel_type = CHANNEL_TYPE_UART;
+ g_hdl_channel.m_com_init = hdl_uart_init;
+ g_hdl_channel.m_com_get_byte = hdl_uart_get_byte;
+ g_hdl_channel.m_com_get_byte_status = hdl_uart_get_byte_status;
+ g_hdl_channel.m_com_get_byte_buffer = hdl_uart_get_byte_buffer;
+ g_hdl_channel.m_com_put_byte = hdl_uart_put_byte;
+ g_hdl_channel.m_com_put_byte_buffer = hdl_uart_put_byte_buffer;
+ g_hdl_channel.m_com_put_byte_complete = hdl_uart_put_byte_complete;
+ g_hdl_channel.m_com_get_data16 = hdl_uart_get_data16;
+ g_hdl_channel.m_com_put_data16 = hdl_uart_put_data16;
+ g_hdl_channel.m_com_get_data32 = hdl_uart_get_data32;
+ g_hdl_channel.m_com_put_data32 = hdl_uart_put_data32;
+ g_hdl_channel.m_com_purge_fifo = hdl_uart_purge_fifo;
+ g_hdl_channel.m_com_set_baudrate = hdl_uart_set_baudrate;
+ g_hdl_channel.m_com_deinit = hdl_uart_deinit;
+
+#elif defined(HDL_VIA_SPI)
+ g_hdl_channel_type = CHANNEL_TYPE_SPI;
+ g_hdl_channel.m_com_init = hdl_spi_master_init;
+ g_hdl_channel.m_com_get_byte = hdl_spi_master_get_byte;
+ g_hdl_channel.m_com_get_byte_status = hdl_spi_master_get_byte_status;
+ g_hdl_channel.m_com_get_byte_buffer = hdl_spi_master_get_byte_buffer;
+ g_hdl_channel.m_com_put_byte = hdl_spi_master_put_byte;
+ g_hdl_channel.m_com_put_byte_buffer = hdl_spi_master_put_byte_buffer;
+ g_hdl_channel.m_com_put_byte_complete = hdl_spi_master_put_byte_complete;
+ g_hdl_channel.m_com_get_data16 = hdl_spi_master_get_data16;
+ g_hdl_channel.m_com_put_data16 = hdl_spi_master_put_data16;
+ g_hdl_channel.m_com_get_data32 = hdl_spi_master_get_data32;
+ g_hdl_channel.m_com_put_data32 = hdl_spi_master_put_data32;
+ g_hdl_channel.m_com_purge_fifo = hdl_spi_master_purge_fifo;
+ g_hdl_channel.m_com_set_baudrate = hdl_spi_master_set_baudrate;
+ g_hdl_channel.m_com_deinit = hdl_spi_master_deinit;
+
+#elif defined(HDL_VIA_I2C)
+ g_hdl_channel_type = CHANNEL_TYPE_I2C;
+ g_hdl_channel.m_com_init = hdl_i2c_master_init;
+ g_hdl_channel.m_com_get_byte = hdl_i2c_master_get_byte;
+ g_hdl_channel.m_com_get_byte_status = hdl_i2c_master_get_byte_status;
+ g_hdl_channel.m_com_get_byte_buffer = hdl_i2c_master_get_byte_buffer;
+ g_hdl_channel.m_com_put_byte = hdl_i2c_master_put_byte;
+ g_hdl_channel.m_com_put_byte_buffer = hdl_i2c_master_put_byte_buffer;
+ g_hdl_channel.m_com_put_byte_complete = hdl_i2c_master_put_byte_complete;
+ g_hdl_channel.m_com_get_data16 = hdl_i2c_master_get_data16;
+ g_hdl_channel.m_com_put_data16 = hdl_i2c_master_put_data16;
+ g_hdl_channel.m_com_get_data32 = hdl_i2c_master_get_data32;
+ g_hdl_channel.m_com_put_data32 = hdl_i2c_master_put_data32;
+ g_hdl_channel.m_com_purge_fifo = hdl_i2c_master_purge_fifo;
+ g_hdl_channel.m_com_set_baudrate = hdl_i2c_master_set_baudrate;
+ g_hdl_channel.m_com_deinit = hdl_i2c_master_deinit;
+
+#else
+#error "No Define HDL_VIA_UART/SPI/I2C"
+#endif
+
+ HDL_LOGI("hdl_channel_type=%d", g_hdl_channel_type);
+ success = HDL_COM_Init();
+ return success;
+}
+
+uint8_t hdl_get_channel_type()
+{
+ return g_hdl_channel_type;
+}
+
+
+/*
+void data_channel_put_byte(uint8 data)
+{
+ if (g_slave_channel == SLAVE_CHANNEL_UART) {
+ UART1_PutData32(CHANNEL_MARKER);
+ UART1_PutData32(DATA_CHANNEL);
+ UART1_PutByte(data);
+ } else if (g_slave_channel == SLAVE_CHANNEL_SPI) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_I2C) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_USB) {
+
+ } else {
+
+ }
+}
+
+void data_channel_put_byte_buffer(uint32* buf, uint32 length)
+{
+ if (g_slave_channel == SLAVE_CHANNEL_UART) {
+ UART1_PutData32(CHANNEL_MARKER);
+ UART1_PutData32(DATA_CHANNEL);
+ UART1_PutByte_Buffer(buf, length);
+ } else if (g_slave_channel == SLAVE_CHANNEL_SPI) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_I2C) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_USB) {
+
+ } else {
+
+ }
+}
+
+void data_channel_put_byte_complete(uint8 data)
+{
+ if (g_slave_channel == SLAVE_CHANNEL_UART) {
+ UART1_PutData32(CHANNEL_MARKER);
+ UART1_PutData32(DATA_CHANNEL);
+ UART1_PutByte_Complete(data);
+ } else if (g_slave_channel == SLAVE_CHANNEL_SPI) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_I2C) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_USB) {
+
+ } else {
+
+ }
+}
+
+void data_channel_put_data16(uint16 data)
+{
+ if (g_slave_channel == SLAVE_CHANNEL_UART) {
+ UART1_PutData32(CHANNEL_MARKER);
+ UART1_PutData32(DATA_CHANNEL);
+ UART1_PutData16(data);
+ } else if (g_slave_channel == SLAVE_CHANNEL_SPI) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_I2C) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_USB) {
+
+ } else {
+
+ }
+}
+
+void data_channel_put_data32(uint32 data)
+{
+ if (g_slave_channel == SLAVE_CHANNEL_UART) {
+ UART1_PutData32(CHANNEL_MARKER);
+ UART1_PutData32(DATA_CHANNEL);
+ UART1_PutData32(data);
+ } else if (g_slave_channel == SLAVE_CHANNEL_SPI) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_I2C) {
+
+ } else if (g_slave_channel == SLAVE_CHANNEL_USB) {
+
+ } else {
+
+ }
+}
+
+void logging_channel_init(uint8 enable)
+{
+ if (TRUE == enable)
+ {
+ g_com_driver.m_com_put_byte = data_channel_put_byte;
+ g_com_driver.m_com_put_byte_buffer = data_channel_put_byte_buffer;
+ g_com_driver.m_com_put_byte_complete = data_channel_put_byte_complete;
+ g_com_driver.m_com_put_data16 = data_channel_put_data16;
+ g_com_driver.m_com_put_data32 = data_channel_put_data32;
+ }
+}
+
+void logging_channel_put_byte_buffer(uint32* buf, uint32 length)
+{_
+ if (channel_is_usb_download_mode())
+ {
+ USB2COM_PutData32(CHANNEL_MARKER);
+ USB2COM_PutData32(LOGGING_CHANNEL);
+ USB2COM_PutData32(length);
+ USB2COM_PutByte_Buffer(buf, length);
+ }
+ else
+ {
+ UART1_PutData32(CHANNEL_MARKER);
+ UART1_PutData32(LOGGING_CHANNEL);
+ UART1_PutData32(length);
+ UART1_PutByte_Buffer(buf, length);
+ }
+}
+*/
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_da_cmd.h"
+
+extern uint8_t g_hdl_data_buf[];
+
+// DA HandShake
+const char HDL_DA_SYNC_CMD[4] = {0xC0, 0x0C, 0x3F, 0xF3};
+// [3F]->[C0] [F3]->[0C] [C0]->[3F] [0C]->[F3]
+static bool hdl_da_handshake()
+{
+ bool success = FALSE;
+ HDL_LOGI("hdl_da_handshake start");
+
+ for (int i = 0; i < 4; i++) {
+ uint8_t da_rx_data = HDL_COM_GetByte();
+ if (da_rx_data == HDL_DA_SYNC_CMD[i]) {
+ HDL_COM_PutByte(~da_rx_data);
+ if (i == 3) {
+ da_rx_data = HDL_COM_GetByte();
+ if (da_rx_data == DA_ACK) {
+ success = TRUE;
+ }
+ }
+ } else {
+ break;
+ }
+ }
+ return success;
+}
+
+static bool hdl_da_check_cmd_arg(uint32_t *error_status)
+{
+ uint8_t da_rx_data = HDL_COM_GetByte();
+ if (da_rx_data == DA_ACK) {
+ return TRUE;
+ } else if (da_rx_data == DA_NACK) {
+ *error_status = HDL_COM_GetData32();
+ return FALSE;
+ } else {
+ return FALSE;
+ }
+}
+
+static bool hdl_wirte_packet(uint8_t *packet_buf, uint32_t packet_len, uint32_t checksum)
+{
+ if (packet_buf == NULL || packet_len != DA_SEND_PACKET_LEN) {
+ HDL_LOGE("hdl_wirte_packet fail, invalid parameter");
+ return FALSE;
+ }
+ uint8_t retry_count = 0;
+ while (retry_count < 3) {
+ uint8_t response = 0;
+ uint32_t total_sent_len = 0;
+ while (total_sent_len < packet_len) {
+ total_sent_len += HDL_COM_PutByte_Buffer(packet_buf + total_sent_len, packet_len - total_sent_len);
+ }
+
+ HDL_LOGI("hdl_wirte_packet, host checksum=0x%08X", checksum);
+ HDL_COM_PutData32(checksum);
+
+ // Get checksum_slave from slave
+ //uint32_t checksum_slave = HDL_COM_GetData32();
+ //HDL_LOGI("hdl_wirte_packet, slave checksum=0x%08X", checksum_slave);
+
+ response = HDL_COM_GetByte();
+ HDL_LOGI("hdl_wirte_packet, response=0x%02X", response);
+ if (response == DA_CONT_CHAR) {
+ // hdl_wirte_packet successfully
+ return TRUE;
+ } else if (response == DA_STOP_CHAR) {
+ return FALSE;
+ } else if (response == DA_NACK) {
+ uint32_t ret = HDL_COM_GetData32();
+ HDL_LOGI("hdl_wirte_packet, NACK ret=%d", ret);
+ if (ret == DA_S_UART_RX_BUF_FULL) {
+ uint8_t da_flush_state = HDL_COM_GetByte();
+ while (da_flush_state == DA_FLUSH_CONT) {
+ da_flush_state = HDL_COM_GetByte();
+ }
+ }
+
+ if (ret == DA_S_UART_RX_BUF_FULL
+ || ret == DA_S_UART_GET_DATA_TIMEOUT
+ || ret == DA_S_UART_GET_CHKSUM_LSB_TIMEOUT
+ || ret == DA_S_UART_GET_CHKSUM_MSB_TIMEOUT
+ || ret == DA_S_UART_DATA_CKSUM_ERROR) {
+ if (retry_count < 3) {
+ retry_count++;
+ uint8_t da_retry_state = HDL_COM_GetByte();
+ if (da_retry_state == DA_ACK) {
+ HDL_COM_PutByte(DA_CONT_CHAR);
+ continue;
+ } else {
+ return FALSE;
+ }
+ } else {
+ HDL_COM_PutByte(DA_NACK);
+ return FALSE;
+ }
+ }
+ }
+ }
+
+ return FALSE;
+}
+
+#ifdef PSRAM_DOWNLOAD
+bool hdl_sync_with_da(bool enable_log)
+{
+ // DA HandShake
+ bool success = FALSE;
+ bool da_handshake = hdl_da_handshake();
+ HDL_Require_Noerr_Action(da_handshake, exit, "hdl_da_handshake");
+
+ // DA Init_logging
+ HDL_COM_PutByte((enable_log ? 1 : 0));
+ uint8_t da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "Init_logging");
+
+ // EPP Function - PMU Latch Power
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "DA Latch Power");
+ HDL_COM_PutByte(DA_ACK);
+
+ // EPP Function - Disable long press power key
+ HDL_COM_PutByte(0);
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "DA Disable Long Press Power Key");
+ HDL_COM_PutByte(DA_ACK);
+
+ // EPP Function - Raise MCU Speed
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "DA Raise MCU Speed");
+ HDL_COM_PutByte(DA_ACK);
+
+#if defined (HDL_VIA_UART)
+ // EPP Function - Setup Uart HighBaud
+ hdl_delay(100); // Wait previous DA_ACK to sent (115200)
+
+ //HDL_COM_SetBaudRate(HAL_UART_BAUDRATE_921600);
+ HDL_COM_SetBaudRate(HAL_UART_BAUDRATE_3000000);
+
+ hdl_delay(100); // Wait Device DA Update BaudRate 921600 or 3000000
+
+ for (int i = 0; i < 20; i++) {
+ HDL_COM_PutByte(DA_SYNC_CHAR);
+ da_rx_data = HDL_COM_GetByte();
+ if (da_rx_data == DA_SYNC_CHAR) {
+ HDL_LOGE("DA Setup Uart HighBaud 1 pass");
+ break;
+ } else {
+ hdl_delay(100);
+ HDL_LOGE("DA Setup Uart HighBaud 1 fail, 0x%02X", da_rx_data);
+ }
+ }
+
+ HDL_COM_PutByte(DA_ACK);
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_ACK, exit, "DA Setup Uart HighBaud 2");
+
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "DA Setup Uart HighBaud 3");
+ HDL_COM_PutByte(DA_ACK);
+#endif
+ success = TRUE;
+
+exit:
+ return success;
+}
+#else
+bool hdl_sync_with_da(bool enable_log, hdl_da_report_t *da_report)
+{
+ // DA HandShake
+ bool success = FALSE;
+ bool da_handshake = hdl_da_handshake();
+ HDL_Require_Noerr_Action(da_handshake, exit, "hdl_da_handshake");
+
+ // DA Init_logging
+ HDL_COM_PutByte((enable_log ? 1 : 0));
+ uint8_t da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "Init_logging");
+
+ // EPP Function - PMU Latch Power
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "DA Latch Power");
+ HDL_COM_PutByte(DA_ACK);
+
+ // EPP Function - Disable long press power key
+ HDL_COM_PutByte(0);
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "DA Disable Long Press Power Key");
+ HDL_COM_PutByte(DA_ACK);
+
+ // EPP Function - Raise MCU Speed
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "DA Raise MCU Speed");
+ HDL_COM_PutByte(DA_ACK);
+
+#if defined (HDL_VIA_UART)
+ // EPP Function - Setup Uart HighBaud
+ hdl_delay(100); // Wait previous DA_ACK to sent (115200)
+ HDL_COM_SetBaudRate(HAL_UART_BAUDRATE_921600);
+ hdl_delay(100); // Wait Device DA Update BaudRate 921600
+ for (int i = 0; i < 20; i++) {
+ HDL_COM_PutByte(DA_SYNC_CHAR);
+ da_rx_data = HDL_COM_GetByte();
+ if (da_rx_data == DA_SYNC_CHAR) {
+ HDL_LOGE("DA Setup Uart HighBaud 1 pass");
+ break;
+ } else {
+ hdl_delay(100);
+ HDL_LOGE("DA Setup Uart HighBaud 1 fail, 0x%02X", da_rx_data);
+ }
+ }
+
+ HDL_COM_PutByte(DA_ACK);
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_ACK, exit, "DA Setup Uart HighBaud 2");
+
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_CONT_CHAR, exit, "DA Setup Uart HighBaud 3");
+ HDL_COM_PutByte(DA_ACK);
+#endif
+
+ // DA Mount Flash
+ uint16_t manufacturer_id = HDL_COM_GetData16();
+ uint16_t device_id1 = HDL_COM_GetData16();
+ uint16_t device_id2 = HDL_COM_GetData16();
+ HDL_LOGI("DA Flash ID: 0x%04X 0x%04X 0x%04X", manufacturer_id, device_id1, device_id2);
+ uint32_t status = HDL_COM_GetData32();
+ HDL_Require_Noerr_Action(status == 0, exit, "DA Mount Flash");
+
+ uint32_t base_addr = HDL_COM_GetData32();
+ uint32_t size = HDL_COM_GetData32();
+ HDL_LOGI("DA Flash Base_Addr=0x%08X Size=0x%08X", base_addr, size);
+ da_rx_data = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(da_rx_data == DA_ACK, exit, "DA Mount Flash");
+ HDL_COM_PutByte(DA_ACK);
+
+ // DA Report
+ da_report->flash_manufacturer_id = manufacturer_id;
+ da_report->flash_id1 = device_id1;
+ da_report->flash_id2 = device_id2;
+ da_report->flash_base_addr = base_addr;
+ da_report->flash_size = size;
+ success = TRUE;
+
+exit:
+ return success;
+}
+#endif
+
+bool hdl_da_format(const hdl_format_arg_t *format_arg)
+{
+ bool success = FALSE;
+ uint32_t error_status = 0;
+ HDL_COM_PutByte(DA_FORMAT_CMD);
+ HDL_COM_PutByte(0);
+ HDL_COM_PutData32(format_arg->format_addr);
+ HDL_COM_PutData32(format_arg->format_size);
+
+ // DA Check Format Arg
+ bool da_check_success = hdl_da_check_cmd_arg(&error_status);
+ HDL_Require_Noerr_Action(da_check_success, exit, "DA Format CMD");
+ da_check_success = hdl_da_check_cmd_arg(&error_status);
+ HDL_Require_Noerr_Action(da_check_success, exit, "DA Format Check Flash Base_Addr/Range");
+
+ // DA Format Init Callback
+ if (format_arg != NULL && format_arg->format_init_cb != NULL) {
+ format_arg->format_init_cb(format_arg->format_init_cb_arg);
+ }
+
+ while (1) {
+ uint32_t ret = HDL_COM_GetData32();
+ if (ret == DA_S_DONE) {
+ uint8_t progress = HDL_COM_GetByte();
+ HDL_COM_PutByte(DA_ACK);
+ HDL_LOGI("received S_DONE progress=%d", progress);
+ if (format_arg != NULL && format_arg->format_progress_cb != NULL) {
+ format_arg->format_progress_cb(format_arg->format_progress_cb_arg, 100);
+ }
+ break;
+ } else if (ret == DA_S_IN_PROGRESS) {
+ uint8_t progress = HDL_COM_GetByte();
+ HDL_COM_PutByte(DA_ACK);
+ if (format_arg != NULL && format_arg->format_progress_cb != NULL) {
+ format_arg->format_progress_cb(format_arg->format_progress_cb_arg, progress);
+ }
+ } else {
+ uint32_t erase_addr = HDL_COM_GetData32();
+ uint8_t stop_char = HDL_COM_GetByte();
+ HDL_LOGE("hdl_da_format error=%d erase_addr=0x%08X stop_char=0x%02X",
+ erase_addr, stop_char);
+ goto exit;
+ }
+ }
+
+ uint8_t ack = HDL_COM_GetByte();
+ HDL_Require_Noerr_Action(ack == DA_ACK, exit, "DA Format End-ACK");
+ success = TRUE;
+
+exit:
+ if (error_status != 0) {
+ HDL_LOGE("hdl_da_format error_status=%d", error_status);
+ }
+ return success;
+}
+
+bool hdl_da_download(hdl_image_t *image, hdl_download_cb download_cb, void *download_cb_arg)
+{
+ bool success = FALSE;
+ uint32_t error_status = 0;
+ const uint32_t addr = image->image_slave_flash_addr;
+ // image_len must 4K align
+ const uint32_t image_len = image->image_len;
+ const uint32_t packet_num = ((image_len - 1) / DA_SEND_PACKET_LEN) + 1;
+ const uint32_t image_4k_len = packet_num * DA_SEND_PACKET_LEN;
+ HDL_COM_PutByte(DA_NOR_WRITE_DATA);
+ HDL_COM_PutData32(addr);
+ HDL_COM_PutData32(image_4k_len);
+ HDL_COM_PutData32(DA_SEND_PACKET_LEN);
+
+ // DA Check Download Arg
+ bool da_check_success = hdl_da_check_cmd_arg(&error_status);
+ HDL_Require_Noerr_Action(da_check_success, exit, "DA Download CMD, Check Range");
+
+#ifndef PSRAM_DOWNLOAD
+ da_check_success = hdl_da_check_cmd_arg(&error_status);
+ HDL_Require_Noerr_Action(da_check_success, exit, "DA Download CMD, first block erase");
+#endif
+
+ // Compute & Send Packet
+ uint32_t packet_sent_num = 0;
+ uint8_t *packet_buf = NULL;
+ uint32_t image_checksum = 0;
+ while (packet_sent_num < packet_num) {
+ uint32_t packet_checksum = 0;
+ const bool is_last_packet = (packet_sent_num == (packet_num - 1));
+ const uint32_t start_offset = packet_sent_num * DA_SEND_PACKET_LEN;
+ const uint32_t cur_packet_len = is_last_packet ? (image_len - start_offset) : DA_SEND_PACKET_LEN;
+ HDL_LOGI("hdl_da_download (%s) packet %d/%d %d", image->image_name,
+ (packet_sent_num + 1), packet_num, cur_packet_len);
+
+ bool ret = hdl_flash_read(image->image_host_flash_addr + start_offset,
+ g_hdl_data_buf, cur_packet_len);
+ if (ret) {
+ if (is_last_packet && cur_packet_len < DA_SEND_PACKET_LEN) {
+ // DA Must received whole DA_SEND_PACKET_LEN, so Fill 0xFF to packet_buf
+ uint32_t fill_num = DA_SEND_PACKET_LEN - cur_packet_len;
+ memset(packet_buf + cur_packet_len, 0xFF, fill_num);
+ }
+ packet_buf = g_hdl_data_buf;
+ packet_checksum = hdl_compute_simple_checksum(packet_buf, DA_SEND_PACKET_LEN);
+ image_checksum += packet_checksum;
+
+ bool wirte_packet_success = hdl_wirte_packet(packet_buf, DA_SEND_PACKET_LEN, packet_checksum);
+ HDL_Require_Noerr_Action(wirte_packet_success, exit, "hdl_wirte_packet");
+ // Download Progress callback
+ if (download_cb != NULL) {
+ download_cb(download_cb_arg, image->image_name,
+ start_offset + cur_packet_len, image_len);
+ }
+ } else {
+ HDL_LOGE("hdl_flash_read addr=0x%08X len=0x%08X fail",
+ image->image_host_flash_addr + start_offset, cur_packet_len);
+ continue;
+ }
+
+ packet_sent_num++;
+ }
+
+ // Read ACK & Image CheckSum
+ da_check_success = hdl_da_check_cmd_arg(&error_status);
+ HDL_Require_Noerr_Action(da_check_success, exit, "DA Write Image Packets");
+ // Send image_checksum after DA compute checksum completely
+ HDL_COM_PutData32(image_checksum);
+ uint8_t status = HDL_COM_GetByte();
+ if (status != DA_ACK) {
+ uint32_t checksum_from_device = HDL_COM_GetData32();
+ HDL_LOGE("DA Download Imgae (%s) CheckSum Fail, 0x%08X != 0x%08X",
+ image->image_name, image_checksum, checksum_from_device);
+ return FALSE;
+ }
+
+#ifndef PSRAM_DOWNLOAD
+ // For Bootloader(ACC)
+ HDL_COM_PutByte((image->image_is_bootloader ? DA_ACK : DA_NACK));
+ da_check_success = hdl_da_check_cmd_arg(&error_status);
+ HDL_Require_Noerr_Action(da_check_success, exit, "DA Download End");
+#endif
+
+ if (packet_sent_num == packet_num && error_status == 0) {
+ success = TRUE;
+ }
+
+exit:
+ if (error_status != 0) {
+ HDL_LOGE("hdl_da_download error_status=%d", error_status);
+ }
+ return success;
+}
+
+#ifndef PSRAM_DOWNLOAD
+bool hdl_da_readback(const hdl_readback_arg_t *readback_arg)
+{
+ bool success = FALSE;
+ uint32_t error_status = 0;
+ const uint32_t readback_flash_addr = readback_arg->readback_flash_addr;
+ const uint32_t readback_total_len = readback_arg->readback_total_len;
+ HDL_COM_PutByte(DA_READ_CMD);
+ HDL_COM_PutData32(readback_flash_addr);
+ HDL_COM_PutData32(readback_total_len);
+ HDL_COM_PutData32(DA_RECV_PACKET_LEN);
+
+ // DA Check Readback Arg
+ bool da_check_success = hdl_da_check_cmd_arg(&error_status);
+ HDL_Require_Noerr_Action(da_check_success, exit, "DA Readback CMD, Check Range");
+
+ // Readback init callback
+ if (readback_arg->readback_init_cb != NULL) {
+ readback_arg->readback_init_cb(readback_arg->readback_init_cb_arg);
+ }
+
+ // Readback Packet(4K) & Callback
+ const uint32_t packet_num = ((readback_total_len - 1) / DA_RECV_PACKET_LEN) + 1;
+ uint32_t packet_read_num = 0;
+ uint32_t read_total_bytes = 0;
+ while (packet_read_num < packet_num) {
+ const bool is_last_packet = (packet_read_num == (packet_num - 1));
+ const uint32_t start_offset = packet_read_num * DA_RECV_PACKET_LEN;
+ const uint32_t cur_packet_len = is_last_packet ? (readback_total_len - start_offset) : DA_RECV_PACKET_LEN;
+ HDL_LOGI("hdl_da_readback packet %d/%d %d", packet_read_num + 1, packet_num, cur_packet_len);
+
+ uint32_t packet_read_bytes = 0;
+ uint8_t *packet_read_buf = g_hdl_data_buf;
+ while (packet_read_bytes < cur_packet_len) {
+ // Even if last_packet, should also read DA_RECV_PACKET_LEN
+ packet_read_bytes += HDL_COM_GetByte_Buffer(packet_read_buf + packet_read_bytes,
+ DA_RECV_PACKET_LEN - packet_read_bytes);
+ }
+ read_total_bytes += cur_packet_len;
+ #if defined (HDL_VIA_I2C)
+ // ToDo Note: Wait DA to compute checksum
+ // hdl_delay(50);
+ #endif
+ uint32_t packet_checksum_from_local = hdl_compute_simple_checksum(packet_read_buf, cur_packet_len);
+ uint32_t packet_checksum_from_device = HDL_COM_GetData32();
+ HDL_Require_Noerr_Action(packet_checksum_from_device == packet_checksum_from_local, exit,
+ "hdl_readback packet checksum");
+ // Readback Callback
+ if (readback_arg->readback_cb != NULL) {
+ readback_arg->readback_cb(readback_arg->readback_cb_arg, readback_flash_addr + start_offset,
+ packet_read_buf, cur_packet_len,
+ read_total_bytes, readback_total_len);
+ }
+
+ // Next
+ HDL_COM_PutByte(DA_ACK);
+
+ packet_read_num++;
+ }
+ if (read_total_bytes == readback_total_len) {
+ success = TRUE;
+ }
+
+exit:
+ if (error_status != 0) {
+ HDL_LOGE("hdl_da_readback error_status=%d", error_status);
+ }
+ return success;
+}
+
+bool hdl_da_enable_wdt(uint16_t wdt_sec)
+{
+ HDL_COM_PutByte(DA_ENABLE_WATCHDOG_CMD);
+ HDL_COM_PutData16(wdt_sec);
+ uint8_t ack = HDL_COM_GetByte();
+ return (ack == DA_ACK);
+}
+
+bool hdl_da_finish(bool power_off)
+{
+ HDL_COM_PutByte(DA_FINISH_CMD);
+ HDL_COM_PutByte((power_off ? 1 : 0));
+ uint8_t ack = HDL_COM_GetByte();
+ return (ack == DA_ACK);
+}
+#endif
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_debug.h"
+#include "syslog.h"
+
+//log_create_module(HostDL, PRINT_LEVEL_INFO);
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "../inc/hdl_demo.h"
+#include "../inc/hdl_brom_base.h"
+#include "../inc/hdl_debug.h"
+#include "../inc/hdl_api.h"
+
+void init_cb_demo(void *usr_arg)
+{
+ if (usr_arg != NULL && strlen((const char *)usr_arg) > 0) {
+ HDL_MAIN_LOG("%s", usr_arg);
+ }
+}
+
+void da_send_cb_demo(void *usr_arg, uint32_t sent_bytes, uint32_t da_total_bytes)
+{
+ uint8_t percent = sent_bytes * 100 / da_total_bytes;
+ HDL_MAIN_LOG("DA Send Progress %d%% (%d/%d Bytes)", percent, sent_bytes, da_total_bytes);
+}
+
+void download_cb_demo(void *usr_arg, char *cur_image_name, uint32_t sent_bytes, uint32_t total_bytes)
+{
+ uint8_t percent = sent_bytes * 100 / total_bytes;
+ HDL_MAIN_LOG("Image (%s) Download Progress %d%% (%d/%d Bytes)",
+ cur_image_name, percent, sent_bytes, total_bytes);
+}
+
+#ifndef PSRAM_DOWNLOAD
+// Host Local Flash Read Buffer, only for Test Readback
+uint8_t g_hdl_flash_read_buf[4096] = {0};
+bool g_readback_check_result = TRUE;
+void readback_cb_demo(void *usr_arg, uint32_t cur_flash_addr,
+ uint8_t *readback_buf, uint32_t readback_buf_len,
+ uint32_t read_len, uint32_t readback_total_len)
+{
+ uint8_t percent = read_len * 100 / readback_total_len;
+ HDL_MAIN_LOG("Readback Progress %d%% (%d/%d Bytes)", percent, read_len, readback_total_len);
+
+ uint32_t host_flash_addr = cur_flash_addr - 0x08000000 + 0x00100000;
+ bool ret = hdl_flash_read(host_flash_addr, g_hdl_flash_read_buf, readback_buf_len);
+ if (ret) {
+ uint8_t md5_local[16] = {0};
+ uint8_t md5_readback[16] = {0};
+ // ToDo Note: Use mbedTLS MD5 API to verify readback result,
+ // you could ignore the readback verification function.
+ hdl_md5(g_hdl_flash_read_buf, readback_buf_len, md5_local);
+ hdl_md5(readback_buf, readback_buf_len, md5_readback);
+ int ret = memcmp(md5_local, md5_readback, 16);
+ if (ret != 0) {
+ g_readback_check_result = FALSE;
+ HDL_LOGE("readback_cb_demo, check fail 0x%08X %d", cur_flash_addr, readback_buf_len);
+ }
+ }
+}
+#endif
+
+void progress_cb_demo(void *usr_arg, uint8_t percent)
+{
+ HDL_MAIN_LOG("%s %d%%", (usr_arg != NULL ? usr_arg : "percent "), percent);
+}
+
+
+void hdl_host_dl_demo()
+{
+#ifdef PSRAM_DOWNLOAD
+ // Init Connect ARG
+ hdl_da_info_t da_info;
+ da_info.da_flash_addr = HDL_DA_FLASH_POS;
+ da_info.da_run_addr = HDL_DA_RUN_ADDR;
+ da_info.da_len = HDL_DA_SIZE;
+ hdl_connect_arg_t connect_arg;
+ connect_arg.conn_da_init_cb = init_cb_demo;
+ connect_arg.conn_da_init_cb_arg = "Download DA now...";
+ connect_arg.conn_da_send_cb = da_send_cb_demo;
+ connect_arg.conn_da_send_cb_arg = "";
+ connect_arg.conn_enable_log = FALSE;
+
+ // Connect Device
+ bool success = hdl_connect(&da_info, &connect_arg);
+ HDL_Require_Noerr_Action(success, exit, "hdl_connect");
+
+ hdl_image_t cm4_image;
+ cm4_image.image_host_flash_addr = HDL_CM4_IMAGE_HOST_FLASH_POS;
+ cm4_image.image_slave_flash_addr = HDL_CM4_IMAGE_SLAVE_FLASH_POS;
+ cm4_image.image_len = HDL_CM4_IMAGE_SIZE;
+ cm4_image.image_name = HDL_CM4_IMAGE_NAME;
+ cm4_image.image_is_bootloader = FALSE;
+ cm4_image.next = NULL;
+
+ hdl_download_arg_t download_arg;
+ download_arg.download_init_cb = init_cb_demo;
+ download_arg.download_init_cb_arg = "Download Images now...";
+ download_arg.download_cb = download_cb_demo;
+ download_arg.download_cb_arg = "";
+ download_arg.download_images = &cm4_image;
+ success = hdl_download(&download_arg);
+ HDL_Require_Noerr_Action(success, exit, "hdl_download");
+#else
+ // Init Connect ARG
+ hdl_da_info_t da_info;
+ da_info.da_flash_addr = HDL_DA_FLASH_POS;
+ da_info.da_run_addr = HDL_DA_RUN_ADDR;
+ da_info.da_len = HDL_DA_SIZE;
+ hdl_connect_arg_t connect_arg;
+ connect_arg.conn_da_init_cb = init_cb_demo;
+ connect_arg.conn_da_init_cb_arg = "Download DA now...";
+ connect_arg.conn_da_send_cb = da_send_cb_demo;
+ connect_arg.conn_da_send_cb_arg = "";
+ connect_arg.conn_enable_log = FALSE;
+ hdl_da_report_t da_report;
+ memset((void *)&da_report, 0, sizeof(da_report));
+
+ // Connect Device
+ bool success = hdl_connect(&da_info, &connect_arg, &da_report);
+ HDL_Require_Noerr_Action(success, exit, "hdl_connect");
+
+ // Format All
+ hdl_format_arg_t format_arg;
+ format_arg.format_init_cb = init_cb_demo;
+ format_arg.format_init_cb_arg = "Format All now...";
+ format_arg.format_progress_cb = progress_cb_demo;
+ format_arg.format_progress_cb_arg = "Format Progress";
+ format_arg.format_addr = da_report.flash_base_addr;
+ format_arg.format_size = da_report.flash_size;
+ success = hdl_format(&format_arg);
+ HDL_Require_Noerr_Action(success, exit, "hdl_format");
+
+ // Download 3 Images (Bootloader, CM4, Other)
+ hdl_image_t bl_image;
+ hdl_image_t cm4_image;
+ hdl_image_t other_image;
+ bl_image.image_host_flash_addr = HDL_BL_IMAGE_HOST_FLASH_POS;
+ bl_image.image_slave_flash_addr = HDL_BL_IMAGE_SLAVE_FLASH_POS;
+ bl_image.image_len = HDL_BL_IMAGE_SIZE;
+ bl_image.image_name = HDL_BL_IMAGE_NAME;
+ bl_image.image_is_bootloader = TRUE;
+ bl_image.next = &cm4_image;
+ cm4_image.image_host_flash_addr = HDL_CM4_IMAGE_HOST_FLASH_POS;
+ cm4_image.image_slave_flash_addr = HDL_CM4_IMAGE_SLAVE_FLASH_POS;
+ cm4_image.image_len = HDL_CM4_IMAGE_SIZE;
+ cm4_image.image_name = HDL_CM4_IMAGE_NAME;
+ cm4_image.image_is_bootloader = FALSE;
+ cm4_image.next = &other_image;
+ other_image.image_host_flash_addr = HDL_OTHER_IMAGE_HOST_FLASH_POS;
+ other_image.image_slave_flash_addr = HDL_OTHER_IMAGE_SLAVE_FLASH_POS;
+ other_image.image_len = HDL_OTHER_IMAGE_SIZE;
+ other_image.image_name = HDL_OTHER_IMAGE_NAME;
+ other_image.image_is_bootloader = FALSE;
+ other_image.next = NULL;
+
+ hdl_download_arg_t download_arg;
+ download_arg.download_init_cb = init_cb_demo;
+ download_arg.download_init_cb_arg = "Download Images now...";
+ download_arg.download_cb = download_cb_demo;
+ download_arg.download_cb_arg = "";
+ download_arg.download_images = &bl_image;
+ success = hdl_download(&download_arg);
+ HDL_Require_Noerr_Action(success, exit, "hdl_download");
+
+ // Disconnect Device
+ success = hdl_disconnect(DISCONNECT_NONE);
+ HDL_Require_Noerr_Action(success, exit, "hdl_disconnect");
+#endif
+exit:
+ HDL_SUCCESS_LOG(__func__);
+}
+
+//static void vHostDLTask(void *pvParameters)
+//{
+// LOG_I(main, "hdl_host_dl_demo start");
+// hdl_host_dl_demo();
+// LOG_I(main, "hdl_host_dl_demo done");
+//
+// hdl_delete_task(NULL);
+//}
+//
+//void hdl_main_entry()
+//{
+// hdl_create_main_task(vHostDLTask);
+//}
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_ports/hdl_flash_api.h"
+
+bool hdl_flash_init()
+{
+ // hal_flash_status_t status = hal_flash_init();
+// HDL_LOGI("hdl_flash_init status=%d", status);
+// return (status == HAL_FLASH_STATUS_OK);
+ return true;
+}
+
+bool hdl_flash_read(uint32_t start_address, uint8_t *buffer, uint32_t length)
+{
+ //hal_flash_status_t status = hal_flash_read(start_address, buffer, length);
+// HDL_LOGI("hdl_flash_read status=%d", status);
+// return (status == HAL_FLASH_STATUS_OK);
+ return true;
+}
+
+bool hdl_flash_deinit()
+{
+ //hal_flash_status_t status = hal_flash_deinit();
+// HDL_LOGI("hdl_flash_deinit status=%d", status);
+// return (status == HAL_FLASH_STATUS_OK);
+ return true;
+}
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_ports/hdl_i2c.h"
+#include "hdl_ports/hdl_os_util.h"
+
+
+
+
+#ifdef HDL_VIA_I2C
+#include "hal_i2c_master_internal.h"
+#define HDL_I2C_SLAVE_ADDR 0x08
+#define HDL_I2C_FREQ I2C_FREQUENCY_300K
+#define HDL_I2C_BUF_SIZE 256
+
+#define HDL_I2C_DATA_MARK 0x66
+#define HDL_I2C_READ_PACKET_LEN (HDL_I2C_BUF_SIZE - 1)
+#define HDL_I2C_SEND_PACKET_LEN (HDL_I2C_BUF_SIZE)
+
+uint32_t g_i2c_check_data_valid_flag = 0;
+
+volatile uint32_t g_i2c_finish_flag = 0;
+ATTR_RWDATA_IN_NONCACHED_RAM_4BYTE_ALIGN uint8_t g_i2c_send_data[HDL_I2C_BUF_SIZE] = {0};
+ATTR_RWDATA_IN_NONCACHED_RAM_4BYTE_ALIGN uint8_t g_i2c_recv_data[HDL_I2C_BUF_SIZE] = {0};
+
+// I2C master will read "the last byte of the previous send data" when 3335 I2C Slave's data is not ready
+// This is HW design of 3335 I2C Slave, Brom/host_dl_demo/DA must follow it.
+// The read operation is invalid when read (HDL_I2C_DATA_MARK * read_length).
+static bool i2c_read_valid(uint8_t *read_data, uint32_t read_length)
+{
+ if (read_data == NULL || read_length < 1) {
+ return FALSE;
+ }
+ if (read_data[read_length - 1] != HDL_I2C_DATA_MARK) {
+ HDL_LOGI("i2c_read_valid read_data[%d] 0x%02X != HDL_I2C_DATA_MARK",
+ (read_length - 1), read_data[read_length - 1]);
+ return FALSE;
+ }
+ for (int i = 0; i < read_length; i++) {
+ if (read_data[i] != HDL_I2C_DATA_MARK) {
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+static void i2c_callback(uint8_t slave_address, hal_i2c_callback_event_t event, void *user_data)
+{
+ // HDL_LOGI("i2c_callback event=%d", event);
+ g_i2c_finish_flag = 1;
+}
+
+static bool i2c_dma_send(uint8_t *send_data, uint32_t data_length)
+{
+ bool success = FALSE;
+ hal_i2c_config_t i2c_init;
+ hal_i2c_port_t i2c_port = I2C_MASTER_NUM;
+ hal_i2c_send_config_t i2c_send_config;
+ hal_i2c_frequency_t input_frequency = HDL_I2C_FREQ / 100;
+ if (input_frequency > 4) {
+ input_frequency = HAL_I2C_FREQUENCY_1M;
+ }
+ i2c_init.frequency = input_frequency;
+ HDL_LOGI("i2c_dma_send data_length=%d", data_length);
+
+ g_i2c_finish_flag = 0;
+ if (data_length > HDL_I2C_BUF_SIZE) {
+ HDL_LOGE("i2c_dma_send fail, Length > HDL_I2C_BUF_SIZE");
+ return success;
+ }
+
+ hal_gpio_init(I2C_SCL_PIN_USED);
+ hal_gpio_init(I2C_SDA_PIN_USED);
+ hal_pinmux_set_function(I2C_SCL_PIN_USED, I2C_SCL_MODE_USED);
+ hal_pinmux_set_function(I2C_SDA_PIN_USED, I2C_SDA_MODE_USED);
+
+ hal_i2c_status_t status = hal_i2c_master_init(i2c_port, &i2c_init);
+ HDL_Require_Noerr(status == HAL_I2C_STATUS_OK, exit);
+
+ status = hal_i2c_master_set_io_config(i2c_port, I2C_MODE);
+ HDL_Require_Noerr(status == HAL_I2C_STATUS_OK, exit);
+
+ status = hal_i2c_master_register_callback(i2c_port, i2c_callback, NULL);
+ HDL_Require_Noerr(status == HAL_I2C_STATUS_OK, exit);
+
+ i2c_send_config.slave_address = HDL_I2C_SLAVE_ADDR;
+ memset(g_i2c_send_data, 0, HDL_I2C_BUF_SIZE);
+ memcpy(g_i2c_send_data, send_data, data_length);
+ i2c_send_config.send_data = g_i2c_send_data;
+ i2c_send_config.send_packet_length = data_length;
+ i2c_send_config.send_bytes_in_one_packet = 1;
+
+ while (1) {
+ status = hal_i2c_master_send_dma_ex(i2c_port, &i2c_send_config);
+ // HDL_LOGI("hal_i2c_master_send_dma_ex status=%d", status);
+ // send_dma_ex successfully & wait i2c_callback (g_i2c_finish_flag=1)
+ if (HAL_I2C_STATUS_OK == status) {
+ while (0 == g_i2c_finish_flag) {
+ hdl_delay(1);
+ }
+ g_i2c_finish_flag = 0;
+ break;
+ } else {
+ hdl_delay(50);
+ }
+ }
+
+ status = hal_i2c_master_deinit(i2c_port);
+ HDL_Require_Noerr(status == HAL_I2C_STATUS_OK, exit);
+ success = TRUE;
+ HDL_LOGI("i2c_dma_send success data_length=%d", data_length);
+
+exit:
+ hal_gpio_deinit(I2C_SCL_PIN_USED);
+ hal_gpio_deinit(I2C_SDA_PIN_USED);
+ return success;
+}
+
+static bool i2c_dma_receive(uint8_t *recv_data, uint32_t data_length)
+{
+ bool success = FALSE;
+ hal_i2c_config_t i2c_init;
+ hal_i2c_port_t i2c_port = I2C_MASTER_NUM;
+ hal_i2c_receive_config_t i2c_receive_config;
+ hal_i2c_frequency_t input_frequency = HDL_I2C_FREQ / 100;
+ if (input_frequency > 4) {
+ input_frequency = HAL_I2C_FREQUENCY_1M;
+ }
+ i2c_init.frequency = input_frequency;
+ HDL_LOGI("i2c_dma_receive data_length=%d", data_length);
+
+ g_i2c_finish_flag = 0;
+
+ // data_length must count HDL_I2C_DATA_MARK
+ data_length = data_length + 1;
+ if (data_length > HDL_I2C_BUF_SIZE) {
+ HDL_LOGE("i2c_dma_receive fail, Length > HDL_I2C_BUF_SIZE");
+ return success;
+ }
+
+ hal_gpio_init(I2C_SCL_PIN_USED);
+ hal_gpio_init(I2C_SDA_PIN_USED);
+ hal_pinmux_set_function(I2C_SCL_PIN_USED, I2C_SCL_MODE_USED);
+ hal_pinmux_set_function(I2C_SDA_PIN_USED, I2C_SDA_MODE_USED);
+
+ hal_i2c_status_t status = hal_i2c_master_init(i2c_port, &i2c_init);
+ status += hal_i2c_master_set_io_config(i2c_port, I2C_MODE);
+ status += hal_i2c_master_register_callback(i2c_port, i2c_callback, NULL);
+ HDL_Require_Noerr(status == HAL_I2C_STATUS_OK, exit);
+
+ i2c_receive_config.slave_address = HDL_I2C_SLAVE_ADDR;
+ i2c_receive_config.receive_buffer = g_i2c_recv_data;
+ memset(g_i2c_recv_data, 0, HDL_I2C_BUF_SIZE);
+ i2c_receive_config.receive_packet_length = 1;
+ i2c_receive_config.receive_bytes_in_one_packet = data_length;
+
+ while (1) {
+ status = hal_i2c_master_receive_dma_ex(i2c_port, &i2c_receive_config);
+ // HDL_LOGI("hal_i2c_master_receive_dma_ex status=%d", status);
+ // receive_dma_ex successfully & wait i2c_callback (g_i2c_finish_flag=1)
+ if (HAL_I2C_STATUS_OK == status) {
+ while (0 == g_i2c_finish_flag) {
+ hdl_delay(1);
+ }
+ // receive_dma_ex pass (g_i2c_finish_flag=1), reset g_i2c_finish_flag
+ g_i2c_finish_flag = 0;
+
+ // i2c_read_valid check
+ bool data_valid = g_i2c_check_data_valid_flag
+ ? i2c_read_valid(g_i2c_recv_data, data_length) : TRUE;
+ if (data_valid) {
+ break;
+ } else {
+ HDL_LOGE("hal_i2c_master_receive_dma_ex i2c_read invalid data length=%d", data_length);
+ }
+ }
+ hdl_delay(50);
+ }
+
+ // only copy data without HDL_I2C_DATA_MARK from g_i2c_recv_data
+ memcpy(recv_data, g_i2c_recv_data, data_length - 1);
+ /*
+ if (data_length <= 4 + 1) {
+ for (int i = 0; i < data_length; i++) {
+ HDL_LOGI("g_i2c_recv_data[%d]=0x%02X", i, g_i2c_recv_data[i]);
+ }
+ } else {
+ for (int i = 0; i < 256; i+=16) {
+ HDL_LOGI("g_i2c_recv_data 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X"
+ "0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X"
+ "0x%02X 0x%02X 0x%02X 0x%02X", g_i2c_recv_data[i+0], g_i2c_recv_data[i+1],
+ g_i2c_recv_data[i+2],g_i2c_recv_data[i+3],g_i2c_recv_data[i+4],
+ g_i2c_recv_data[i+5],g_i2c_recv_data[i+6],g_i2c_recv_data[i+7],
+ g_i2c_recv_data[i+8],g_i2c_recv_data[i+9],g_i2c_recv_data[i+10],
+ g_i2c_recv_data[i+11],g_i2c_recv_data[i+12],g_i2c_recv_data[i+13],
+ g_i2c_recv_data[i+14],g_i2c_recv_data[i+15]);
+ hdl_delay(10);
+ }
+ }
+ */
+
+ status = hal_i2c_master_deinit(i2c_port);
+ HDL_Require_Noerr(status == HAL_I2C_STATUS_OK, exit);
+ success = TRUE;
+
+exit:
+ hal_gpio_deinit(I2C_SCL_PIN_USED);
+ hal_gpio_deinit(I2C_SDA_PIN_USED);
+ return success;
+}
+
+bool hdl_i2c_master_init()
+{
+ // Do init and deinit for each I2C send/receive
+ HDL_LOGI("hdl_i2c_master_init: empty");
+ return TRUE;
+}
+
+bool hdl_i2c_master_deinit()
+{
+ // Do init and deinit for each I2C send/receive
+ HDL_LOGI("hdl_i2c_master_deinit: empty");
+ return TRUE;
+}
+
+uint8_t hdl_i2c_master_get_byte()
+{
+ uint8_t data = 0;
+ i2c_dma_receive(&data, 1);
+ return data;
+}
+
+bool hdl_i2c_master_get_byte_status(uint8_t *data)
+{
+ return i2c_dma_receive(data, 1);
+}
+
+uint32_t hdl_i2c_master_get_byte_buffer(uint8_t *buf, uint32_t length)
+{
+ bool success = FALSE;
+ uint32_t read_len = 0;
+ uint32_t read_packet_len = min(length, HDL_I2C_READ_PACKET_LEN);
+ while (read_len < length) {
+ success = i2c_dma_receive(buf, read_packet_len);
+ read_len += read_packet_len;
+ buf += read_packet_len;
+ read_packet_len = min(length - read_len, HDL_I2C_READ_PACKET_LEN);
+ }
+ return (success ? length : 0);
+}
+
+void hdl_i2c_master_put_byte(uint8_t data)
+{
+ i2c_dma_send((uint8_t *)&data, 1);
+}
+
+uint32_t hdl_i2c_master_put_byte_buffer(uint8_t *buf, uint32_t length)
+{
+ bool success = FALSE;
+ uint32_t sent_len = 0;
+ uint32_t send_packet_len = min(length, HDL_I2C_SEND_PACKET_LEN);
+ while (sent_len < length) {
+ success = i2c_dma_send(buf, send_packet_len);
+ sent_len += send_packet_len;
+ buf += send_packet_len;
+ send_packet_len = min(length - sent_len, HDL_I2C_SEND_PACKET_LEN);
+ hdl_delay(20);
+ }
+ return (success ? length : 0);
+}
+
+void hdl_i2c_master_put_byte_complete(uint8_t data)
+{
+ i2c_dma_send((uint8_t *)&data, 1);
+}
+
+uint16_t hdl_i2c_master_get_data16()
+{
+ uint16_t data = 0;
+ i2c_dma_receive((uint8_t *)&data, 2);
+ return data;
+}
+
+void hdl_i2c_master_put_data16(uint16_t data)
+{
+ i2c_dma_send((uint8_t *)&data, 2);
+}
+
+uint32_t hdl_i2c_master_get_data32()
+{
+ uint32_t data = 0;
+ i2c_dma_receive((uint8_t *)&data, 4);
+ return data;
+}
+
+void hdl_i2c_master_put_data32(uint32_t data)
+{
+ i2c_dma_send((uint8_t *)&data, 4);
+}
+
+void hdl_i2c_master_purge_fifo()
+{
+ HDL_LOGI("hdl_i2c_master_purge_fifo: empty");
+}
+
+void hdl_i2c_master_set_baudrate(hal_uart_baudrate_t baud_rate)
+{
+ HDL_LOGI("hdl_i2c_master_set_baudrate: empty");
+}
+
+void hdl_i2c_enable_check_data_valid()
+{
+ g_i2c_check_data_valid_flag = 1;
+}
+
+#endif
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_ports/hdl_os_util.h"
+#include "hdl_ports/md5.h"
+
+uint16_t hdl_compute_checksum(uint8_t *buf, uint32_t buf_len)
+{
+ uint16_t checksum = 0;
+ if (buf == NULL || buf_len == 0) {
+ HDL_LOGE("hdl_compute_checksum, invalid arg");
+ return 0;
+ }
+
+ int i = 0;
+ for (i = 0; i < buf_len / 2; i++) {
+ checksum ^= *(uint16_t *)(buf + i * 2);
+ }
+
+ if ((buf_len % 2) == 1) {
+ checksum ^= buf[i * 2];
+ }
+ return checksum;
+}
+
+uint32_t hdl_compute_simple_checksum(uint8_t *buf, uint32_t buf_len)
+{
+ uint32_t checksum = 0;
+ if (buf == NULL || buf_len == 0) {
+ HDL_LOGE("hdl_compute_simple_checksum, invalid arg");
+ return 0;
+ }
+
+ for (int i = 0; i < buf_len; i++) {
+ checksum += *(buf + i);
+ }
+ return checksum;
+}
+//使用select实现精确到1微秒(0.000001秒)的sleep
+void sleep_us(unsigned int nusecs)
+{
+ struct timeval tval;
+
+ tval.tv_sec = nusecs / 1000000;
+ tval.tv_usec = nusecs % 1000000;
+ select(0, NULL, NULL, NULL, &tval);
+}
+
+void hdl_md5(const uint8_t *input, size_t len, uint8_t output[16])
+{
+ MD5_CTX ctx;
+ MD5Init(&ctx);
+ MD5Update(&ctx, (unsigned char *) input, len);
+ MD5Final(output, &ctx);
+}
+
+
+#define GH_IOC_MAGIC 'G'
+#define GH_IOCTL_CMD_RESET _IOW(GH_IOC_MAGIC, 0x02, uint32_t)
+#define AG3335_DEVICE "/dev/ag3335m"
+int ag3335m_reset(int enabled){
+ int dev_fd;
+ dev_fd = open(AG3335_DEVICE, O_RDWR | O_SYNC);
+ if (dev_fd < 0) {
+ printf( "cannot open %s\n", AG3335_DEVICE);
+ return 1;
+ }
+ int err = 0;
+ {// enable step counter
+
+ LOGD("ag3335m_reset ioctl");
+ err = ioctl(dev_fd, GH_IOCTL_CMD_RESET,
+ &enabled);
+
+ LOGD("ag3335m_reset done");
+
+ if (err != 0) {
+ LOGE("ag3335m_reset failed (%s)", strerror(errno));
+ return err;
+ }
+ }// enable step counter end
+
+ close(dev_fd);
+ return 0;
+}
\ No newline at end of file
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_ports/hdl_spi.h"
+
+#ifdef HDL_VIA_SPI
+
+#define SPIS_CFG_RD_CMD 0x02
+#define SPIS_RD_CMD 0x81
+#define SPIS_CFG_WR_CMD 0x04
+#define SPIS_WR_CMD 0x06
+#define SPIS_RS_CMD 0x0a
+#define SPIS_PWON_CMD 0x0e
+#define SPIS_PWOFF_CMD 0x0c
+#define SPIS_CT_CMD 0x10
+
+#define SPIS_ADDRESS_ID 0x55aa0000
+
+static volatile bool g_spi_transaction_finish;
+ATTR_ZIDATA_IN_NONCACHED_RAM_4BYTE_ALIGN static uint8_t g_transfer_tx_buffer[4096 + 1];
+ATTR_ZIDATA_IN_NONCACHED_RAM_4BYTE_ALIGN static uint8_t g_transfer_rx_buffer[4096 + 1];
+
+/**
+*@brief In this function we notice spi driver owner that spi transfer has been completed.
+*@param[in] event: event of spi driver.
+*@param[in] user_data: pointer to the data that registered to spi driver.
+*@return None.
+*/
+static void spi_master_dma_callback(hal_spi_master_callback_event_t event, void *user_data)
+{
+ HDL_LOGI("spi_master_dma_callback enter, event = %d", event);
+ g_spi_transaction_finish = TRUE;
+}
+
+
+/**
+*@brief In this function we query status of spi slaver.
+*@param[in] status: Pointer to the result of spi slaver's status.
+*@return None.
+*/
+static void spi_query_slave_status(uint8_t *status)
+{
+ uint8_t status_cmd = SPIS_RS_CMD;
+ uint8_t status_receive[2];
+ hal_spi_master_send_and_receive_config_t spi_send_and_receive_config;
+
+ /* Note:
+ * The value of receive_length is the valid number of bytes received plus the number of bytes to send.
+ * For example, here the valid number of bytes received is 1 byte,
+ * and the number of bytes to send also is 1 byte, so the receive_length is 2.
+ */
+ status_receive[1] = 0;
+ spi_send_and_receive_config.receive_length = 2;
+ spi_send_and_receive_config.send_length = 1;
+ spi_send_and_receive_config.send_data = &status_cmd;
+ spi_send_and_receive_config.receive_buffer = status_receive;
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_send_and_receive_polling(SPIM_TEST_PORT, &spi_send_and_receive_config)) {
+ HDL_LOGE("SPI master query status of slaver failed");
+ return;
+ }
+
+ HDL_LOGI("Status receive: %d", status_receive[1]);
+ *status = status_receive[1];
+}
+
+/**
+*@brief In this function the SPI master read the request from the SPI slave.
+*@param[in] buffer: the buffer to store the request information from the spi slave.
+*@param[in] length: length of the buffer.
+*@return None.
+*/
+static void spi_master_read_data(uint8_t *buffer, uint32_t length)
+{
+ uint8_t cfg_rd_cmd[9];
+ uint8_t status_receive = 0;
+ hal_spi_master_send_and_receive_config_t spi_send_and_receive_config;
+
+ HDL_LOGI("SPI master starts to send CR command to slave");
+ cfg_rd_cmd[0] = SPIS_CFG_RD_CMD;
+ cfg_rd_cmd[1] = SPIS_ADDRESS_ID & 0xff;
+ cfg_rd_cmd[2] = (SPIS_ADDRESS_ID >> 8) & 0xff;
+ cfg_rd_cmd[3] = (SPIS_ADDRESS_ID >> 16) & 0xff;
+ cfg_rd_cmd[4] = (SPIS_ADDRESS_ID >> 24) & 0xff;
+ cfg_rd_cmd[5] = (length - 1) & 0xff;
+ cfg_rd_cmd[6] = ((length - 1) >> 8) & 0xff;
+ cfg_rd_cmd[7] = ((length - 1) >> 16) & 0xff;
+ cfg_rd_cmd[8] = ((length - 1) >> 24) & 0xff;
+ do {
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_send_polling(SPIM_TEST_PORT, cfg_rd_cmd, 9)) {
+ HDL_LOGE("SPI master send CR command failed");
+ return;
+ }
+ hal_gpt_delay_ms(100);
+ spi_query_slave_status(&status_receive);
+ } while ((status_receive & (uint8_t)SPIS_STA_TXRX_FIFO_RDY_MASK) != (uint8_t)SPIS_STA_TXRX_FIFO_RDY_MASK);
+
+ HDL_LOGI("SPI master starts to send RD command to slave using DMA mode");
+ g_spi_transaction_finish = FALSE;
+ g_transfer_tx_buffer[0] = SPIS_RD_CMD;
+ memset(buffer, 0, length);
+ spi_send_and_receive_config.receive_length = length + 1;
+ spi_send_and_receive_config.send_length = 1;
+ spi_send_and_receive_config.send_data = g_transfer_tx_buffer;
+ spi_send_and_receive_config.receive_buffer = g_transfer_rx_buffer;
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_send_and_receive_dma(SPIM_TEST_PORT, &spi_send_and_receive_config)) {
+ HDL_LOGE("SPI master send dma failed");
+ }
+ while (g_spi_transaction_finish == FALSE) {
+ // do nothing
+ };
+ do {
+ spi_query_slave_status(&status_receive);
+ } while ((status_receive & (uint8_t)SPIS_STA_RDWR_FINISH_MASK) != (uint8_t)SPIS_STA_RDWR_FINISH_MASK);
+
+ memcpy(buffer, &(g_transfer_rx_buffer[1]), length);
+}
+
+/**
+*@brief In this function the SPI master write the data to the SPI slave.
+*@param[in] buffer: the buffer to store the data needed to sent to the spi slave.
+*@param[in] length: length of the buffer.
+*@return None.
+*/
+static void spi_master_write_data(uint8_t *buffer, uint32_t length)
+{
+ uint8_t cfg_wr_cmd[9];
+ uint8_t status_receive = 0;
+
+ HDL_LOGI("SPI master starts to send cfg_wr_cmd command to slave");
+ cfg_wr_cmd[0] = SPIS_CFG_WR_CMD;
+ cfg_wr_cmd[1] = SPIS_ADDRESS_ID & 0xff;
+ cfg_wr_cmd[2] = (SPIS_ADDRESS_ID >> 8) & 0xff;
+ cfg_wr_cmd[3] = (SPIS_ADDRESS_ID >> 16) & 0xff;
+ cfg_wr_cmd[4] = (SPIS_ADDRESS_ID >> 24) & 0xff;
+ cfg_wr_cmd[5] = (length - 1) & 0xff;
+ cfg_wr_cmd[6] = ((length - 1) >> 8) & 0xff;
+ cfg_wr_cmd[7] = ((length - 1) >> 16) & 0xff;
+ cfg_wr_cmd[8] = ((length - 1) >> 24) & 0xff;
+ while ((status_receive & (uint8_t)SPIS_STA_TXRX_FIFO_RDY_MASK) != (uint8_t)SPIS_STA_TXRX_FIFO_RDY_MASK) {
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_send_polling(SPIM_TEST_PORT, cfg_wr_cmd, 9)) {
+ HDL_LOGE("SPI master send cfg_wr_cmd command failed");
+ return;
+ }
+ for (int i = 0; i < 10; i++) {
+ hal_gpt_delay_ms(5);
+ spi_query_slave_status(&status_receive);
+ if ((status_receive & (uint8_t)SPIS_STA_TXRX_FIFO_RDY_MASK) == (uint8_t)SPIS_STA_TXRX_FIFO_RDY_MASK) {
+ break;
+ }
+ }
+ }
+
+ HDL_LOGI("SPI master starts to send wr_cmd command to slave using DMA mode");
+ g_spi_transaction_finish = FALSE;
+ g_transfer_tx_buffer[0] = SPIS_WR_CMD;
+ memcpy(&(g_transfer_tx_buffer[1]), buffer, length);
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_send_dma(SPIM_TEST_PORT, g_transfer_tx_buffer, (length + 1))) {
+ HDL_LOGE("SPI master send wr_cmd command failed");
+ }
+ while (g_spi_transaction_finish == FALSE) {
+ // do nothing
+ };
+ do {
+ spi_query_slave_status(&status_receive);
+ } while ((status_receive & (uint8_t)SPIS_STA_RDWR_FINISH_MASK) != (uint8_t)SPIS_STA_RDWR_FINISH_MASK);
+}
+
+
+
+
+bool hdl_spi_master_init()
+{
+ /* Step1: GPIO configuration for SPI master */
+ hal_gpio_init(SPIM_PIN_NUMBER_CS);
+ hal_gpio_init(SPIM_PIN_NUMBER_CLK);
+ hal_gpio_init(SPIM_PIN_NUMBER_MOSI);
+ hal_gpio_init(SPIM_PIN_NUMBER_MISO);
+ hal_pinmux_set_function(SPIM_PIN_NUMBER_CS, SPIM_PIN_FUNC_CS);
+ hal_pinmux_set_function(SPIM_PIN_NUMBER_CLK, SPIM_PIN_FUNC_CLK);
+ hal_pinmux_set_function(SPIM_PIN_NUMBER_MOSI, SPIM_PIN_FUNC_MOSI);
+ hal_pinmux_set_function(SPIM_PIN_NUMBER_MISO, SPIM_PIN_FUNC_MISO);
+
+ /* Step2: Initializes SPI master with normal mode */
+ hal_spi_master_config_t spi_config;
+ hal_spi_master_advanced_config_t advanced_config;
+ spi_config.bit_order = HAL_SPI_MASTER_LSB_FIRST;
+ spi_config.clock_frequency = SPIM_TEST_FREQUENCY;
+ spi_config.phase = HAL_SPI_MASTER_CLOCK_PHASE0;
+ spi_config.polarity = HAL_SPI_MASTER_CLOCK_POLARITY0;
+ spi_config.slave_port = HAL_SPI_MASTER_SLAVE_0;
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_init(SPIM_TEST_PORT, &spi_config)) {
+ HDL_LOGE("spi_master_init, fail");
+ return FALSE;
+ }
+ advanced_config.byte_order = HAL_SPI_MASTER_LITTLE_ENDIAN;
+ advanced_config.chip_polarity = HAL_SPI_MASTER_CHIP_SELECT_LOW;
+ advanced_config.get_tick = HAL_SPI_MASTER_NO_GET_TICK_MODE;
+ advanced_config.sample_select = HAL_SPI_MASTER_SAMPLE_POSITIVE;
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_set_advanced_config(SPIM_TEST_PORT, &advanced_config)) {
+ HDL_LOGE("spi_master_init, advanced config fail");
+ return FALSE;
+ }
+
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_register_callback(SPIM_TEST_PORT, spi_master_dma_callback, NULL)) {
+ HDL_LOGE("spi_master_init, register callback fail");
+ return FALSE;
+ }
+ return TRUE;
+}
+
+bool hdl_spi_master_deinit()
+{
+ if (HAL_SPI_MASTER_STATUS_OK != hal_spi_master_deinit(SPIM_TEST_PORT)) {
+ HDL_LOGE("hdl_spi_master_deinit, fail");
+ return FALSE;
+ }
+ hal_gpio_deinit(SPIM_PIN_NUMBER_CS);
+ hal_gpio_deinit(SPIM_PIN_NUMBER_CLK);
+ hal_gpio_deinit(SPIM_PIN_NUMBER_MOSI);
+ hal_gpio_deinit(SPIM_PIN_NUMBER_MISO);
+ return TRUE;
+}
+
+uint8_t hdl_spi_master_get_byte()
+{
+ uint8_t data = 0;
+ spi_master_read_data(&data, 1);
+ HDL_LOGI("hdl_spi_master_get_byte 0x%02X", data);
+ return data;
+}
+
+bool hdl_spi_master_get_byte_status(uint8_t *data)
+{
+ spi_master_read_data(data, 1);
+ HDL_LOGI("hdl_spi_master_get_byte_status 0x%02X", *data);
+ return TRUE;
+}
+
+uint32_t hdl_spi_master_get_byte_buffer(uint8_t *buf, uint32_t length)
+{
+ HDL_LOGI("hdl_spi_master_get_byte_buffer start length=%d", length);
+ spi_master_read_data(buf, length);
+ HDL_LOGI("hdl_spi_master_get_byte_buffer end length=%d", length);
+ return length;
+}
+
+void hdl_spi_master_put_byte(uint8_t data)
+{
+ spi_master_write_data(&data, 1);
+}
+
+uint32_t hdl_spi_master_put_byte_buffer(uint8_t *buf, uint32_t length)
+{
+ HDL_LOGI("hdl_spi_master_put_byte_buffer start length=%d", length);
+ spi_master_write_data(buf, length);
+ HDL_LOGI("hdl_spi_master_put_byte_buffer end length=%d", length);
+ return length;
+}
+
+void hdl_spi_master_put_byte_complete(uint8_t data)
+{
+ spi_master_write_data((uint8_t *)&data, 1);
+}
+
+uint16_t hdl_spi_master_get_data16()
+{
+ uint16_t result = 0;
+ spi_master_read_data((uint8_t *)&result, 2);
+ HDL_LOGI("hdl_spi_master_get_data16 0x%04X", result);
+ return result;
+}
+
+void hdl_spi_master_put_data16(uint16_t data)
+{
+ spi_master_write_data((uint8_t *)&data, 2);
+}
+
+uint32_t hdl_spi_master_get_data32()
+{
+ uint32_t result = 0;
+ spi_master_read_data((uint8_t *)&result, 4);
+ HDL_LOGI("hdl_spi_master_get_data32 0x%08X", result);
+ return result;
+}
+
+void hdl_spi_master_put_data32(uint32_t data)
+{
+ spi_master_write_data((uint8_t *)&data, 4);
+}
+
+void hdl_spi_master_purge_fifo()
+{
+ HDL_LOGI("hdl_spi_master_purge_fifo: empty");
+}
+
+void hdl_spi_master_set_baudrate(hal_uart_baudrate_t baud_rate)
+{
+ HDL_LOGI("hdl_spi_master_set_baudrate: empty");
+}
+#endif
--- /dev/null
+/* Copyright Statement:
+ *
+ * (C) 2018 Airoha Technology Corp. All rights reserved.
+ *
+ * This software/firmware and related documentation ("Airoha Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to Airoha Technology Corp. ("Airoha") and/or its licensors.
+ * Without the prior written permission of Airoha and/or its licensors,
+ * any reproduction, modification, use or disclosure of Airoha Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ * You may only use, reproduce, modify, or distribute (as applicable) Airoha Software
+ * if you have agreed to and been bound by the applicable license agreement with
+ * Airoha ("License Agreement") and been granted explicit permission to do so within
+ * the License Agreement ("Permitted User"). If you are not a Permitted User,
+ * please cease any access or use of Airoha Software immediately.
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT AIROHA SOFTWARE RECEIVED FROM AIROHA AND/OR ITS REPRESENTATIVES
+ * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. AIROHA EXPRESSLY DISCLAIMS ANY AND ALL
+ * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES AIROHA PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH AIROHA SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN AIROHA SOFTWARE. AIROHA SHALL ALSO NOT BE RESPONSIBLE FOR ANY AIROHA
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AIROHA'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO AIROHA SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT AIROHA'S OPTION, TO REVISE OR REPLACE AIROHA SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * AIROHA FOR SUCH AIROHA SOFTWARE AT ISSUE.
+ */
+
+#include "hdl_ports/hdl_uart.h"
+
+#ifdef HDL_VIA_UART
+
+static int gps_fd=-1;
+
+static void set_fdattr(int fd , int baud )
+{
+ struct termios termios;
+ int status;
+ char stop_bits = 0;
+ //int baud = B921600;//B921600 B115200;
+
+ tcflush(fd, TCIOFLUSH);
+ tcgetattr(fd, &termios);
+
+ cfmakeraw(&termios);
+ // termios.c_oflag &= ~OPOST;
+ // termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
+ // termios.c_cflag &= ~(CSIZE | PARENB |CRTSCTS);//CRTSCTS
+ termios.c_cflag |= (CS8 |CRTSCTS );//CRTSCTS
+ //termios.c_cflag |= (CS8 );//CRTSCTS
+ /* set input/output baudrate */
+ cfsetospeed(&termios, baud);
+ cfsetispeed(&termios, baud);
+
+
+ status = tcsetattr(fd, TCSANOW, &termios);
+ if (status != 0)
+ {
+ HDL_LOGE("the set UART error:%s\r\n",strerror(errno));
+ }
+ tcflush(fd, TCIOFLUSH);
+ HDL_LOGI("TCIOFLUSH");
+}
+
+static int openSerialPort(const char* pSerialName)
+{
+
+ int ret = 0;
+ char time = 3;
+ int fd=0;
+ do
+ {
+ if ((fd = open(pSerialName, O_RDWR | O_NOCTTY)) >= 0)
+ break;
+ usleep(100000);
+ } while (time--);
+
+
+ if (fd < 0)
+ {
+ HDL_LOGE("%s: no gps Hardware detected, errno = %d, %s", __FUNCTION__, errno, strerror(errno));
+ ret = -1;
+ }
+ //it add debug information
+ HDL_LOGI("openSerialPort name %s ,fd=%d,ret =%d\r\n", pSerialName,fd, ret);
+
+ return fd;
+}
+
+
+void close_engine(int fd)
+{
+ int ret = 0;
+ struct termios termios;
+
+ tcflush(fd, TCIOFLUSH);
+ // tcgetattr(fd, &termios);
+ // cfmakeraw(&termios);
+ // tcsetattr(fd, TCSANOW, &termios);
+ ret = close(fd);
+ HDL_LOGI("close_engine:%d, ret:%d\n",fd,ret);
+ fd= -1;
+}
+
+/*--------------------------------------------------------------------------
+ Function: gps_hardware_open
+
+ Description:
+ it open the device and power On device
+ Parameters:
+ void:
+ Return: SUCCESS:0 ; FAILED : others
+--------------------------------------------------------------------------*/
+int gps_hardware_open(void)
+{
+ HDL_LOGI("gps_hardware_open enter");
+
+ if(gps_fd < 0)// it has not open
+ {
+ gps_fd = openSerialPort("/dev/ttyS2");
+ if(0 > gps_fd)// the serial open error
+ {
+ HDL_LOGE("fd <0 open error !");
+ return gps_fd;
+ }
+ }
+
+ return gps_fd;
+}
+
+/*--------------------------------------------------------------------------
+ Function: gps_hardware_close
+
+ Description:
+ it close the device and power off device
+ Parameters:
+ void:
+ Return: SUCCESS:0 ; FAILED : others
+--------------------------------------------------------------------------*/
+int gps_hardware_close(void)
+{
+ close_engine(gps_fd);
+ gps_fd=-1;
+ return 0;
+}
+
+char readbufgps[2048]={0};
+
+void sendThread(void* arg){
+ int ret=0;
+ while(1==1){
+ ret=read(gps_fd,readbufgps,2047);
+ }
+}
+
+bool hdl_uart_init()
+{
+ gps_hardware_open();
+ //init the serial port
+ HDL_LOGI("gps_hardware_open set_fdattr");
+ set_fdattr(gps_fd,B115200);
+ // Use UART Polling Mode, 115200
+ return (gps_fd>0);
+}
+
+bool hdl_uart_deinit()
+{
+
+ gps_hardware_close();
+ return true;
+}
+
+uint8_t hdl_uart_get_byte()
+{
+ uint8_t data = 0;
+ int ret=read(gps_fd,&data,1);
+ HDL_LOGI("hdl_uart_get_byte 0x%02X ret=%d", data,ret);
+ return data;
+}
+
+bool hdl_uart_get_byte_status(uint8_t *data)
+{
+ int ret=read(gps_fd,data,1);
+ HDL_LOGI("hdl_uart_get_byte 0x%02X ret=%d", *data,ret);
+ return TRUE;
+}
+
+uint32_t hdl_uart_get_byte_buffer(uint8_t *buf, uint32_t length)
+{
+ HDL_LOGI("hdl_uart_get_byte_buffer start length=%d", length);
+ uint32_t received_len = read(gps_fd, buf, length);
+ HDL_LOGI("hdl_uart_get_byte_buffer length=%d received_len=%d", length, received_len);
+ return received_len;
+}
+
+void hdl_uart_put_byte(uint8_t data)
+{
+ write(gps_fd,&data,1);
+ HDL_LOGI("hdl_uart_put_byte 0x%02X", data);
+}
+
+uint32_t hdl_uart_put_byte_buffer(uint8_t *buf, uint32_t length)
+{
+ write(gps_fd,buf,length);
+ HDL_LOGI("hdl_uart_put_byte_buffer length=%d", length);
+ return length;
+}
+
+void hdl_uart_put_byte_complete(uint8_t data)
+{
+ write(gps_fd,&data,1);
+ HDL_LOGI("hdl_uart_put_byte_complete 0x%02X", data);
+}
+
+uint16_t hdl_uart_get_data16()
+{
+ uint16_t result = 0;
+ int ret=read(gps_fd,(char*)result,2);
+ HDL_LOGI("hdl_uart_get_data16 0x%04X", result);
+ return result;
+}
+
+void hdl_uart_put_data16(uint16_t data)
+{
+ write(gps_fd,(char*)data,2);
+ HDL_LOGI("hdl_uart_put_data16 0x%04X ", data);
+}
+
+uint32_t hdl_uart_get_data32()
+{
+ uint32_t result = 0;
+ int ret=read(gps_fd,(char*)result,4);
+ HDL_LOGI("hdl_uart_get_data32 0x%08X", result);
+ return result;
+}
+
+void hdl_uart_put_data32(uint32_t data)
+{
+ write(gps_fd,(char*)data,4);
+ HDL_LOGI("hdl_uart_put_data32 0x%08X", data);
+}
+
+void hdl_uart_purge_fifo()
+{
+ HDL_LOGI("hdl_uart_purge_fifo: empty");
+ /*
+ #define UART_FCR_FIFOINI 0x0007
+ #define UART_FCR_RX62Byte_Level 0x00c0
+ #define UART_FCR_TX62Byte_Level 0x0030
+ #define UART_FCR_MaxFIFO (UART_FCR_RX62Byte_Level | UART_FCR_TX62Byte_Level | UART_FCR_FIFOINI)
+ *(volatile uint8_t *)((0xA0100000) + 0x0014) = (uint8_t)UART_FCR_MaxFIFO;
+ */
+}
+
+void hdl_uart_set_baudrate(hal_uart_baudrate_t baud_rate)
+{
+ // hal_uart_status_t status = hal_uart_set_baudrate(g_hdl_uart_port, baud_rate);
+ set_fdattr(gps_fd,baud_rate);
+ HDL_LOGI("hdl_uart_set_baudrate baud_rate=%d", baud_rate);
+}
+
+#endif
--- /dev/null
+
+/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
+ */
+
+/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+rights reserved.
+License to copy and use this software is granted provided that it
+is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+Algorithm" in all material mentioning or referencing this software
+or this function.
+License is also granted to make and use derivative works provided
+that such works are identified as "derived from the RSA Data
+Security, Inc. MD5 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work.
+RSA Data Security, Inc. makes no representations concerning either
+the merchantability of this software or the suitability of this
+software for any particular purpose. It is provided "as is"
+without express or implied warranty of any kind.
+These notices must be retained in any copies of any part of this
+documentation and/or software.
+ */
+#include "md5.h"
+
+
+/* Constants for MD5Transform routine.
+ */
+
+#define S11 7
+#define S12 12
+#define S13 17
+#define S14 22
+#define S21 5
+#define S22 9
+#define S23 14
+#define S24 20
+#define S31 4
+#define S32 11
+#define S33 16
+#define S34 23
+#define S41 6
+#define S42 10
+#define S43 15
+#define S44 21
+
+static unsigned char PADDING[64] = {
+ 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/* F, G, H and I are basic MD5 functions.
+ */
+#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
+#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
+#define H(x, y, z) ((x) ^ (y) ^ (z))
+#define I(x, y, z) ((y) ^ ((x) | (~z)))
+
+/* ROTATE_LEFT rotates x left n bits.
+ */
+#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
+
+/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
+Rotation is separate from addition to prevent recomputation.
+ */
+#define FF(a, b, c, d, x, s, ac) { \
+ (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
+ (a) = ROTATE_LEFT ((a), (s)); \
+ (a) += (b); \
+ }
+#define GG(a, b, c, d, x, s, ac) { \
+ (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
+ (a) = ROTATE_LEFT ((a), (s)); \
+ (a) += (b); \
+ }
+#define HH(a, b, c, d, x, s, ac) { \
+ (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
+ (a) = ROTATE_LEFT ((a), (s)); \
+ (a) += (b); \
+ }
+#define II(a, b, c, d, x, s, ac) { \
+ (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
+ (a) = ROTATE_LEFT ((a), (s)); \
+ (a) += (b); \
+ }
+
+/* MD5 initialization. Begins an MD5 operation, writing a new context.
+ */
+void MD5Init (MD5_CTX *context)
+{
+ context->count[0] = context->count[1] = 0;
+ /* Load magic initialization constants.
+ */
+ context->state[0] = 0x67452301;
+ context->state[1] = 0xefcdab89;
+ context->state[2] = 0x98badcfe;
+ context->state[3] = 0x10325476;
+}
+
+/* MD5 block update operation. Continues an MD5 message-digest
+ operation, processing another message block, and updating the
+ context.
+ */
+void MD5Update (MD5_CTX *context,unsigned char *input,unsigned int inputLen)
+{
+ unsigned int i, index, partLen;
+
+ /* Compute number of bytes mod 64 */
+ index = (unsigned int)((context->count[0] >> 3) & 0x3F);
+
+ /* Update number of bits */
+ if ((context->count[0] += ((UINT4)inputLen << 3))
+ < ((UINT4)inputLen << 3))
+ context->count[1]++;
+ context->count[1] += ((UINT4)inputLen >> 29);
+
+ partLen = 64 - index;
+
+ /* Transform as many times as possible.
+ */
+ if (inputLen >= partLen) {
+ MD5_memcpy
+ ((POINTER)&context->buffer[index], (POINTER)input, partLen);
+ MD5Transform (context->state, context->buffer);
+
+ for (i = partLen; i + 63 < inputLen; i += 64)
+ MD5Transform (context->state, &input[i]);
+
+ index = 0;
+ }
+ else
+ i = 0;
+
+ /* Buffer remaining input */
+ MD5_memcpy
+ ((POINTER)&context->buffer[index], (POINTER)&input[i],
+ inputLen-i);
+}
+
+/* MD5 finalization. Ends an MD5 message-digest operation, writing the
+ the message digest and zeroizing the context.
+ */
+void MD5Final (unsigned char digest[16], MD5_CTX *context)
+{
+ unsigned char bits[8];
+ unsigned int index, padLen;
+
+ /* Save number of bits */
+ Encode (bits, context->count, 8);
+
+ /* Pad out to 56 mod 64.
+ */
+ index = (unsigned int)((context->count[0] >> 3) & 0x3f);
+ padLen = (index < 56) ? (56 - index) : (120 - index);
+ MD5Update (context, PADDING, padLen);
+
+ /* Append length (before padding) */
+ MD5Update (context, bits, 8);
+
+ /* Store state in digest */
+ Encode (digest, context->state, 16);
+
+ /* Zeroize sensitive information.
+ */
+ MD5_memset ((POINTER)context, 0, sizeof (*context));
+}
+
+/* MD5 basic transformation. Transforms state based on block.
+ */
+static void MD5Transform (UINT4 state[4], unsigned char block[64])
+{
+ UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
+
+ Decode (x, block, 64);
+
+ /* Round 1 */
+ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
+ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
+ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
+ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
+ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
+ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
+ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
+ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
+ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
+ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
+ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
+ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
+ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
+ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
+ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
+ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
+
+ /* Round 2 */
+ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
+ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
+ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
+ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
+ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
+ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
+ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
+ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
+ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
+ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
+ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
+ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
+ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
+ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
+ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
+ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
+
+ /* Round 3 */
+ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
+ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
+ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
+ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
+ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
+ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
+ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
+ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
+ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
+ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
+ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
+ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
+ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
+ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
+ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
+ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
+
+ /* Round 4 */
+ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
+ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
+ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
+ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
+ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
+ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
+ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
+ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
+ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
+ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
+ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
+ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
+ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
+ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
+ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
+ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
+
+ state[0] += a;
+ state[1] += b;
+ state[2] += c;
+ state[3] += d;
+
+ /* Zeroize sensitive information.
+ */
+ MD5_memset ((POINTER)x, 0, sizeof (x));
+}
+
+/* Encodes input (UINT4) into output (unsigned char). Assumes len is
+ a multiple of 4.
+ */
+static void Encode (unsigned char *output, UINT4 *input, unsigned int len)
+{
+ unsigned int i, j;
+
+ for (i = 0, j = 0; j < len; i++, j += 4) {
+ output[j] = (unsigned char)(input[i] & 0xff);
+ output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
+ output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
+ output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
+ }
+}
+
+/* Decodes input (unsigned char) into output (UINT4). Assumes len is
+ a multiple of 4.
+ */
+static void Decode (UINT4 *output, unsigned char *input, unsigned int len)
+{
+ unsigned int i, j;
+
+ for (i = 0, j = 0; j < len; i++, j += 4)
+ output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
+ (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
+}
+
+/* Note: Replace "for loop" with standard memcpy if possible.
+ */
+
+static void MD5_memcpy (POINTER output, POINTER input, unsigned int len)
+{
+ unsigned int i;
+
+ for (i = 0; i < len; i++)
+ output[i] = input[i];
+}
+
+/* Note: Replace "for loop" with standard memset if possible.
+ */
+static void MD5_memset (POINTER output, int value, unsigned int len)
+{
+ unsigned int i;
+
+ for (i = 0; i < len; i++)
+ ((char *)output)[i] = (char)value;
+}
\ No newline at end of file
JNIEXPORT jint JNICALL Java_com_ic_jni_ag3335m_1jni_resetPower
(JNIEnv *env, jclass jclass1) {
- ag3335m_reset();
+ ag3335m_reset(1);
return 0;
}
- rc = pthread_create(&pt1, NULL, (void*)&sendThread, (void*)msg1); if (rc != 0)
+ rc = pthread_create(&pt1, NULL, (void*)&sendThread, (void*)msg1);
+ if (rc != 0)
{
XX_CREATE_FAILED(rc);
}
- rc = pthread_create(&pt2, NULL, (void*)&recvThread, (void*)msg1); if (rc != 0)
+ rc = pthread_create(&pt2, NULL, (void*)&recvThread, (void*)msg1);
+ if (rc != 0)
{
XX_CREATE_FAILED(rc);
}
sleep(1);
- ag3335m_reset();
+ ag3335m_reset(0);
pthread_join(pt1, NULL);
pthread_join(pt2, NULL);
gps_hardware_close();
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/arm64-v8a/objs/ag3335m_jni/gps_hardware.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\gps_hardware.c
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/arm64-v8a/objs/ag3335m_jni/native-lib.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\native-lib.c \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\com_ic_jni_ag3335m_jni.h \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\com_ic_jni_ag3335m_jni.h:
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h:
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/arm64-v8a/objs/ag333m_tool/test.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\test.c \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h:
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/armeabi-v7a/objs/ag3335m_jni/gps_hardware.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\gps_hardware.c
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/armeabi-v7a/objs/ag3335m_jni/native-lib.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\native-lib.c \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\com_ic_jni_ag3335m_jni.h \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\com_ic_jni_ag3335m_jni.h:
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h:
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/armeabi-v7a/objs/ag333m_tool/test.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\test.c \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h:
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/x86/objs/ag3335m_jni/gps_hardware.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\gps_hardware.c
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/x86/objs/ag3335m_jni/native-lib.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\native-lib.c \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\com_ic_jni_ag3335m_jni.h \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\com_ic_jni_ag3335m_jni.h:
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h:
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/x86/objs/ag333m_tool/test.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\test.c \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h:
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/x86_64/objs/ag3335m_jni/gps_hardware.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\gps_hardware.c
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/x86_64/objs/ag3335m_jni/native-lib.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\native-lib.c \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\com_ic_jni_ag3335m_jni.h \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\com_ic_jni_ag3335m_jni.h:
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h:
+++ /dev/null
-D:/workspace/AG3335/ag3335m_download_demo/app/src/main/obj/local/x86_64/objs/ag333m_tool/test.o: \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\test.c \
- D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h
-
-D:\workspace\AG3335\ag3335m_download_demo\app\src\main\jni\hardware.h:
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="fffff"
- android:textOff="PPGOff"
- android:textOn="PPGOn" />
+ android:textOff="DebugOFF"
+ android:textOn="DebugOn" />
+ <ToggleButton
+ android:id="@+id/toggleButtonGPS"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="fffff"
+ android:textOff="GPSOFF"
+ android:textOn="GPSOn" />
</LinearLayout>
--- /dev/null
+package com.ic.test.util;
+
+import java.util.BitSet;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class BitSetTestCase {
+
+ @Before
+ public void setUp() throws Exception {
+ }
+
+ @Test
+ public void testShort() {
+
+ BitSet bs = BitSet.valueOf(new long[]{8});
+ System.out.println("Length: " + bs.length());
+
+ System.out.println("content: " + bs.toString());
+
+ bs = BitSet.valueOf(new long[] {612});
+ System.out.println("content: " + bs.toString());
+ }
+
+}
--- /dev/null
+package com.ic.test.util;
+
+import org.junit.Test;
+
+import com.antu.nmea.util.UtcDate;
+
+public class DateTimeTestCase {
+
+ @Test
+ public void testDate() {
+
+ UtcDate d1 = new UtcDate();
+ d1.year = 1999;
+ d1.month = 13;
+ d1.day = 1;
+
+ assert(d1.isValid() == false);
+
+ UtcDate d2 = new UtcDate();
+ d2.year = 1999;
+ d2.month = 1;
+ d2.day = 32;
+
+ assert(d2.isValid() == false);
+
+ UtcDate d3 = new UtcDate();
+ d3.year = 1999;
+ d3.month = 2;
+ d3.day = 28;
+
+ assert(d3.isValid() == false);
+
+ UtcDate d4 = new UtcDate();
+ d4.year = 2000;
+ d4.month = 2;
+ d4.day = 28;
+
+ assert(d4.isValid() == true);
+
+ UtcDate d5 = new UtcDate();
+ d5.year = 2000;
+ d5.month = 1;
+ d5.day = 31;
+
+ assert(d5.isValid() == true);
+ }
+
+}
--- /dev/null
+package com.ic.test.util;
+
+import static org.junit.Assert.*;
+
+import java.util.List;
+import java.util.Observable;
+import java.util.Observer;
+
+import org.junit.Test;
+
+import com.antu.nmea.codec.exception.SentenceCodecNotFoundException;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.sentence.EncapsulationSentence;
+import com.antu.nmea.sentence.NmeaSentence;
+
+public class EncapsulationSentenceTestCase {
+
+ public void setUp() {
+ System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog");
+ System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "trace");
+ }
+
+ @Test
+ public void testBitConversion() {
+ Byte[] bits = EncapsulationSentence.convertStringToBits("1P000Oh1IT1svTP2r:43grwb05q4");
+
+ assertEquals(168, bits.length);
+
+ String content = EncapsulationSentence.convertSixBitsToString(bits);
+
+ assertEquals("1P000Oh1IT1svTP2r:43grwb05q4", content);
+ }
+
+ @Test
+ public void testMessage1() {
+ final com.antu.nmea.codec.CodecManager manager = new com.antu.nmea.codec.CodecManager();
+ manager.addObserver(new Observer() {
+
+ @Override
+ public void update(Observable o, Object arg) {
+
+ if (arg instanceof NmeaSentence) {
+ System.out.println(arg.toString());
+
+ List<String> result = manager.encode("AI", (NmeaSentence)arg);
+ System.out.println("Encoded message: " + result.get(0));
+ assertEquals(1, result.size());
+ assertEquals("!AIVDM,1,1,,1,1P000Oh1IT1svTP2r:43grwb05q4,0*01\r\n", result.get(0));
+ }
+ }
+
+ });
+ manager.acceptanceList().addAllMessages("vdm");
+
+ try {
+ manager.decode("!AIVDM,1,1,,1,1P000Oh1IT1svTP2r:43grwb05q4,0*01\r\n");
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ } catch (InstantiationException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ } catch (SentenceFieldCodecNotFoundException e) {
+ e.printStackTrace();
+ } catch (SentenceCodecNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+}
--- /dev/null
+package com.ic.test.util;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+import com.antu.nmea.util.StringHelper;
+import com.antu.util.GenericFactory;
+
+public class FactoryTestCase {
+
+ @Test
+ public void testBySymbol() {
+
+ GenericFactory<Object> factory = new GenericFactory<Object>("com.antu.nmea.sentence.field.codec", "?SentenceFieldCodec");
+
+ try {
+ Object obj = factory.createBySymbol(StringHelper.capitalizeFirstChar("integer"));
+
+ assertNotNull(obj);
+ assertEquals(obj.getClass(), com.antu.nmea.sentence.field.codec.IntegerSentenceFieldCodec.class);
+ } catch (InstantiationException e) {
+ fail(e.toString());
+ } catch (IllegalAccessException e) {
+ fail(e.toString());
+ }
+ }
+
+}
--- /dev/null
+package com.ic.test.util;
+import org.junit.Test;
+
+import com.antu.nmea.sentence.field.codec.FieldCodecHelper;
+
+
+public class FieldCodecHelperTestCase {
+
+ @Test
+ public void testParseShort() {
+ assert(FieldCodecHelper.parseShort("", 0, 0) == null);
+ assert(FieldCodecHelper.parseShort("20", 10, 0) == null);
+ assert(FieldCodecHelper.parseShort("20", 1, 3) == null);
+
+ assert(FieldCodecHelper.parseShort("20", 1, 1) == 0);
+ assert(FieldCodecHelper.parseShort("201", 1, 2) == 1);
+ assert(FieldCodecHelper.parseShort("201", 0, 0) == 201);
+ }
+
+ @Test
+ public void testParseInteger() {
+ assert(FieldCodecHelper.parseInt("", 0, 0) == null);
+ assert(FieldCodecHelper.parseInt("20", 10, 0) == null);
+ assert(FieldCodecHelper.parseInt("20", 1, 3) == null);
+
+ assert(FieldCodecHelper.parseInt("20", 1, 1) == 0);
+ assert(FieldCodecHelper.parseInt("201", 1, 2) == 1);
+ assert(FieldCodecHelper.parseInt("201.4", 0, 0) == 201.4);
+ }
+
+ @Test
+ public void testParseDouble() {
+ assert(FieldCodecHelper.parseDouble("", 0, 0) == null);
+ assert(FieldCodecHelper.parseDouble("20", 10, 0) == null);
+ assert(FieldCodecHelper.parseDouble("20", 1, 3) == null);
+
+ assert(FieldCodecHelper.parseDouble("20", 1, 1) == 0);
+ assert(FieldCodecHelper.parseDouble("20.1", 1, 3) == 0.1);
+ assert(FieldCodecHelper.parseDouble("201", 0, 3) == 201);
+ }
+}
--- /dev/null
+package com.ic.test.util;
+
+import static org.junit.Assert.*;
+
+import org.apache.commons.logging.LogFactory;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.antu.nmea.util.StringHelper;
+import com.antu.util.GenericFactory;
+
+public class GenericFactoryTestCase {
+
+ @Before
+ public void setUp() throws Exception {
+ System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog");
+ System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "debug");
+ LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
+ }
+
+ @Test
+ public void test() {
+
+ GenericFactory<Object> factory = new GenericFactory<Object>("com.antu.nmea.sentence.field.codec", "?SentenceFieldCodec");
+
+ try {
+ Object obj = factory.createBySymbol(StringHelper.capitalizeFirstChar("integer"));
+
+ assertNotNull(obj);
+ assertEquals(obj.getClass(), com.antu.nmea.sentence.field.codec.IntegerSentenceFieldCodec.class);
+ } catch (InstantiationException e) {
+ fail(e.toString());
+ } catch (IllegalAccessException e) {
+ fail(e.toString());
+ }
+ }
+
+}
--- /dev/null
+package com.ic.test.util;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+import com.antu.nmea.message.field.codec.MessageFieldCodecHelper;
+import com.antu.util.PrintableList;
+
+public class MessageFieldCodecHelperTestCase {
+
+ @Test
+ public void testParseByte() {
+
+ PrintableList<Byte> bits = new PrintableList<Byte>();
+ bits.add((byte) 1);
+ bits.add((byte) 1);
+ bits.add((byte) 0);
+ bits.add((byte) 0);
+ bits.add((byte) 0);
+ bits.add((byte) 0);
+
+ Short value = MessageFieldCodecHelper.parseShort(bits, 0, 6, false);
+
+ assertNotNull(value);
+ assertEquals(new Short((short) 48), value);
+
+ value = MessageFieldCodecHelper.parseShort(bits, 0, 6, true);
+
+ assertNotNull(value);
+ assertEquals(new Short((short) -16), value);
+
+ PrintableList<Byte> newBits = new PrintableList<Byte>();
+ assertEquals(true, MessageFieldCodecHelper.shortToBits(newBits, value, 6, true));
+ assertEquals(bits, newBits);
+ }
+}
--- /dev/null
+package com.ic.test.util;
+
+import static org.junit.Assert.*;
+
+import java.util.List;
+import java.util.Observable;
+import java.util.Observer;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.antu.nmea.codec.exception.SentenceCodecNotFoundException;
+import com.antu.nmea.codec.exception.SentenceFieldCodecNotFoundException;
+import com.antu.nmea.sentence.NmeaSentence;
+
+public class TutTestCase {
+
+ @Before
+ public void setUp() throws Exception {
+ System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog");
+ System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "trace");
+ }
+
+ @Test
+ public void testDecode() {
+ final com.antu.nmea.codec.CodecManager manager = new com.antu.nmea.codec.CodecManager();
+ manager.addObserver(new Observer() {
+
+ @Override
+ public void update(Observable o, Object arg) {
+
+ if (arg instanceof NmeaSentence) {
+ System.out.println(arg.toString());
+
+ List<String> result = manager.encode("IN", (NmeaSentence)arg);
+ System.out.println("Encoded message: " + result.get(0));
+ assertEquals(1, result.size());
+ assertEquals("$INTUT,SD,01,01,0,A,5368616C6C6F7720576174657221*4A\r\n", result.get(0));
+ }
+ }
+
+ });
+ manager.acceptanceList().addAllMessages("tut");
+ try {
+ manager.decode("$INTUT,SD,01,01,0,A,5368616C6C6F7720576174657221*4A\r\n");
+ } catch (ClassNotFoundException | InstantiationException
+ | IllegalAccessException | SentenceFieldCodecNotFoundException
+ | SentenceCodecNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+
+}