mirror of
https://github.com/intrepidcs/libicsneo.git
synced 2026-11-04 12:59:07 +01:00
Compare commits
72
Commits
1.3.0
..
dffb0bcefb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dffb0bcefb | ||
|
|
f4fe69f992 | ||
|
|
7ff14ae86d | ||
|
|
5c61a3b3c1 | ||
|
|
320fec74bd | ||
|
|
fd8f7b328f | ||
|
|
6ac041cadc | ||
|
|
4db27aa187 | ||
|
|
1d3039775d | ||
|
|
fb241dc5cd | ||
|
|
3932b54947 | ||
|
|
f4836f279f | ||
|
|
7ef57e6737 | ||
|
|
4c0781190e | ||
|
|
0a67c9cf5d | ||
|
|
f310938684 | ||
|
|
f0b1341cdf | ||
|
|
b54bf80c40 | ||
|
|
0164cef376 | ||
|
|
8cd907250d | ||
|
|
bb892bfd9b | ||
|
|
8801e949da | ||
|
|
d95a17b360 | ||
|
|
3a6501d116 | ||
|
|
34875129ee | ||
|
|
236c6ad089 | ||
|
|
cf58f819cb | ||
|
|
07e4eca14a | ||
|
|
936566170f | ||
|
|
3aaacb6cc8 | ||
|
|
1dda9f5412 | ||
|
|
78c2e3ff89 | ||
|
|
afedd4bb1f | ||
|
|
9b01e488da | ||
|
|
77a886bbe0 | ||
|
|
aff547b738 | ||
|
|
7a5c8c2879 | ||
|
|
0dd8dbfb64 | ||
|
|
d708f8081a | ||
|
|
743246e813 | ||
|
|
4ed29b4a5e | ||
|
|
55d69246b0 | ||
|
|
19232def41 | ||
|
|
9d91524dc0 | ||
|
|
d86e3164af | ||
|
|
3d99898598 | ||
|
|
4b9cf1a37f | ||
|
|
40d83f3b7c | ||
|
|
60918c4b6d | ||
|
|
749552e443 | ||
|
|
8af6d5f2a8 | ||
|
|
54fb89b675 | ||
|
|
299766403f | ||
|
|
2d0b0c63ed | ||
|
|
30606be7a8 | ||
|
|
4dd97f734a | ||
|
|
44d0e3de64 | ||
|
|
023f5aa089 | ||
|
|
bb711ae7e2 | ||
|
|
476b5ff35c | ||
|
|
99792a0ee1 | ||
|
|
d42c51d772 | ||
|
|
3ab06199c3 | ||
|
|
49e578a657 | ||
|
|
0bf279c7b9 | ||
|
|
9de0cf688c | ||
|
|
eded388b83 | ||
|
|
00b7b4a6de | ||
|
|
0ecb360195 | ||
|
|
b3bb033ecb | ||
|
|
c3762bbf22 | ||
|
|
e926e10dc5 |
+23
-48
@@ -1,3 +1,6 @@
|
||||
default:
|
||||
interruptible: true
|
||||
|
||||
variables:
|
||||
DEBIAN_FRONTEND: noninteractive
|
||||
LIBICSNEO_ICSPB_REPO: https://gitlab-ci-token:${CI_JOB_TOKEN}@${LIBICSNEO_ICSPB_GIT}
|
||||
@@ -35,30 +38,6 @@ unit_test windows/x64:
|
||||
- libicsneo-win-x64
|
||||
timeout: 5m
|
||||
|
||||
build windows/x86:
|
||||
stage: build
|
||||
script:
|
||||
- cmd /C ci\build-windows32.bat
|
||||
artifacts:
|
||||
when: always
|
||||
paths:
|
||||
- build
|
||||
expire_in: 3 days
|
||||
tags:
|
||||
- libicsneo-win-x64
|
||||
|
||||
unit_test windows/x86:
|
||||
stage: unit_test
|
||||
script:
|
||||
- build\libicsneo-unit-tests.exe
|
||||
dependencies:
|
||||
- build windows/x86
|
||||
needs:
|
||||
- build windows/x86
|
||||
tags:
|
||||
- libicsneo-win-x64
|
||||
timeout: 5m
|
||||
|
||||
#-------------------------------------------------------------------------------
|
||||
# Ubuntu
|
||||
#-------------------------------------------------------------------------------
|
||||
@@ -68,7 +47,7 @@ unit_test windows/x86:
|
||||
script:
|
||||
- apt update -y
|
||||
- apt upgrade -y
|
||||
- apt install -y g++ ninja-build cmake libpcap-dev git ca-certificates
|
||||
- apt install -y g++ ninja-build cmake git ca-certificates
|
||||
- echo "$ICS_IPA_CA_CRT" >/usr/local/share/ca-certificates/ica-ipa-ca.crt
|
||||
- update-ca-certificates --fresh
|
||||
- sh ci/build-posix.sh
|
||||
@@ -85,7 +64,6 @@ unit_test windows/x86:
|
||||
script:
|
||||
- apt update -y
|
||||
- apt upgrade -y
|
||||
- apt install -y libpcap-dev
|
||||
- build/libicsneo-unit-tests
|
||||
tags:
|
||||
- linux-build
|
||||
@@ -96,7 +74,7 @@ unit_test windows/x86:
|
||||
script:
|
||||
- apt update -y
|
||||
- apt upgrade -y
|
||||
- apt install -y clang lld ninja-build cmake libpcap-dev git ca-certificates
|
||||
- apt install -y clang lld ninja-build cmake git ca-certificates
|
||||
- echo "$ICS_IPA_CA_CRT" >/usr/local/share/ca-certificates/ica-ipa-ca.crt
|
||||
- update-ca-certificates --fresh
|
||||
- CC=clang CXX=clang++ LDFLAGS=-fuse-ld=lld sh ci/build-posix.sh
|
||||
@@ -113,7 +91,6 @@ unit_test windows/x86:
|
||||
script:
|
||||
- apt update -y
|
||||
- apt upgrade -y
|
||||
- apt install -y libpcap-dev
|
||||
- build/libicsneo-unit-tests
|
||||
tags:
|
||||
- linux-build
|
||||
@@ -180,7 +157,7 @@ unit_test linux/ubuntu/2604/amd64/clang:
|
||||
- echo max_parallel_downloads=10 >>/etc/dnf/dnf.conf
|
||||
- echo fastestmirror=True >>/etc/dnf/dnf.conf
|
||||
- dnf upgrade -y
|
||||
- dnf install -y g++ libpcap-devel cmake ninja-build git ca-certificates
|
||||
- dnf install -y g++ cmake ninja-build git ca-certificates
|
||||
- echo "$ICS_IPA_CA_CRT" >/etc/pki/ca-trust/source/anchors/ica-ipa-ca.crt
|
||||
- update-ca-trust
|
||||
- sh ci/build-posix.sh
|
||||
@@ -201,7 +178,6 @@ unit_test linux/ubuntu/2604/amd64/clang:
|
||||
- echo max_parallel_downloads=10 >>/etc/dnf/dnf.conf
|
||||
- echo fastestmirror=True >>/etc/dnf/dnf.conf
|
||||
- dnf upgrade -y
|
||||
- dnf install -y libpcap-devel
|
||||
- build/libicsneo-unit-tests
|
||||
tags:
|
||||
- linux-build
|
||||
@@ -216,7 +192,7 @@ unit_test linux/ubuntu/2604/amd64/clang:
|
||||
- echo max_parallel_downloads=10 >>/etc/dnf/dnf.conf
|
||||
- echo fastestmirror=True >>/etc/dnf/dnf.conf
|
||||
- dnf upgrade -y
|
||||
- dnf install -y clang lld libpcap-devel cmake ninja-build git ca-certificates
|
||||
- dnf install -y clang lld cmake ninja-build git ca-certificates
|
||||
- echo "$ICS_IPA_CA_CRT" >/etc/pki/ca-trust/source/anchors/ica-ipa-ca.crt
|
||||
- update-ca-trust
|
||||
- CC=clang CXX=clang++ LDFLAGS=-fuse-ld=lld sh ci/build-posix.sh
|
||||
@@ -237,7 +213,6 @@ unit_test linux/ubuntu/2604/amd64/clang:
|
||||
- echo max_parallel_downloads=10 >>/etc/dnf/dnf.conf
|
||||
- echo fastestmirror=True >>/etc/dnf/dnf.conf
|
||||
- dnf upgrade -y
|
||||
- dnf install -y libpcap-devel
|
||||
- build/libicsneo-unit-tests
|
||||
tags:
|
||||
- linux-build
|
||||
@@ -300,12 +275,9 @@ build python/linux/amd64:
|
||||
tags:
|
||||
- linux-native-amd64
|
||||
variables:
|
||||
CIBW_BEFORE_ALL: sh ci/bootstrap-cibuildwheel.sh && sh ci/bootstrap-libpcap.sh
|
||||
CIBW_BUILD: "*manylinux*" # no musl
|
||||
CIBW_ARCHS: x86_64
|
||||
CIBW_ENVIRONMENT: CMAKE_PREFIX_PATH=/project/libpcap/install
|
||||
script:
|
||||
- sh ci/build-wheel-posix.sh
|
||||
- sh ci/build-wheel-linux.sh
|
||||
artifacts:
|
||||
paths:
|
||||
- wheelhouse
|
||||
@@ -315,12 +287,9 @@ build python/linux/arm64:
|
||||
tags:
|
||||
- arm64-linux-build
|
||||
variables:
|
||||
CIBW_BEFORE_ALL: sh ci/bootstrap-cibuildwheel.sh && sh ci/bootstrap-libpcap.sh
|
||||
CIBW_BUILD: "*manylinux*" # no musl
|
||||
CIBW_ARCHS: aarch64
|
||||
CIBW_ENVIRONMENT: CMAKE_PREFIX_PATH=/project/libpcap/install
|
||||
script:
|
||||
- sh ci/build-wheel-posix.sh
|
||||
- sh ci/build-wheel-linux.sh
|
||||
artifacts:
|
||||
paths:
|
||||
- wheelhouse
|
||||
@@ -329,13 +298,8 @@ build python/macos:
|
||||
stage: build
|
||||
tags:
|
||||
- macos-arm64
|
||||
variables:
|
||||
CIBW_BEFORE_ALL: sh ci/bootstrap-libpcap.sh
|
||||
CIBW_ARCHS: arm64
|
||||
CIBW_ENVIRONMENT: CMAKE_PREFIX_PATH=$CI_PROJECT_DIR/libpcap/install
|
||||
MACOSX_DEPLOYMENT_TARGET: 10.14
|
||||
script:
|
||||
- sh ci/build-wheel-posix.sh
|
||||
- sh ci/build-wheel-macos.sh
|
||||
artifacts:
|
||||
paths:
|
||||
- wheelhouse
|
||||
@@ -347,6 +311,7 @@ build python/windows:
|
||||
variables:
|
||||
CIBW_ARCHS: AMD64
|
||||
CIBW_ENVIRONMENT: CMAKE_GENERATOR=Ninja
|
||||
SKBUILD_CMAKE_DEFINE: ICSPB_BOOTSTRAP_DIR=$CI_PROJECT_DIR/icspb
|
||||
script:
|
||||
- cmd /c ci\build-wheel-windows.bat
|
||||
artifacts:
|
||||
@@ -355,6 +320,7 @@ build python/windows:
|
||||
|
||||
deploy python/pypi:
|
||||
stage: deploy
|
||||
interruptible: false
|
||||
variables:
|
||||
TWINE_USERNAME: __token__
|
||||
TWINE_PASSWORD: $PYPI_TOKEN
|
||||
@@ -363,9 +329,10 @@ deploy python/pypi:
|
||||
image: python:3.13
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
- if: $CI_COMMIT_TAG
|
||||
script:
|
||||
- python3 -m pip install -U twine
|
||||
- twine upload wheelhouse/*
|
||||
- twine upload --verbose wheelhouse/*
|
||||
dependencies:
|
||||
- build python/linux/amd64
|
||||
- build python/linux/arm64
|
||||
@@ -379,6 +346,7 @@ deploy python/pypi:
|
||||
|
||||
push github:
|
||||
stage: deploy
|
||||
interruptible: false
|
||||
tags:
|
||||
- linux-build
|
||||
image: alpine:latest
|
||||
@@ -386,10 +354,17 @@ push github:
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
when: delayed
|
||||
start_in: 10 minutes
|
||||
variables:
|
||||
REFSPEC: HEAD:master
|
||||
- if: $CI_COMMIT_TAG
|
||||
when: delayed
|
||||
start_in: 10 minutes
|
||||
variables:
|
||||
REFSPEC: $CI_COMMIT_TAG
|
||||
dependencies:
|
||||
- deploy python/pypi
|
||||
needs:
|
||||
- deploy python/pypi
|
||||
script:
|
||||
- apk add git
|
||||
- git push https://$LIBICSNEO_GITHUB_USERNAME:$LIBICSNEO_GITHUB_TOKEN@github.com/intrepidcs/libicsneo.git HEAD:master
|
||||
- git push https://$LIBICSNEO_GITHUB_USERNAME:$LIBICSNEO_GITHUB_TOKEN@github.com/intrepidcs/libicsneo.git $REFSPEC
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
# Intrepid Control System, Inc. neoVI Devices
|
||||
SUBSYSTEM=="usb", ATTRS{idVendor}=="093c", GROUP="users", MODE="0666"
|
||||
KERNEL=="ttyUSB?", ATTRS{idVendor}=="093c", GROUP="users", MODE="0666"
|
||||
KERNEL=="ttyACM?", ATTRS{idVendor}=="093c", GROUP="users", MODE="0666"
|
||||
|
||||
ACTION=="add", SUBSYSTEMS=="usb", ATTRS{idVendor}=="093c", KERNEL=="ttyUSB*", \
|
||||
RUN+="/bin/sh -c 'echo $id:1.0>/sys/bus/usb/drivers/ftdi_sio/unbind'"
|
||||
|
||||
ACTION=="add", SUBSYSTEMS=="usb", ATTRS{idVendor}=="093c", DRIVER=="usbhid", \
|
||||
RUN+="/bin/sh -c 'echo $id:1.0>/sys/bus/usb/drivers/usbhid/unbind'"
|
||||
+132
-147
@@ -1,5 +1,43 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(libicsneo VERSION 1.0.0)
|
||||
|
||||
function(git_tag_version VERSION_RESULT)
|
||||
set(${VERSION_RESULT} "0.0.0.0" PARENT_SCOPE)
|
||||
find_package(Git)
|
||||
if(NOT Git_FOUND)
|
||||
return()
|
||||
endif()
|
||||
execute_process(
|
||||
COMMAND ${GIT_EXECUTABLE} describe --tags --abbrev=0
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
OUTPUT_VARIABLE LAST_TAG
|
||||
RESULT_VARIABLE RESULT
|
||||
ERROR_QUIET
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
if(NOT RESULT EQUAL 0)
|
||||
return()
|
||||
endif()
|
||||
execute_process(
|
||||
COMMAND ${GIT_EXECUTABLE} rev-list ${LAST_TAG}..HEAD --count
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
OUTPUT_VARIABLE COMMIT_COUNT_SINCE_TAG
|
||||
RESULT_VARIABLE RESULT
|
||||
ERROR_QUIET
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
if(NOT RESULT EQUAL 0)
|
||||
return()
|
||||
endif()
|
||||
set(${VERSION_RESULT} "${LAST_TAG}.${COMMIT_COUNT_SINCE_TAG}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
git_tag_version(LIBICSNEO_VERSION)
|
||||
|
||||
if(LIBICSNEO_VERSION STREQUAL "0.0.0.0")
|
||||
message(WARNING "Unable to parse version from git history")
|
||||
endif()
|
||||
|
||||
project(libicsneo VERSION ${LIBICSNEO_VERSION})
|
||||
|
||||
cmake_policy(SET CMP0074 NEW)
|
||||
if(POLICY CMP0135)
|
||||
@@ -15,22 +53,20 @@ option(LIBICSNEO_BUILD_ICSNEOC2 "Build dynamic C2 library" ON)
|
||||
option(LIBICSNEO_BUILD_ICSNEOC2_STATIC "Build static C2 library" ON)
|
||||
option(LIBICSNEO_BUILD_ICSNEOLEGACY "Build icsnVC40 compatibility library" ON)
|
||||
option(LIBICSNEO_BUILD_ICSNEOLEGACY_STATIC "Build static icsnVC40 compatibility library" ON)
|
||||
set(LIBICSNEO_NPCAP_INCLUDE_DIR "" CACHE STRING "Npcap include directory; set to build with Npcap")
|
||||
|
||||
# Device Drivers
|
||||
# You almost certainly don't want firmio for your build,
|
||||
# it is only relevant for communication between Linux and
|
||||
# CoreMini from the onboard processor of the device.
|
||||
option(LIBICSNEO_ENABLE_FIRMIO "Enable communication between Linux and CoreMini within the same device" OFF)
|
||||
option(LIBICSNEO_ENABLE_RAW_ETHERNET "Enable devices which communicate over raw ethernet" ON)
|
||||
option(LIBICSNEO_ENABLE_CDCACM "Enable devices which communicate over USB CDC ACM" ON)
|
||||
option(LIBICSNEO_ENABLE_TCP "Enable devices which communicate over TCP" OFF)
|
||||
option(LIBICSNEO_ENABLE_DXX "Enable devices which communicate over D2XX/D3XX via libredxx" ON)
|
||||
|
||||
option(LIBICSNEO_ENABLE_BINDINGS_PYTHON "Enable Python library" OFF)
|
||||
|
||||
option(LIBICSNEO_ENABLE_BOOTLOADER "Enable bootloader firmware update support" OFF)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded")
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
@@ -44,7 +80,7 @@ if(MSVC)
|
||||
add_definitions(-D_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING)
|
||||
add_definitions(-D_ITERATOR_DEBUG_LEVEL=0)
|
||||
else() #if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
|
||||
set(LIBICSNEO_COMPILER_WARNINGS -Wall -Wno-switch -Wno-unknown-pragmas)
|
||||
set(LIBICSNEO_COMPILER_WARNINGS -Wall -Wno-unknown-pragmas)
|
||||
endif()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
@@ -104,82 +140,10 @@ if(LIBICSNEO_BUILD_DOCS)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
set(PLATFORM_SRC
|
||||
platform/windows/strings.cpp
|
||||
platform/windows/registry.cpp
|
||||
)
|
||||
|
||||
if(LIBICSNEO_ENABLE_RAW_ETHERNET)
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/windows/pcap.cpp
|
||||
platform/windows/internal/pcapdll.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_ENABLE_CDCACM)
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/windows/cdcacm.cpp
|
||||
)
|
||||
endif()
|
||||
else() # Darwin or Linux
|
||||
set(PLATFORM_SRC)
|
||||
|
||||
if(LIBICSNEO_ENABLE_FIRMIO)
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/posix/firmio.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_ENABLE_RAW_ETHERNET)
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/posix/pcap.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_ENABLE_CDCACM)
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/posix/cdcacm.cpp
|
||||
)
|
||||
|
||||
if(${CMAKE_SYSTEM_NAME} STREQUAL "Darwin")
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/posix/darwin/cdcacmdarwin.cpp
|
||||
)
|
||||
else() # Linux or other
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/posix/linux/cdcacmlinux.cpp
|
||||
)
|
||||
if(NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
|
||||
message(WARNING
|
||||
"There is no CDCACM platform port defined for ${CMAKE_SYSTEM_NAME}!\n"
|
||||
"The Linux platform code will be used, as it will generally allow building, but some devices may not enumerate properly."
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
if(LIBICSNEO_ENABLE_FIRMIO AND NOT WIN32)
|
||||
set(PLATFORM_SRC platform/posix/firmio.cpp)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_ENABLE_DXX)
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/dxx.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_ENABLE_TCP)
|
||||
list(APPEND PLATFORM_SRC
|
||||
platform/tcp.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
# Extensions
|
||||
set(LIBICSNEO_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
foreach(EXT_PATH ${LIBICSNEO_EXTENSION_DIRS})
|
||||
get_filename_component(EXT_DIR ${EXT_PATH} NAME)
|
||||
message("Adding extension " ${EXT_DIR})
|
||||
add_subdirectory(${EXT_PATH} ${CMAKE_CURRENT_BINARY_DIR}/${EXT_DIR})
|
||||
endforeach()
|
||||
|
||||
set(SRC_FILES
|
||||
communication/message/flexray/control/flexraycontrolmessage.cpp
|
||||
communication/message/callback/streamoutput/a2bwavoutput.cpp
|
||||
@@ -192,10 +156,18 @@ set(SRC_FILES
|
||||
communication/message/logdatamessage.cpp
|
||||
communication/message/tc10statusmessage.cpp
|
||||
communication/message/gptpstatusmessage.cpp
|
||||
communication/message/allmacaddressesmessage.cpp
|
||||
communication/message/ethernetstatusmessage.cpp
|
||||
communication/message/networkmutexmessage.cpp
|
||||
communication/message/clientidmessage.cpp
|
||||
communication/message/mfgconfigmessage.cpp
|
||||
communication/message/transmitmessage.cpp
|
||||
|
||||
|
||||
communication/message/spiportkeymessage.cpp
|
||||
communication/message/genericapidatamessage.cpp
|
||||
communication/message/genericapistatusmessage.cpp
|
||||
communication/message/iso15765message.cpp
|
||||
communication/packet/flexraypacket.cpp
|
||||
communication/packet/canpacket.cpp
|
||||
communication/packet/a2bpacket.cpp
|
||||
@@ -260,6 +232,28 @@ set(SRC_FILES
|
||||
${PLATFORM_SRC}
|
||||
)
|
||||
|
||||
if(LIBICSNEO_ENABLE_BOOTLOADER)
|
||||
list(APPEND SRC_FILES
|
||||
device/extensions/bootloader/api.cpp
|
||||
device/extensions/bootloader/version.cpp
|
||||
device/extensions/bootloader/platform/logging.cpp
|
||||
device/extensions/bootloader/parser/ief.cpp
|
||||
device/extensions/bootloader/parser/fwzip.cpp
|
||||
device/extensions/bootloader/parser/fwbin.cpp
|
||||
device/extensions/bootloader/parser/fwbundle.cpp
|
||||
device/extensions/bootloader/parser/fwloader.cpp
|
||||
device/extensions/bootloader/communication/red.cpp
|
||||
device/extensions/bootloader/communication/radmultichipcommunication.cpp
|
||||
device/extensions/bootloader/communication/communication.cpp
|
||||
device/extensions/bootloader/communication/radperiphcommunication.cpp
|
||||
device/extensions/bootloader/communication/radcommunication.cpp
|
||||
device/extensions/bootloader/communication/redpacketizer.cpp
|
||||
device/extensions/bootloader/communication/redcore.cpp
|
||||
device/extensions/bootloader/communication/application.cpp
|
||||
device/extensions/bootloader/communication/redbase.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
# Generate build info header
|
||||
execute_process(
|
||||
COMMAND git rev-parse --abbrev-ref HEAD
|
||||
@@ -289,98 +283,34 @@ configure_file(api/icsneocpp/buildinfo.h.template ${CMAKE_CURRENT_BINARY_DIR}/ge
|
||||
configure_file(api/icsneoc/version.rc.template ${CMAKE_CURRENT_BINARY_DIR}/generated/icsneoc/version.rc)
|
||||
configure_file(api/icsneoc2/version.rc.template ${CMAKE_CURRENT_BINARY_DIR}/generated/icsneoc2/version.rc)
|
||||
|
||||
foreach(EXTINC ${LIBICSNEO_EXTENSION_INCLUDES})
|
||||
message("Including " ${EXTINC})
|
||||
list(APPEND LIBICSNEO_EXT_CODE_INCS_LIST "#include \"${EXTINC}\"")
|
||||
endforeach()
|
||||
list(JOIN LIBICSNEO_EXT_CODE_INCS_LIST "\n" LIBICSNEO_EXT_CODE_INCS)
|
||||
foreach(EXTCLASS ${LIBICSNEO_EXTENSION_CLASSES})
|
||||
list(APPEND LIBICSNEO_EXT_CODE_LIST "device->addExtension(std::make_shared<${EXTCLASS}>(*device))\;")
|
||||
endforeach()
|
||||
list(JOIN LIBICSNEO_EXT_CODE_LIST "\n\t" LIBICSNEO_EXT_CODE)
|
||||
configure_file(include/icsneo/device/extensions/builtin.h.template ${CMAKE_CURRENT_BINARY_DIR}/generated/extensions/builtin.h)
|
||||
|
||||
include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
add_library(icsneocpp
|
||||
api/icsneocpp/icsneocpp.cpp
|
||||
api/icsneocpp/event.cpp
|
||||
api/icsneocpp/eventmanager.cpp
|
||||
api/icsneocpp/heartbeat.cpp
|
||||
api/icsneocpp/version.cpp
|
||||
${SRC_FILES}
|
||||
)
|
||||
message("Include paths " ${LIBICSNEO_EXTENSION_INCLUDE_PATHS})
|
||||
target_include_directories(icsneocpp
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:>
|
||||
PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
${LIBICSNEO_EXTENSION_INCLUDE_PATHS}
|
||||
)
|
||||
target_link_libraries(icsneocpp PUBLIC Threads::Threads $<$<BOOL:${WIN32}>:ws2_32 iphlpapi>)
|
||||
set_property(TARGET icsneocpp PROPERTY POSITION_INDEPENDENT_CODE ON)
|
||||
target_compile_features(icsneocpp PUBLIC cxx_auto_type cxx_constexpr cxx_lambdas cxx_nullptr cxx_range_for cxx_rvalue_references cxx_sizeof_member cxx_strong_enums)
|
||||
target_compile_options(icsneocpp PRIVATE ${LIBICSNEO_COMPILER_WARNINGS})
|
||||
message("Loaded extensions: " ${LIBICSNEO_EXTENSION_TARGETS})
|
||||
target_link_libraries(icsneocpp PUBLIC ${LIBICSNEO_EXTENSION_TARGETS})
|
||||
if(LIBICSNEO_ENABLE_FIRMIO)
|
||||
target_compile_definitions(icsneocpp PRIVATE ICSNEO_ENABLE_FIRMIO)
|
||||
endif()
|
||||
if(LIBICSNEO_ENABLE_RAW_ETHERNET)
|
||||
target_compile_definitions(icsneocpp PRIVATE ICSNEO_ENABLE_RAW_ETHERNET)
|
||||
endif()
|
||||
if(LIBICSNEO_ENABLE_CDCACM)
|
||||
target_compile_definitions(icsneocpp PRIVATE ICSNEO_ENABLE_CDCACM)
|
||||
if(APPLE)
|
||||
find_library(CORE_FOUNDATION_FRAMEWORK CoreFoundation REQUIRED)
|
||||
find_library(IO_KIT_FRAMEWORK IOKit REQUIRED)
|
||||
target_link_libraries(icsneocpp PRIVATE ${CORE_FOUNDATION_FRAMEWORK} ${IO_KIT_FRAMEWORK})
|
||||
endif()
|
||||
endif()
|
||||
if(LIBICSNEO_ENABLE_DXX)
|
||||
target_compile_definitions(icsneocpp PRIVATE ICSNEO_ENABLE_DXX)
|
||||
target_link_libraries(icsneocpp PRIVATE libredxx::libredxx)
|
||||
endif()
|
||||
if(LIBICSNEO_ENABLE_TCP)
|
||||
target_compile_definitions(icsneocpp PRIVATE ICSNEO_ENABLE_TCP)
|
||||
if(WIN32)
|
||||
target_link_libraries(icsneocpp PRIVATE ws2_32 iphlpapi)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# fatfs
|
||||
add_subdirectory(third-party/fatfs)
|
||||
set_property(TARGET fatfs PROPERTY POSITION_INDEPENDENT_CODE ON)
|
||||
target_link_libraries(icsneocpp PRIVATE fatfs)
|
||||
|
||||
# dxx
|
||||
if(LIBICSNEO_ENABLE_DXX)
|
||||
include(FetchContent)
|
||||
FetchContent_Declare(libredxx
|
||||
GIT_REPOSITORY https://github.com/Zeranoe/libredxx.git
|
||||
GIT_TAG e823a96c39a64ab41b7d1632dbe8f86bb854df83
|
||||
)
|
||||
set(LIBREDXX_DISABLE_INSTALL ON)
|
||||
FetchContent_MakeAvailable(libredxx)
|
||||
endif()
|
||||
|
||||
# pcap
|
||||
if(LIBICSNEO_ENABLE_RAW_ETHERNET)
|
||||
if(WIN32)
|
||||
if(LIBICSNEO_NPCAP_INCLUDE_DIR STREQUAL "")
|
||||
target_include_directories(icsneocpp PUBLIC AFTER third-party/winpcap/include)
|
||||
add_definitions(-DWPCAP -DHAVE_REMOTE)
|
||||
else()
|
||||
target_include_directories(icsneocpp PUBLIC AFTER ${LIBICSNEO_NPCAP_INCLUDE_DIR})
|
||||
endif()
|
||||
else()
|
||||
find_package(PCAP REQUIRED)
|
||||
target_include_directories(icsneocpp PUBLIC ${PCAP_INCLUDE_DIR})
|
||||
target_link_libraries(icsneocpp PUBLIC ${PCAP_LIBRARY})
|
||||
endif(WIN32)
|
||||
endif(LIBICSNEO_ENABLE_RAW_ETHERNET)
|
||||
|
||||
# protobuf
|
||||
if(DEFINED ENV{LIBICSNEO_ICSPB_REPO})
|
||||
set(LIBICSNEO_ICSPB_REPO "$ENV{LIBICSNEO_ICSPB_REPO}")
|
||||
@@ -396,6 +326,59 @@ FetchContent_Declare(icspb
|
||||
FetchContent_MakeAvailable(icspb)
|
||||
target_link_libraries(icsneocpp PRIVATE icspb::icspb)
|
||||
|
||||
# libicsbl
|
||||
if(LIBICSNEO_ENABLE_BOOTLOADER)
|
||||
if(NOT LIBICSNEO_LIBICSBL_ZIP_URL)
|
||||
if(DEFINED ENV{LIBICSNEO_LIBICSBL_ZIP_URL})
|
||||
set(LIBICSNEO_LIBICSBL_ZIP_URL "$ENV{LIBICSNEO_LIBICSBL_ZIP_URL}")
|
||||
else()
|
||||
if(NOT LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX)
|
||||
if(DEFINED ENV{LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX})
|
||||
set(LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX "$ENV{LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX}")
|
||||
else()
|
||||
set(LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX "https://cdn.intrepidcs.net/libicsbl/5ce699ada0ccaadb92cabda6e3537c09b333020e")
|
||||
endif()
|
||||
endif()
|
||||
if(NOT LIBICSNEO_LIBICSBL_VERSION)
|
||||
if(DEFINED ENV{LIBICSNEO_LIBICSBL_VERSION})
|
||||
set(LIBICSNEO_LIBICSBL_VERSION "$ENV{LIBICSNEO_LIBICSBL_VERSION}")
|
||||
else()
|
||||
set(LIBICSNEO_LIBICSBL_VERSION "26.4.0")
|
||||
endif()
|
||||
endif()
|
||||
if(WIN32)
|
||||
if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8 OR CMAKE_CXX_COMPILER_ARCHITECTURE_ID MATCHES "ARM")
|
||||
message(FATAL_ERROR "Unsupported bootloader architecture: ${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}")
|
||||
endif()
|
||||
set(LIBICSNEO_LIBICSBL_ZIP_URL "${LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX}/libicsbl-${LIBICSNEO_LIBICSBL_VERSION}-windows-amd64.zip")
|
||||
elseif(APPLE)
|
||||
set(LIBICSNEO_LIBICSBL_ZIP_URL "${LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX}/libicsbl-${LIBICSNEO_LIBICSBL_VERSION}-macos-universal.zip")
|
||||
else()
|
||||
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
|
||||
set(LIBICSNEO_LIBICSBL_ZIP_URL "${LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX}/libicsbl-${LIBICSNEO_LIBICSBL_VERSION}-linux-x86_64-glibc.zip")
|
||||
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
|
||||
set(LIBICSNEO_LIBICSBL_ZIP_URL "${LIBICSNEO_LIBICSBL_ZIP_URL_PREFIX}/libicsbl-${LIBICSNEO_LIBICSBL_VERSION}-linux-aarch64-glibc.zip")
|
||||
else()
|
||||
message(FATAL_ERROR "Unsupported CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
FetchContent_Declare(
|
||||
libicsbl
|
||||
URL "${LIBICSNEO_LIBICSBL_ZIP_URL}"
|
||||
)
|
||||
FetchContent_MakeAvailable(libicsbl)
|
||||
set(libicsbl_ROOT "${libicsbl_SOURCE_DIR}")
|
||||
find_package(libicsbl CONFIG REQUIRED)
|
||||
target_link_libraries(icsneocpp PUBLIC libicsbl::icsbl)
|
||||
|
||||
# miniz
|
||||
add_subdirectory(third-party/miniz)
|
||||
target_link_libraries(icsneocpp PRIVATE miniz)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_ICSNEOC)
|
||||
add_library(icsneoc SHARED api/icsneoc/icsneoc.cpp ${CMAKE_CURRENT_BINARY_DIR}/generated/icsneoc/version.rc)
|
||||
target_include_directories(icsneoc
|
||||
@@ -523,10 +506,12 @@ if(LIBICSNEO_BUILD_UNIT_TESTS)
|
||||
test/unit/a2bencoderdecodertest.cpp
|
||||
test/unit/mdioencoderdecodertest.cpp
|
||||
test/unit/livedataencoderdecodertest.cpp
|
||||
test/unit/macsectest.cpp
|
||||
test/unit/ringbuffertest.cpp
|
||||
test/unit/apperrordecodertest.cpp
|
||||
test/unit/icsneoc2.cpp
|
||||
test/unit/windowsstrings.cpp
|
||||
test/unit/ethphyregistertest.cpp
|
||||
test/unit/tc10test.cpp
|
||||
test/unit/periodictest.cpp
|
||||
)
|
||||
|
||||
|
||||
@@ -30,13 +30,13 @@ Instructions for installing each API can be found in its respective documentatio
|
||||
- neoVI PLASMA
|
||||
- neoVI RED 2
|
||||
- RAD-A2B
|
||||
- RAD-Argos
|
||||
- RAD-Comet 2
|
||||
- RAD-Comet 3
|
||||
- RAD-Epsilon
|
||||
- RAD-EpsilonXL
|
||||
- RAD-Galaxy
|
||||
- RAD-Galaxy 2
|
||||
- RAD-Gemini
|
||||
- RAD-Gigastar
|
||||
- RAD-Gigastar 2
|
||||
- RAD-Moon 2
|
||||
@@ -45,7 +45,7 @@ Instructions for installing each API can be found in its respective documentatio
|
||||
- RAD-Pluto
|
||||
- RAD-Star 2
|
||||
- RAD-SuperMoon
|
||||
- RADComet
|
||||
- RAD-wBMS
|
||||
- ValueCAN 3
|
||||
- ValueCAN 4
|
||||
|
||||
|
||||
+309
-22
@@ -5,6 +5,7 @@
|
||||
#include "icsneo/device/devicefinder.h"
|
||||
#include "icsneo/icsneocpp.h"
|
||||
#include "icsneo/communication/io.h"
|
||||
#include "icsneo/communication/network.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -12,8 +13,10 @@
|
||||
#include <map>
|
||||
#include <algorithm>
|
||||
#include <optional>
|
||||
#include <chrono>
|
||||
#include <sstream>
|
||||
#include <fstream>
|
||||
#include <cstring>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
@@ -69,6 +72,7 @@ icsneoc2_error_t icsneoc2_error_code_get(icsneoc2_error_t error_code, char* valu
|
||||
"Close failed", // icsneoc2_error_close_failed
|
||||
"Reconnect failed", // icsneoc2_error_reconnect_failed
|
||||
"Invalid data", // icsneoc2_error_invalid_data
|
||||
"Force disk config update failed", // icsneoc2_error_force_disk_config_update_failed
|
||||
};
|
||||
static_assert(std::size(error_strings) == icsneoc2_error_maxsize,
|
||||
"error_strings is out of sync with _icsneoc2_error_t enum - update both together");
|
||||
@@ -84,6 +88,61 @@ icsneoc2_error_t icsneoc2_error_code_get(icsneoc2_error_t error_code, char* valu
|
||||
return safe_str_copy(value, value_length, error_strings[error_code]) ? icsneoc2_error_success : icsneoc2_error_string_copy_failed;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_supported_devices_enumerate(icsneoc2_supported_device_t** supported_devices) {
|
||||
if(!supported_devices) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
|
||||
auto device_types = DeviceFinder::GetSupportedDevices();
|
||||
icsneoc2_supported_device_t* head = nullptr;
|
||||
icsneoc2_supported_device_t* tail = nullptr;
|
||||
for(auto& device_type : device_types) {
|
||||
auto* node = new (std::nothrow) icsneoc2_supported_device_t;
|
||||
if(!node) {
|
||||
return icsneoc2_error_out_of_memory;
|
||||
}
|
||||
node->device_type = device_type;
|
||||
node->next = nullptr;
|
||||
if(!head) {
|
||||
head = node;
|
||||
} else {
|
||||
tail->next = node;
|
||||
}
|
||||
tail = node;
|
||||
}
|
||||
|
||||
*supported_devices = head;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_supported_devices_free(icsneoc2_supported_device_t* supported_devices) {
|
||||
if(!supported_devices) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
|
||||
while(supported_devices) {
|
||||
auto* next = supported_devices->next;
|
||||
delete supported_devices;
|
||||
supported_devices = next;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_supported_device_t* icsneoc2_supported_devices_next(const icsneoc2_supported_device_t* supported_device) {
|
||||
if(!supported_device) {
|
||||
return nullptr;
|
||||
}
|
||||
return supported_device->next;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_supported_device_get(const icsneoc2_supported_device_t* supported_device, icsneoc2_devicetype_t* device_type) {
|
||||
if(!supported_device || !device_type) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
*device_type = static_cast<icsneoc2_devicetype_t>(supported_device->device_type);
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_type_name_get(icsneoc2_devicetype_t device_type, char* value, size_t* value_length) {
|
||||
if(!value || !value_length) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
@@ -214,7 +273,9 @@ static icsneoc2_error_t open_device_with_options(std::shared_ptr<Device> dev, ic
|
||||
if(!dev) {
|
||||
return icsneoc2_error_invalid_device;
|
||||
}
|
||||
if(!dev->enableMessagePolling(std::make_optional<MessageFilter>())) {
|
||||
MessageFilter filter;
|
||||
filter.includeInternalInAny = true;
|
||||
if(!dev->enableMessagePolling(std::make_optional(filter))) {
|
||||
return icsneoc2_error_enable_message_polling_failed;
|
||||
}
|
||||
if(!dev->isOpen() && !dev->open()) {
|
||||
@@ -251,12 +312,12 @@ icsneoc2_error_t icsneoc2_device_open_serial(const char* serial, icsneoc2_open_o
|
||||
std::string_view target(serial);
|
||||
for(auto* cur = devs; cur; cur = cur->next) {
|
||||
if(cur->device && cur->device->getSerial() == target) {
|
||||
if (res = icsneoc2_device_create(cur, device); res != icsneoc2_error_success) {
|
||||
if(res = icsneoc2_device_create(cur, device); res != icsneoc2_error_success) {
|
||||
icsneoc2_enumeration_free(devs);
|
||||
return res;
|
||||
}
|
||||
res = open_device_with_options((*device)->device, options);
|
||||
if (res != icsneoc2_error_success) {
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_device_free(*device);
|
||||
*device = nullptr;
|
||||
}
|
||||
@@ -279,12 +340,12 @@ icsneoc2_error_t icsneoc2_device_open_first(icsneoc2_devicetype_t device_type, i
|
||||
}
|
||||
for(auto* cur = devs; cur; cur = cur->next) {
|
||||
if(cur->device && !cur->device->isOpen()) {
|
||||
if (res = icsneoc2_device_create(cur, device); res != icsneoc2_error_success) {
|
||||
if(res = icsneoc2_device_create(cur, device); res != icsneoc2_error_success) {
|
||||
icsneoc2_enumeration_free(devs);
|
||||
return res;
|
||||
}
|
||||
res = open_device_with_options((*device)->device, options);
|
||||
if (res != icsneoc2_error_success) {
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_device_free(*device);
|
||||
*device = nullptr;
|
||||
}
|
||||
@@ -302,7 +363,7 @@ icsneoc2_error_t icsneoc2_device_reconnect(icsneoc2_device_t* device, icsneoc2_o
|
||||
return res;
|
||||
}
|
||||
// If the device is currently open, close it first before trying to reconnect
|
||||
if (device->device->isOpen()) {
|
||||
if(device->device->isOpen()) {
|
||||
res = icsneoc2_device_close(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
@@ -342,7 +403,7 @@ icsneoc2_error_t icsneoc2_device_free(icsneoc2_device_t* device) {
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if (device->device->isOpen()) {
|
||||
if(device->device->isOpen()) {
|
||||
res = icsneoc2_device_close(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
@@ -382,6 +443,16 @@ icsneoc2_error_t icsneoc2_device_serial_get(const icsneoc2_device_t* device, cha
|
||||
return safe_str_copy(value, value_length, dev->getSerial()) ? icsneoc2_error_success : icsneoc2_error_string_copy_failed;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_product_name_get(const icsneoc2_device_t* device, char* value, size_t* value_length) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
auto dev = device->device;
|
||||
// Copy the string into value
|
||||
return safe_str_copy(value, value_length, dev->getProductName()) ? icsneoc2_error_success : icsneoc2_error_string_copy_failed;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_pcb_serial_get(const icsneoc2_device_t* device, uint8_t* value, size_t* value_length) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
@@ -395,35 +466,94 @@ icsneoc2_error_t icsneoc2_device_pcb_serial_get(const icsneoc2_device_t* device,
|
||||
return icsneoc2_error_invalid_type;
|
||||
}
|
||||
const auto& data = *pcbSerial;
|
||||
if(value) {
|
||||
size_t copyLen = std::min(*value_length, data.size());
|
||||
std::copy(data.begin(), data.begin() + copyLen, value);
|
||||
if(!value) {
|
||||
*value_length = data.size();
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
*value_length = data.size();
|
||||
size_t copyLen = std::min(*value_length, data.size());
|
||||
std::copy(data.begin(), data.begin() + copyLen, value);
|
||||
*value_length = copyLen;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_mac_address_get(const icsneoc2_device_t* device, uint8_t* value, size_t* value_length) {
|
||||
icsneoc2_error_t icsneoc2_device_mac_addresses_enumerate(const icsneoc2_device_t* device, icsneoc2_mac_addr_entry_t** mac_entries) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value_length) {
|
||||
if(!mac_entries) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
auto macAddress = device->device->getMACAddress();
|
||||
if(!macAddress.has_value()) {
|
||||
const auto result = device->device->getMACAddresses();
|
||||
if(result.empty()) {
|
||||
return icsneoc2_error_invalid_type;
|
||||
}
|
||||
const auto& data = *macAddress;
|
||||
if(value) {
|
||||
size_t copyLen = std::min(*value_length, data.size());
|
||||
std::copy(data.begin(), data.begin() + copyLen, value);
|
||||
icsneoc2_mac_addr_entry_t* head = nullptr;
|
||||
icsneoc2_mac_addr_entry_t* tail = nullptr;
|
||||
for(auto addr_pair : result) {
|
||||
auto* node = new (std::nothrow) icsneoc2_mac_addr_entry_t;
|
||||
if(!node) {
|
||||
icsneoc2_mac_addresses_free(head);
|
||||
return icsneoc2_error_out_of_memory;
|
||||
}
|
||||
node->network_id = static_cast<uint16_t>(addr_pair.first);
|
||||
std::copy(addr_pair.second.begin(), addr_pair.second.end(), node->address);
|
||||
node->next = nullptr;
|
||||
if(!head) {
|
||||
head = node;
|
||||
} else {
|
||||
tail->next = node;
|
||||
}
|
||||
tail = node;
|
||||
}
|
||||
*value_length = data.size();
|
||||
*mac_entries = head;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_mac_network_id_get(const icsneoc2_mac_addr_entry_t* mac_address, icsneoc2_netid_t* network_id) {
|
||||
if(!mac_address || !network_id) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
const auto netid = static_cast<Network::NetID>(mac_address->network_id);
|
||||
*network_id = Network::GetCoreMiniNetworkFromNetID(netid).has_value()
|
||||
? mac_address->network_id
|
||||
: static_cast<icsneoc2_netid_t>(icsneoc2_netid_invalid);
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_mac_address_get(const icsneoc2_mac_addr_entry_t* mac_address, uint8_t* value, size_t* value_length) {
|
||||
if(!mac_address || !value_length) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(!value) {
|
||||
*value_length = static_cast<size_t>(ICSNEO_MAC_ADDRESS_LEN);
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
size_t copyLen = std::min(*value_length, static_cast<size_t>(ICSNEO_MAC_ADDRESS_LEN));
|
||||
std::copy(mac_address->address, mac_address->address + copyLen, value);
|
||||
*value_length = copyLen;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_mac_addr_entry_t* icsneoc2_mac_addresses_next(const icsneoc2_mac_addr_entry_t* mac_address) {
|
||||
if(!mac_address) {
|
||||
return nullptr;
|
||||
}
|
||||
return mac_address->next;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_mac_addresses_free(icsneoc2_mac_addr_entry_t* mac_address) {
|
||||
if(!mac_address) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
|
||||
while(mac_address) {
|
||||
auto* next = mac_address->next;
|
||||
delete mac_address;
|
||||
mac_address = next;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_go_online(const icsneoc2_device_t* device, bool go_online) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
@@ -671,15 +801,76 @@ icsneoc2_error_t icsneoc2_device_tc10_status_get(const icsneoc2_device_t* device
|
||||
if(!cpp_status.has_value()) {
|
||||
return icsneoc2_error_invalid_type;
|
||||
}
|
||||
if (sleep_status) {
|
||||
if(sleep_status) {
|
||||
*sleep_status = static_cast<icsneoc2_tc10_sleep_status_t>(cpp_status->sleepStatus);
|
||||
}
|
||||
if (wake_status) {
|
||||
if(wake_status) {
|
||||
*wake_status = static_cast<icsneoc2_tc10_wake_status_t>(cpp_status->wakeStatus);
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_supports_gptp(const icsneoc2_device_t* device, bool* supported) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!supported) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
*supported = device->device->supportsGPTP();
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_gptp_status_get(const icsneoc2_device_t* device, uint32_t timeout_ms, icsneoc2_gptp_status_t* status) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!status) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
auto cpp_status = device->device->getGPTPStatus(std::chrono::milliseconds(timeout_ms));
|
||||
if(!cpp_status.has_value()) {
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
status->current_time_seconds = cpp_status->currentTime.seconds;
|
||||
status->current_time_nanoseconds = cpp_status->currentTime.nanoseconds;
|
||||
status->ms_offset_ns = cpp_status->msOffsetNs;
|
||||
status->is_sync = cpp_status->isSync;
|
||||
status->link_status = cpp_status->linkStatus;
|
||||
status->link_delay_ns = cpp_status->linkDelayNS;
|
||||
status->selected_role = cpp_status->selectedRole;
|
||||
status->as_capable = cpp_status->asCapable;
|
||||
status->is_syntonized = cpp_status->isSyntonized;
|
||||
status->short_format = cpp_status->shortFormat;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_supports_reboot(const icsneoc2_device_t* device, bool* supported) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!supported) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
*supported = device->device->supportsReboot();
|
||||
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_reboot(const icsneoc2_device_t* device, bool safe) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!device->device->reboot(safe)) {
|
||||
return icsneoc2_error_transmit_message_failed;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_digital_io_get(const icsneoc2_device_t* device, icsneoc2_io_type_t type, uint32_t number, bool* value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
@@ -916,6 +1107,21 @@ icsneoc2_error_t icsneoc2_device_format_disk(const icsneoc2_device_t* device, ic
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_force_disk_config_update(const icsneoc2_device_t* device, icsneoc2_disk_details_t* disk_details) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!disk_details || !disk_details->details) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
|
||||
if(!device->device->forceDiskConfigUpdate(*disk_details->details)) {
|
||||
return icsneoc2_error_force_disk_config_update_failed;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
static icsneoc2_error_t get_supported_networks(const icsneoc2_device_t* device, const std::vector<Network>& nets, icsneoc2_netid_t* networks, size_t* count) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
@@ -1208,3 +1414,84 @@ icsneoc2_error_t icsneoc2_script_status_max_coremini_size_kb_get(const icsneoc2_
|
||||
*value = script_status->status->maxCoreminiSizeKB;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_device_chip_versions_enumerate(const icsneoc2_device_t* device, icsneoc2_chip_versions_t** chip_versions, bool refresh, size_t* count) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!chip_versions) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
|
||||
auto version_reports = device->device->getChipVersions(refresh);
|
||||
if(count) {
|
||||
*count = version_reports.size();
|
||||
}
|
||||
|
||||
icsneoc2_chip_versions_t* head = nullptr;
|
||||
icsneoc2_chip_versions_t* tail = nullptr;
|
||||
for(auto& version_report : version_reports) {
|
||||
auto* node = new (std::nothrow) icsneoc2_chip_versions_t;
|
||||
if(!node) {
|
||||
icsneoc2_chip_versions_free(head);
|
||||
return icsneoc2_error_out_of_memory;
|
||||
}
|
||||
node->version_report = version_report;
|
||||
node->next = nullptr;
|
||||
if(!head) {
|
||||
head = node;
|
||||
} else {
|
||||
tail->next = node;
|
||||
}
|
||||
tail = node;
|
||||
}
|
||||
|
||||
*chip_versions = head;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_chip_versions_free(icsneoc2_chip_versions_t* chip_versions) {
|
||||
if(!chip_versions) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
|
||||
while(chip_versions) {
|
||||
auto* next = chip_versions->next;
|
||||
delete chip_versions;
|
||||
chip_versions = next;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_chip_versions_t* icsneoc2_chip_versions_next(const icsneoc2_chip_versions_t* chip_versions) {
|
||||
if(!chip_versions) {
|
||||
return nullptr;
|
||||
}
|
||||
return chip_versions->next;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_chip_versions_props_get(const icsneoc2_chip_versions_t* chip_versions, char* name, size_t* name_length, uint8_t* major, uint8_t* minor, uint8_t* maintenance, uint8_t* build) {
|
||||
if(!chip_versions) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
auto& report = chip_versions->version_report;
|
||||
if(name && name_length) {
|
||||
if(!safe_str_copy(name,name_length, report.name)) {
|
||||
return icsneoc2_error_string_copy_failed;
|
||||
}
|
||||
}
|
||||
if(major) {
|
||||
*major = report.major;
|
||||
}
|
||||
if(minor) {
|
||||
*minor = report.minor;
|
||||
}
|
||||
if(maintenance) {
|
||||
*maintenance = report.maintenance;
|
||||
}
|
||||
if(build) {
|
||||
*build = report.build;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
typedef struct icsneoc2_supported_device_t {
|
||||
DeviceType device_type;
|
||||
icsneoc2_supported_device_t* next;
|
||||
} icsneoc2_supported_device_t;
|
||||
|
||||
typedef struct icsneoc2_message_t {
|
||||
std::shared_ptr<Message> message;
|
||||
} icsneoc2_message_t;
|
||||
@@ -38,6 +43,22 @@ typedef struct icsneoc2_script_status_t {
|
||||
std::shared_ptr<ScriptStatusMessage> status;
|
||||
} icsneoc2_script_status_t;
|
||||
|
||||
typedef struct icsneoc2_chip_versions_t {
|
||||
VersionReport version_report;
|
||||
icsneoc2_chip_versions_t* next;
|
||||
} icsneoc2_chip_versions_t;
|
||||
|
||||
typedef struct icsneoc2_termination_group_t {
|
||||
std::vector<icsneoc2_netid_t> netids;
|
||||
icsneoc2_termination_group_t* next;
|
||||
} icsneoc2_termination_group_t;
|
||||
|
||||
typedef struct icsneoc2_mac_addr_entry_t {
|
||||
uint16_t network_id;
|
||||
uint8_t address[ICSNEO_MAC_ADDRESS_LEN];
|
||||
icsneoc2_mac_addr_entry_t* next;
|
||||
} icsneoc2_mac_addr_entry_t;
|
||||
|
||||
/**
|
||||
* Safely copies a std::string to a char array.
|
||||
*
|
||||
|
||||
@@ -7,8 +7,10 @@
|
||||
#include "icsneo/communication/message/message.h"
|
||||
#include "icsneo/communication/message/canmessage.h"
|
||||
#include "icsneo/communication/message/canerrormessage.h"
|
||||
#include "icsneo/communication/message/apperrormessage.h"
|
||||
#include "icsneo/communication/message/linmessage.h"
|
||||
#include "icsneo/communication/message/ethernetmessage.h"
|
||||
#include "icsneo/communication/message/ethernetstatusmessage.h"
|
||||
#include "icsneo/communication/packet/canpacket.h"
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_is_valid(icsneoc2_message_t* message, bool* is_valid) {
|
||||
@@ -126,6 +128,28 @@ icsneoc2_error_t icsneoc2_message_data_get(icsneoc2_message_t* message, uint8_t*
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_timestamp_set(icsneoc2_message_t* message, uint64_t timestamp) {
|
||||
if(!message) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(!message->message) {
|
||||
return icsneoc2_error_invalid_message;
|
||||
}
|
||||
message->message->timestamp = timestamp;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_timestamp_get(icsneoc2_message_t* message, uint64_t* timestamp) {
|
||||
if(!message || !timestamp) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(!message->message) {
|
||||
return icsneoc2_error_invalid_message;
|
||||
}
|
||||
*timestamp = message->message->timestamp;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_can_create(icsneoc2_message_t** message) {
|
||||
if(!message) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
@@ -294,6 +318,44 @@ icsneoc2_error_t icsneoc2_message_can_error_props_get(
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_is_app_error(icsneoc2_message_t* message, bool* is_app_error) {
|
||||
if(!message || !is_app_error) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
*is_app_error = std::dynamic_pointer_cast<AppErrorMessage>(message->message) != nullptr;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_app_error_props_get(icsneoc2_message_t* message,
|
||||
icsneoc2_app_error_type_t* error_type, icsneoc2_netid_t* error_netid) {
|
||||
if(!message) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
auto app_err = std::dynamic_pointer_cast<AppErrorMessage>(message->message);
|
||||
if(!app_err) {
|
||||
return icsneoc2_error_invalid_type;
|
||||
}
|
||||
if(error_type) {
|
||||
*error_type = static_cast<icsneoc2_app_error_type_t>(app_err->getAppErrorType());
|
||||
}
|
||||
if(error_netid) {
|
||||
*error_netid = static_cast<icsneoc2_netid_t>(app_err->errorNetID);
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_app_error_string_get(icsneoc2_message_t* message,
|
||||
char* value, size_t* value_length) {
|
||||
if(!message || !value_length) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
auto app_err = std::dynamic_pointer_cast<AppErrorMessage>(message->message);
|
||||
if(!app_err) {
|
||||
return icsneoc2_error_invalid_type;
|
||||
}
|
||||
return safe_str_copy(value, value_length, app_err->getAppErrorString()) ? icsneoc2_error_success : icsneoc2_error_string_copy_failed;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_is_lin(icsneoc2_message_t* message, bool* is_lin) {
|
||||
if(!message || !is_lin) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
@@ -409,6 +471,7 @@ icsneoc2_error_t icsneoc2_message_lin_status_flags_get(const icsneoc2_message_t*
|
||||
if(lin_msg->statusFlags.HasUpdatedResponderOnce) *status_flags |= ICSNEOC2_LIN_STATUS_HAS_UPDATED_RESPONDER_ONCE;
|
||||
if(lin_msg->statusFlags.BusRecovered) *status_flags |= ICSNEOC2_LIN_STATUS_BUS_RECOVERED;
|
||||
if(lin_msg->statusFlags.BreakOnly) *status_flags |= ICSNEOC2_LIN_STATUS_BREAK_ONLY;
|
||||
if(lin_msg->statusFlags.WakeupRequest) *status_flags |= ICSNEOC2_LIN_STATUS_WAKEUP_REQUEST;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
@@ -609,9 +672,40 @@ icsneoc2_error_t icsneoc2_message_eth_t1s_props_get(icsneoc2_message_t* message,
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_is_ethernet(icsneoc2_message_t* message, bool* is_ethernet) {
|
||||
if(!message) {
|
||||
if(!message || !is_ethernet) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
*is_ethernet = std::dynamic_pointer_cast<EthernetMessage>(message->message) != nullptr;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_is_ethernet_status(icsneoc2_message_t* message, bool* is_ethernet_status) {
|
||||
if(!message || !is_ethernet_status) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
*is_ethernet_status = std::dynamic_pointer_cast<EthernetStatusMessage>(message->message) != nullptr;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_message_eth_status_props_get(icsneoc2_message_t* message, bool* link_state, bool* duplex, icsneoc2_link_speed_t* link_speed, icsneoc2_link_mode_t* link_mode) {
|
||||
if(!message) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
auto msg = std::dynamic_pointer_cast<EthernetStatusMessage>(message->message);
|
||||
if(!msg) {
|
||||
return icsneoc2_error_invalid_type;
|
||||
}
|
||||
if(link_state) {
|
||||
*link_state = msg->state;
|
||||
}
|
||||
if(duplex) {
|
||||
*duplex = msg->duplex;
|
||||
}
|
||||
if(link_speed) {
|
||||
*link_speed = static_cast<icsneoc2_link_speed_t>(msg->speed);
|
||||
}
|
||||
if(link_mode) {
|
||||
*link_mode = static_cast<icsneoc2_link_mode_t>(msg->mode);
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
@@ -179,6 +179,82 @@ icsneoc2_error_t icsneoc2_settings_termination_set(icsneoc2_device_t* device, ic
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_termination_groups_enumerate(icsneoc2_device_t* device, icsneoc2_termination_group_t** groups, size_t* count) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!groups) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
|
||||
auto termination_groups = device->device->settings->getTerminationGroups();
|
||||
|
||||
icsneoc2_termination_group_t* head = nullptr;
|
||||
icsneoc2_termination_group_t* tail = nullptr;
|
||||
for(const auto& group : termination_groups) {
|
||||
auto* node = new (std::nothrow) icsneoc2_termination_group_t;
|
||||
if(!node) {
|
||||
icsneoc2_settings_termination_groups_free(head);
|
||||
return icsneoc2_error_out_of_memory;
|
||||
}
|
||||
node->netids.reserve(group.size());
|
||||
for(const auto& network : group) {
|
||||
node->netids.push_back(static_cast<icsneoc2_netid_t>(network.getNetID()));
|
||||
}
|
||||
node->next = nullptr;
|
||||
if(!head) {
|
||||
head = node;
|
||||
} else {
|
||||
tail->next = node;
|
||||
}
|
||||
tail = node;
|
||||
}
|
||||
|
||||
*groups = head;
|
||||
if(count) {
|
||||
*count = termination_groups.size();
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_termination_group_t* icsneoc2_termination_group_next(const icsneoc2_termination_group_t* group) {
|
||||
if(!group) {
|
||||
return nullptr;
|
||||
}
|
||||
return group->next;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_termination_group_networks_get(const icsneoc2_termination_group_t* group, icsneoc2_netid_t* networks, size_t* count) {
|
||||
if(!group || !count) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(!networks) {
|
||||
*count = group->netids.size();
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
size_t to_copy = std::min<size_t>(*count, group->netids.size());
|
||||
for(size_t i = 0; i < to_copy; i++) {
|
||||
networks[i] = group->netids[i];
|
||||
}
|
||||
*count = to_copy;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_termination_groups_free(icsneoc2_termination_group_t* groups) {
|
||||
if(!groups) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
|
||||
while(groups) {
|
||||
auto* next = groups->next;
|
||||
delete groups;
|
||||
groups = next;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_commander_resistor_enabled(icsneoc2_device_t* device, icsneoc2_netid_t netid, bool* enabled) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
@@ -630,7 +706,7 @@ icsneoc2_error_t icsneoc2_settings_t1s_burst_timer_set(icsneoc2_device_t* device
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_t1s_max_burst_timer_for_get(icsneoc2_device_t* device, icsneoc2_netid_t netid, uint8_t* value) {
|
||||
icsneoc2_error_t icsneoc2_settings_t1s_max_burst_get(icsneoc2_device_t* device, icsneoc2_netid_t netid, uint8_t* value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
@@ -649,7 +725,7 @@ icsneoc2_error_t icsneoc2_settings_t1s_max_burst_timer_for_get(icsneoc2_device_t
|
||||
}
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_t1s_max_burst_timer_for_set(icsneoc2_device_t* device, icsneoc2_netid_t netid, uint8_t value) {
|
||||
icsneoc2_error_t icsneoc2_settings_t1s_max_burst_set(icsneoc2_device_t* device, icsneoc2_netid_t netid, uint8_t value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
@@ -867,6 +943,120 @@ icsneoc2_error_t icsneoc2_settings_misc_io_analog_output_set(icsneoc2_device_t*
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_linux_boot_enabled_get(icsneoc2_device_t* device, bool* value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(auto result = device->device->settings->getLinuxBootEnabled(); result.has_value()) {
|
||||
*value = result.value();
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_linux_boot_enabled_set(icsneoc2_device_t* device, bool value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!device->device->settings->setLinuxBootEnabled(value)) {
|
||||
return icsneoc2_error_set_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_external_wifi_antenna_enabled_get(icsneoc2_device_t* device, bool* value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(auto result = device->device->settings->getExternalWifiAntennaEnabled(); result.has_value()) {
|
||||
*value = result.value();
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_external_wifi_antenna_enabled_set(icsneoc2_device_t* device, bool value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!device->device->settings->setExternalWifiAntennaEnabled(value)) {
|
||||
return icsneoc2_error_set_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_perf_test_enabled_get(icsneoc2_device_t* device, bool* value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(auto result = device->device->settings->isPerfTestEnabled(); result.has_value()) {
|
||||
*value = result.value();
|
||||
return icsneoc2_error_success;
|
||||
} else {
|
||||
*value = false;
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_perf_test_enabled_set(icsneoc2_device_t* device, bool value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!device->device->settings->setPerfTestEnable(value)) {
|
||||
return icsneoc2_error_set_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_linux_configuration_port_get(icsneoc2_device_t* device, icsneoc2_linux_configuration_port_t* value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(auto result = device->device->settings->getLinuxConfigurationPort(); result.has_value()) {
|
||||
*value = static_cast<icsneoc2_linux_configuration_port_t>(result.value());
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_linux_configuration_port_set(icsneoc2_device_t* device, icsneoc2_linux_configuration_port_t value) {
|
||||
// Make sure the device is valid
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!device->device->settings->setLinuxConfigurationPort(static_cast<LinuxConfigurationPort>(value))) {
|
||||
return icsneoc2_error_set_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_disabled_get(icsneoc2_device_t* device, bool* value) {
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
@@ -892,3 +1082,113 @@ icsneoc2_error_t icsneoc2_settings_readonly_get(icsneoc2_device_t* device, bool*
|
||||
*value = device->device->settings->readonly;
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_gptp_profile_get(icsneoc2_device_t* device, icsneoc2_gptp_profile_t* value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(auto result = device->device->settings->getGPTPProfile(); result.has_value()) {
|
||||
*value = static_cast<icsneoc2_gptp_profile_t>(result.value());
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_gptp_profile_set(icsneoc2_device_t* device, icsneoc2_gptp_profile_t value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(value >= icsneoc2_gptp_profile_maxsize) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(!device->device->settings->setGPTPProfile(static_cast<RADGPTPProfile>(value))) {
|
||||
return icsneoc2_error_set_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_gptp_role_get(icsneoc2_device_t* device, icsneoc2_gptp_role_t* value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(auto result = device->device->settings->getGPTPRole(); result.has_value()) {
|
||||
*value = static_cast<icsneoc2_gptp_role_t>(result.value());
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_gptp_role_set(icsneoc2_device_t* device, icsneoc2_gptp_role_t value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(value >= icsneoc2_gptp_role_maxsize) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(!device->device->settings->setGPTPRole(static_cast<RADGPTPRole>(value))) {
|
||||
return icsneoc2_error_set_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_gptp_enabled_port_get(icsneoc2_device_t* device, uint8_t* value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(auto result = device->device->settings->getGPTPEnabledPort(); result.has_value()) {
|
||||
*value = result.value();
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_gptp_enabled_port_set(icsneoc2_device_t* device, uint8_t value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!device->device->settings->setGPTPEnabledPort(value)) {
|
||||
return icsneoc2_error_set_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_gptp_clock_syntonization_enabled_get(icsneoc2_device_t* device, bool* value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!value) {
|
||||
return icsneoc2_error_invalid_parameters;
|
||||
}
|
||||
if(auto result = device->device->settings->isGPTPClockSyntonizationEnabled(); result.has_value()) {
|
||||
*value = result.value();
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
|
||||
icsneoc2_error_t icsneoc2_settings_gptp_clock_syntonization_enabled_set(icsneoc2_device_t* device, bool value) {
|
||||
auto res = icsneoc2_device_is_valid(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return res;
|
||||
}
|
||||
if(!device->device->settings->setGPTPClockSyntonizationEnabled(value)) {
|
||||
return icsneoc2_error_set_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
+24
-8
@@ -4,10 +4,10 @@
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
APIEvent::APIEvent(Type type, APIEvent::Severity severity, const Device* device) : eventStruct({}) {
|
||||
this->device = device;
|
||||
if(device) {
|
||||
serial = device->getSerial();
|
||||
APIEvent::APIEvent(Type type, APIEvent::Severity severity, std::weak_ptr<Device> device) : eventStruct({}), device(device) {
|
||||
auto shared = device.lock();
|
||||
if(shared) {
|
||||
serial = shared->getSerial();
|
||||
eventStruct.serial[serial.copy(eventStruct.serial, sizeof(eventStruct.serial))] = '\0';
|
||||
}
|
||||
|
||||
@@ -27,9 +27,10 @@ void APIEvent::downgradeFromError() noexcept {
|
||||
}
|
||||
|
||||
bool APIEvent::isForDevice(std::string filterSerial) const noexcept {
|
||||
if(!device || filterSerial.length() == 0)
|
||||
auto shared = device.lock();
|
||||
if(!shared || filterSerial.length() == 0)
|
||||
return false;
|
||||
return device->getSerial() == filterSerial;
|
||||
return shared->getSerial() == filterSerial;
|
||||
}
|
||||
|
||||
// API Errors
|
||||
@@ -116,6 +117,9 @@ static constexpr const char* GPTP_NOT_SUPPORTED = "GPTP clock synchronization is
|
||||
static constexpr const char* SETTING_NOT_AVAILABLE = "Requested a setting that is not available on this device";
|
||||
static constexpr const char* DISK_FORMAT_NOT_SUPPORTED = "Disk formatting is not supported on this device.";
|
||||
static constexpr const char* DISK_FORMAT_INVALID_COUNT = "Disk format config disk count is mismatched with device disk count.";
|
||||
static constexpr const char* TC10_REQUEST_FAILED = "The device rejected the TC10 request.";
|
||||
static constexpr const char* FIRMWARE_UPDATE_NOT_SUPPORTED = "Firmware updates are not supported for this device.";
|
||||
static constexpr const char* FIRMWARE_UPDATE_FAILED = "The firmware update failed.";
|
||||
|
||||
// Transport Errors
|
||||
static constexpr const char* FAILED_TO_READ = "A read operation failed.";
|
||||
@@ -167,6 +171,7 @@ static constexpr const char* SERVD_POLL_ERROR = "Error polling on Servd socket";
|
||||
static constexpr const char* SERVD_NODATA_ERROR = "No data received from Servd";
|
||||
static constexpr const char* SERVD_JOIN_MULTICAST_ERROR = "Error joining Servd multicast group";
|
||||
static constexpr const char* SERVD_NOT_REACHABLE = "Could not reach Servd; ensure it is installed and running";
|
||||
static constexpr const char* SERVD_DISABLED = "Servd is disabled via LIBICSNEO_USE_SERVD; no devices will be found";
|
||||
|
||||
// DXX
|
||||
static constexpr const char* DXX_ERROR_SYS = "System error, check errno/GetLastError()";
|
||||
@@ -380,6 +385,12 @@ const char* APIEvent::DescriptionForType(Type type) {
|
||||
return DISK_FORMAT_NOT_SUPPORTED;
|
||||
case Type::DiskFormatInvalidCount:
|
||||
return DISK_FORMAT_INVALID_COUNT;
|
||||
case Type::TC10RequestFailed:
|
||||
return TC10_REQUEST_FAILED;
|
||||
case Type::FirmwareUpdateNotSupported:
|
||||
return FIRMWARE_UPDATE_NOT_SUPPORTED;
|
||||
case Type::FirmwareUpdateFailed:
|
||||
return FIRMWARE_UPDATE_FAILED;
|
||||
|
||||
// VSA
|
||||
case Type::VSABufferCorrupted:
|
||||
@@ -441,6 +452,8 @@ const char* APIEvent::DescriptionForType(Type type) {
|
||||
return SERVD_JOIN_MULTICAST_ERROR;
|
||||
case Type::ServdNotReachable:
|
||||
return SERVD_NOT_REACHABLE;
|
||||
case Type::ServdDisabled:
|
||||
return SERVD_DISABLED;
|
||||
|
||||
// DXX
|
||||
case Type::DXXErrorSys:
|
||||
@@ -461,14 +474,17 @@ const char* APIEvent::DescriptionForType(Type type) {
|
||||
return TOO_MANY_EVENTS;
|
||||
case Type::Unknown:
|
||||
return UNKNOWN;
|
||||
case Type::Any:
|
||||
break;
|
||||
}
|
||||
return INVALID;
|
||||
}
|
||||
|
||||
std::string APIEvent::describe() const noexcept {
|
||||
std::stringstream ss;
|
||||
if(device)
|
||||
ss << *device; // Makes use of device.describe()
|
||||
auto shared = device.lock();
|
||||
if(shared)
|
||||
ss << *shared; // Makes use of device.describe()
|
||||
else
|
||||
ss << "API";
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
using namespace icsneo;
|
||||
|
||||
EventManager& EventManager::GetInstance() {
|
||||
static EventManager inst;
|
||||
return inst;
|
||||
static EventManager* inst = new EventManager();
|
||||
return *inst;
|
||||
}
|
||||
|
||||
void EventManager::downgradeErrorsOnCurrentThread() {
|
||||
@@ -65,7 +65,6 @@ void EventManager::add(APIEvent event) {
|
||||
std::lock_guard<std::mutex> eventsLock(eventsMutex);
|
||||
addEventInternal(event);
|
||||
} // free the lock so that callbacks may modify events
|
||||
runCallbacks(event);
|
||||
} else {
|
||||
std::lock_guard<std::mutex> errorsLock(errorsMutex);
|
||||
lastUserErrors[std::this_thread::get_id()] = event;
|
||||
@@ -75,8 +74,8 @@ void EventManager::add(APIEvent event) {
|
||||
std::lock_guard<std::mutex> eventsLock(eventsMutex);
|
||||
addEventInternal(event);
|
||||
} // free the lock so that callbacks may modify events
|
||||
runCallbacks(event);
|
||||
}
|
||||
runCallbacks(event);
|
||||
}
|
||||
|
||||
void EventManager::addEventInternal(APIEvent event) {
|
||||
@@ -100,9 +99,13 @@ void EventManager::addEventInternal(APIEvent event) {
|
||||
}
|
||||
|
||||
void EventManager::runCallbacks(APIEvent event) {
|
||||
std::lock_guard<std::mutex> lk(callbacksMutex);
|
||||
for(auto& i : callbacks)
|
||||
i.second.callIfMatch(std::make_shared<APIEvent>(event));
|
||||
std::map<int, icsneo::EventCallback> tempCallbacks;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(callbacksMutex);
|
||||
tempCallbacks = callbacks;
|
||||
}
|
||||
for(auto& i : tempCallbacks)
|
||||
i.second.callIfMatch(std::make_shared<APIEvent>(event));
|
||||
}
|
||||
|
||||
void EventManager::setEventLimit(size_t newLimit) {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
#include "icsneo/api/heartbeat.h"
|
||||
#include "icsneo/api/lifetime.h"
|
||||
#include "icsneo/device/device.h"
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
Heartbeat::Heartbeat(Device& device) :
|
||||
device(device), mode(device.isOnline() ? Mode::Passive : Mode::Active), thread(&Heartbeat::run, this) {
|
||||
}
|
||||
|
||||
Heartbeat::~Heartbeat() {
|
||||
{
|
||||
std::lock_guard lk(mutex);
|
||||
stop = true;
|
||||
}
|
||||
cv.notify_one();
|
||||
thread.join();
|
||||
}
|
||||
|
||||
void Heartbeat::run() {
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
|
||||
auto filter = std::make_shared<MessageFilter>();
|
||||
filter->includeInternalInAny = true;
|
||||
bool status = false;
|
||||
auto cbHandle = device.com->addMessageCallback(std::make_shared<MessageCallback>(filter, [&](std::shared_ptr<Message> msg) {
|
||||
// TODO: remove DeviceStatus after 2027-08-17, as ResetStatus should be widely supported
|
||||
const bool isHeartbeat =
|
||||
(msg->type == Message::Type::ResetStatus) ||
|
||||
(msg->type == Message::Type::RawMessage && std::static_pointer_cast<RawMessage>(msg)->network == Network::NetID::DeviceStatus);
|
||||
if(!isHeartbeat)
|
||||
return;
|
||||
{
|
||||
std::lock_guard lk(mutex);
|
||||
status = true;
|
||||
}
|
||||
cv.notify_one();
|
||||
}));
|
||||
Lifetime cbLifetime([&] {
|
||||
device.com->removeMessageCallback(cbHandle);
|
||||
});
|
||||
while(true) {
|
||||
std::unique_lock lk(mutex);
|
||||
if(mode == Mode::Active) {
|
||||
if(cv.wait_for(lk, std::chrono::milliseconds(100), [&] { return stop; })) {
|
||||
break;
|
||||
}
|
||||
device.com->sendCommand(Command::RequestStatusUpdate);
|
||||
}
|
||||
if(!cv.wait_for(lk, std::chrono::seconds(2), [&] { return status || stop; })) {
|
||||
// we disconnect instead of close because it indicates to the user that a cleanup is still required (our thread join)
|
||||
device.report(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
device.com->driver->setIsDisconnected(true);
|
||||
break;
|
||||
}
|
||||
if(stop)
|
||||
break;
|
||||
status = false;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,13 @@
|
||||
#include <windows.h>
|
||||
#include "icsneo/icsnVC40.h"
|
||||
|
||||
// Vehicle Spy 3.26.3.9 removed these legacy settings structure definitions from
|
||||
// icsnVC40.h. The corresponding functions only ever treat them as opaque
|
||||
// buffers, so forward declarations keep the existing API/ABI intact.
|
||||
typedef struct _SFireSettings SFireSettings;
|
||||
typedef struct _SVCAN3Settings SVCAN3Settings;
|
||||
typedef struct _SVCANRFSettings SVCANRFSettings;
|
||||
|
||||
|
||||
|
||||
bool LoadDLLAPI(HINSTANCE &hAPIDLL);
|
||||
|
||||
@@ -545,15 +545,13 @@ int LegacyDLLExport icsneoGetTimeStampForMsg(void* hObject, icsSpyMessage* pMsg,
|
||||
void LegacyDLLExport icsneoGetISO15765Status(void* hObject, int lNetwork, int lClearTxStatus, int lClearRxStatus,
|
||||
int* lTxStatus, int* lRxStatus)
|
||||
{
|
||||
// TODO Implement
|
||||
return;
|
||||
// Not supported
|
||||
}
|
||||
|
||||
void LegacyDLLExport icsneoSetISO15765RxParameters(void* hObject, int lNetwork, int lEnable, spyFilterLong* pFF_CFMsgFilter,
|
||||
icsSpyMessage* pTxMsg, int lCFTimeOutMs, int lFlowCBlockSize, int lUsesExtendedAddressing, int lUseHardwareIfPresent)
|
||||
{
|
||||
// TODO Implement
|
||||
return;
|
||||
// Not supported
|
||||
}
|
||||
|
||||
int LegacyDLLExport icsneoGetRTC(void* hObject, icsSpyTime* time)
|
||||
@@ -835,26 +833,25 @@ int LegacyDLLExport icsneoGetErrorInfo(int lErrorNumber, char* szErrorDescriptio
|
||||
//ISO15765-2 Functions
|
||||
int LegacyDLLExport icsneoISO15765_EnableNetworks(void* hObject, unsigned long ulNetworks)
|
||||
{
|
||||
// TODO Implement
|
||||
// Not supported
|
||||
return false;
|
||||
}
|
||||
|
||||
int LegacyDLLExport icsneoISO15765_DisableNetworks(void* hObject)
|
||||
{
|
||||
// TODO Implement
|
||||
// Not supported
|
||||
return false;
|
||||
}
|
||||
|
||||
int LegacyDLLExport icsneoISO15765_TransmitMessage(void* hObject, unsigned long ulNetworkID, stCM_ISO157652_TxMessage* pMsg,
|
||||
unsigned long ulBlockingTimeout)
|
||||
int LegacyDLLExport icsneoISO15765_TransmitMessage(void* hObject, unsigned long ulNetworkID, stCM_ISO157652_TxMessage* pMsg, unsigned long ulBlockingTimeout)
|
||||
{
|
||||
// TODO Implement
|
||||
// Not supported
|
||||
return false;
|
||||
}
|
||||
|
||||
int LegacyDLLExport icsneoISO15765_ReceiveMessage(void* hObject, int ulNetworkID, stCM_ISO157652_RxMessage* pMsg)
|
||||
{
|
||||
// TODO Implement
|
||||
// Not supported
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1035,10 +1032,10 @@ int LegacyDLLExport icsneoGetDeviceSettingsType(void* hObject, EPlasmaIonVnetCha
|
||||
case NEODEVICE_ION:
|
||||
*pDeviceSettingsType = DeviceFire2SettingsType; //defaults to FIRE2 vnets with libicsneo - no firevnets!
|
||||
break;
|
||||
case NEODEVICE_VCAN3:
|
||||
*pDeviceSettingsType = DeviceVCAN3SettingsType;
|
||||
case NEODEVICE_VCAN3_DEPRECATED:
|
||||
*pDeviceSettingsType = DeviceVCAN3SettingsTypeDeprecated;
|
||||
break;
|
||||
case NEODEVICE_FIRE:
|
||||
case NEODEVICE_FIRE_DEPRECATED:
|
||||
*pDeviceSettingsType = DeviceFireSettingsType;
|
||||
break;
|
||||
case NEODEVICE_FIRE2:
|
||||
@@ -1061,23 +1058,23 @@ int LegacyDLLExport icsneoGetDeviceSettingsType(void* hObject, EPlasmaIonVnetCha
|
||||
case NEODEVICE_VIVIDCAN:
|
||||
*pDeviceSettingsType = DeviceVividCANSettingsType;
|
||||
break;
|
||||
case NEODEVICE_ECU_AVB:
|
||||
*pDeviceSettingsType = DeviceECU_AVBSettingsType;
|
||||
case NEODEVICE_ECU_AVB_DEPRECATED:
|
||||
*pDeviceSettingsType = DeviceECU_AVBSettingsTypeDeprecated;
|
||||
break;
|
||||
case NEODEVICE_RADSUPERMOON:
|
||||
*pDeviceSettingsType = DeviceRADSuperMoonSettingsType;
|
||||
case NEODEVICE_RADSUPERMOON_DEPRECATED:
|
||||
*pDeviceSettingsType = DeviceRADSuperMoonSettingsTypeDeprecated;
|
||||
break;
|
||||
case NEODEVICE_RADMOON2:
|
||||
*pDeviceSettingsType = DeviceRADMoon2SettingsType;
|
||||
break;
|
||||
case NEODEVICE_RADGIGALOG:
|
||||
*pDeviceSettingsType = DeviceRADGigalogSettingsType;
|
||||
case NEODEVICE_RADGIGALOG_DEPRECATED:
|
||||
*pDeviceSettingsType = DeviceRADGigalogSettingsTypeDeprecated;
|
||||
break;
|
||||
case NEODEVICE_RADMOON3:
|
||||
*pDeviceSettingsType = DeviceRADMoon3SettingsType;
|
||||
break;
|
||||
case NEODEVICE_RADGEMINI:
|
||||
*pDeviceSettingsType = DeviceRADGeminiSettingsType;
|
||||
case NEODEVICE_RADARGOS:
|
||||
*pDeviceSettingsType = DeviceRADArgosSettingsType;
|
||||
break;
|
||||
case NEODEVICE_RED2:
|
||||
*pDeviceSettingsType = DeviceRed2SettingsType;
|
||||
@@ -1088,6 +1085,8 @@ int LegacyDLLExport icsneoGetDeviceSettingsType(void* hObject, EPlasmaIonVnetCha
|
||||
case NEODEVICE_FIRE3_FLEXRAY:
|
||||
*pDeviceSettingsType = DeviceFire3FlexraySettingsType;
|
||||
break;
|
||||
case NEODEVICE_RAD_BMS:
|
||||
*pDeviceSettingsType = DeviceRADBMSSettingsType;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
@@ -1283,10 +1282,11 @@ int LegacyDLLExport icsneoJ2534Cmd(void* hObject, unsigned char* CmdBuf, short L
|
||||
return false;
|
||||
|
||||
neodevice_t* device = reinterpret_cast<neodevice_t*>(hObject);
|
||||
const auto& cmd = static_cast<icsneo::J2534Command>(*CmdBuf);
|
||||
|
||||
switch (*CmdBuf)
|
||||
switch (cmd)
|
||||
{
|
||||
case J2534NVCMD_SetNetworkBaudRate:
|
||||
case icsneo::J2534Command::SetNetworkBaudRate:
|
||||
|
||||
pTmp = (uint64_t *)&CmdBuf[1];
|
||||
NetworkID = (uint16_t)*pTmp;
|
||||
@@ -1296,7 +1296,7 @@ int LegacyDLLExport icsneoJ2534Cmd(void* hObject, unsigned char* CmdBuf, short L
|
||||
iRetVal = 0;
|
||||
break;
|
||||
|
||||
case J2534NVCMD_GetNetworkBaudRate:
|
||||
case icsneo::J2534Command::GetNetworkBaudRate:
|
||||
{
|
||||
pTmp = (uint64_t *)&CmdBuf[1];
|
||||
NetworkID = (uint16_t)*pTmp;
|
||||
@@ -1309,7 +1309,7 @@ int LegacyDLLExport icsneoJ2534Cmd(void* hObject, unsigned char* CmdBuf, short L
|
||||
*pTmp = static_cast<uint64_t>(ret);
|
||||
break;
|
||||
}
|
||||
case J2534NVCMD_SetCANFDRate:
|
||||
case icsneo::J2534Command::SetCANFDRate:
|
||||
|
||||
pTmp = (uint64_t *)&CmdBuf[1];
|
||||
NetworkID = (uint16_t)*pTmp;
|
||||
@@ -1320,7 +1320,7 @@ int LegacyDLLExport icsneoJ2534Cmd(void* hObject, unsigned char* CmdBuf, short L
|
||||
iRetVal = 0;
|
||||
break;
|
||||
|
||||
case J2534NVCMD_GetCANFDRate:
|
||||
case icsneo::J2534Command::GetCANFDRate:
|
||||
|
||||
pTmp = (uint64_t *)&CmdBuf[1];
|
||||
NetworkID = (uint16_t)*pTmp;
|
||||
@@ -1330,7 +1330,7 @@ int LegacyDLLExport icsneoJ2534Cmd(void* hObject, unsigned char* CmdBuf, short L
|
||||
*pTmp = icsneo_getFDBaudrate(device, NetworkID);
|
||||
break;
|
||||
|
||||
case J2534NVCMD_GetCANFDTermination:
|
||||
case icsneo::J2534Command::GetCANFDTermination:
|
||||
|
||||
pTmp = (uint64_t *)&CmdBuf[1];
|
||||
NetworkID = (uint16_t)*pTmp;
|
||||
@@ -1366,7 +1366,7 @@ int LegacyDLLExport icsneoJ2534Cmd(void* hObject, unsigned char* CmdBuf, short L
|
||||
}
|
||||
break;
|
||||
|
||||
case J2534NVCMD_SetCANFDTermination:
|
||||
case icsneo::J2534Command::SetCANFDTermination:
|
||||
|
||||
pTmp = (uint64_t *)&CmdBuf[1];
|
||||
NetworkID = (uint16_t)*pTmp;
|
||||
@@ -1420,11 +1420,9 @@ int LegacyDLLExport icsneoEnableBusVoltageMonitor(void* hObject, unsigned int en
|
||||
return false;
|
||||
}
|
||||
|
||||
int LegacyDLLExport icsneoISO15765_TransmitMessageEx(void* hObject,
|
||||
unsigned long ulNetworkID,
|
||||
ISO15765_2015_TxMessage* pMsg,
|
||||
unsigned long ulBlockingTimeout)
|
||||
int LegacyDLLExport icsneoISO15765_TransmitMessageEx(void* hObject, unsigned long ulNetworkID, ISO15765_2015_TxMessage* pMsg, unsigned long ulBlockingTimeout)
|
||||
{
|
||||
// Not supported
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -26,11 +26,14 @@ pybind11_add_module(icsneopy
|
||||
icsneopy/communication/message/message.cpp
|
||||
icsneopy/communication/message/canmessage.cpp
|
||||
icsneopy/communication/message/canerrormessage.cpp
|
||||
icsneopy/communication/message/iso15765message.cpp
|
||||
icsneopy/communication/message/ethernetmessage.cpp
|
||||
icsneopy/communication/message/linmessage.cpp
|
||||
icsneopy/communication/message/tc10statusmessage.cpp
|
||||
icsneopy/communication/message/mdiomessage.cpp
|
||||
icsneopy/communication/message/gptpstatusmessage.cpp
|
||||
icsneopy/communication/message/allmacaddressesmessage.cpp
|
||||
icsneopy/communication/message/apperrormessage.cpp
|
||||
icsneopy/communication/message/ethernetstatusmessage.cpp
|
||||
icsneopy/communication/message/spimessage.cpp
|
||||
icsneopy/communication/message/scriptstatusmessage.cpp
|
||||
@@ -38,6 +41,9 @@ pybind11_add_module(icsneopy
|
||||
icsneopy/communication/message/livedatamessage.cpp
|
||||
icsneopy/communication/message/callback/messagecallback.cpp
|
||||
icsneopy/communication/message/filter/messagefilter.cpp
|
||||
icsneopy/communication/message/filter/main51messagefilter.cpp
|
||||
icsneopy/communication/message/main51message.cpp
|
||||
icsneopy/communication/command.cpp
|
||||
icsneopy/core/macseccfg.cpp
|
||||
icsneopy/flexray/flexray.cpp
|
||||
icsneopy/disk/diskdriver.cpp
|
||||
@@ -51,11 +57,30 @@ pybind11_add_module(icsneopy
|
||||
)
|
||||
target_link_libraries(icsneopy PRIVATE icsneocpp)
|
||||
|
||||
if(LIBICSNEO_ENABLE_BOOTLOADER)
|
||||
target_sources(icsneopy PRIVATE icsneopy/bootloader/bootloader.cpp)
|
||||
target_compile_definitions(icsneopy PRIVATE ICSNEO_ENABLE_BOOTLOADER)
|
||||
if(WIN32)
|
||||
# Windows has no build RPATH; the .pyd only finds DLLs in its own directory
|
||||
add_custom_command(TARGET icsneopy POST_BUILD
|
||||
COMMAND "${CMAKE_COMMAND}" -E copy_if_different "$<TARGET_FILE:libicsbl::icsbl>" "$<TARGET_FILE_DIR:icsneopy>"
|
||||
VERBATIM
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
install(TARGETS icsneopy LIBRARY DESTINATION icsneopy)
|
||||
|
||||
find_program(STUBGEN_EXE stubgen)
|
||||
if(STUBGEN_EXE)
|
||||
add_custom_command(TARGET icsneopy POST_BUILD COMMAND stubgen -v -p icsneopy -o .)
|
||||
# Multi-config generators put the extension in Release/ or Debug/. Import
|
||||
# that freshly built module, not a globally installed older icsneopy.
|
||||
add_custom_command(TARGET icsneopy POST_BUILD
|
||||
COMMAND "${CMAKE_COMMAND}" -E rm -f "${CMAKE_CURRENT_BINARY_DIR}/icsneopy.pyi"
|
||||
COMMAND "${STUBGEN_EXE}" -v -p icsneopy -o "${CMAKE_CURRENT_BINARY_DIR}"
|
||||
WORKING_DIRECTORY "$<TARGET_FILE_DIR:icsneopy>"
|
||||
VERBATIM
|
||||
)
|
||||
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/icsneopy.pyi py.typed DESTINATION icsneopy)
|
||||
endif()
|
||||
|
||||
|
||||
@@ -92,6 +92,9 @@ void init_event(pybind11::module_& m) {
|
||||
.value("SettingNotAvaiableDevice", APIEvent::Type::SettingNotAvaiableDevice)
|
||||
.value("DiskFormatNotSupported", APIEvent::Type::DiskFormatNotSupported)
|
||||
.value("DiskFormatInvalidCount", APIEvent::Type::DiskFormatInvalidCount)
|
||||
.value("TC10RequestFailed", APIEvent::Type::TC10RequestFailed)
|
||||
.value("FirmwareUpdateNotSupported", APIEvent::Type::FirmwareUpdateNotSupported)
|
||||
.value("FirmwareUpdateFailed", APIEvent::Type::FirmwareUpdateFailed)
|
||||
.value("FailedToRead", APIEvent::Type::FailedToRead)
|
||||
.value("FailedToWrite", APIEvent::Type::FailedToWrite)
|
||||
.value("DriverFailedToOpen", APIEvent::Type::DriverFailedToOpen)
|
||||
@@ -127,6 +130,7 @@ void init_event(pybind11::module_& m) {
|
||||
.value("ServdNoDataError", APIEvent::Type::ServdNoDataError)
|
||||
.value("ServdJoinMulticastError", APIEvent::Type::ServdJoinMulticastError)
|
||||
.value("ServdNotReachable", APIEvent::Type::ServdNotReachable)
|
||||
.value("ServdDisabled", APIEvent::Type::ServdDisabled)
|
||||
.value("DXXErrorSys", APIEvent::Type::DXXErrorSys)
|
||||
.value("DXXErrorInt", APIEvent::Type::DXXErrorInt)
|
||||
.value("DXXErrorOverflow", APIEvent::Type::DXXErrorOverflow)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
#include <pybind11/functional.h>
|
||||
|
||||
#include "icsneo/device/extensions/bootloader/api.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwloader.h"
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
struct BootloaderNamespace {};
|
||||
|
||||
void init_bootloader(pybind11::module_& m) {
|
||||
// Dummy class to act as Bootloader namespace
|
||||
pybind11::classh<BootloaderNamespace> bootloader(m, "Bootloader");
|
||||
|
||||
// Opaque handle returned by FWLoader.load and consumed by update
|
||||
pybind11::classh<Bootloader::FWRepo>(bootloader, "FWRepo");
|
||||
|
||||
pybind11::classh<Bootloader::FWLoader>(bootloader, "FWLoader")
|
||||
.def_static("load", &Bootloader::FWLoader::Load, pybind11::arg("path"), pybind11::call_guard<pybind11::gil_scoped_release>());
|
||||
|
||||
bootloader.def_static("update",
|
||||
[](Device& device, const Bootloader::FWRepo& fw, Bootloader::Logger logger, bool alreadyInBootloader, bool forceFlash) {
|
||||
if(!logger) {
|
||||
logger = [](Device::OpenStatusType, const std::string&, std::optional<double>) { return Device::OpenDirective::Continue; };
|
||||
}
|
||||
return Bootloader::update(device, fw, logger, alreadyInBootloader, forceFlash);
|
||||
},
|
||||
pybind11::arg("device"),
|
||||
pybind11::arg("fw"),
|
||||
pybind11::arg("logger") = pybind11::none(),
|
||||
pybind11::arg("already_in_bootloader") = false,
|
||||
pybind11::arg("force_flash") = false,
|
||||
pybind11::call_guard<pybind11::gil_scoped_release>());
|
||||
}
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,40 @@
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/native_enum.h>
|
||||
|
||||
#include "icsneo/communication/command.h"
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
void init_command(pybind11::module_& m) {
|
||||
pybind11::native_enum<Command>(m, "Command", "enum.IntEnum")
|
||||
.value("Main51RxBufferOverflow", Command::Main51RxBufferOverflow)
|
||||
.value("Main51StartCmd", Command::Main51StartCmd)
|
||||
.value("Main51TxFifoOverflow", Command::Main51TxFifoOverflow)
|
||||
.value("Main51BulkInNoData", Command::Main51BulkInNoData)
|
||||
.value("Main51SetModeComplete", Command::Main51SetModeComplete)
|
||||
.value("Main51ReadEeprom", Command::Main51ReadEeprom)
|
||||
.value("Main51CmdDone", Command::Main51CmdDone)
|
||||
.value("Main51ErrStatus", Command::Main51ErrStatus)
|
||||
.value("Main51ReadSectorBuff", Command::Main51ReadSectorBuff)
|
||||
.value("Main51WriteSectorBuff", Command::Main51WriteSectorBuff)
|
||||
.value("Main51MmcProcessDone", Command::Main51MmcProcessDone)
|
||||
.value("Main51ReInitDone", Command::Main51ReInitDone)
|
||||
.value("EnableNetworkCommunication", Command::EnableNetworkCommunication)
|
||||
.value("EnableNetworkCommunicationEx", Command::EnableNetworkCommunicationEx)
|
||||
.value("KeepAlive", Command::KeepAlive)
|
||||
.value("RequestSerialNumber", Command::RequestSerialNumber)
|
||||
.value("GetMainVersion", Command::GetMainVersion)
|
||||
.value("SetSettings", Command::SetSettings)
|
||||
.value("SaveSettings", Command::SaveSettings)
|
||||
.value("SetDefaultSettings", Command::SetDefaultSettings)
|
||||
.value("ReadSettings", Command::ReadSettings)
|
||||
.value("ScriptStatus", Command::ScriptStatus)
|
||||
.value("WiVICommand", Command::WiVICommand)
|
||||
.value("Extended", Command::Extended)
|
||||
.value("ExtendedData", Command::ExtendedData)
|
||||
.value("FlexRayControl", Command::FlexRayControl)
|
||||
.value("CoreMiniPreload", Command::CoreMiniPreload)
|
||||
.finalize();
|
||||
}
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,13 @@
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
|
||||
#include "icsneo/communication/message/allmacaddressesmessage.h"
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
void init_allmacaddressesmessage(pybind11::module_& m) {
|
||||
pybind11::classh<AllMACAddressesMessage, Message>(m, "AllMACAddressesMessage")
|
||||
.def_readonly("addresses", &AllMACAddressesMessage::addresses);
|
||||
}
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,71 @@
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
#include <pybind11/native_enum.h>
|
||||
|
||||
#include "icsneo/communication/message/apperrormessage.h"
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
void init_errortypes(pybind11::module_& m) {
|
||||
pybind11::native_enum<AppErrorType>(m, "AppErrorType", "enum.IntEnum")
|
||||
.value("RxMessagesFull", AppErrorType::AppErrorRxMessagesFull)
|
||||
.value("TxMessagesFull", AppErrorType::AppErrorTxMessagesFull)
|
||||
.value("TxReportMessagesFull", AppErrorType::AppErrorTxReportMessagesFull)
|
||||
.value("BadCommWithDspIC", AppErrorType::AppErrorBadCommWithDspIC)
|
||||
.value("DriverOverflow", AppErrorType::AppErrorDriverOverflow)
|
||||
.value("PCBuffOverflow", AppErrorType::AppErrorPCBuffOverflow)
|
||||
.value("PCChksumError", AppErrorType::AppErrorPCChksumError)
|
||||
.value("PCMissedByte", AppErrorType::AppErrorPCMissedByte)
|
||||
.value("PCOverrunError", AppErrorType::AppErrorPCOverrunError)
|
||||
.value("SettingFailure", AppErrorType::AppErrorSettingFailure)
|
||||
.value("TooManySelectedNetworks", AppErrorType::AppErrorTooManySelectedNetworks)
|
||||
.value("NetworkNotEnabled", AppErrorType::AppErrorNetworkNotEnabled)
|
||||
.value("RtcNotCorrect", AppErrorType::AppErrorRtcNotCorrect)
|
||||
.value("LoadedDefaultSettings", AppErrorType::AppErrorLoadedDefaultSettings)
|
||||
.value("FeatureNotUnlocked", AppErrorType::AppErrorFeatureNotUnlocked)
|
||||
.value("FeatureRtcCmdDropped", AppErrorType::AppErrorFeatureRtcCmdDropped)
|
||||
.value("TxMessagesFlushed", AppErrorType::AppErrorTxMessagesFlushed)
|
||||
.value("TxMessagesHalfFull", AppErrorType::AppErrorTxMessagesHalfFull)
|
||||
.value("NetworkNotValid", AppErrorType::AppErrorNetworkNotValid)
|
||||
.value("TxInterfaceNotImplemented", AppErrorType::AppErrorTxInterfaceNotImplemented)
|
||||
.value("TxMessagesCommEnableIsOff", AppErrorType::AppErrorTxMessagesCommEnableIsOff)
|
||||
.value("RxFilterMatchCountExceeded", AppErrorType::AppErrorRxFilterMatchCountExceeded)
|
||||
.value("EthPreemptionNotEnabled", AppErrorType::AppErrorEthPreemptionNotEnabled)
|
||||
.value("TxNotSupportedInMode", AppErrorType::AppErrorTxNotSupportedInMode)
|
||||
.value("JumboFramesNotSupported", AppErrorType::AppErrorJumboFramesNotSupported)
|
||||
.value("EthernetIpFragment", AppErrorType::AppErrorEthernetIpFragment)
|
||||
.value("TxMessagesUnderrun", AppErrorType::AppErrorTxMessagesUnderrun)
|
||||
.value("DeviceFanFailure", AppErrorType::AppErrorDeviceFanFailure)
|
||||
.value("DeviceOvertemperature", AppErrorType::AppErrorDeviceOvertemperature)
|
||||
.value("TxMessageIndexOutOfRange", AppErrorType::AppErrorTxMessageIndexOutOfRange)
|
||||
.value("UndersizedFrameDropped", AppErrorType::AppErrorUndersizedFrameDropped)
|
||||
.value("OversizedFrameDropped", AppErrorType::AppErrorOversizedFrameDropped)
|
||||
.value("WatchdogEvent", AppErrorType::AppErrorWatchdogEvent)
|
||||
.value("SystemClockFailure", AppErrorType::AppErrorSystemClockFailure)
|
||||
.value("SystemClockRecovered", AppErrorType::AppErrorSystemClockRecovered)
|
||||
.value("SystemPeripheralReset", AppErrorType::AppErrorSystemPeripheralReset)
|
||||
.value("SystemCommunicationFailure", AppErrorType::AppErrorSystemCommunicationFailure)
|
||||
.value("TxMessagesUnsupportedSourceOrPacketId", AppErrorType::AppErrorTxMessagesUnsupportedSourceOrPacketId)
|
||||
.value("WbmsManagerConnectFailed", AppErrorType::AppErrorWbmsManagerConnectFailed)
|
||||
.value("WbmsManagerConnectBadState", AppErrorType::AppErrorWbmsManagerConnectBadState)
|
||||
.value("WbmsManagerConnectTimeout", AppErrorType::AppErrorWbmsManagerConnectTimeout)
|
||||
.value("FailedToInitializeLoggerDisk", AppErrorType::AppErrorFailedToInitializeLoggerDisk)
|
||||
.value("InvalidSetting", AppErrorType::AppErrorInvalidSetting)
|
||||
.value("SystemFailureRequestedReset", AppErrorType::AppErrorSystemFailureRequestedReset)
|
||||
.value("PortKeyMistmatch", AppErrorType::AppErrorPortKeyMistmatch)
|
||||
.value("BusFailure", AppErrorType::AppErrorBusFailure)
|
||||
.value("TapOverflow", AppErrorType::AppErrorTapOverflow)
|
||||
.value("EthTxNoLink", AppErrorType::AppErrorEthTxNoLink)
|
||||
.value("ErrorBufferOverflow", AppErrorType::AppErrorErrorBufferOverflow)
|
||||
.value("NoError", AppErrorType::AppNoError)
|
||||
.finalize();
|
||||
}
|
||||
|
||||
void init_apperrormessage(pybind11::module_& m) {
|
||||
init_errortypes(m);
|
||||
pybind11::classh<AppErrorMessage, Message>(m, "AppErrorMessage")
|
||||
.def("get_app_error_type", &AppErrorMessage::getAppErrorType)
|
||||
.def("get_app_error_string", &AppErrorMessage::getAppErrorString);
|
||||
}
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -7,7 +7,7 @@
|
||||
namespace icsneo {
|
||||
|
||||
void init_ethernetstatusmessage(pybind11::module_& m) {
|
||||
pybind11::classh<EthernetStatusMessage, Message> ethernetStatusMessage(m, "EthernetStatusMessage");
|
||||
pybind11::classh<EthernetStatusMessage, RawMessage> ethernetStatusMessage(m, "EthernetStatusMessage");
|
||||
|
||||
pybind11::enum_<EthernetStatusMessage::LinkSpeed>(ethernetStatusMessage, "LinkSpeed")
|
||||
.value("LinkSpeedAuto", EthernetStatusMessage::LinkSpeed::LinkSpeedAuto)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
#include "icsneo/communication/message/filter/main51messagefilter.h"
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
void init_main51messagefilter(pybind11::module_& m) {
|
||||
pybind11::classh<Main51MessageFilter, MessageFilter>(m, "Main51MessageFilter")
|
||||
.def(pybind11::init<>())
|
||||
.def(pybind11::init<Command>());
|
||||
}
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,48 @@
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
|
||||
#include "icsneo/communication/message/iso15765message.h"
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
void init_iso15765message(pybind11::module_& m) {
|
||||
auto args = pybind11::classh<Iso15765MessageArgs>(m, "Iso15765MessageArgs");
|
||||
|
||||
pybind11::classh<Iso15765MessageArgs::ArbId>(args, "ArbId")
|
||||
.def(pybind11::init<uint32_t, bool>(), pybind11::arg("id") = 0, pybind11::arg("is_29bit") = false)
|
||||
.def_readwrite("id", &Iso15765MessageArgs::ArbId::Id)
|
||||
.def_readwrite("is_29bit", &Iso15765MessageArgs::ArbId::Is29Bit);
|
||||
|
||||
args.def(pybind11::init<>())
|
||||
.def_property("tx_index", &Iso15765MessageArgs::getTxIndex, &Iso15765MessageArgs::setTxIndex)
|
||||
.def_property("arb_id",
|
||||
[](Iso15765MessageArgs& self) -> Iso15765MessageArgs::ArbId& {
|
||||
return const_cast<Iso15765MessageArgs::ArbId&>(self.getArbId());
|
||||
},
|
||||
&Iso15765MessageArgs::setArbId,
|
||||
pybind11::return_value_policy::reference_internal)
|
||||
.def_property("flow_control_arb_id",
|
||||
[](Iso15765MessageArgs& self) -> Iso15765MessageArgs::ArbId& {
|
||||
return const_cast<Iso15765MessageArgs::ArbId&>(self.getFlowControlArbId());
|
||||
},
|
||||
&Iso15765MessageArgs::setFlowControlArbId,
|
||||
pybind11::return_value_policy::reference_internal)
|
||||
.def_property("flow_control_arb_id_mask", &Iso15765MessageArgs::getFlowControlArbIdMask, &Iso15765MessageArgs::setFlowControlArbIdMask)
|
||||
.def_property("is_can_fd", &Iso15765MessageArgs::getIsCanFd, &Iso15765MessageArgs::setIsCanFd)
|
||||
.def_property("is_brs_enabled", &Iso15765MessageArgs::getIsBrsEnabled, &Iso15765MessageArgs::setIsBrsEnabled)
|
||||
.def_property("tx_dl", &Iso15765MessageArgs::getTxDl, &Iso15765MessageArgs::setTxDl)
|
||||
.def_property("st_min", &Iso15765MessageArgs::getStMin, &Iso15765MessageArgs::setStMin)
|
||||
.def_property("block_size", &Iso15765MessageArgs::getBlockSize, &Iso15765MessageArgs::setBlockSize)
|
||||
.def_property("extended_address", &Iso15765MessageArgs::getExtendedAddress, &Iso15765MessageArgs::setExtendedAddress)
|
||||
.def_property("flow_control_extended_address", &Iso15765MessageArgs::getFlowControlExtendedAddress, &Iso15765MessageArgs::setFlowControlExtendedAddress)
|
||||
.def_property("padding_value", &Iso15765MessageArgs::getPaddingValue, &Iso15765MessageArgs::setPaddingValue)
|
||||
.def_property("fs_timeout", &Iso15765MessageArgs::getFsTimeout, &Iso15765MessageArgs::setFsTimeout)
|
||||
.def_property("fs_wait_timeout", &Iso15765MessageArgs::getFsWaitTimeout, &Iso15765MessageArgs::setFsWaitTimeout)
|
||||
.def_property("cf_timeout", &Iso15765MessageArgs::getCfTimeout, &Iso15765MessageArgs::setCfTimeout)
|
||||
.def_property("data",
|
||||
&Iso15765MessageArgs::getData,
|
||||
[](Iso15765MessageArgs& self, std::vector<uint8_t> data) { self.setData(std::move(data)); })
|
||||
.def_property("is_flow_control_enabled", &Iso15765MessageArgs::getIsFlowControlEnabled, &Iso15765MessageArgs::setIsFlowControlEnabled);
|
||||
}
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -28,7 +28,8 @@ void init_linmessage(pybind11::module_& m) {
|
||||
.def_readwrite("UpdateResponderOnce", &LINStatusFlags::UpdateResponderOnce)
|
||||
.def_readwrite("HasUpdatedResponderOnce", &LINStatusFlags::HasUpdatedResponderOnce)
|
||||
.def_readwrite("BusRecovered", &LINStatusFlags::BusRecovered)
|
||||
.def_readwrite("BreakOnly", &LINStatusFlags::BreakOnly);
|
||||
.def_readwrite("BreakOnly", &LINStatusFlags::BreakOnly)
|
||||
.def_readwrite("WakeupRequest", &LINStatusFlags::WakeupRequest);
|
||||
|
||||
pybind11::classh<LINMessage, Frame> linMessage(m, "LINMessage");
|
||||
|
||||
@@ -39,7 +40,8 @@ void init_linmessage(pybind11::module_& m) {
|
||||
.value("LIN_BREAK_ONLY", LINMessage::Type::LIN_BREAK_ONLY)
|
||||
.value("LIN_SYNC_ONLY", LINMessage::Type::LIN_SYNC_ONLY)
|
||||
.value("LIN_UPDATE_RESPONDER", LINMessage::Type::LIN_UPDATE_RESPONDER)
|
||||
.value("LIN_ERROR", LINMessage::Type::LIN_ERROR);
|
||||
.value("LIN_ERROR", LINMessage::Type::LIN_ERROR)
|
||||
.value("LIN_WAKEUP_REQUEST", LINMessage::Type::LIN_WAKEUP_REQUEST);
|
||||
|
||||
linMessage
|
||||
.def(pybind11::init<>())
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
#include "icsneo/communication/message/main51message.h"
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
void init_main51message(pybind11::module_& m) {
|
||||
pybind11::classh<Main51Message, RawMessage>(m, "Main51Message")
|
||||
.def(pybind11::init<>())
|
||||
.def_readonly("command", &Main51Message::command);
|
||||
}
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -154,7 +154,6 @@ void init_macsecconfig(pybind11::module_ & m)
|
||||
.def("set_storage", &MACsecConfig::setStorage, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("clear", &MACsecConfig::clear, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("serialize", &MACsecConfig::serialize, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_bin_index", &MACsecConfig::getBinIndex, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_type", &MACsecConfig::getType, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_max_num_rule", &MACsecConfig::getMaxNumRule, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_max_num_secy", &MACsecConfig::getMaxNumSecY, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
|
||||
@@ -120,7 +120,7 @@ void init_chipid(pybind11::module_& m) {
|
||||
.value("VEM_01_8DW_ZCHIP", ChipID::VEM_01_8DW_ZCHIP)
|
||||
.value("RADGalaxy_FFG_Zynq", ChipID::RADGalaxy_FFG_Zynq)
|
||||
.value("RADMoon3_MCHIP", ChipID::RADMoon3_MCHIP)
|
||||
.value("RADComet_ZYNQ", ChipID::RADComet_ZYNQ)
|
||||
.value("RADComet2_ZYNQ", ChipID::RADComet2_ZYNQ)
|
||||
.value("VEM_02_FR_ZCHIP", ChipID::VEM_02_FR_ZCHIP)
|
||||
.value("RADA2B_REVB_ZCHIP", ChipID::RADA2B_REVB_ZCHIP)
|
||||
.value("RADGigastar_FFG_ZYNQ", ChipID::RADGigastar_FFG_ZYNQ)
|
||||
@@ -134,7 +134,8 @@ void init_chipid(pybind11::module_& m) {
|
||||
.value("SFPModule_lan8670_MCHIP", ChipID::SFPModule_lan8670_MCHIP)
|
||||
.value("RADGigastar2_ZYNQ", ChipID::RADGigastar2_ZYNQ)
|
||||
.value("SFPModule_ent11100_MCHIP", ChipID::SFPModule_ent11100_MCHIP)
|
||||
.value("RADGemini_MCHIP", ChipID::RADGemini_MCHIP)
|
||||
.value("RADArgos_MCHIP", ChipID::RADArgos_MCHIP)
|
||||
.value("SFPModule_ad1101_MCHIP", ChipID::SFPModule_ad1101_MCHIP)
|
||||
.value("Invalid", ChipID::Invalid)
|
||||
.finalize();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include <pybind11/stl.h>
|
||||
#include <pybind11/functional.h>
|
||||
#include <pybind11/chrono.h>
|
||||
#include <pybind11/native_enum.h>
|
||||
|
||||
#include "icsneo/device/device.h"
|
||||
#include "icsneo/device/extensions/deviceextension.h"
|
||||
@@ -12,7 +13,22 @@
|
||||
namespace icsneo {
|
||||
|
||||
void init_device(pybind11::module_& m) {
|
||||
pybind11::classh<Device>(m, "Device")
|
||||
pybind11::classh<Device> device(m, "Device");
|
||||
|
||||
pybind11::native_enum<Device::OpenDirective>(device, "OpenDirective", "enum.IntEnum")
|
||||
.value("Continue", Device::OpenDirective::Continue)
|
||||
.value("Cancel", Device::OpenDirective::Cancel)
|
||||
.value("Skip", Device::OpenDirective::Skip)
|
||||
.finalize();
|
||||
|
||||
pybind11::native_enum<Device::OpenStatusType>(device, "OpenStatusType", "enum.IntEnum")
|
||||
.value("QuestionContinueSkipCancel", Device::OpenStatusType::QuestionContinueSkipCancel)
|
||||
.value("QuestionContinueCancel", Device::OpenStatusType::QuestionContinueCancel)
|
||||
.value("Progress", Device::OpenStatusType::Progress)
|
||||
.value("Failed", Device::OpenStatusType::Failed)
|
||||
.finalize();
|
||||
|
||||
device
|
||||
.def("__repr__", &Device::describe)
|
||||
.def("add_message_callback", &Device::addMessageCallback, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("clear_script", &Device::clearScript, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
@@ -33,7 +49,8 @@ void init_device(pybind11::module_& m) {
|
||||
.def("get_serial_number", &Device::getSerialNumber)
|
||||
.def("get_serial", &Device::getSerial)
|
||||
.def("get_pcb_serial", &Device::getPCBSerial, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_mac_address", &Device::getMACAddress, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_mac_addresses", &Device::getMACAddresses, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_macsec_networks", &Device::getMACsecNetworks)
|
||||
.def("get_supported_rx_networks", &Device::getSupportedRXNetworks, pybind11::return_value_policy::reference)
|
||||
.def("get_supported_tx_networks", &Device::getSupportedTXNetworks, pybind11::return_value_policy::reference)
|
||||
.def("get_tc10_status", &Device::getTC10Status, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
@@ -44,6 +61,10 @@ void init_device(pybind11::module_& m) {
|
||||
.def("is_online_supported", &Device::isOnlineSupported)
|
||||
.def("is_online", &Device::isOnline)
|
||||
.def("is_open", &Device::isOpen)
|
||||
.def("iso15765_enable", &Device::iso15765Enable, pybind11::arg("network"), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("iso15765_disable_all", &Device::iso15765DisableAll, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("iso15765_transmit_message", &Device::iso15765TransmitMessage, pybind11::arg("network"), pybind11::arg("message"), pybind11::arg("timeout"), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("iso15765_setup_rx_flow_control", &Device::iso15765SetupRxFlowControl, pybind11::arg("network"), pybind11::arg("message"), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("open", [](Device& device) { return device.open(); }, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("prepare_script_load", &Device::prepareScriptLoad, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("remove_message_callback", &Device::removeMessageCallback, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
@@ -52,9 +73,11 @@ void init_device(pybind11::module_& m) {
|
||||
.def("set_digital_io", pybind11::overload_cast<IO, size_t, bool>(&Device::setDigitalIO), pybind11::arg("type"), pybind11::arg("number"), pybind11::arg("value"), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_polling_message_limit", &Device::setPollingMessageLimit)
|
||||
.def("set_rtc", &Device::setRTC, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("reboot", &Device::reboot, pybind11::arg("safe") = false, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("start_script", &Device::startScript, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("stop_script", &Device::stopScript, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("supports_tc10", &Device::supportsTC10)
|
||||
.def("supports_reboot", &Device::supportsReboot)
|
||||
.def("supports_live_data", &Device::supportsLiveData)
|
||||
.def("subscribe_live_data", &Device::subscribeLiveData, pybind11::arg("message"), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("unsubscribe_live_data", &Device::unsubscribeLiveData, pybind11::arg("handle"), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
@@ -62,7 +85,7 @@ void init_device(pybind11::module_& m) {
|
||||
.def("set_value_live_data", &Device::setValueLiveData, pybind11::arg("message"), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("transmit", pybind11::overload_cast<std::shared_ptr<Frame>>(&Device::transmit), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("upload_coremini", [](Device& device, std::string& path, Disk::MemoryType memType) { std::ifstream ifs(path, std::ios::binary); return device.uploadCoremini(ifs, memType); }, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("write_macsec_config", &Device::writeMACsecConfig, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("write_macsec_config", &Device::writeMACsecConfig, pybind11::arg("config"), pybind11::arg("network"), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("send_eth_phy_msg", &Device::sendEthPhyMsg, pybind11::arg("message"), pybind11::arg("timeout") = std::chrono::milliseconds(50), pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_chip_versions", &Device::getChipVersions, pybind11::arg("refreshComponents") = true, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("supports_disk_formatting", &Device::supportsDiskFormatting, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
|
||||
@@ -36,9 +36,10 @@ void init_devicetype(pybind11::module_& m) {
|
||||
.value("RADEpsilon", DeviceType::Enum::RADEpsilon)
|
||||
.value("RADEpsilonXL", DeviceType::Enum::RADEpsilonXL)
|
||||
.value("RADGalaxy2", DeviceType::Enum::RADGalaxy2)
|
||||
.value("RADwBMS", DeviceType::Enum::RADwBMS)
|
||||
.value("RADMoon3", DeviceType::Enum::RADMoon3)
|
||||
.value("RADGemini", DeviceType::Enum::RADGemini)
|
||||
.value("RADComet", DeviceType::Enum::RADComet)
|
||||
.value("RADArgos", DeviceType::Enum::RADArgos)
|
||||
.value("RADComet2", DeviceType::Enum::RADComet2)
|
||||
.value("FIRE3_FlexRay", DeviceType::Enum::FIRE3_FlexRay)
|
||||
.value("FIRE3_T1S_LIN", DeviceType::Enum::FIRE3_T1S_LIN)
|
||||
.value("FIRE3_T1S_SENT", DeviceType::Enum::FIRE3_T1S_SENT)
|
||||
|
||||
@@ -40,6 +40,16 @@ void init_idevicesettings(pybind11::module_& m) {
|
||||
.value("Normal", LINMode::NORMAL_MODE)
|
||||
.value("Fast", LINMode::FAST_MODE);
|
||||
|
||||
pybind11::enum_<RADGPTPProfile>(settings, "GPTPProfile")
|
||||
.value("Standard", RADGPTPProfile::RAD_GPTP_PROFILE_STANDARD)
|
||||
.value("Automotive", RADGPTPProfile::RAD_GPTP_PROFILE_AUTOMOTIVE);
|
||||
|
||||
pybind11::enum_<RADGPTPRole>(settings, "GPTPRole")
|
||||
.value("Disabled", RADGPTPRole::RAD_GPTP_ROLE_DISABLED)
|
||||
.value("Passive", RADGPTPRole::RAD_GPTP_ROLE_PASSIVE)
|
||||
.value("Master", RADGPTPRole::RAD_GPTP_ROLE_MASTER)
|
||||
.value("Slave", RADGPTPRole::RAD_GPTP_ROLE_SLAVE);
|
||||
|
||||
pybind11::enum_<MiscIOAnalogVoltage>(settings, "MiscIOAnalogVoltage")
|
||||
.value("V0", MiscIOAnalogVoltage::V0)
|
||||
.value("V1", MiscIOAnalogVoltage::V1)
|
||||
@@ -48,6 +58,10 @@ void init_idevicesettings(pybind11::module_& m) {
|
||||
.value("V4", MiscIOAnalogVoltage::V4)
|
||||
.value("V5", MiscIOAnalogVoltage::V5);
|
||||
|
||||
pybind11::enum_<LinuxConfigurationPort>(settings, "LinuxConfigurationPort")
|
||||
.value("USB", LinuxConfigurationPort::USB)
|
||||
.value("ETH01", LinuxConfigurationPort::ETH01);
|
||||
|
||||
pybind11::classh<IDeviceSettings>(m, "IDeviceSettings")
|
||||
.def("apply", &IDeviceSettings::apply, pybind11::arg("temporary") = 0, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("apply_defaults", &IDeviceSettings::applyDefaults, pybind11::arg("temporary") = 0, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
@@ -119,7 +133,28 @@ void init_idevicesettings(pybind11::module_& m) {
|
||||
|
||||
.def("set_misc_io_analog_output_enabled", &IDeviceSettings::setMiscIOAnalogOutputEnabled, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_misc_io_analog_output", &IDeviceSettings::setMiscIOAnalogOutput, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
|
||||
|
||||
// Performance blast
|
||||
.def("is_perf_test_enabled", &IDeviceSettings::isPerfTestEnabled, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_perf_test_enable", &IDeviceSettings::setPerfTestEnable, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
// gPTP methods
|
||||
.def("get_gptp_profile", &IDeviceSettings::getGPTPProfile, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_gptp_profile", &IDeviceSettings::setGPTPProfile, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_gptp_role", &IDeviceSettings::getGPTPRole, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_gptp_role", &IDeviceSettings::setGPTPRole, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_gptp_enabled_port", &IDeviceSettings::getGPTPEnabledPort, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_gptp_enabled_port", &IDeviceSettings::setGPTPEnabledPort, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("is_gptp_clock_syntonization_enabled", &IDeviceSettings::isGPTPClockSyntonizationEnabled, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_gptp_clock_syntonization_enabled", &IDeviceSettings::setGPTPClockSyntonizationEnabled, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
|
||||
// Linux operating-system settings (Fire3 family devices)
|
||||
.def("get_linux_boot_enabled", &IDeviceSettings::getLinuxBootEnabled, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_linux_boot_enabled", &IDeviceSettings::setLinuxBootEnabled, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_external_wifi_antenna_enabled", &IDeviceSettings::getExternalWifiAntennaEnabled, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_external_wifi_antenna_enabled", &IDeviceSettings::setExternalWifiAntennaEnabled, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("get_linux_configuration_port", &IDeviceSettings::getLinuxConfigurationPort, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
.def("set_linux_configuration_port", &IDeviceSettings::setLinuxConfigurationPort, pybind11::call_guard<pybind11::gil_scoped_release>())
|
||||
|
||||
// Status properties
|
||||
.def_readonly("disabled", &IDeviceSettings::disabled)
|
||||
.def_readonly("readonly", &IDeviceSettings::readonly);
|
||||
|
||||
@@ -15,10 +15,13 @@ void init_devicetype(pybind11::module_&);
|
||||
void init_message(pybind11::module_&);
|
||||
void init_canmessage(pybind11::module_&);
|
||||
void init_canerrormessage(pybind11::module_&);
|
||||
void init_iso15765message(pybind11::module_&);
|
||||
void init_ethernetmessage(pybind11::module_&);
|
||||
void init_linmessage(pybind11::module_&);
|
||||
void init_tc10statusmessage(pybind11::module_&);
|
||||
void init_gptpstatusmessage(pybind11::module_&);
|
||||
void init_allmacaddressesmessage(pybind11::module_&);
|
||||
void init_apperrormessage(pybind11::module_&);
|
||||
void init_mdiomessage(pybind11::module_&);
|
||||
void init_spimessage(pybind11::module_&);
|
||||
void init_ethernetstatusmessage(pybind11::module_&);
|
||||
@@ -30,7 +33,10 @@ void init_deviceextension(pybind11::module_&);
|
||||
void init_chipid(pybind11::module_&);
|
||||
void init_versionreport(pybind11::module_&);
|
||||
void init_device(pybind11::module_&);
|
||||
void init_command(pybind11::module_&);
|
||||
void init_main51message(pybind11::module_&);
|
||||
void init_messagefilter(pybind11::module_&);
|
||||
void init_main51messagefilter(pybind11::module_&);
|
||||
void init_messagecallback(pybind11::module_&);
|
||||
void init_version(pybind11::module_&);
|
||||
void init_flexray(pybind11::module_& m);
|
||||
@@ -38,6 +44,9 @@ void init_idevicesettings(pybind11::module_&);
|
||||
void init_ethphymessage(pybind11::module_&);
|
||||
void init_livedata(pybind11::module_&);
|
||||
void init_livedatamessage(pybind11::module_&);
|
||||
#ifdef ICSNEO_ENABLE_BOOTLOADER
|
||||
void init_bootloader(pybind11::module_&);
|
||||
#endif
|
||||
|
||||
PYBIND11_MODULE(icsneopy, m) {
|
||||
pybind11::options options;
|
||||
@@ -55,17 +64,23 @@ PYBIND11_MODULE(icsneopy, m) {
|
||||
init_message(m);
|
||||
init_canmessage(m);
|
||||
init_canerrormessage(m);
|
||||
init_iso15765message(m);
|
||||
init_ethernetmessage(m);
|
||||
init_linmessage(m);
|
||||
init_tc10statusmessage(m);
|
||||
init_gptpstatusmessage(m);
|
||||
init_allmacaddressesmessage(m);
|
||||
init_apperrormessage(m);
|
||||
init_mdiomessage(m);
|
||||
init_ethernetstatusmessage(m);
|
||||
init_macsecconfig(m);
|
||||
init_scriptstatusmessage(m);
|
||||
init_spimessage(m);
|
||||
init_livedatamessage(m);
|
||||
init_command(m);
|
||||
init_main51message(m);
|
||||
init_messagefilter(m);
|
||||
init_main51messagefilter(m);
|
||||
init_messagecallback(m);
|
||||
init_diskdriver(m);
|
||||
init_diskdetails(m);
|
||||
@@ -76,6 +91,9 @@ PYBIND11_MODULE(icsneopy, m) {
|
||||
init_device(m);
|
||||
init_deviceextension(m);
|
||||
init_idevicesettings(m);
|
||||
#ifdef ICSNEO_ENABLE_BOOTLOADER
|
||||
init_bootloader(m);
|
||||
#endif
|
||||
|
||||
m.def("find_all_devices", &FindAllDevices);
|
||||
m.def("get_supported_devices", &GetSupportedDevices);
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
VERSION="1.10.5"
|
||||
ROOT="$PWD/libpcap"
|
||||
SOURCE="$ROOT/source"
|
||||
BUILD="$ROOT/build"
|
||||
INSTALL="$ROOT/install"
|
||||
|
||||
mkdir -p "$ROOT"
|
||||
cd "$ROOT" || exit 1
|
||||
|
||||
curl -LO "https://www.tcpdump.org/release/libpcap-$VERSION.tar.xz" || exit 1
|
||||
tar -xf "libpcap-$VERSION.tar.xz" || exit 1
|
||||
mv "libpcap-$VERSION" "$SOURCE" || exit 1
|
||||
|
||||
cmake -D CMAKE_POSITION_INDEPENDENT_CODE=ON -D CMAKE_INSTALL_PREFIX="$INSTALL" -D BUILD_SHARED_LIBS=OFF -D BUILD_WITH_LIBNL=OFF -D DISABLE_DBUS=ON -D DISABLE_LINUX_USBMON=ON -D DISABLE_BLUETOOTH=ON -D DISABLE_NETMAP=ON -D DISABLE_DPDK=ON -D DISABLE_RDMA=ON -D DISABLE_DAG=ON -D DISABLE_SEPTEL=ON -D DISABLE_SNF=ON -D DISABLE_TC=ON -B "$BUILD" -S "$SOURCE" || exit 1
|
||||
cmake --build "$BUILD" || exit 1
|
||||
cmake --install "$BUILD" || exit 1
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
#!/bin/sh
|
||||
|
||||
cmake -GNinja -Bbuild -DCMAKE_BUILD_TYPE=Release -DLIBICSNEO_BUILD_EXAMPLES=ON \
|
||||
-DLIBICSNEO_BUILD_UNIT_TESTS=ON -DLIBICSNEO_ENABLE_TCP=OFF || exit 1
|
||||
cmake -GNinja -Bbuild -DCMAKE_BUILD_TYPE=Release -DLIBICSNEO_BUILD_EXAMPLES=ON -DLIBICSNEO_BUILD_UNIT_TESTS=ON -DLIBICSNEO_ENABLE_BOOTLOADER=ON || exit 1
|
||||
|
||||
cmake --build build || exit 1
|
||||
|
||||
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
|
||||
export CIBW_BEFORE_ALL="sh ci/bootstrap-cibuildwheel.sh"
|
||||
export CIBW_BUILD="*manylinux*" # no musl
|
||||
export CIBW_ENVIRONMENT="LD_LIBRARY_PATH=/project/fc/libicsbl-src/lib64"
|
||||
export SKBUILD_CMAKE_DEFINE="LIBICSNEO_ENABLE_BOOTLOADER=ON;ICSPB_BOOTSTRAP_DIR=/project/icspb;FETCHCONTENT_BASE_DIR=/project/fc"
|
||||
|
||||
sh ci/build-wheel-posix.sh
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
|
||||
export CIBW_ARCHS="arm64"
|
||||
export SKBUILD_CMAKE_DEFINE="LIBICSNEO_ENABLE_BOOTLOADER=ON;ICSPB_BOOTSTRAP_DIR=$PWD/icspb;FETCHCONTENT_BASE_DIR=$PWD/fc"
|
||||
export REPAIR_LIBRARY_PATH="$PWD/fc/libicsbl-src/lib"
|
||||
export MACOSX_DEPLOYMENT_TARGET="10.14"
|
||||
|
||||
sh ci/build-wheel-posix.sh
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
call "%VCVARS64_2022%"
|
||||
|
||||
set "SKBUILD_CMAKE_DEFINE=LIBICSNEO_ENABLE_BOOTLOADER=ON;ICSPB_BOOTSTRAP_DIR=%CD%\icspb;FETCHCONTENT_BASE_DIR=%CD%\fc"
|
||||
set "PATH=%CD%\fc\libicsbl-src\bin;%PATH%"
|
||||
|
||||
python.exe -m venv env || exit /b 1
|
||||
call env\Scripts\Activate.bat || exit /b 1
|
||||
python.exe -m pip install cibuildwheel || exit /b 1
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
mkdir build >nul 2>&1
|
||||
|
||||
cmake -GNinja -Bbuild -DCMAKE_BUILD_TYPE=Release -DLIBICSNEO_BUILD_UNIT_TESTS=ON ^
|
||||
-DLIBICSNEO_ENABLE_TCP=ON || exit /b 1
|
||||
cmake -GNinja -Bbuild -DCMAKE_BUILD_TYPE=Release -DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DLIBICSNEO_BUILD_UNIT_TESTS=ON -DLIBICSNEO_ENABLE_BOOTLOADER=ON || exit /b 1
|
||||
|
||||
cmake --build build || exit /b 1
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
# - Try to find libpcap include dirs and libraries
|
||||
#
|
||||
# Usage of this module as follows:
|
||||
#
|
||||
# find_package(PCAP)
|
||||
#
|
||||
# Variables used by this module, they can change the default behaviour and need
|
||||
# to be set before calling find_package:
|
||||
#
|
||||
# PCAP_ROOT_DIR Set this variable to the root installation of
|
||||
# libpcap if the module has problems finding the
|
||||
# proper installation path.
|
||||
#
|
||||
# Variables defined by this module:
|
||||
#
|
||||
# PCAP_FOUND System has libpcap, include and library dirs found
|
||||
# PCAP_INCLUDE_DIR The libpcap include directories.
|
||||
# PCAP_LIBRARY The libpcap library (possibly includes a thread
|
||||
# library e.g. required by pf_ring's libpcap)
|
||||
# HAVE_PF_RING If a found version of libpcap supports PF_RING
|
||||
|
||||
find_path(PCAP_ROOT_DIR
|
||||
NAMES include/pcap.h
|
||||
)
|
||||
|
||||
find_path(PCAP_INCLUDE_DIR
|
||||
NAMES pcap.h
|
||||
HINTS ${PCAP_ROOT_DIR}/include
|
||||
)
|
||||
|
||||
find_library(PCAP_LIBRARY
|
||||
NAMES pcap
|
||||
HINTS ${PCAP_ROOT_DIR}/lib
|
||||
)
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
find_package_handle_standard_args(PCAP DEFAULT_MSG
|
||||
PCAP_LIBRARY
|
||||
PCAP_INCLUDE_DIR
|
||||
)
|
||||
|
||||
include(CheckCSourceCompiles)
|
||||
set(CMAKE_REQUIRED_LIBRARIES ${PCAP_LIBRARY})
|
||||
check_c_source_compiles("int main() { return 0; }" PCAP_LINKS_SOLO)
|
||||
set(CMAKE_REQUIRED_LIBRARIES)
|
||||
|
||||
# check if linking against libpcap also needs to link against a thread library
|
||||
if (NOT PCAP_LINKS_SOLO)
|
||||
find_package(Threads)
|
||||
if (THREADS_FOUND)
|
||||
set(CMAKE_REQUIRED_LIBRARIES ${PCAP_LIBRARY} ${CMAKE_THREAD_LIBS_INIT})
|
||||
check_c_source_compiles("int main() { return 0; }" PCAP_NEEDS_THREADS)
|
||||
set(CMAKE_REQUIRED_LIBRARIES)
|
||||
endif ()
|
||||
if (THREADS_FOUND AND PCAP_NEEDS_THREADS)
|
||||
set(_tmp ${PCAP_LIBRARY} ${CMAKE_THREAD_LIBS_INIT})
|
||||
list(REMOVE_DUPLICATES _tmp)
|
||||
set(PCAP_LIBRARY ${_tmp}
|
||||
CACHE STRING "Libraries needed to link against libpcap" FORCE)
|
||||
else ()
|
||||
message(FATAL_ERROR "Couldn't determine how to link against libpcap")
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
include(CheckFunctionExists)
|
||||
set(CMAKE_REQUIRED_LIBRARIES ${PCAP_LIBRARY})
|
||||
check_function_exists(pcap_get_pfring_id HAVE_PF_RING)
|
||||
set(CMAKE_REQUIRED_LIBRARIES)
|
||||
|
||||
mark_as_advanced(
|
||||
PCAP_ROOT_DIR
|
||||
PCAP_INCLUDE_DIR
|
||||
PCAP_LIBRARY
|
||||
)
|
||||
@@ -21,10 +21,15 @@
|
||||
#include "icsneo/communication/message/hardwareinfo.h"
|
||||
#include "icsneo/communication/message/tc10statusmessage.h"
|
||||
#include "icsneo/communication/message/gptpstatusmessage.h"
|
||||
#include "icsneo/communication/message/allmacaddressesmessage.h"
|
||||
#include "icsneo/communication/message/apperrormessage.h"
|
||||
#include "icsneo/communication/message/ethernetstatusmessage.h"
|
||||
#include "icsneo/communication/message/networkmutexmessage.h"
|
||||
#include "icsneo/communication/message/clientidmessage.h"
|
||||
#include "icsneo/communication/message/mfgconfigmessage.h"
|
||||
#include "icsneo/communication/message/spiportkeymessage.h"
|
||||
#include "icsneo/communication/message/genericapidatamessage.h"
|
||||
#include "icsneo/communication/message/genericapistatusmessage.h"
|
||||
#include "icsneo/communication/command.h"
|
||||
#include "icsneo/device/device.h"
|
||||
#include "icsneo/communication/packet/canpacket.h"
|
||||
@@ -39,6 +44,7 @@
|
||||
#include "icsneo/communication/packet/i2cpacket.h"
|
||||
#include "icsneo/communication/packet/scriptstatuspacket.h"
|
||||
#include "icsneo/communication/packet/linpacket.h"
|
||||
#include "icsneo/communication/message/iso15765message.h"
|
||||
#include "icsneo/communication/packet/componentversionpacket.h"
|
||||
#include "icsneo/communication/packet/supportedfeaturespacket.h"
|
||||
#include "icsneo/communication/packet/mdiopacket.h"
|
||||
@@ -340,9 +346,21 @@ bool Decoder::decode(std::shared_ptr<Message>& result, const std::shared_ptr<Pac
|
||||
case ExtendedCommand::LiveData:
|
||||
result = HardwareLiveDataPacket::DecodeToMessage(packet->data, report);
|
||||
return true;
|
||||
case ExtendedCommand::ExecuteSPIPortKeyOperation:
|
||||
result = SPIPortKeyMessage::DecodeToMessage(packet->data);
|
||||
return true;
|
||||
case ExtendedCommand::ReadGenericAPIData:
|
||||
result = GenericAPIDataMessage::DecodeToMessage(packet->data);
|
||||
return true;
|
||||
case ExtendedCommand::ReadGenericAPIStatus:
|
||||
result = GenericAPIStatusMessage::DecodeToMessage(packet->data);
|
||||
return true;
|
||||
case ExtendedCommand::GetTC10Status:
|
||||
result = TC10StatusMessage::DecodeToMessage(packet->data);
|
||||
return true;
|
||||
case ExtendedCommand::GetAllMACAddresses:
|
||||
result = AllMACAddressesMessage::DecodeToMessage(packet->data);
|
||||
return true;
|
||||
case ExtendedCommand::GetGPTPStatus: {
|
||||
result = GPTPStatus::DecodeToMessage(packet->data, report);
|
||||
return true;
|
||||
@@ -355,6 +373,9 @@ bool Decoder::decode(std::shared_ptr<Message>& result, const std::shared_ptr<Pac
|
||||
);
|
||||
protoapi::Id protoId = protoapi::getProtoId(responseBody.data(), responseBody.size());
|
||||
switch(protoId) {
|
||||
case protoapi::Id::MfgConfig:
|
||||
result = MfgConfigMessage::DecodeToMessage(responseBody);
|
||||
return true;
|
||||
case protoapi::Id::NetworkMutex:
|
||||
result = NetworkMutexMessage::DecodeToMessage(responseBody);
|
||||
return true;
|
||||
@@ -459,6 +480,14 @@ bool Decoder::decode(std::shared_ptr<Message>& result, const std::shared_ptr<Pac
|
||||
|
||||
return true;
|
||||
}
|
||||
case Command::J2534Command: {
|
||||
result = J2534CommandMessage::decodeToMessage(packet->data);
|
||||
if(!result) {
|
||||
report(APIEvent::Type::PacketDecodingError, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
auto msg = std::make_shared<Main51Message>();
|
||||
msg->command = Command(packet->data[0]);
|
||||
@@ -559,6 +588,9 @@ bool Decoder::decode(std::shared_ptr<Message>& result, const std::shared_ptr<Pac
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
report(APIEvent::Type::UnexpectedNetworkType, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
// For the moment other types of messages will automatically be decoded as raw messages
|
||||
|
||||
@@ -234,7 +234,9 @@ bool Encoder::encode(const Packetizer& packetizer, std::vector<uint8_t>& result,
|
||||
result = packetizer.packetWrap(result, false);
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
report(APIEvent::Type::MessageFormattingError, APIEvent::Severity::Error);
|
||||
return false; // The message was not a properly formed Message
|
||||
}
|
||||
|
||||
// Early returns may mean we don't reach this far, check the type you're concerned with
|
||||
|
||||
@@ -163,6 +163,8 @@ void A2BMessage::setChannelSample(Direction dir, uint8_t channel, size_t frame,
|
||||
case PCMType::L24:
|
||||
sampleToSet = sampleToSet << 8;
|
||||
break;
|
||||
case PCMType::L32:
|
||||
break;
|
||||
}
|
||||
|
||||
if(channelSize16) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#include "icsneo/communication/message/allmacaddressesmessage.h"
|
||||
#include "icsneo/communication/command.h"
|
||||
#include "icsneo/communication/network.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
#pragma pack(push, 2)
|
||||
struct ResponseHeader {
|
||||
ExtendedCommand command;
|
||||
uint16_t length;
|
||||
uint16_t count;
|
||||
};
|
||||
|
||||
struct MacAddrEntryPacket {
|
||||
uint16_t networkId;
|
||||
uint8_t address[MACAddressLength];
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
std::shared_ptr<AllMACAddressesMessage> AllMACAddressesMessage::DecodeToMessage(const std::vector<uint8_t>& bytestream) {
|
||||
if(bytestream.size() < sizeof(ResponseHeader))
|
||||
return nullptr;
|
||||
|
||||
const auto* hdr = reinterpret_cast<const ResponseHeader*>(bytestream.data());
|
||||
|
||||
if(hdr->command != ExtendedCommand::GetAllMACAddresses)
|
||||
return nullptr;
|
||||
|
||||
if(hdr->count > MaxMACAddressCount)
|
||||
return nullptr;
|
||||
|
||||
const size_t required = sizeof(ResponseHeader) + hdr->count * sizeof(MacAddrEntryPacket);
|
||||
if(bytestream.size() < required)
|
||||
return nullptr;
|
||||
|
||||
auto msg = std::make_shared<AllMACAddressesMessage>();
|
||||
|
||||
const auto* entries = reinterpret_cast<const MacAddrEntryPacket*>(bytestream.data() + sizeof(ResponseHeader));
|
||||
for(uint16_t i = 0; i < hdr->count; ++i) {
|
||||
// The firmware sends CoreMini network IDs — convert to NetID for consistent use in libicsneo
|
||||
Network::NetID netId = Network::GetNetIDFromCoreMiniNetwork(static_cast<Network::CoreMini>(entries[i].networkId));
|
||||
auto addr = entries[i].address;
|
||||
MACAddress arrAddr;
|
||||
std::copy(addr, addr + MACAddressLength, arrAddr.begin());
|
||||
msg->addresses.emplace(std::make_pair(netId, arrAddr));
|
||||
}
|
||||
|
||||
return msg;
|
||||
}
|
||||
@@ -37,7 +37,7 @@ struct Packet {
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
std::shared_ptr<Message> EthernetStatusMessage::DecodeToMessage(const std::vector<uint8_t>& bytestream) {
|
||||
std::shared_ptr<RawMessage> EthernetStatusMessage::DecodeToMessage(const std::vector<uint8_t>& bytestream) {
|
||||
if(bytestream.size() < sizeof(Packet)) {
|
||||
return nullptr;
|
||||
}
|
||||
@@ -76,5 +76,5 @@ std::shared_ptr<Message> EthernetStatusMessage::DecodeToMessage(const std::vecto
|
||||
break;
|
||||
default: return nullptr;
|
||||
}
|
||||
return std::make_shared<EthernetStatusMessage>(packet->network, packet->state, speed, packet->duplex, mode);
|
||||
}
|
||||
return std::make_shared<EthernetStatusMessage>(packet->network, packet->state != 0, speed, packet->duplex != 0, mode);
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ bool EthPhyMessage::appendPhyMessage(bool writeEnable, bool clause45, uint8_t ph
|
||||
|
||||
bool EthPhyMessage::appendPhyMessage(std::shared_ptr<PhyMessage> message)
|
||||
{
|
||||
if(message != nullptr)
|
||||
if(message)
|
||||
{
|
||||
messages.push_back(message);
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#include "icsneo/communication/message/genericapidatamessage.h"
|
||||
#include "icsneo/communication/message/extendedresponsemessage.h"
|
||||
#include "icsneo/communication/command.h"
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
std::shared_ptr<GenericAPIDataMessage> GenericAPIDataMessage::DecodeToMessage(const std::vector<uint8_t>& bytestream) {
|
||||
if(bytestream.size() < sizeof(ExtendedResponseMessage::ResponseHeader))
|
||||
return nullptr;
|
||||
|
||||
const auto* hdr = reinterpret_cast<const ExtendedResponseMessage::ResponseHeader*>(bytestream.data());
|
||||
|
||||
if(hdr->command != ExtendedCommand::ReadGenericAPIData)
|
||||
return nullptr;
|
||||
|
||||
const size_t required = sizeof(ExtendedResponseMessage::ResponseHeader) + sizeof(GenericAPIDataHeader);
|
||||
if(bytestream.size() < required)
|
||||
return nullptr;
|
||||
|
||||
auto msg = std::make_shared<GenericAPIDataMessage>();
|
||||
|
||||
const auto* packet = reinterpret_cast<const GenericAPIDataPacket*>(bytestream.data() + sizeof(ExtendedResponseMessage::ResponseHeader));
|
||||
|
||||
msg->functionId = packet->header.functionId;
|
||||
msg->buffer.resize(packet->header.bufferLength);
|
||||
std::copy(packet->buffer, packet->buffer + packet->header.bufferLength, msg->buffer.data());
|
||||
return msg;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#include "icsneo/communication/message/genericapistatusmessage.h"
|
||||
#include "icsneo/communication/message/extendedresponsemessage.h"
|
||||
#include "icsneo/communication/command.h"
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
std::shared_ptr<GenericAPIStatusMessage> GenericAPIStatusMessage::DecodeToMessage(const std::vector<uint8_t>& bytestream) {
|
||||
if(bytestream.size() < sizeof(ExtendedResponseMessage::ResponseHeader))
|
||||
return nullptr;
|
||||
|
||||
const auto* hdr = reinterpret_cast<const ExtendedResponseMessage::ResponseHeader*>(bytestream.data());
|
||||
|
||||
if(hdr->command != ExtendedCommand::ReadGenericAPIStatus)
|
||||
return nullptr;
|
||||
|
||||
const size_t required = sizeof(ExtendedResponseMessage::ResponseHeader) + sizeof(GenericAPIStatusResponsePacket);
|
||||
if(bytestream.size() < required)
|
||||
return nullptr;
|
||||
|
||||
auto msg = std::make_shared<GenericAPIStatusMessage>();
|
||||
|
||||
const auto* packet = reinterpret_cast<const GenericAPIStatusResponsePacket*>(bytestream.data() + sizeof(ExtendedResponseMessage::ResponseHeader));
|
||||
|
||||
msg->functionId = packet->functionId;
|
||||
msg->finishedProcessing = static_cast<bool>(packet->finishedProcessing);
|
||||
msg->functionError = packet->functionError;
|
||||
msg->callbackError = packet->callbackError;
|
||||
return msg;
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
#include "icsneo/communication/message/iso15765message.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
std::shared_ptr<J2534CommandMessage> J2534CommandMessage::decodeToMessage(const std::vector<uint8_t>& data) {
|
||||
if(data.size() < 2)
|
||||
return nullptr;
|
||||
|
||||
auto msg = std::make_shared<J2534CommandMessage>((J2534Command)data[1]);
|
||||
if(data.size() > 2)
|
||||
msg->setArgumentData(std::vector<uint8_t>(data.begin() + 2, data.end()));
|
||||
|
||||
return msg;
|
||||
}
|
||||
|
||||
uint16_t J2534CommandMessage::read16LE(size_t o) const {
|
||||
return (uint16_t)((uint16_t)argumentData[o] | ((uint16_t)argumentData[o + 1] << 8));
|
||||
}
|
||||
|
||||
void J2534CommandMessage::write16LE(size_t o, uint16_t v) {
|
||||
argumentData[o] = (uint8_t)(v & 0xFF);
|
||||
argumentData[o + 1] = (uint8_t)((v >> 8) & 0xFF);
|
||||
}
|
||||
|
||||
uint16_t J2534CommandMessage::read16BE(size_t o) const {
|
||||
return (uint16_t)(((uint16_t)argumentData[o] << 8) | argumentData[o + 1]);
|
||||
}
|
||||
|
||||
void J2534CommandMessage::write16BE(size_t o, uint16_t v) {
|
||||
argumentData[o] = (uint8_t)((v >> 8) & 0xFF);
|
||||
argumentData[o + 1] = (uint8_t)(v & 0xFF);
|
||||
}
|
||||
|
||||
void J2534CommandMessage::writeBits16LE(size_t o, unsigned bitPos, unsigned bitCount, uint32_t value) {
|
||||
const uint16_t mask = (uint16_t)(((1u << bitCount) - 1u) << bitPos);
|
||||
uint16_t word = read16LE(o);
|
||||
word = (uint16_t)((word & ~mask) | (((value << bitPos) & mask)));
|
||||
write16LE(o, word);
|
||||
}
|
||||
|
||||
uint32_t J2534CommandMessage::read32LE(size_t o) const {
|
||||
return (uint32_t)argumentData[o]
|
||||
| ((uint32_t)argumentData[o + 1] << 8)
|
||||
| ((uint32_t)argumentData[o + 2] << 16)
|
||||
| ((uint32_t)argumentData[o + 3] << 24);
|
||||
}
|
||||
|
||||
void J2534CommandMessage::write32LE(size_t o, uint32_t v) {
|
||||
argumentData[o] = (uint8_t)(v & 0xFF);
|
||||
argumentData[o + 1] = (uint8_t)((v >> 8) & 0xFF);
|
||||
argumentData[o + 2] = (uint8_t)((v >> 16) & 0xFF);
|
||||
argumentData[o + 3] = (uint8_t)((v >> 24) & 0xFF);
|
||||
}
|
||||
|
||||
uint32_t J2534CommandMessage::read32BE(size_t o) const {
|
||||
return ((uint32_t)argumentData[o] << 24) | ((uint32_t)argumentData[o + 1] << 16)
|
||||
| ((uint32_t)argumentData[o + 2] << 8) | (uint32_t)argumentData[o + 3];
|
||||
}
|
||||
|
||||
void J2534CommandMessage::write32BE(size_t o, uint32_t v) {
|
||||
argumentData[o] = (uint8_t)((v >> 24) & 0xFF);
|
||||
argumentData[o + 1] = (uint8_t)((v >> 16) & 0xFF);
|
||||
argumentData[o + 2] = (uint8_t)((v >> 8) & 0xFF);
|
||||
argumentData[o + 3] = (uint8_t)(v & 0xFF);
|
||||
}
|
||||
|
||||
J2534_RxCanFilter J2534SetupCanRxFilteringMessage::getRxCanFilter() const {
|
||||
constexpr size_t filterSize = sizeof(J2534_RxCanFilter::fb);
|
||||
J2534_RxCanFilter filter = {};
|
||||
if(argumentData.size() >= (10 + filterSize))
|
||||
{
|
||||
filter.idx = (argumentData[2] << 8) | argumentData[3];
|
||||
filter.enabled = (argumentData[4] << 8) | argumentData[5];
|
||||
filter.filterCount = (argumentData[6] << 8) | argumentData[7];
|
||||
filter.fb = *((MessageFilterBytes*)(argumentData.data() + 8));
|
||||
filter.networkId = (argumentData[8 + filterSize] << 8) | argumentData[9 + filterSize];
|
||||
}
|
||||
return filter;
|
||||
}
|
||||
|
||||
void J2534SetupCanRxFilteringMessage::setRxCanFilter(const J2534_RxCanFilter& filter) {
|
||||
argumentData.resize(10 + sizeof(filter.fb));
|
||||
argumentData[2] = (filter.idx >> 8) & 0xFF;
|
||||
argumentData[3] = filter.idx & 0xFF;
|
||||
argumentData[4] = (filter.enabled >> 8) & 0xFF;
|
||||
argumentData[5] = filter.enabled & 0xFF;
|
||||
argumentData[6] = (filter.filterCount >> 8) & 0xFF;
|
||||
argumentData[7] = filter.filterCount & 0xFF;
|
||||
*((MessageFilterBytes*)(argumentData.data() + 8)) = filter.fb;
|
||||
argumentData[8 + sizeof(filter.fb)] = (filter.networkId >> 8) & 0xFF;
|
||||
argumentData[9 + sizeof(filter.fb)] = filter.networkId & 0xFF;
|
||||
}
|
||||
|
||||
|
||||
J2534SetupIso15765FlowControlMessage::J2534SetupIso15765FlowControlMessage()
|
||||
: J2534CommandMessage(J2534Command::SetupIso15765RxFilter) {
|
||||
argumentData.resize(MessageSize);
|
||||
// Bytes [0..1] were populated by the base constructor. Everything else starts at zero
|
||||
// (matches the previous behavior which zeroed the flt region and left the rest of the
|
||||
// caller-supplied struct as-is; typical callers value-initialized their struct too).
|
||||
for(size_t i = 2; i < MessageSize; ++i)
|
||||
argumentData[i] = 0;
|
||||
}
|
||||
|
||||
void J2534SetupIso15765FlowControlMessage::rebuildFilterBytes(void) {
|
||||
// Zero the 28-byte flt region.
|
||||
for(size_t i = 0; i < FltSize; ++i)
|
||||
argumentData[FltOffset + i] = 0;
|
||||
|
||||
const uint32_t id = read32LE(IdOffset);
|
||||
const uint32_t idMask = read32LE(IdMaskOffset);
|
||||
const bool is29Bit = getFlagBit(FlagId29BitEnable);
|
||||
const bool extAddr = getFlagBit(FlagExtAddressEnable);
|
||||
const uint8_t extAddrByte = argumentData[ExtAddrOffset];
|
||||
|
||||
// CoreMiniMessageFilterBytes has an interleaved layout:
|
||||
// uiFilterMask0 at flt+0, uiFilterID0 at flt+2
|
||||
// uiFilterMask1 at flt+4, uiFilterID1 at flt+6
|
||||
// uiFilterMask2 at flt+8, uiFilterID2 at flt+10
|
||||
// datalink.uiFilterMask3 at flt+12, datalink.uiFilterID3 at flt+14
|
||||
//
|
||||
// CoreMiniMsgBitsCAN bit layout within each 16-bit unit:
|
||||
// unit0: IDE(bit0), SRR(bit1), SID(bits2-12), NETWORKINDEX(bits13-15)
|
||||
// unit1: EID(bits0-11), TXMSG(bit12), ...
|
||||
// unit2: DLC(bits0-3), ..., RTR(bit9), EID2(bits10-15)
|
||||
const size_t MaskUnit0 = FltOffset + 0;
|
||||
const size_t MaskUnit1 = FltOffset + 4;
|
||||
const size_t MaskUnit2 = FltOffset + 8;
|
||||
const size_t ValueUnit0 = FltOffset + 2;
|
||||
const size_t ValueUnit1 = FltOffset + 6;
|
||||
const size_t ValueUnit2 = FltOffset + 10;
|
||||
|
||||
// filter arbid: pMask->IDE = 1
|
||||
writeBits16LE(MaskUnit0, /*bit*/0, /*width*/1, 1);
|
||||
|
||||
if(is29Bit) {
|
||||
// pValue->IDE = 1; pValue->SID = (id >> 18) & 0x7FF
|
||||
writeBits16LE(ValueUnit0, 0, 1, 1);
|
||||
writeBits16LE(ValueUnit0, 2, 11, (id >> 18) & 0x7FF);
|
||||
// pValue->EID = (id >> 6) & 0xFFF
|
||||
writeBits16LE(ValueUnit1, 0, 12, (id >> 6) & 0xFFF);
|
||||
// pValue->EID2 = id & 0x3F
|
||||
writeBits16LE(ValueUnit2, 10, 6, id & 0x3F);
|
||||
// pMask->SID = (id_mask >> 18) & 0x7FF
|
||||
writeBits16LE(MaskUnit0, 2, 11, (idMask >> 18) & 0x7FF);
|
||||
// pMask->EID = (id_mask >> 6) & 0xFFF (overlaps pValue->{IDE,SID} storage)
|
||||
writeBits16LE(MaskUnit1, 0, 12, (idMask >> 6) & 0xFFF);
|
||||
// pMask->EID2 = id_mask & 0x3F (overlaps pValue->EID storage)
|
||||
writeBits16LE(MaskUnit2, 10, 6, idMask & 0x3F);
|
||||
} else {
|
||||
// pValue->IDE = 0 (already zero); pValue->SID = id
|
||||
writeBits16LE(ValueUnit0, 2, 11, id & 0x7FF);
|
||||
// pMask->SID = id_mask
|
||||
writeBits16LE(MaskUnit0, 2, 11, idMask & 0x7FF);
|
||||
}
|
||||
|
||||
// Extended-address filter: writes into the datalink.uiFilterID3 / uiFilterMask3 bytes.
|
||||
// uiFilterMask3 = flt[12..13] = wire[37..38]
|
||||
// uiFilterID3 = flt[14..15] = wire[39..40]
|
||||
if(extAddr) {
|
||||
const size_t kValueBytes = FltOffset + 14; // uiFilterID3
|
||||
const size_t kMaskBytes = FltOffset + 12; // uiFilterMask3
|
||||
argumentData[kValueBytes + 0] = extAddrByte;
|
||||
argumentData[kMaskBytes + 0] = 0xFF;
|
||||
argumentData[kValueBytes + 1] = 0;
|
||||
argumentData[kMaskBytes + 1] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t J2534SetupIso15765FlowControlMessage::getIdx(void) const { return read16LE(IdxOffset); }
|
||||
void J2534SetupIso15765FlowControlMessage::setIdx(uint16_t idx) { write16LE(IdxOffset, idx); }
|
||||
|
||||
uint16_t J2534SetupIso15765FlowControlMessage::getCoreMiniId(void) const { return read16LE(CoreMiniOffset); }
|
||||
void J2534SetupIso15765FlowControlMessage::setCoreMiniId(uint16_t coreMiniId) { write16LE(CoreMiniOffset, coreMiniId); }
|
||||
|
||||
uint8_t J2534SetupIso15765FlowControlMessage::getPadding(void) const { return argumentData[PaddingOffset]; }
|
||||
void J2534SetupIso15765FlowControlMessage::setPadding(uint8_t padding) { argumentData[PaddingOffset] = padding; }
|
||||
|
||||
uint32_t J2534SetupIso15765FlowControlMessage::getId(void) const { return read32LE(IdOffset); }
|
||||
void J2534SetupIso15765FlowControlMessage::setId(uint32_t id) { write32LE(IdOffset, id); rebuildFilterBytes(); }
|
||||
|
||||
uint32_t J2534SetupIso15765FlowControlMessage::getIdMask(void) const { return read32LE(IdMaskOffset); }
|
||||
void J2534SetupIso15765FlowControlMessage::setIdMask(uint32_t idMask) { write32LE(IdMaskOffset, idMask); rebuildFilterBytes(); }
|
||||
|
||||
uint32_t J2534SetupIso15765FlowControlMessage::getFcId(void) const { return read32LE(FcIdOffset); }
|
||||
void J2534SetupIso15765FlowControlMessage::setFcId(uint32_t fcId) { write32LE(FcIdOffset, fcId); }
|
||||
|
||||
uint8_t J2534SetupIso15765FlowControlMessage::getFlowControlExtendedAddress(void) const { return argumentData[FcExtAddrOffset]; }
|
||||
void J2534SetupIso15765FlowControlMessage::setFlowControlExtendedAddress(uint8_t addr) { argumentData[FcExtAddrOffset] = addr; }
|
||||
|
||||
uint8_t J2534SetupIso15765FlowControlMessage::getExtendedAddress(void) const { return argumentData[ExtAddrOffset]; }
|
||||
void J2534SetupIso15765FlowControlMessage::setExtendedAddress(uint8_t addr) { argumentData[ExtAddrOffset] = addr; rebuildFilterBytes(); }
|
||||
|
||||
uint8_t J2534SetupIso15765FlowControlMessage::getBlockSize(void) const { return argumentData[BlockSizeOffset]; }
|
||||
void J2534SetupIso15765FlowControlMessage::setBlockSize(uint8_t blockSize) { argumentData[BlockSizeOffset] = blockSize; }
|
||||
|
||||
uint8_t J2534SetupIso15765FlowControlMessage::getStMin(void) const { return argumentData[StMinOffset]; }
|
||||
void J2534SetupIso15765FlowControlMessage::setStMin(uint8_t stMin) { argumentData[StMinOffset] = stMin; }
|
||||
|
||||
uint16_t J2534SetupIso15765FlowControlMessage::getCfTimeout(void) const { return read16LE(CfTimeoutOffset); }
|
||||
void J2534SetupIso15765FlowControlMessage::setCfTimeout(uint16_t cfTimeout) { write16LE(CfTimeoutOffset, cfTimeout); }
|
||||
|
||||
uint32_t J2534SetupIso15765FlowControlMessage::getFlags(void) const { return read32LE(FlagsOffset); }
|
||||
void J2534SetupIso15765FlowControlMessage::setFlags(uint32_t flags) { write32LE(FlagsOffset, flags); rebuildFilterBytes(); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getEnable(void) const { return getFlagBit(FlagEnable); }
|
||||
void J2534SetupIso15765FlowControlMessage::setEnable(bool enable) { setFlagBit(FlagEnable, enable); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getIs29BitEnabled(void) const { return getFlagBit(FlagId29BitEnable); }
|
||||
void J2534SetupIso15765FlowControlMessage::setIs29BitEnabled(bool enable) { setFlagBit(FlagId29BitEnable, enable); rebuildFilterBytes(); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getIsFc29BitEnabled(void) const { return getFlagBit(FlagFcId29BitEnable); }
|
||||
void J2534SetupIso15765FlowControlMessage::setIsFc29BitEnabled(bool enable) { setFlagBit(FlagFcId29BitEnable, enable); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getExtAddressEnabled(void) const { return getFlagBit(FlagExtAddressEnable); }
|
||||
void J2534SetupIso15765FlowControlMessage::setExtAddressEnabled(bool enable) { setFlagBit(FlagExtAddressEnable, enable); rebuildFilterBytes(); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getFcExtAddressEnabled(void) const { return getFlagBit(FlagFcExtAddressEnable); }
|
||||
void J2534SetupIso15765FlowControlMessage::setFcExtAddressEnabled(bool enable) { setFlagBit(FlagFcExtAddressEnable, enable); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getFlowControlTransmissionEnabled(void) const { return getFlagBit(FlagEnableFlowControlTransmit); }
|
||||
void J2534SetupIso15765FlowControlMessage::setFlowControlTransmissionEnabled(bool enable) { setFlagBit(FlagEnableFlowControlTransmit, enable); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getPaddingEnabled(void) const { return getFlagBit(FlagPaddingEnable); }
|
||||
void J2534SetupIso15765FlowControlMessage::setPaddingEnabled(bool enable) { setFlagBit(FlagPaddingEnable, enable); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getIsCanFd(void) const { return getFlagBit(FlagIsCanFd); }
|
||||
void J2534SetupIso15765FlowControlMessage::setIsCanFd(bool enable) { setFlagBit(FlagIsCanFd, enable); }
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getIsBrsEnabled(void) const { return getFlagBit(FlagIsBrsEnabled); }
|
||||
void J2534SetupIso15765FlowControlMessage::setIsBrsEnabled(bool enable) { setFlagBit(FlagIsBrsEnabled, enable); }
|
||||
|
||||
void J2534SetupIso15765FlowControlMessage::setFlagBit(uint32_t mask, bool enable) {
|
||||
uint32_t f = read32LE(FlagsOffset);
|
||||
if(enable) f |= mask;
|
||||
else f &= ~mask;
|
||||
write32LE(FlagsOffset, f);
|
||||
}
|
||||
|
||||
bool J2534SetupIso15765FlowControlMessage::getFlagBit(uint32_t mask) const {
|
||||
return (read32LE(FlagsOffset) & mask) != 0;
|
||||
}
|
||||
|
||||
uint16_t Iso15765TxSetupMessage::getIdx(void) const { return read16LE(SetupIdxOffset); }
|
||||
void Iso15765TxSetupMessage::setIdx(uint16_t idx) { write16LE(SetupIdxOffset, idx); }
|
||||
|
||||
uint16_t Iso15765TxSetupMessage::getCoreMiniId(void) const { return read16LE(SetupCoreMiniOffset); }
|
||||
void Iso15765TxSetupMessage::setCoreMiniId(uint16_t coreMiniId) { write16LE(SetupCoreMiniOffset, coreMiniId); }
|
||||
|
||||
uint32_t Iso15765TxSetupMessage::getMessageLength(void) const { return read32LE(SetupMsgLenOffset); }
|
||||
void Iso15765TxSetupMessage::setMessageLength(uint32_t messageLength) { write32LE(SetupMsgLenOffset, messageLength); }
|
||||
|
||||
uint8_t Iso15765TxSetupMessage::getPadding(void) const { return argumentData[SetupPaddingOffset]; }
|
||||
void Iso15765TxSetupMessage::setPadding(uint8_t padding) { argumentData[SetupPaddingOffset] = padding; }
|
||||
|
||||
uint8_t Iso15765TxSetupMessage::getTxDl(void) const { return argumentData[SetupTxDlOffset]; }
|
||||
void Iso15765TxSetupMessage::setTxDl(uint8_t txDl) { argumentData[SetupTxDlOffset] = txDl; }
|
||||
|
||||
uint32_t Iso15765TxSetupMessage::getId(void) const { return read32LE(SetupIdOffset); }
|
||||
void Iso15765TxSetupMessage::setId(uint32_t id) { write32LE(SetupIdOffset, id); }
|
||||
|
||||
uint32_t Iso15765TxSetupMessage::getFcId(void) const { return read32LE(SetupFcIdOffset); }
|
||||
void Iso15765TxSetupMessage::setFcId(uint32_t fcId) { write32LE(SetupFcIdOffset, fcId); }
|
||||
|
||||
uint32_t Iso15765TxSetupMessage::getFcIdMask(void) const { return read32LE(SetupFcIdMaskOffset); }
|
||||
void Iso15765TxSetupMessage::setFcIdMask(uint32_t fcIdMask) { write32LE(SetupFcIdMaskOffset, fcIdMask); }
|
||||
|
||||
uint8_t Iso15765TxSetupMessage::getFlowControlExtendedAddress(void) const { return argumentData[SetupFcExtAddrOffset]; }
|
||||
void Iso15765TxSetupMessage::setFlowControlExtendedAddress(uint8_t addr) { argumentData[SetupFcExtAddrOffset] = addr; }
|
||||
|
||||
uint8_t Iso15765TxSetupMessage::getExtendedAddress(void) const { return argumentData[SetupExtAddrOffset]; }
|
||||
void Iso15765TxSetupMessage::setExtendedAddress(uint8_t addr) { argumentData[SetupExtAddrOffset] = addr; }
|
||||
|
||||
uint16_t Iso15765TxSetupMessage::getFsTimeout(void) const { return read16LE(SetupFsTimeoutOffset); }
|
||||
void Iso15765TxSetupMessage::setFsTimeout(uint16_t timeout) { write16LE(SetupFsTimeoutOffset, timeout); }
|
||||
|
||||
uint16_t Iso15765TxSetupMessage::getFsWait(void) const { return read16LE(SetupFsWaitOffset); }
|
||||
void Iso15765TxSetupMessage::setFsWait(uint16_t wait) { write16LE(SetupFsWaitOffset, wait); }
|
||||
|
||||
uint32_t Iso15765TxSetupMessage::getFlags(void) const { return read32LE(SetupFlagsOffset); }
|
||||
void Iso15765TxSetupMessage::setFlags(uint32_t flags) { write32LE(SetupFlagsOffset, flags); }
|
||||
|
||||
uint8_t Iso15765TxSetupMessage::getStMin(void) const { return argumentData[SetupStMinOffset]; }
|
||||
void Iso15765TxSetupMessage::setStMin(uint8_t stMin) { argumentData[SetupStMinOffset] = stMin; }
|
||||
|
||||
uint8_t Iso15765TxSetupMessage::getBlockSize(void) const { return argumentData[SetupBlockSizeOffset]; }
|
||||
void Iso15765TxSetupMessage::setBlockSize(uint8_t blockSize) { argumentData[SetupBlockSizeOffset] = blockSize; }
|
||||
|
||||
bool Iso15765TxSetupMessage::getIs29BitEnabled(void) const { return getFlagBit(FlagId29BitEnable); }
|
||||
void Iso15765TxSetupMessage::setIs29BitEnabled(bool enable) { setFlagBit(FlagId29BitEnable, enable); }
|
||||
bool Iso15765TxSetupMessage::getIsFc29BitEnabled(void) const { return getFlagBit(FlagFcId29BitEnable); }
|
||||
void Iso15765TxSetupMessage::setIsFc29BitEnabled(bool enable) { setFlagBit(FlagFcId29BitEnable, enable); }
|
||||
bool Iso15765TxSetupMessage::getExtAddressEnabled(void) const { return getFlagBit(FlagExtAddressEnable); }
|
||||
void Iso15765TxSetupMessage::setExtAddressEnabled(bool enable) { setFlagBit(FlagExtAddressEnable, enable); }
|
||||
bool Iso15765TxSetupMessage::getFcExtAddressEnabled(void) const { return getFlagBit(FlagFcExtAddressEnable); }
|
||||
void Iso15765TxSetupMessage::setFcExtAddressEnabled(bool enable) { setFlagBit(FlagFcExtAddressEnable, enable); }
|
||||
bool Iso15765TxSetupMessage::getOverrideStMin(void) const { return getFlagBit(FlagOverrideStMin); }
|
||||
void Iso15765TxSetupMessage::setOverrideStMin(bool enable) { setFlagBit(FlagOverrideStMin, enable); }
|
||||
bool Iso15765TxSetupMessage::getOverrideBlockSize(void) const { return getFlagBit(FlagOverrideBlockSize); }
|
||||
void Iso15765TxSetupMessage::setOverrideBlockSize(bool enable) { setFlagBit(FlagOverrideBlockSize, enable); }
|
||||
bool Iso15765TxSetupMessage::getPaddingEnabled(void) const { return getFlagBit(FlagPaddingEnable); }
|
||||
void Iso15765TxSetupMessage::setPaddingEnabled(bool enable) { setFlagBit(FlagPaddingEnable, enable); }
|
||||
bool Iso15765TxSetupMessage::getIsCanFd(void) const { return getFlagBit(FlagIsCanFd); }
|
||||
void Iso15765TxSetupMessage::setIsCanFd(bool enable) { setFlagBit(FlagIsCanFd, enable); }
|
||||
bool Iso15765TxSetupMessage::getIsBrsEnabled(void) const { return getFlagBit(FlagIsBrsEnabled); }
|
||||
void Iso15765TxSetupMessage::setIsBrsEnabled(bool enable) { setFlagBit(FlagIsBrsEnabled, enable); }
|
||||
|
||||
bool Iso15765TxSetupMessage::getFlagBit(uint32_t mask) const {
|
||||
return (getFlags() & mask) != 0;
|
||||
}
|
||||
|
||||
void Iso15765TxSetupMessage::setFlagBit(uint32_t mask, bool enable) {
|
||||
uint32_t f = getFlags();
|
||||
if(enable) f |= mask;
|
||||
else f &= ~mask;
|
||||
setFlags(f);
|
||||
}
|
||||
|
||||
uint16_t Iso15765TxDataMessage::getIdx(void) const { return read16LE(DataIdxOffset); }
|
||||
void Iso15765TxDataMessage::setIdx(uint16_t idx) { write16LE(DataIdxOffset, idx); }
|
||||
|
||||
uint32_t Iso15765TxDataMessage::getOffset(void) const { return read32LE(DataOffsetOffset); }
|
||||
void Iso15765TxDataMessage::setOffset(uint32_t offset) { write32LE(DataOffsetOffset, offset); }
|
||||
|
||||
uint16_t Iso15765TxDataMessage::getLen(void) const { return read16LE(DataLenOffset); }
|
||||
|
||||
const uint8_t* Iso15765TxDataMessage::getData(void) const { return argumentData.data() + DataPayloadOffset; }
|
||||
|
||||
void Iso15765TxDataMessage::setData(const uint8_t* sourceData, uint16_t len) {
|
||||
len = std::min(len, (uint16_t)MaxDataLength);
|
||||
argumentData.resize(DataPayloadOffset + len);
|
||||
write16LE(DataLenOffset, len);
|
||||
if(len > 0 && sourceData != nullptr)
|
||||
std::copy(sourceData, sourceData + len, argumentData.begin() + DataPayloadOffset);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
#include "icsneo/communication/message/mfgconfigmessage.h"
|
||||
#include "icsneo/communication/icspb.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
static MfgConfigMessage::VersionNumber versionFromProto(const settings::common::v1::VersionNumber& version) {
|
||||
MfgConfigMessage::VersionNumber decoded;
|
||||
decoded.major = version.major();
|
||||
decoded.minor = version.minor();
|
||||
if(version.has_release())
|
||||
decoded.release = version.release();
|
||||
if(version.has_build())
|
||||
decoded.build = version.build();
|
||||
return decoded;
|
||||
}
|
||||
|
||||
std::shared_ptr<MfgConfigMessage> MfgConfigMessage::DecodeToMessage(const std::vector<uint8_t>& bytestream) {
|
||||
MfgConfigMessage decoded;
|
||||
settings::manufacturing::v1::MfgConfig msg;
|
||||
|
||||
if(!protoapi::processResponse(bytestream.data(), bytestream.size(), msg)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if(msg.has_serial_number()) {
|
||||
decoded.serialNumber = msg.serial_number();
|
||||
}
|
||||
if(msg.has_manufacture_date()) {
|
||||
const auto& date = msg.manufacture_date();
|
||||
decoded.manufactureDate = MfgDate{date.manufacture_day(), date.manufacture_month(), date.manufacture_year()};
|
||||
}
|
||||
if(msg.has_hardware_rev()) {
|
||||
decoded.hardwareRev = versionFromProto(msg.hardware_rev());
|
||||
}
|
||||
if(msg.has_product_id()) {
|
||||
decoded.productId = static_cast<uint8_t>(msg.product_id());
|
||||
}
|
||||
if(msg.has_bootloader_rev()) {
|
||||
decoded.bootloaderRev = versionFromProto(msg.bootloader_rev());
|
||||
}
|
||||
if(msg.has_usb_descriptor()) {
|
||||
decoded.usbDescriptor = msg.usb_descriptor();
|
||||
}
|
||||
for(const auto& mac : msg.mac_addresses()) {
|
||||
const auto& bytes = mac.mac_addr();
|
||||
if(bytes.size() < MACAddressLength)
|
||||
continue;
|
||||
MACAddress address{};
|
||||
std::copy_n(bytes.begin(), MACAddressLength, address.begin());
|
||||
decoded.macAddresses.push_back(address);
|
||||
}
|
||||
if(msg.has_pcb_serial()) {
|
||||
decoded.pcbSerial = msg.pcb_serial().pcb_serial();
|
||||
}
|
||||
if(msg.has_chip_id()) {
|
||||
decoded.chipId = static_cast<ChipID>(msg.chip_id());
|
||||
}
|
||||
if(msg.has_imei()) {
|
||||
decoded.imei = msg.imei();
|
||||
}
|
||||
if(msg.has_parent_product_id()) {
|
||||
decoded.parentProductId = static_cast<uint8_t>(msg.parent_product_id());
|
||||
}
|
||||
if(msg.has_software_version_lock()) {
|
||||
decoded.softwareVersionLock = versionFromProto(msg.software_version_lock());
|
||||
}
|
||||
|
||||
return std::make_shared<MfgConfigMessage>(decoded);
|
||||
}
|
||||
|
||||
std::vector<uint8_t> MfgConfigMessage::EncodeArgumentsForGet() {
|
||||
settings::manufacturing::v1::MfgConfig msg;
|
||||
msg.Clear();
|
||||
return protoapi::getPayload(protoapi::Command::GET, msg);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#include "icsneo/communication/message/spiportkeymessage.h"
|
||||
#include "icsneo/communication/message/extendedresponsemessage.h"
|
||||
#include "icsneo/communication/command.h"
|
||||
#include "icsneo/communication/network.h"
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
std::shared_ptr<SPIPortKeyMessage> SPIPortKeyMessage::DecodeToMessage(const std::vector<uint8_t>& bytestream) {
|
||||
if(bytestream.size() < sizeof(ExtendedResponseMessage::ResponseHeader))
|
||||
return nullptr;
|
||||
|
||||
const auto* hdr = reinterpret_cast<const ExtendedResponseMessage::ResponseHeader*>(bytestream.data());
|
||||
|
||||
if(hdr->command != ExtendedCommand::ExecuteSPIPortKeyOperation)
|
||||
return nullptr;
|
||||
|
||||
const size_t required = sizeof(ExtendedResponseMessage::ResponseHeader) + sizeof(SPIPortKeyPacket);
|
||||
if(bytestream.size() < required)
|
||||
return nullptr;
|
||||
|
||||
auto msg = std::make_shared<SPIPortKeyMessage>();
|
||||
|
||||
const auto* packet = reinterpret_cast<const SPIPortKeyPacket*>(bytestream.data() + sizeof(ExtendedResponseMessage::ResponseHeader));
|
||||
msg->isKeyLoaded = packet->isKeyLoaded;
|
||||
|
||||
return msg;
|
||||
}
|
||||
@@ -137,6 +137,7 @@ static std::vector<uint8_t> EncodeFromMessageLIN(std::shared_ptr<Frame> frame, c
|
||||
linpacket->CoreMiniBitsLIN.TXResponder = 1;
|
||||
break;
|
||||
case LINMessage::Type::LIN_BREAK_ONLY:
|
||||
linpacket->CoreMiniBitsLIN.TXCommander = 1;
|
||||
linpacket->CoreMiniBitsLIN.BreakOnly = 1;
|
||||
break;
|
||||
default:
|
||||
@@ -151,6 +152,7 @@ static std::vector<uint8_t> EncodeFromMessageLIN(std::shared_ptr<Frame> frame, c
|
||||
linmsg->linMsgType == LINMessage::Type::LIN_UPDATE_RESPONDER) && dataLen > 0;
|
||||
|
||||
if(hasData) {
|
||||
LINMessage::calcChecksum(*linmsg);
|
||||
// len includes data bytes + 1 checksum byte
|
||||
linpacket->CoreMiniBitsLIN.len = static_cast<uint16_t>(dataLen + 1);
|
||||
std::copy(linmsg->data.begin(), linmsg->data.begin() + dataLen, linpacket->data);
|
||||
|
||||
@@ -142,6 +142,8 @@ void MultiChannelCommunication::hidReadTask() {
|
||||
dispatchMessage(msg);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if(currentQueue == nullptr) {
|
||||
|
||||
@@ -20,7 +20,7 @@ std::shared_ptr<EthPhyMessage> HardwareEthernetPhyRegisterPacket::DecodeToMessag
|
||||
if(
|
||||
(PhyPacketVersion == pHeader->version) &&
|
||||
(sizeof(PhyRegisterPacket_t) == pHeader->entryBytes) &&
|
||||
(numEntries <= MaxPhyEntries) &&
|
||||
(numEntries > 0 && numEntries <= MaxPhyEntries) &&
|
||||
((bytestream.size() - sizeof(PhyRegisterHeader_t))
|
||||
== (sizeof(PhyRegisterPacket_t) * numEntries))
|
||||
)
|
||||
@@ -30,11 +30,16 @@ std::shared_ptr<EthPhyMessage> HardwareEthernetPhyRegisterPacket::DecodeToMessag
|
||||
for(size_t entryIdx{0}; entryIdx < numEntries; ++entryIdx)
|
||||
{
|
||||
const PhyRegisterPacket_t* pEntry = (pFirstEntry + entryIdx);
|
||||
if(pEntry->version != PhyPacketVersion) {
|
||||
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
|
||||
return nullptr;
|
||||
}
|
||||
auto phyMessage = std::make_shared<PhyMessage>();
|
||||
phyMessage->Enabled = (pEntry->Enabled != 0u);
|
||||
phyMessage->WriteEnable = (pEntry->WriteEnable != 0u);
|
||||
phyMessage->Clause45Enable = (pEntry->Clause45Enable != 0u);
|
||||
phyMessage->BusIndex = static_cast<uint8_t>(pEntry->BusIndex);
|
||||
phyMessage->Status = static_cast<uint8_t>(pEntry->status);
|
||||
phyMessage->Version = static_cast<uint8_t>(pEntry->version);
|
||||
if(phyMessage->Clause45Enable)
|
||||
phyMessage->Clause45 = pEntry->clause45;
|
||||
@@ -43,6 +48,10 @@ std::shared_ptr<EthPhyMessage> HardwareEthernetPhyRegisterPacket::DecodeToMessag
|
||||
msg->messages.push_back(phyMessage);
|
||||
}
|
||||
}
|
||||
else {
|
||||
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
|
||||
return nullptr;
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
@@ -59,7 +68,20 @@ bool HardwareEthernetPhyRegisterPacket::EncodeFromMessage(const EthPhyMessage& m
|
||||
report(APIEvent::Type::MessageMaxLengthExceeded, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
auto byteSize = (messageCount * sizeof(PhyRegisterPacket_t)) + sizeof(PhyRegisterHeader_t);
|
||||
// Validate every entry before touching the caller's output or submitting a command.
|
||||
for(const auto& entry : message.messages) {
|
||||
if(!entry) {
|
||||
report(APIEvent::Type::RequiredParameterNull, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
if(entry->BusIndex > 15 || entry->Version != PhyPacketVersion ||
|
||||
(entry->Clause45Enable ? (entry->Clause45.port > FiveBits || entry->Clause45.device > FiveBits) :
|
||||
(entry->Clause22.phyAddr > FiveBits || entry->Clause22.regAddr > FiveBits))) {
|
||||
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
auto byteSize = bytestream.size() + (messageCount * sizeof(PhyRegisterPacket_t)) + sizeof(PhyRegisterHeader_t);
|
||||
bytestream.reserve(byteSize);
|
||||
bytestream.push_back(static_cast<uint8_t>(messageCount & 0xFF));
|
||||
bytestream.push_back(static_cast<uint8_t>((messageCount >> 8) & 0xFF));
|
||||
@@ -67,7 +89,7 @@ bool HardwareEthernetPhyRegisterPacket::EncodeFromMessage(const EthPhyMessage& m
|
||||
bytestream.push_back(static_cast<uint8_t>(sizeof(PhyRegisterPacket_t)));
|
||||
for(auto& phyMessage : message.messages)
|
||||
{
|
||||
PhyRegisterPacket_t tempPacket;
|
||||
PhyRegisterPacket_t tempPacket{};
|
||||
tempPacket.Enabled = phyMessage->Enabled ? 0x1u : 0x0u;
|
||||
tempPacket.WriteEnable = phyMessage->WriteEnable ? 0x1u : 0x0u;
|
||||
tempPacket.BusIndex = (phyMessage->BusIndex & 0xF);
|
||||
|
||||
@@ -72,18 +72,30 @@ std::shared_ptr<Message> HardwareLINPacket::DecodeToMessage(const std::vector<ui
|
||||
static_cast<bool>(packet->CoreMiniBitsLIN.UpdateResponderOnce),
|
||||
static_cast<bool>(packet->CoreMiniBitsLIN.HasUpdatedResponderOnce),
|
||||
static_cast<bool>(packet->CoreMiniBitsLIN.BusRecovered),
|
||||
static_cast<bool>(packet->CoreMiniBitsLIN.BreakOnly)
|
||||
static_cast<bool>(packet->CoreMiniBitsLIN.BreakOnly),
|
||||
static_cast<bool>(packet->CoreMiniBitsLIN.WakeupRequest)
|
||||
};
|
||||
if(msg->statusFlags.TxCommander || msg->statusFlags.TxResponder)
|
||||
// Wake type only for a wake-only pulse. A UART/LIN break or a complete
|
||||
// frame may also carry WakeupRequest; those keep their existing type.
|
||||
const bool wakeupPulse = msg->statusFlags.WakeupRequest &&
|
||||
packet->CoreMiniBitsLIN.len == 0 &&
|
||||
packet->CoreMiniBitsLIN.ID == 0 &&
|
||||
!msg->statusFlags.BreakOnly &&
|
||||
!msg->errFlags.ErrRxBreakOnly &&
|
||||
!msg->errFlags.ErrRxBreakSyncOnly;
|
||||
if(wakeupPulse)
|
||||
msg->linMsgType = LINMessage::Type::LIN_WAKEUP_REQUEST;
|
||||
else if(msg->statusFlags.TxCommander || msg->statusFlags.TxResponder)
|
||||
msg->linMsgType = LINMessage::Type::LIN_COMMANDER_MSG;
|
||||
else if(msg->statusFlags.BreakOnly)
|
||||
msg->linMsgType = LINMessage::Type::LIN_BREAK_ONLY;
|
||||
if( msg->errFlags.ErrRxBreakOnly || msg->errFlags.ErrRxBreakSyncOnly ||
|
||||
if( !wakeupPulse &&
|
||||
(msg->errFlags.ErrRxBreakOnly || msg->errFlags.ErrRxBreakSyncOnly ||
|
||||
msg->errFlags.ErrTxRxMismatch || msg->errFlags.ErrRxBreakNotZero ||
|
||||
msg->errFlags.ErrRxBreakTooShort || msg->errFlags.ErrRxSyncNot55 ||
|
||||
msg->errFlags.ErrRxDataLenOver8 || msg->errFlags.ErrFrameSync ||
|
||||
msg->errFlags.ErrFrameMessageID || msg->errFlags.ErrChecksumMatch ||
|
||||
msg->errFlags.ErrFrameResponderData )
|
||||
msg->errFlags.ErrFrameResponderData) )
|
||||
{ msg->linMsgType = LINMessage::Type::LIN_ERROR; }
|
||||
|
||||
msg->timestamp = packet->timestamp;
|
||||
@@ -103,7 +115,7 @@ bool HardwareLINPacket::EncodeFromMessage(LINMessage& message, std::vector<uint8
|
||||
}
|
||||
case LINMessage::Type::LIN_BREAK_ONLY:
|
||||
{
|
||||
size |= 0x20u;
|
||||
size |= 0x80u | 0x20u;
|
||||
break;
|
||||
}
|
||||
case LINMessage::Type::NOT_SET:
|
||||
|
||||
@@ -80,7 +80,7 @@ bool Packetizer::input(RingBuffer& bytes) {
|
||||
* end of the payload. The short packet length, for reference, only encompasses the length of the actual
|
||||
* payload, and not the header or checksum.
|
||||
*/
|
||||
if(packetLength < 6 || packetLength > 4000) {
|
||||
if(packetLength < 6 || packetLength > std::numeric_limits<uint16_t>::max()) {
|
||||
bytes.pop_front();
|
||||
EventManager::GetInstance().add(APIEvent::Type::FailedToRead, APIEvent::Severity::Error);
|
||||
state = ReadState::SearchForHeader;
|
||||
|
||||
+3
-6
@@ -230,16 +230,17 @@ MACsecConfig::MACsecConfig(const DeviceType& deviceType) : type(deviceType) {
|
||||
case icsneo::DeviceType::Enum::RADMoon2:
|
||||
case icsneo::DeviceType::Enum::RADMoon3:
|
||||
case icsneo::DeviceType::Enum::RADEpsilon:
|
||||
case icsneo::DeviceType::Enum::RADGigastar2:
|
||||
case icsneo::DeviceType::Enum::RADComet2:
|
||||
case icsneo::DeviceType::Enum::RADComet3:
|
||||
maxSecY = 2;
|
||||
maxRule = 2;
|
||||
maxSa = 4;
|
||||
binIndex = 0;
|
||||
break;
|
||||
default:
|
||||
maxSecY = 0;
|
||||
maxSa = 0;
|
||||
maxRule = 0;
|
||||
binIndex = 0;
|
||||
ReportEvent(APIEvent::Type::MACsecNotSupported, APIEvent::Severity::Error);
|
||||
return;
|
||||
}
|
||||
@@ -514,10 +515,6 @@ MACsecConfig::operator bool() const {
|
||||
return (maxSa != 0) || (maxSecY != 0) || (maxRule != 0);
|
||||
}
|
||||
|
||||
uint16_t MACsecConfig::getBinIndex() const {
|
||||
return binIndex;
|
||||
}
|
||||
|
||||
DeviceType MACsecConfig::getType() const {
|
||||
return type;
|
||||
}
|
||||
|
||||
+435
-150
@@ -8,6 +8,7 @@
|
||||
#include "icsneo/disk/fat.h"
|
||||
#include "icsneo/communication/message/filter/extendedresponsefilter.h"
|
||||
#include "icsneo/communication/message/networkmutexmessage.h"
|
||||
#include "icsneo/communication/message/mfgconfigmessage.h"
|
||||
#include "icsneo/communication/message/transmitmessage.h"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
@@ -92,10 +93,6 @@ Device::~Device() {
|
||||
disableMessagePolling();
|
||||
if(isOpen())
|
||||
close();
|
||||
if(heartbeatThread.joinable()) {
|
||||
stopHeartbeatThread = true;
|
||||
heartbeatThread.join();
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t Device::getTimestampResolution() const {
|
||||
@@ -242,12 +239,12 @@ std::vector<VersionReport> Device::getChipVersions(bool refreshComponents) {
|
||||
auto& version = chipVersions.back();
|
||||
|
||||
auto disectedVersion = disectVersion(component.dotVersion);
|
||||
version.id = chipInfo.id;
|
||||
version.name = chipInfo.name;
|
||||
version.major = disectedVersion[0];
|
||||
version.minor = disectedVersion[1];
|
||||
version.id = chipInfo.id;
|
||||
version.name = chipInfo.name;
|
||||
version.major = disectedVersion[0];
|
||||
version.minor = disectedVersion[1];
|
||||
version.maintenance = disectedVersion[2];
|
||||
version.build = disectedVersion[3];
|
||||
version.build = disectedVersion[3];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -267,12 +264,12 @@ std::vector<VersionReport> Device::getChipVersions(bool refreshComponents) {
|
||||
chipVersions.emplace_back();
|
||||
auto& version = chipVersions.back();
|
||||
|
||||
version.id = chipInfo.id;
|
||||
version.name = chipInfo.name;
|
||||
version.major = appVer->major;
|
||||
version.minor = appVer->minor;
|
||||
version.id = chipInfo.id;
|
||||
version.name = chipInfo.name;
|
||||
version.major = appVer->major;
|
||||
version.minor = appVer->minor;
|
||||
version.maintenance = 0;
|
||||
version.build = 0;
|
||||
version.build = 0;
|
||||
}
|
||||
}
|
||||
return chipVersions;
|
||||
@@ -288,6 +285,8 @@ bool Device::open(OpenFlags flags, OpenStatusHandler handler) {
|
||||
return false;
|
||||
}
|
||||
|
||||
startHeartbeat();
|
||||
|
||||
APIEvent::Type attemptErr = attemptToBeginCommunication();
|
||||
if(attemptErr != APIEvent::Type::NoErrorFound) {
|
||||
// We could not communicate with the device, let's see if an extension can
|
||||
@@ -334,79 +333,6 @@ bool Device::open(OpenFlags flags, OpenStatusHandler handler) {
|
||||
EventManager::GetInstance().cancelErrorDowngradingOnCurrentThread();
|
||||
}
|
||||
|
||||
MessageFilter filter;
|
||||
filter.includeInternalInAny = true;
|
||||
internalHandlerCallbackID = com->addMessageCallback(std::make_shared<MessageCallback>(filter, [this](std::shared_ptr<Message> message) {
|
||||
handleInternalMessage(message);
|
||||
}));
|
||||
|
||||
// Clear the previous heartbeat thread, in case open() was called on this instance more than once
|
||||
if(heartbeatThread.joinable())
|
||||
heartbeatThread.join();
|
||||
|
||||
stopHeartbeatThread = false;
|
||||
|
||||
heartbeatThread = std::thread([this]() {
|
||||
EventManager::GetInstance().downgradeErrorsOnCurrentThread();
|
||||
|
||||
MessageFilter filter;
|
||||
filter.includeInternalInAny = true;
|
||||
|
||||
std::condition_variable heartbeatCV;
|
||||
std::mutex receivedMessageMutex;
|
||||
bool receivedMessage = false;
|
||||
auto messageReceivedCallbackID = com->addMessageCallback(std::make_shared<MessageCallback>(filter, [&](std::shared_ptr<Message>) {
|
||||
{
|
||||
std::scoped_lock<std::mutex> lk(receivedMessageMutex);
|
||||
receivedMessage = true;
|
||||
}
|
||||
heartbeatCV.notify_all();
|
||||
}));
|
||||
|
||||
// Give the device time to get situated
|
||||
auto i = 150;
|
||||
while(!stopHeartbeatThread && i != 0) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
i--;
|
||||
}
|
||||
|
||||
while(!stopHeartbeatThread) {
|
||||
std::unique_lock<std::mutex> recvLk(receivedMessageMutex);
|
||||
// Wait for 110ms for a possible heartbeat
|
||||
if(heartbeatCV.wait_for(recvLk, std::chrono::milliseconds(110), [&]() { return receivedMessage; })) {
|
||||
receivedMessage = false;
|
||||
} else if(!stopHeartbeatThread) { // Add this condition here in case the thread was stopped while waiting for the last message
|
||||
|
||||
// Some communication, such as the bootloader and extractor interfaces, must
|
||||
// redirect the input stream from the device as it will no longer be in the
|
||||
// packet format we expect here. As a result, status updates will not reach
|
||||
// us here and suppressDisconnects() must be used. We don't want to request
|
||||
// a status and then redirect the stream, as we'll then be polluting an
|
||||
// otherwise quiet stream. This lock makes sure suppressDisconnects() will
|
||||
// block until we've either gotten our status update or disconnected from
|
||||
// the device.
|
||||
std::unique_lock<std::mutex> lk(heartbeatMutex);
|
||||
if(heartbeatSuppressed()) continue;
|
||||
|
||||
// No heartbeat received, request a status
|
||||
com->sendCommand(Command::RequestStatusUpdate);
|
||||
|
||||
// Check if we got a message, and if not, if settings are being applied
|
||||
if(heartbeatCV.wait_for(recvLk, std::chrono::milliseconds(3500), [&](){ return receivedMessage; })) {
|
||||
receivedMessage = false;
|
||||
} else {
|
||||
if(!stopHeartbeatThread) {
|
||||
close();
|
||||
report(APIEvent::Type::DeviceDisconnected, APIEvent::Severity::Error);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
com->removeMessageCallback(messageReceivedCallbackID);
|
||||
});
|
||||
|
||||
if(supportsLiveData())
|
||||
clearAllLiveData();
|
||||
|
||||
@@ -503,7 +429,7 @@ bool Device::close() {
|
||||
return false;
|
||||
}
|
||||
|
||||
stopHeartbeatThread = true;
|
||||
stopHeartbeat();
|
||||
|
||||
if (isMessagePollingEnabled()) {
|
||||
disableMessagePolling();
|
||||
@@ -534,31 +460,15 @@ bool Device::goOnline() {
|
||||
if(!enableNetworkCommunication(true, onlineTimeoutMs))
|
||||
return false;
|
||||
|
||||
auto startTime = std::chrono::system_clock::now();
|
||||
|
||||
ledState = LEDState::Online;
|
||||
|
||||
updateLEDState();
|
||||
|
||||
std::shared_ptr<MessageFilter> filter = std::make_shared<MessageFilter>(Network::NetID::Reset_Status);
|
||||
filter->includeInternalInAny = true;
|
||||
|
||||
// Wait until communication is enabled or 5 seconds, whichever comes first
|
||||
while((std::chrono::system_clock::now() - startTime) < std::chrono::seconds(5)) {
|
||||
if(latestResetStatus && latestResetStatus->comEnabled)
|
||||
break;
|
||||
|
||||
bool failOut = false;
|
||||
com->waitForMessageSync([this, &failOut]() {
|
||||
if(!com->sendCommand(Command::RequestStatusUpdate)) {
|
||||
failOut = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}, filter, std::chrono::milliseconds(100));
|
||||
if(failOut)
|
||||
return false;
|
||||
}
|
||||
// (re)start the keeponline
|
||||
keeponline = std::make_unique<Periodic>([this] {
|
||||
static std::vector<uint8_t> timeoutBytes = std::vector<uint8_t>((uint8_t*)&onlineTimeoutMs, (uint8_t*)&onlineTimeoutMs + sizeof(onlineTimeoutMs));
|
||||
return com->sendCommand(Command::KeepAlive, timeoutBytes);
|
||||
}, std::chrono::milliseconds(onlineTimeoutMs / 4));
|
||||
|
||||
if(supportsNetworkMutex) {
|
||||
assignedClientId = com->getClientIDSync();
|
||||
@@ -575,41 +485,46 @@ bool Device::goOnline() {
|
||||
case NetworkMutexEvent::Acquired:
|
||||
lockedNetworks.emplace(*netMutexMsg->networks.begin());
|
||||
break;
|
||||
case NetworkMutexEvent::Expired:
|
||||
case NetworkMutexEvent::Preempted:
|
||||
case NetworkMutexEvent::Released: {
|
||||
auto it = lockedNetworks.find(*netMutexMsg->networks.begin());
|
||||
if (it != lockedNetworks.end())
|
||||
lockedNetworks.erase(it);
|
||||
break;
|
||||
}
|
||||
case NetworkMutexEvent::Queued:
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// (re)start the keeponline
|
||||
keeponline = std::make_unique<Periodic>([this] {
|
||||
static std::vector<uint8_t> timeoutBytes = std::vector<uint8_t>((uint8_t*)&onlineTimeoutMs, (uint8_t*)&onlineTimeoutMs + sizeof(onlineTimeoutMs));
|
||||
return com->sendCommand(Command::KeepAlive, timeoutBytes);
|
||||
}, std::chrono::milliseconds(onlineTimeoutMs / 4));
|
||||
|
||||
online = true;
|
||||
|
||||
// restart the heartbeat in online mode
|
||||
restartHeartbeat();
|
||||
|
||||
forEachExtension([](const std::shared_ptr<DeviceExtension>& ext) { ext->onGoOnline(); return true; });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Device::goOffline() {
|
||||
online = false;
|
||||
|
||||
keeponline.reset();
|
||||
|
||||
// restart the heartbeat in offline mode
|
||||
restartHeartbeat();
|
||||
|
||||
if(networkMutexCallbackHandle)
|
||||
removeMessageCallback(*networkMutexCallbackHandle);
|
||||
|
||||
forEachExtension([](const std::shared_ptr<DeviceExtension>& ext) { ext->onGoOffline(); return true; });
|
||||
|
||||
if(isDisconnected()) {
|
||||
online = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -625,8 +540,6 @@ bool Device::goOffline() {
|
||||
|
||||
updateLEDState();
|
||||
|
||||
online = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -737,15 +650,17 @@ bool Device::uploadCoremini(std::istream& stream, Disk::MemoryType memType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto connected = isLogicalDiskConnected();
|
||||
|
||||
if(!connected) {
|
||||
return false; // Already added an API error
|
||||
}
|
||||
|
||||
if(!(*connected)) {
|
||||
report(APIEvent::Type::DiskNotConnected, APIEvent::Severity::Error);
|
||||
return false;
|
||||
if (memType == Disk::MemoryType::SD) {
|
||||
auto connected = isLogicalDiskConnected();
|
||||
|
||||
if(!connected) {
|
||||
return false; // Already added an API error
|
||||
}
|
||||
|
||||
if(!(*connected)) {
|
||||
report(APIEvent::Type::DiskNotConnected, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if(!stopScript()) {
|
||||
@@ -756,7 +671,6 @@ bool Device::uploadCoremini(std::istream& stream, Disk::MemoryType memType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if(!eraseScriptMemory(memType, static_cast<uint64_t>(bin.size()))) {
|
||||
return false;
|
||||
}
|
||||
@@ -846,10 +760,12 @@ std::optional<CoreminiHeader> Device::readCoreminiHeader(Disk::MemoryType memTyp
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto connected = isLogicalDiskConnected();
|
||||
|
||||
if(!connected) {
|
||||
return std::nullopt; // Already added an API error
|
||||
if (memType == Disk::MemoryType::SD) {
|
||||
auto connected = isLogicalDiskConnected();
|
||||
|
||||
if(!connected) {
|
||||
return std::nullopt; // Already added an API error
|
||||
}
|
||||
}
|
||||
|
||||
#pragma pack(push, 2)
|
||||
@@ -1008,6 +924,36 @@ std::shared_ptr<HardwareInfo> Device::getHardwareInfo(std::chrono::milliseconds
|
||||
return hardwareInfo;
|
||||
}
|
||||
|
||||
std::shared_ptr<MfgConfigMessage> Device::getMfgConfig() {
|
||||
if(!isOpen()) {
|
||||
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> payload = MfgConfigMessage::EncodeArgumentsForGet();
|
||||
|
||||
auto response = com->waitForMessageSync(
|
||||
[this, payload]() {
|
||||
return com->sendCommand(ExtendedCommand::ProtobufAPI, payload);
|
||||
},
|
||||
std::make_shared<MessageFilter>(Message::Type::MfgConfig),
|
||||
std::chrono::milliseconds(250)
|
||||
);
|
||||
|
||||
if(!response) {
|
||||
report(APIEvent::Type::Timeout, APIEvent::Severity::Error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto mfgConfig = std::dynamic_pointer_cast<MfgConfigMessage>(response);
|
||||
if(!mfgConfig) {
|
||||
report(APIEvent::Type::UnexpectedResponse, APIEvent::Severity::Error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return mfgConfig;
|
||||
}
|
||||
|
||||
|
||||
std::optional<uint64_t> Device::readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout, Disk::MemoryType memType) {
|
||||
if(!into || timeout <= std::chrono::milliseconds(0)) {
|
||||
@@ -1985,11 +1931,9 @@ void Device::stopScriptStatusThreadIfNecessary(std::unique_lock<std::mutex> lk)
|
||||
}
|
||||
|
||||
Lifetime Device::suppressDisconnects() {
|
||||
std::lock_guard<std::mutex> lk(heartbeatMutex);
|
||||
heartbeatSuppressedByUser++;
|
||||
stopHeartbeat();
|
||||
return Lifetime([this] {
|
||||
std::lock_guard<std::mutex> lk2(heartbeatMutex);
|
||||
heartbeatSuppressedByUser--;
|
||||
startHeartbeat();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2109,7 +2053,12 @@ std::optional<EthPhyMessage> Device::sendEthPhyMsg(const EthPhyMessage& message,
|
||||
}
|
||||
|
||||
std::vector<uint8_t> bytes;
|
||||
HardwareEthernetPhyRegisterPacket::EncodeFromMessage(message, bytes, report);
|
||||
if(timeout.count() <= 0) {
|
||||
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
|
||||
return std::nullopt;
|
||||
}
|
||||
if(!HardwareEthernetPhyRegisterPacket::EncodeFromMessage(message, bytes, report))
|
||||
return std::nullopt;
|
||||
std::shared_ptr<Message> response = com->waitForMessageSync(
|
||||
[this, bytes](){ return com->sendCommand(Command::PHYControlRegisters, bytes); },
|
||||
std::make_shared<MessageFilter>(Message::Type::EthernetPhyRegister), timeout);
|
||||
@@ -2125,6 +2074,18 @@ std::optional<EthPhyMessage> Device::sendEthPhyMsg(const EthPhyMessage& message,
|
||||
return std::make_optional<EthPhyMessage>(*retMsg);
|
||||
}
|
||||
|
||||
bool Device::sendSPIPortKeyOperation(uint8_t portIndex, SPIPortKeyMessage::Operation op, std::array<uint8_t, 16> key) {
|
||||
std::vector<uint8_t> args(sizeof(SPIPortKeyMessage::SPIPortKeyPacket));
|
||||
auto& params = *reinterpret_cast<SPIPortKeyMessage::SPIPortKeyPacket*>(args.data());
|
||||
params.op = op;
|
||||
params.portIndex = portIndex;
|
||||
std::copy(key.begin(), key.end(), params.key);
|
||||
if(!com->sendCommand(ExtendedCommand::ExecuteSPIPortKeyOperation, args)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<bool> Device::SetRootDirectoryEntryFlags(uint8_t mask, uint8_t values, uint32_t collectionEntryByteAddress)
|
||||
{
|
||||
if(!supportsWiVI())
|
||||
@@ -2263,13 +2224,34 @@ std::optional<std::vector<uint8_t>> Device::getPCBSerial() {
|
||||
return std::vector<uint8_t>(serialMsg->pcbSerial, serialMsg->pcbSerial + sizeof(serialMsg->pcbSerial));
|
||||
}
|
||||
|
||||
std::optional<std::vector<uint8_t>> Device::getMACAddress() {
|
||||
auto serialMsg = com->getSerialNumberSync();
|
||||
if(!serialMsg || !serialMsg->hasMacAddress) {
|
||||
return std::nullopt;
|
||||
std::unordered_map<Network::NetID, MACAddress> Device::getMACAddresses() {
|
||||
if(supportsGetAllMACAddresses()) {
|
||||
if(!isOpen()) {
|
||||
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
|
||||
return {};
|
||||
}
|
||||
auto msg = com->waitForMessageSync(
|
||||
[this](){ return com->sendCommand(ExtendedCommand::GetAllMACAddresses, {}); },
|
||||
std::make_shared<MessageFilter>(Message::Type::AllMACAddresses),
|
||||
std::chrono::milliseconds(100)
|
||||
);
|
||||
if(msg) {
|
||||
const auto typed = std::dynamic_pointer_cast<AllMACAddressesMessage>(msg);
|
||||
if(typed)
|
||||
return typed->addresses;
|
||||
}
|
||||
}
|
||||
|
||||
return std::vector<uint8_t>(serialMsg->macAddress, serialMsg->macAddress + sizeof(serialMsg->macAddress));
|
||||
auto serialMsg = com->getSerialNumberSync();
|
||||
if(!serialMsg || !serialMsg->hasMacAddress)
|
||||
return {};
|
||||
|
||||
std::unordered_map<Network::NetID, MACAddress> addresses;
|
||||
auto addr = serialMsg->macAddress;
|
||||
MACAddress arrAddr;
|
||||
std::copy(addr, addr + MACAddressLength, arrAddr.begin());
|
||||
addresses.emplace(std::make_pair(Network::NetID::ETHERNET_01, arrAddr));
|
||||
return addresses;
|
||||
}
|
||||
|
||||
std::optional<std::set<SupportedFeature>> Device::getSupportedFeatures() {
|
||||
@@ -3273,11 +3255,12 @@ bool Device::findVSAOffsetFromTimepoint(ICSClock::time_point point, uint64_t& vs
|
||||
std::shared_ptr<VSA> midRecord;
|
||||
auto midRecordStatus = parser.getRecordFromBytes(buffer.data(), Disk::SectorSize, midRecord);
|
||||
switch(midRecordStatus) {
|
||||
case VSAParser::RecordParseStatus::NotARecordStart:
|
||||
case VSAParser::RecordParseStatus::NotARecordStart: {
|
||||
// This part of the buffer does not contain records
|
||||
rightIndex = midIndex - 1;
|
||||
continue;
|
||||
case VSAParser::RecordParseStatus::ConsecutiveExtended:
|
||||
}
|
||||
case VSAParser::RecordParseStatus::ConsecutiveExtended: {
|
||||
// We dropped in the middle of an extended message record
|
||||
auto extendedRecord = std::dynamic_pointer_cast<VSAExtendedMessage>(midRecord);
|
||||
uint64_t pos = readPos;
|
||||
@@ -3292,6 +3275,9 @@ bool Device::findVSAOffsetFromTimepoint(ICSClock::time_point point, uint64_t& vs
|
||||
midIndex = (pos - firstOffset) / Disk::SectorSize;
|
||||
midRecord = extendedRecord;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if(midIndex <= leftIndex) {
|
||||
// Extended records cause problems with binary search
|
||||
@@ -3673,7 +3659,7 @@ bool Device::requestTC10Wake(Network::NetID network) {
|
||||
*(Network::NetID*)args.data() = network;
|
||||
auto msg = com->waitForMessageSync([&] {
|
||||
return com->sendCommand(ExtendedCommand::RequestTC10Wake, args);
|
||||
}, std::make_shared<MessageFilter>(Message::Type::ExtendedResponse), std::chrono::milliseconds(1000));
|
||||
}, std::make_shared<ExtendedResponseFilter>(ExtendedCommand::RequestTC10Wake), std::chrono::milliseconds(1000));
|
||||
|
||||
if(!msg) {
|
||||
report(APIEvent::Type::NoDeviceResponse, APIEvent::Severity::Error);
|
||||
@@ -3686,7 +3672,11 @@ bool Device::requestTC10Wake(Network::NetID network) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return resp->response == ExtendedResponse::OK;
|
||||
if(resp->response != ExtendedResponse::OK) {
|
||||
report(APIEvent::Type::TC10RequestFailed, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Device::requestTC10Sleep(Network::NetID network) {
|
||||
@@ -3698,7 +3688,7 @@ bool Device::requestTC10Sleep(Network::NetID network) {
|
||||
*(Network::NetID*)args.data() = network;
|
||||
auto msg = com->waitForMessageSync([&] {
|
||||
return com->sendCommand(ExtendedCommand::RequestTC10Sleep, args);
|
||||
}, std::make_shared<MessageFilter>(Message::Type::ExtendedResponse), std::chrono::milliseconds(1000));
|
||||
}, std::make_shared<ExtendedResponseFilter>(ExtendedCommand::RequestTC10Sleep), std::chrono::milliseconds(1000));
|
||||
|
||||
if(!msg) {
|
||||
report(APIEvent::Type::NoDeviceResponse, APIEvent::Severity::Error);
|
||||
@@ -3711,7 +3701,20 @@ bool Device::requestTC10Sleep(Network::NetID network) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return typed->response == ExtendedResponse::OK;
|
||||
if(typed->response != ExtendedResponse::OK) {
|
||||
report(APIEvent::Type::TC10RequestFailed, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Device::reboot(bool safe) {
|
||||
if(!supportsReboot()) {
|
||||
report(APIEvent::Type::NotSupported, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
// The device reboots in response to this command, so no reply is expected.
|
||||
return com->sendCommand(ExtendedCommand::Reboot, { uint8_t(safe ? 1 : 0) });
|
||||
}
|
||||
|
||||
std::optional<TC10StatusMessage> Device::getTC10Status(Network::NetID network) {
|
||||
@@ -3771,7 +3774,15 @@ std::optional<GPTPStatus> Device::getGPTPStatus(std::chrono::milliseconds timeou
|
||||
return *retMsg;
|
||||
}
|
||||
|
||||
bool Device::writeMACsecConfig(const MACsecConfig& cfg) {
|
||||
std::vector<Network> Device::getMACsecNetworks() const {
|
||||
std::vector<Network> networks;
|
||||
for(const auto& network : getMACsecNetworkMap()) {
|
||||
networks.emplace_back(network.first);
|
||||
}
|
||||
return networks;
|
||||
}
|
||||
|
||||
bool Device::writeMACsecConfig(const MACsecConfig& cfg, Network::NetID network) {
|
||||
if(!cfg) {
|
||||
report(APIEvent::Type::MACsecNotSupported, APIEvent::Severity::Error);
|
||||
return false;
|
||||
@@ -3782,8 +3793,15 @@ bool Device::writeMACsecConfig(const MACsecConfig& cfg) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto& networks = getMACsecNetworkMap();
|
||||
const auto binaryIndex = networks.find(network);
|
||||
if(binaryIndex == networks.end()) {
|
||||
report(APIEvent::Type::MACsecNotSupported, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> raw = cfg.serialize();
|
||||
return writeBinaryFile(raw, cfg.getBinIndex());
|
||||
return writeBinaryFile(raw, binaryIndex->second);
|
||||
}
|
||||
|
||||
bool Device::enableNetworkCommunication(bool enable, uint32_t timeout) {
|
||||
@@ -4123,3 +4141,270 @@ bool Device::unlockAllNetworks()
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void Device::startHeartbeat() {
|
||||
if(!heartbeat)
|
||||
heartbeat = std::make_unique<Heartbeat>(*this);
|
||||
}
|
||||
|
||||
void Device::stopHeartbeat() {
|
||||
heartbeat.reset();
|
||||
}
|
||||
|
||||
void Device::restartHeartbeat() {
|
||||
stopHeartbeat();
|
||||
startHeartbeat();
|
||||
}
|
||||
|
||||
bool Device::iso15765Enable(const Network& network) {
|
||||
return J2534_EnableIso15765(network, true);
|
||||
}
|
||||
|
||||
bool Device::iso15765DisableAll(void) {
|
||||
bool ok = true;
|
||||
for(const auto& slot : iso15765FirmwareEnabled)
|
||||
{
|
||||
if (slot.second)
|
||||
{
|
||||
if (!J2534_EnableIso15765(slot.first, false))
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool Device::iso15765TransmitMessage(const Network& network, const Iso15765MessageArgs& msg, const std::chrono::milliseconds& timeout) {
|
||||
if (!isOnline())
|
||||
return false;
|
||||
|
||||
if(iso15765FirmwareEnabled.find(network) == iso15765FirmwareEnabled.end() || !iso15765FirmwareEnabled[network])
|
||||
return false;
|
||||
|
||||
bool result;
|
||||
Iso15765TxSetupMessage setupMsg;
|
||||
|
||||
//Set the network ID to use
|
||||
if(const auto& coreMiniId = network.getCoreMini())
|
||||
setupMsg.setCoreMiniId((uint16_t)*coreMiniId);
|
||||
|
||||
const uint8_t txIndex = msg.getTxIndex();
|
||||
setupMsg.setIdx(txIndex);
|
||||
|
||||
setupMsg.setId(msg.getArbId().Id);
|
||||
setupMsg.setFcId(msg.getFlowControlArbId().Id);
|
||||
setupMsg.setFcIdMask(msg.getFlowControlArbIdMask());
|
||||
|
||||
setupMsg.setFsTimeout(msg.getFsTimeout());
|
||||
setupMsg.setFsWait(msg.getFsWaitTimeout());
|
||||
|
||||
const uint32_t messageLength = (uint32_t)msg.getData().size();
|
||||
setupMsg.setMessageLength(messageLength);
|
||||
setupMsg.setIs29BitEnabled(msg.getArbId().Is29Bit);
|
||||
setupMsg.setIsFc29BitEnabled(msg.getFlowControlArbId().Is29Bit);
|
||||
if(const auto& extAddress = msg.getExtendedAddress())
|
||||
{
|
||||
setupMsg.setExtAddressEnabled(true);
|
||||
setupMsg.setExtendedAddress(*extAddress);
|
||||
}
|
||||
if(const auto& extFcAddress = msg.getFlowControlExtendedAddress())
|
||||
{
|
||||
setupMsg.setFcExtAddressEnabled(true);
|
||||
setupMsg.setFlowControlExtendedAddress(*extFcAddress);
|
||||
}
|
||||
if(const auto& stMin = msg.getStMin())
|
||||
{
|
||||
setupMsg.setOverrideStMin(true);
|
||||
setupMsg.setStMin(*stMin);
|
||||
}
|
||||
if(const auto& blockSize = msg.getBlockSize())
|
||||
{
|
||||
setupMsg.setOverrideBlockSize(true);
|
||||
setupMsg.setBlockSize(*blockSize);
|
||||
}
|
||||
if(const auto& padding = msg.getPaddingValue())
|
||||
{
|
||||
setupMsg.setPaddingEnabled(true);
|
||||
setupMsg.setPadding(*padding);
|
||||
}
|
||||
setupMsg.setIsBrsEnabled(msg.getIsBrsEnabled());
|
||||
setupMsg.setIsCanFd(msg.getIsCanFd());
|
||||
setupMsg.setTxDl(msg.getTxDl());
|
||||
|
||||
{
|
||||
uint32_t octetsToSend = messageLength;
|
||||
const uint8_t* payload = msg.getData().data();
|
||||
uint32_t offset = 0;
|
||||
|
||||
result = J2534_Transaction(network, std::move(setupMsg), timeout);
|
||||
while(result && octetsToSend)
|
||||
{
|
||||
const uint16_t chunkSize = (uint16_t)std::min((uint32_t)Iso15765TxDataMessage::MaxDataLength, octetsToSend);
|
||||
|
||||
Iso15765TxDataMessage dataMsg;
|
||||
dataMsg.setIdx(txIndex);
|
||||
dataMsg.setOffset(offset);
|
||||
dataMsg.setData(&payload[offset], chunkSize);
|
||||
|
||||
result = J2534_Transaction(network, std::move(dataMsg), timeout);
|
||||
|
||||
offset += chunkSize;
|
||||
octetsToSend -= chunkSize;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool Device::iso15765SetupRxFlowControl(const Network& network, const Iso15765MessageArgs& msg) {
|
||||
if (!isOnline())
|
||||
return false;
|
||||
|
||||
if(iso15765FirmwareEnabled.find(network) == iso15765FirmwareEnabled.end() || !iso15765FirmwareEnabled[network])
|
||||
return false;
|
||||
|
||||
J2534SetupIso15765FlowControlMessage rxFlowControl;
|
||||
|
||||
rxFlowControl.setIsBrsEnabled(msg.getIsBrsEnabled());
|
||||
rxFlowControl.setIsCanFd(msg.getIsCanFd());
|
||||
rxFlowControl.setIdx(msg.getTxIndex());
|
||||
if(const auto& coreMiniId = network.getCoreMini())
|
||||
rxFlowControl.setCoreMiniId((uint16_t)*coreMiniId);
|
||||
rxFlowControl.setEnable(true);
|
||||
if(const auto& blockSize = msg.getBlockSize())
|
||||
{
|
||||
rxFlowControl.setBlockSize(*blockSize);
|
||||
}
|
||||
rxFlowControl.setCfTimeout(msg.getCfTimeout());
|
||||
rxFlowControl.setFlowControlTransmissionEnabled(msg.getIsFlowControlEnabled());
|
||||
if(const auto& extAddress = msg.getExtendedAddress())
|
||||
{
|
||||
rxFlowControl.setExtendedAddress(*extAddress);
|
||||
rxFlowControl.setExtAddressEnabled(true);
|
||||
}
|
||||
if(const auto& fcExtAddress = msg.getFlowControlExtendedAddress())
|
||||
{
|
||||
rxFlowControl.setFlowControlExtendedAddress(*fcExtAddress);
|
||||
rxFlowControl.setFcExtAddressEnabled(true);
|
||||
}
|
||||
rxFlowControl.setFcId(msg.getFlowControlArbId().Id);
|
||||
rxFlowControl.setIsFc29BitEnabled(msg.getFlowControlArbId().Is29Bit);
|
||||
rxFlowControl.setIs29BitEnabled(msg.getArbId().Is29Bit);
|
||||
rxFlowControl.setId(msg.getArbId().Id);
|
||||
rxFlowControl.setIdMask(msg.getFlowControlArbIdMask());
|
||||
if(const auto& padding = msg.getPaddingValue())
|
||||
{
|
||||
rxFlowControl.setPadding(*padding);
|
||||
rxFlowControl.setPaddingEnabled(true);
|
||||
}
|
||||
if(const auto& stMin = msg.getStMin())
|
||||
{
|
||||
rxFlowControl.setStMin(*stMin);
|
||||
}
|
||||
|
||||
return J2534_Transaction(network, std::move(rxFlowControl), std::chrono::milliseconds(0));
|
||||
}
|
||||
|
||||
bool Device::J2534_Transaction(const Network& network, J2534CommandMessage&& msg, const std::chrono::milliseconds& timeout) {
|
||||
msg.network = network;
|
||||
if (timeout.count())
|
||||
{
|
||||
static std::shared_ptr<MessageFilter> filter = std::make_shared<Main51MessageFilter>(Command::J2534Command);
|
||||
const auto& response = com->waitForMessageSync([&](void)
|
||||
{
|
||||
return com->sendCommand(msg.command, msg.getArgumentData());
|
||||
}, filter, timeout);
|
||||
|
||||
if (!response)
|
||||
{
|
||||
report(APIEvent::Type::NoDeviceResponse, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
auto responseMsg = std::dynamic_pointer_cast<Main51Message>(response);
|
||||
if (!responseMsg || responseMsg->command != Command::J2534Command)
|
||||
{
|
||||
report(APIEvent::Type::MessageFormattingError, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return com->sendCommand(msg.command, msg.getArgumentData());
|
||||
}
|
||||
|
||||
// NOTE: responseMsg->data.front()
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool Device::J2534_ClearRxFilters(const Network& network)
|
||||
{
|
||||
return J2534_Transaction(network, J2534CommandMessage(J2534CommandMessage::J2534Command::SetupClearCanRxFilters, { (uint8_t)0 /* is this necessary? */}), std::chrono::milliseconds(0));
|
||||
}
|
||||
|
||||
bool Device::J2534_SetupCanRxFilter(const Network& network, const J2534_RxCanFilter& rxCanFilter)
|
||||
{
|
||||
return J2534_Transaction(network, J2534SetupCanRxFilteringMessage(rxCanFilter), std::chrono::milliseconds(0));
|
||||
}
|
||||
|
||||
bool Device::J2534_EnableFiltering(const Network& network, const bool enable)
|
||||
{
|
||||
return J2534_Transaction(network, J2534EnableFilteringMessage(enable), std::chrono::milliseconds(0));
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool Device::J2534_EnableIso15765(const Network& network, const bool enable)
|
||||
{
|
||||
if (iso15765FirmwareEnabled[network] == enable)
|
||||
return true;
|
||||
|
||||
if (!J2534_Transaction(network, J2534EnableMessage(enable), std::chrono::milliseconds(0)))
|
||||
return false;
|
||||
|
||||
iso15765FirmwareEnabled[network] = enable;
|
||||
|
||||
if (enable)
|
||||
{
|
||||
// Turn OFF filtering of CAN messages in the firmware
|
||||
return J2534_EnableFirmwareUsbPassFilters(network, false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Device::J2534_ClearRxFilter(const Network& network, unsigned int iIndex)
|
||||
{
|
||||
if (const auto& slot = iso15765FirmwareEnabled.find(network); slot != iso15765FirmwareEnabled.end() && slot->second)
|
||||
{
|
||||
J2534_RxCanFilter rxFilter;
|
||||
memset(&rxFilter, 0, sizeof(rxFilter));
|
||||
rxFilter.idx = (uint16_t)iIndex;
|
||||
return J2534_SetupCanRxFilter(network, rxFilter);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Device::J2534_EnableFirmwareUsbPassFilters(const Network& network, const bool enable)
|
||||
{
|
||||
const auto& slot = iso15765FirmwareEnabled.find(network);
|
||||
if (slot == iso15765FirmwareEnabled.end())
|
||||
return false;
|
||||
//check for disconnect here!
|
||||
if (!slot->second)
|
||||
{
|
||||
// Tried to shut-off Rx table message filtering but FW ISO15765 was not enabled
|
||||
return true; //just ignore it, no filtering can occur anyway
|
||||
}
|
||||
|
||||
if (enable) //turning ON filtering in the Firmware based on the rx table
|
||||
{
|
||||
//Rx table message filtering is on by default in the firmware when m_bISO15765_FW_Enabled is true
|
||||
//need to check here to see if we set index 0 to a PASS all filter (i.e. turned off USB filtering)
|
||||
if (!J2534_ClearRxFilters(network))
|
||||
return false;
|
||||
}
|
||||
|
||||
// New "filtering enable" mechanism - old firmware ignores this frame
|
||||
return J2534_EnableFiltering(network, enable);
|
||||
}
|
||||
|
||||
+16
-47
@@ -1,29 +1,12 @@
|
||||
#include "icsneo/device/devicefinder.h"
|
||||
#include "icsneo/platform/devices.h"
|
||||
#include "icsneo/device/founddevice.h"
|
||||
#include "generated/extensions/builtin.h"
|
||||
#include "icsneo/platform/servd.h"
|
||||
|
||||
#ifdef ICSNEO_ENABLE_FIRMIO
|
||||
#include "icsneo/platform/firmio.h"
|
||||
#endif
|
||||
|
||||
#ifdef ICSNEO_ENABLE_RAW_ETHERNET
|
||||
#include "icsneo/platform/pcap.h"
|
||||
#endif
|
||||
|
||||
#ifdef ICSNEO_ENABLE_CDCACM
|
||||
#include "icsneo/platform/cdcacm.h"
|
||||
#endif
|
||||
|
||||
#ifdef ICSNEO_ENABLE_DXX
|
||||
#include "icsneo/platform/dxx.h"
|
||||
#endif
|
||||
|
||||
#ifdef ICSNEO_ENABLE_TCP
|
||||
#include "icsneo/platform/tcp.h"
|
||||
#endif
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
template<typename T>
|
||||
@@ -56,22 +39,8 @@ std::vector<std::shared_ptr<Device>> DeviceFinder::FindAll() {
|
||||
} else {
|
||||
#ifdef ICSNEO_ENABLE_FIRMIO
|
||||
FirmIO::Find(newDriverFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef ICSNEO_ENABLE_TCP
|
||||
TCP::Find(newDriverFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef ICSNEO_ENABLE_RAW_ETHERNET
|
||||
PCAP::Find(newDriverFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef ICSNEO_ENABLE_CDCACM
|
||||
CDCACM::Find(newDriverFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef ICSNEO_ENABLE_DXX
|
||||
DXX::Find(newDriverFoundDevices);
|
||||
#else
|
||||
EventManager::GetInstance().add(APIEvent::Type::ServdDisabled, APIEvent::Severity::EventWarning);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -165,10 +134,6 @@ std::vector<std::shared_ptr<Device>> DeviceFinder::FindAll() {
|
||||
makeIfSerialMatches<RADA2B>(dev, newFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef __RADCOMET_H_
|
||||
makeIfSerialRangeMatches<RADComet>(dev, newFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef __RADCOMET2_H_
|
||||
makeIfSerialRangeMatches<RADComet2>(dev, newFoundDevices);
|
||||
#endif
|
||||
@@ -225,8 +190,8 @@ std::vector<std::shared_ptr<Device>> DeviceFinder::FindAll() {
|
||||
makeIfSerialMatches<RADMoon3>(dev, newFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef __RADGEMINI_H_
|
||||
makeIfSerialMatches<RADGemini>(dev, newFoundDevices);
|
||||
#ifdef __RADARGOS_H_
|
||||
makeIfSerialMatches<RADArgos>(dev, newFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef __RADMOONDUO_H_
|
||||
@@ -245,6 +210,10 @@ std::vector<std::shared_ptr<Device>> DeviceFinder::FindAll() {
|
||||
makeIfSerialMatches<RADSupermoon>(dev, newFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef __RADWBMS_H_
|
||||
makeIfSerialMatches<RADwBMS>(dev, newFoundDevices);
|
||||
#endif
|
||||
|
||||
#ifdef __VALUECAN3_H_
|
||||
makeIfSerialRangeMatches<ValueCAN3>(dev, newFoundDevices);
|
||||
#endif
|
||||
@@ -274,10 +243,6 @@ std::vector<std::shared_ptr<Device>> DeviceFinder::FindAll() {
|
||||
#endif
|
||||
}
|
||||
|
||||
for(auto& device : newFoundDevices) {
|
||||
AddBuiltInExtensionsTo(device);
|
||||
}
|
||||
|
||||
// Grab a weak pointer from the new devices
|
||||
foundDevices.insert(foundDevices.end(), newFoundDevices.begin(), newFoundDevices.end());
|
||||
|
||||
@@ -340,8 +305,8 @@ const std::vector<DeviceType>& DeviceFinder::GetSupportedDevices() {
|
||||
RADA2B::DEVICE_TYPE,
|
||||
#endif
|
||||
|
||||
#ifdef __RADCOMET_H_
|
||||
RADComet::DEVICE_TYPE,
|
||||
#ifdef __RADCOMET2_H_
|
||||
RADComet2::DEVICE_TYPE,
|
||||
#endif
|
||||
|
||||
#ifdef __RADCOMET3_H_
|
||||
@@ -388,8 +353,8 @@ const std::vector<DeviceType>& DeviceFinder::GetSupportedDevices() {
|
||||
RADMoon3::DEVICE_TYPE,
|
||||
#endif
|
||||
|
||||
#ifdef __RADGEMINI_H_
|
||||
RADGemini::DEVICE_TYPE,
|
||||
#ifdef __RADARGOS_H_
|
||||
RADArgos::DEVICE_TYPE,
|
||||
#endif
|
||||
|
||||
#ifdef __RADMOONDUO_H_
|
||||
@@ -408,6 +373,10 @@ const std::vector<DeviceType>& DeviceFinder::GetSupportedDevices() {
|
||||
RADSupermoon::DEVICE_TYPE,
|
||||
#endif
|
||||
|
||||
#ifdef __RADWBMS_H_
|
||||
RADwBMS::DEVICE_TYPE,
|
||||
#endif
|
||||
|
||||
#ifdef __VALUECAN3_H_
|
||||
ValueCAN3::DEVICE_TYPE,
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
#include "icsneo/device/extensions/bootloader/api.h"
|
||||
#include "icsneo/device/extensions/bootloader/communication/radcommunication.h"
|
||||
#include "icsneo/device/extensions/bootloader/communication/radmultichipcommunication.h"
|
||||
#include "icsneo/device/extensions/bootloader/communication/radperiphcommunication.h"
|
||||
#include "icsneo/device/extensions/bootloader/communication/redcore.h"
|
||||
#include "icsneo/device/extensions/bootloader/communication/red.h"
|
||||
#include "icsneo/device/extensions/bootloader/communication/application.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
#include "icsneo/communication/message/resetstatusmessage.h"
|
||||
#include "icsneo/api/lifetime.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
|
||||
using namespace icsneo;
|
||||
using namespace icsneo::Bootloader;
|
||||
|
||||
static std::unique_ptr<Bootloader::Communication> getCommunication(
|
||||
icsneo::Device& device, const FlashPhase& phase, const ChipInfo& chip
|
||||
) {
|
||||
switch(phase.comm) {
|
||||
case BootloaderCommunication::Application:
|
||||
return std::make_unique<Application>(device, chip, phase.authenticate, phase.encrypt);
|
||||
case BootloaderCommunication::RED:
|
||||
return std::make_unique<REDCommunication>(device, chip, phase.authenticate, phase.encrypt);
|
||||
case BootloaderCommunication::REDCore:
|
||||
return std::make_unique<REDCoreCommunication>(device, chip);
|
||||
case BootloaderCommunication::RAD:
|
||||
return std::make_unique<RADCommunication>(device, chip);
|
||||
case BootloaderCommunication::RADMultiChip:
|
||||
return std::make_unique<RADMultiChipCommunication>(device, chip, phase.authenticate, phase.slot);
|
||||
case BootloaderCommunication::RADGalaxy2Peripheral:
|
||||
return std::make_unique<RADPeriphCommunication>(device, chip);
|
||||
case BootloaderCommunication::Invalid:
|
||||
break;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static bool findInfo(icsneo::Device& device, ChipID chip, ChipInfo& info) {
|
||||
const auto& allInfo = device.getChipInfo();
|
||||
auto iter = std::find_if(allInfo.begin(), allInfo.end(), [chip](const auto& candidate) { return candidate.id == chip; });
|
||||
if(iter == allInfo.end()) {
|
||||
return false;
|
||||
}
|
||||
info = *iter;
|
||||
return true;
|
||||
}
|
||||
|
||||
static const FlashPhase* findCorrespondingFlashPhase(const BootloaderPipeline& pipeline, ChipID chip) {
|
||||
for(const auto& phase : pipeline.phases) {
|
||||
if(phase->getType() == BootloaderPhase::Type::Flash) {
|
||||
const auto* flashPhase = static_cast<const FlashPhase*>(phase.get());
|
||||
if(flashPhase->chip == chip) {
|
||||
return flashPhase;
|
||||
}
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static std::string chipString(ChipID chip) {
|
||||
return "chip id: " + std::to_string(static_cast<int>(chip));
|
||||
}
|
||||
|
||||
bool Bootloader::requiresUpdate(icsneo::Device& device, const FWRepo& fw) {
|
||||
const auto versions = device.getChipVersions();
|
||||
for(const auto& info : device.getChipInfo()) {
|
||||
if(!info.defaultEnabled || !info.iefName) {
|
||||
continue;
|
||||
}
|
||||
auto iter = std::find_if(versions.begin(), versions.end(), [&info](const auto& ver) { return ver.id == info.id; });
|
||||
if(iter == versions.end()) {
|
||||
continue;
|
||||
}
|
||||
auto ver = fw.getChipVersion(info.iefName);
|
||||
if(ver && *ver != iter->makeAppVersion()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the communication, run the action, then close it
|
||||
*/
|
||||
template<typename Action>
|
||||
static bool withCommunication(Bootloader::Communication* com, const ChipInfo& info, const char* phaseName, Action action) {
|
||||
if(!com) {
|
||||
Log::Error(phaseName, "no bootloader communication for " + chipString(info.id));
|
||||
return false;
|
||||
}
|
||||
if(!com->open()) {
|
||||
Log::Error(phaseName, "failed to open communication for " + chipString(info.id));
|
||||
return false;
|
||||
}
|
||||
if(!action(*com)) {
|
||||
return false;
|
||||
}
|
||||
if(!com->close()) {
|
||||
Log::Error(phaseName, "failed to close communication for " + chipString(info.id));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool runPipeline(
|
||||
icsneo::Device& device,
|
||||
const BootloaderPipeline& pipeline,
|
||||
const FWRepo& fw,
|
||||
const Logger& logger,
|
||||
bool alreadyInBootloader,
|
||||
bool forceFlash
|
||||
) {
|
||||
icsneo::Lifetime suppressHeartbeats = device.suppressDisconnects();
|
||||
const auto versions = device.getChipVersions();
|
||||
std::unordered_set<icsneo::ChipID> chipsFlashed;
|
||||
|
||||
bool updateAll = false;
|
||||
if(auto iter = pipeline.settings.find(BootloaderSetting::UpdateAll); iter != pipeline.settings.end()) {
|
||||
updateAll = std::get<bool>(iter->second);
|
||||
}
|
||||
|
||||
for(const auto& phase : pipeline.phases) {
|
||||
switch(phase->getType()) {
|
||||
case BootloaderPhase::Type::EnterBootloader: {
|
||||
if(alreadyInBootloader) {
|
||||
Log::Trace("EnterBootloaderPhase", "device already in bootloader, skipping");
|
||||
break;
|
||||
}
|
||||
Log::Info("EnterBootloaderPhase", "entering bootloader");
|
||||
if(!enterBootloader(device)) {
|
||||
Log::Error("EnterBootloaderPhase", "failed to enter bootloader");
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case BootloaderPhase::Type::Flash: {
|
||||
const auto& flashPhase = static_cast<const FlashPhase&>(*phase);
|
||||
Log::Info("FlashPhase", "started for " + chipString(flashPhase.chip));
|
||||
|
||||
ChipInfo info;
|
||||
if(!findInfo(device, flashPhase.chip, info)) {
|
||||
Log::Error("FlashPhase", "failed to find chip info for " + chipString(flashPhase.chip));
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto sourceVer = info.iefName ? fw.getChipVersion(info.iefName) : std::nullopt;
|
||||
if(!sourceVer) {
|
||||
Log::Trace("FlashPhase", "skipped, no source version for " + chipString(flashPhase.chip));
|
||||
break;
|
||||
}
|
||||
if(!updateAll && !forceFlash) {
|
||||
auto iter = std::find_if(versions.begin(), versions.end(), [&info](const auto& ver) { return ver.id == info.id; });
|
||||
if(iter == versions.end()) {
|
||||
Log::Trace("FlashPhase", "skipped, chip not reported by the device, " + chipString(flashPhase.chip));
|
||||
break;
|
||||
}
|
||||
if(iter->makeAppVersion() == *sourceVer) {
|
||||
Log::Trace("FlashPhase", "skipped, chip already at target version, " + chipString(flashPhase.chip));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
auto com = getCommunication(device, flashPhase, info);
|
||||
if(!withCommunication(com.get(), info, "FlashPhase", [&](Bootloader::Communication& opened) {
|
||||
if(!opened.flash(fw, logger)) {
|
||||
Log::Error("FlashPhase", "failed to flash " + chipString(flashPhase.chip));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})) {
|
||||
return false;
|
||||
}
|
||||
|
||||
chipsFlashed.insert(info.id);
|
||||
Log::Info("FlashPhase", "completed successfully for " + chipString(flashPhase.chip));
|
||||
break;
|
||||
}
|
||||
case BootloaderPhase::Type::Finalize: {
|
||||
const auto& finalizePhase = static_cast<const FinalizePhase&>(*phase);
|
||||
if(!chipsFlashed.count(finalizePhase.chip)) {
|
||||
Log::Trace("FinalizePhase", "skipped, chip not flashed, " + chipString(finalizePhase.chip));
|
||||
break;
|
||||
}
|
||||
Log::Info("FinalizePhase", "started for " + chipString(finalizePhase.chip));
|
||||
const FlashPhase* flashPhase = findCorrespondingFlashPhase(pipeline, finalizePhase.chip);
|
||||
ChipInfo info;
|
||||
if(!flashPhase || !findInfo(device, finalizePhase.chip, info)) {
|
||||
// Should never happen (developer error)
|
||||
Log::Error("FinalizePhase", "no flash phase or chip info for " + chipString(finalizePhase.chip));
|
||||
return false;
|
||||
}
|
||||
|
||||
auto com = getCommunication(device, *flashPhase, info);
|
||||
if(com && !com->hasFinalizationStep()) {
|
||||
Log::Trace("FinalizePhase", "skipped, no finalization step for " + chipString(finalizePhase.chip));
|
||||
break;
|
||||
}
|
||||
|
||||
if(!withCommunication(com.get(), info, "FinalizePhase", [&](Bootloader::Communication& opened) {
|
||||
if(!opened.finalize()) {
|
||||
Log::Error("FinalizePhase", "failed to finalize " + chipString(finalizePhase.chip));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})) {
|
||||
return false;
|
||||
}
|
||||
Log::Info("FinalizePhase", "completed successfully for " + chipString(finalizePhase.chip));
|
||||
break;
|
||||
}
|
||||
case BootloaderPhase::Type::Reconnect: {
|
||||
Log::Info("ReconnectPhase", "reconnecting to device");
|
||||
if(!device.reconnect(std::chrono::milliseconds(60000))) {
|
||||
Log::Error("ReconnectPhase", "failed to reconnect to device");
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case BootloaderPhase::Type::Wait: {
|
||||
const auto& waitPhase = static_cast<const WaitPhase&>(*phase);
|
||||
Log::Trace("WaitPhase", "waiting " + std::to_string(waitPhase.timeout.count()) + "ms");
|
||||
std::this_thread::sleep_for(waitPhase.timeout);
|
||||
break;
|
||||
}
|
||||
case BootloaderPhase::Type::EnterApplication: {
|
||||
const auto& enterAppPhase = static_cast<const EnterApplicationPhase&>(*phase);
|
||||
if(!chipsFlashed.count(enterAppPhase.chip)) {
|
||||
Log::Trace("EnterApplicationPhase", "skipped, chip not flashed, " + chipString(enterAppPhase.chip));
|
||||
break;
|
||||
}
|
||||
Log::Info("EnterApplicationPhase", "started for " + chipString(enterAppPhase.chip));
|
||||
const FlashPhase* flashPhase = findCorrespondingFlashPhase(pipeline, enterAppPhase.chip);
|
||||
ChipInfo info;
|
||||
if(!flashPhase || !findInfo(device, enterAppPhase.chip, info)) {
|
||||
// Should never happen (developer error)
|
||||
Log::Error("EnterApplicationPhase", "no flash phase or chip info for " + chipString(enterAppPhase.chip));
|
||||
return false;
|
||||
}
|
||||
|
||||
auto com = getCommunication(device, *flashPhase, info);
|
||||
if(!withCommunication(com.get(), info, "EnterApplicationPhase", [&](Bootloader::Communication& opened) {
|
||||
if(!opened.enterApplication()) {
|
||||
Log::Error("EnterApplicationPhase", "failed to enter application for " + chipString(enterAppPhase.chip));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})) {
|
||||
return false;
|
||||
}
|
||||
Log::Info("EnterApplicationPhase", "completed successfully for " + chipString(enterAppPhase.chip));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return exitBootloader(device, logger, !chipsFlashed.empty());
|
||||
}
|
||||
|
||||
bool Bootloader::update(
|
||||
icsneo::Device& device,
|
||||
const FWRepo& fw,
|
||||
Logger logger,
|
||||
bool alreadyInBootloader,
|
||||
bool forceFlash
|
||||
) {
|
||||
const auto pipeline = device.getBootloader();
|
||||
if(!pipeline) {
|
||||
device.getEventHandler()(APIEvent::Type::FirmwareUpdateNotSupported, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!runPipeline(device, pipeline, fw, logger, alreadyInBootloader, forceFlash)) {
|
||||
device.getEventHandler()(APIEvent::Type::FirmwareUpdateFailed, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Bootloader::enterBootloader(icsneo::Device& device) {
|
||||
if(!device.com->sendCommand(icsneo::Command::EnterBootloader)) {
|
||||
return false;
|
||||
}
|
||||
return device.reconnect(std::chrono::milliseconds(30000));
|
||||
}
|
||||
|
||||
bool Bootloader::exitBootloader(icsneo::Device& device, Logger logger, bool updatedChips) {
|
||||
if(!updatedChips) {
|
||||
return true;
|
||||
}
|
||||
logger(icsneo::Device::OpenStatusType::Progress, "Connecting to the device...", std::nullopt);
|
||||
return verifyConnection(device, logger);
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle network communication and wait up to 5 seconds for a reset status confirming the change.
|
||||
* Like icsneo::Device::goOnline(), a timeout is not an error.
|
||||
*/
|
||||
static bool setCommunicationEnabled(icsneo::Device& device, const Logger& logger, bool enable, double progressStart) {
|
||||
static constexpr std::chrono::seconds Timeout(5);
|
||||
const auto filter = std::make_shared<MessageFilter>(Message::Type::ResetStatus);
|
||||
|
||||
if(!device.com->sendCommand(Command::EnableNetworkCommunication, enable)) {
|
||||
return false;
|
||||
}
|
||||
device.com->sendCommand(Command::UpdateLEDState, std::vector<uint8_t>({uint8_t(enable ? 0x10 : 0x04)}));
|
||||
|
||||
const auto startTime = std::chrono::steady_clock::now();
|
||||
auto elapsedTime = std::chrono::duration<double>(0);
|
||||
while(elapsedTime < Timeout) {
|
||||
bool failOut = false;
|
||||
auto msg = device.com->waitForMessageSync([&device, &failOut]() {
|
||||
if(!device.com->sendCommand(Command::RequestStatusUpdate)) {
|
||||
failOut = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}, filter, std::chrono::milliseconds(100));
|
||||
|
||||
if(failOut) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(msg && std::static_pointer_cast<icsneo::ResetStatusMessage>(msg)->comEnabled == enable) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Each call covers half of the overall progress
|
||||
logger(icsneo::Device::OpenStatusType::Progress, "Connecting to the device...", progressStart + (elapsedTime / Timeout) / 2.0);
|
||||
elapsedTime = std::chrono::steady_clock::now() - startTime;
|
||||
}
|
||||
logger(icsneo::Device::OpenStatusType::Progress, "Connecting to the device...", progressStart + 0.5);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Bootloader::verifyConnection(icsneo::Device& device, Logger logger) {
|
||||
// Firmware needs to confirm the update by verifying that it can enable/disable the connection on the device
|
||||
return setCommunicationEnabled(device, logger, true, 0.0) && setCommunicationEnabled(device, logger, false, 0.5);
|
||||
}
|
||||
|
||||
bool Bootloader::isSFPChip(const icsneo::Bootloader::Chip& chip) {
|
||||
static const std::set<icsneo::ChipID> sfpChipIDs = {
|
||||
icsneo::ChipID::SFPModule_88q2112_MCHIP,
|
||||
icsneo::ChipID::SFPModule_88q2221_MCHIP,
|
||||
icsneo::ChipID::SFPModule_88q3244_MCHIP,
|
||||
icsneo::ChipID::SFPModule_ent11100_MCHIP,
|
||||
icsneo::ChipID::SFPModule_lan8670_MCHIP,
|
||||
icsneo::ChipID::SFPModule_ad1101_MCHIP,
|
||||
};
|
||||
return sfpChipIDs.find(chip.getID()) != sfpChipIDs.end();
|
||||
}
|
||||
|
||||
bool Bootloader::isSFPIEF(const icsneo::Bootloader::IEF& ief) {
|
||||
static const std::set<icsneo::Device::ProductID> sfpProductIDs = {
|
||||
icsneo::Device::ProductID::SFPModule_88q2112,
|
||||
icsneo::Device::ProductID::SFPModule_88q2221m,
|
||||
icsneo::Device::ProductID::SFPModule_88q4364,
|
||||
icsneo::Device::ProductID::SFPModule_ent11100,
|
||||
icsneo::Device::ProductID::SFPModule_lan8670,
|
||||
icsneo::Device::ProductID::SFPModule_ad1101,
|
||||
};
|
||||
return sfpProductIDs.find(static_cast<icsneo::Device::ProductID>(ief.getVersion().prodId)) != sfpProductIDs.end();
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/application.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwrepo.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
#include "icsneo/device/extensions/bootloader/api.h"
|
||||
#include "icsneo/communication/message/extendedresponsemessage.h"
|
||||
#include "icsneo/communication/message/main51message.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
|
||||
#include <icsbl/icsbl.h>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
bool Application::enterApplication() {
|
||||
// Always reboot
|
||||
Log::Info(__func__, "sending reboot command");
|
||||
bool ok = device.com->sendCommand(icsneo::ExtendedCommand::Reboot);
|
||||
if(!ok) {
|
||||
Log::Error(__func__, "reboot command failed");
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool Application::finalize() {
|
||||
Log::Debug(__func__, "sending finalize command");
|
||||
bool ok = sendCommand(Update::Finalize, [](double) {});
|
||||
if(!ok) {
|
||||
Log::Error(__func__, "finalize command failed");
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool Application::flash(const FWRepo& fw, const icsneo::Device::OpenStatusHandler& handler) {
|
||||
Log::Info(__func__, "starting flash for " + targetChip.getName());
|
||||
const auto& srcVer = fw.getVersion();
|
||||
|
||||
std::vector<uint8_t> bin;
|
||||
if(!fw.getFW(targetChip.getIEFName(), bin)) {
|
||||
Log::Error(__func__, "failed to get firmware for " + targetChip.getIEFName());
|
||||
return false;
|
||||
}
|
||||
|
||||
IEF ief;
|
||||
if(!ief.load(std::move(bin))) {
|
||||
Log::Error(__func__, "failed to load IEF for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
auto currentString = "Preparing to update " + targetChip.getName() + "...";
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, std::nullopt);
|
||||
|
||||
// The supplied IEF is not for this product
|
||||
if(ief.getVersion().prodId != static_cast<uint8_t>(device.getProductID())) {
|
||||
Log::Error(__func__, "IEF product ID mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// The supplied IEF is for this product, but not for this chip
|
||||
if(ief.getVersion().chipId != static_cast<uint8_t>(targetChip.getID())) {
|
||||
Log::Error(__func__, "IEF chip ID mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(doAuthChecks) {
|
||||
if(!authenticate()) {
|
||||
Log::Error(__func__, "authentication failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Tell the application software what version of Vehicle Spy 3 this firmware is from.
|
||||
// We check to make sure it approves, but also, the device will not accept new firmware
|
||||
// if we have not sent this.
|
||||
// Sometimes new hardware revisions can not accept firmware which is too old.
|
||||
if(!sendCommand(Update::CheckVersion, [](double) {}, 0, {srcVer.major, srcVer.minor, srcVer.release, srcVer.build})) {
|
||||
Log::Error(__func__, "version check failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool ok = sendSoftware(ief.getSectors(), ief.getBlockSize(), handler);
|
||||
if(!ok) {
|
||||
Log::Error(__func__, "sendSoftware failed for " + targetChip.getName());
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool Application::authenticate() {
|
||||
icsbl_seed_v1 seed = {};
|
||||
if(!icsbl_generate_seed_v1(device.getSerialNumber(), &seed)) {
|
||||
Log::Error(__func__, "libicsbl could not generate an authentication challenge");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Send the challenge (seed.a), the device replies with seed.b and one trailing byte
|
||||
std::vector<uint8_t> cmdArgs(sizeof(seed.a));
|
||||
writeLE32(cmdArgs.data(), seed.a[0]);
|
||||
writeLE32(cmdArgs.data() + 4, seed.a[1]);
|
||||
|
||||
auto filter = std::make_shared<icsneo::MessageFilter>(icsneo::Message::Type::Main51);
|
||||
auto msg = device.com->waitForMessageSync([&] {
|
||||
return device.com->sendCommand(icsneo::Command::ValidateDevice, cmdArgs);
|
||||
}, filter, std::chrono::milliseconds(200));
|
||||
|
||||
if(!msg) {
|
||||
Log::Error(__func__, "No response from the device");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto main51Msg = std::static_pointer_cast<icsneo::Main51Message>(msg);
|
||||
|
||||
if(main51Msg->data.size() != sizeof(seed.b) + 1) {
|
||||
Log::Error(__func__, "Unexpected authentication reply size from the device");
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool authenticated = readLE32(main51Msg->data.data()) == seed.b[0] && readLE32(main51Msg->data.data() + 4) == seed.b[1];
|
||||
if(!authenticated) {
|
||||
Log::Error(__func__, "The authentication reply does not match, the device did not authenticate");
|
||||
}
|
||||
return authenticated;
|
||||
}
|
||||
|
||||
bool Application::validateFirmware(const DeviceAppVersion& chipSrcVer) {
|
||||
return sendCommand(Update::CheckComponentVersion, [](double) {}, 0, {chipSrcVer.major, chipSrcVer.minor});
|
||||
}
|
||||
|
||||
bool Application::sendSoftware(const std::vector<uint8_t>& bin, const icsneo::Device::OpenStatusHandler& handler) {
|
||||
Log::Debug(__func__, "starting for " + targetChip.getName() + " (" + std::to_string(bin.size()) + " bytes)");
|
||||
auto currentString = "Preparing to update " + targetChip.getName() + "...";
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, std::nullopt);
|
||||
if(bin.empty() || bin.size() > std::numeric_limits<uint32_t>::max()) {
|
||||
Log::Error(__func__, "invalid firmware size for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
const uint32_t totalSize = static_cast<uint32_t>(bin.size());
|
||||
|
||||
Log::Debug(__func__, "erasing " + targetChip.getName());
|
||||
if(!sendCommand(Update::Erase, 0, totalSize, [&](double progress) {
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, progress);
|
||||
}, std::chrono::milliseconds(45000))) {
|
||||
Log::Error(__func__, "erase failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
currentString = "Updating " + targetChip.getName() + "...";
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, std::nullopt);
|
||||
|
||||
const uint32_t stepSize = std::min<uint32_t>(totalSize, 2048);
|
||||
uint32_t bytesTransferred = 0;
|
||||
while(bytesTransferred < totalSize) {
|
||||
const uint32_t bytesToSend = std::min(stepSize, totalSize - bytesTransferred);
|
||||
if(!sendCommand(Update::Write, [](double) {}, bytesTransferred, { bin.begin() + bytesTransferred, bin.begin() + bytesTransferred + bytesToSend})) {
|
||||
Log::Error(__func__, "write failed at offset " + std::to_string(bytesTransferred) + " for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
bytesTransferred += bytesToSend;
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, double(bytesTransferred) / totalSize);
|
||||
}
|
||||
Log::Debug(__func__, "write complete, validating " + targetChip.getName());
|
||||
if(!validateComponent()) {
|
||||
Log::Error(__func__, "validation failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
Log::Debug(__func__, "completed successfully for " + targetChip.getName());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Application::sendSoftware(const std::vector<IEF::Sector>& sectorPairs, uint32_t blockSize, const icsneo::Device::OpenStatusHandler& handler) {
|
||||
if(sectorPairs.empty()) {
|
||||
Log::Error(__func__, "no sectors to flash for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
Log::Debug(__func__, "starting for " + targetChip.getName() + " (" + std::to_string(sectorPairs.size()) + " sectors)");
|
||||
auto currentString = "Preparing to update " + targetChip.getName() + "...";
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, std::nullopt);
|
||||
uint64_t totalSize = 0;
|
||||
for(const auto& sector : sectorPairs) {
|
||||
totalSize += sector.second.size();
|
||||
}
|
||||
if(totalSize > std::numeric_limits<uint32_t>::max()) {
|
||||
Log::Error(__func__, "total size too large for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(totalSize == 0) {
|
||||
Log::Error(__func__, "total size is 0 for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
Log::Debug(__func__, "erasing " + targetChip.getName() + " (" + std::to_string(totalSize) + " bytes)");
|
||||
if(!sendCommand(Update::Erase, 0, static_cast<uint32_t>(totalSize), [&](double progress) {
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, progress);
|
||||
}, std::chrono::milliseconds(45000))) {
|
||||
Log::Error(__func__, "erase failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(isSFPChip(targetChip)) {
|
||||
// SFPs are not ready to write until 4 seconds after finishing erasing (for some reason)
|
||||
Log::Trace(__func__, "SFP chip detected, waiting 4000ms after erase");
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(4000));
|
||||
}
|
||||
|
||||
currentString = "Updating " + targetChip.getName() + "...";
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, std::nullopt);
|
||||
|
||||
uint32_t bytesTransferred = 0;
|
||||
for(const auto& pair : sectorPairs) {
|
||||
const auto& rawData = pair.second;
|
||||
const uint32_t offset = pair.first * blockSize;
|
||||
std::vector<uint8_t> processedData(rawData.begin(), rawData.end());
|
||||
if(encrypted) {
|
||||
if(rawData.size() % 8 != 0) {
|
||||
Log::Error(__func__, "raw data size not aligned");
|
||||
return false;
|
||||
}
|
||||
icsbl_encrypt_v1(device.getSerialNumber(), rawData.data(), rawData.size(), processedData.data());
|
||||
}
|
||||
|
||||
if(!sendCommand(Update::Write, [](double) {}, offset, processedData)) {
|
||||
Log::Error(__func__, "write failed at offset " + std::to_string(offset) + " for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
bytesTransferred += static_cast<uint32_t>(rawData.size());
|
||||
handler(icsneo::Device::OpenStatusType::Progress, currentString, double(bytesTransferred) / double(totalSize));
|
||||
}
|
||||
Log::Debug(__func__, "write complete, validating " + targetChip.getName());
|
||||
bool ok = validateComponent();
|
||||
if(!ok) {
|
||||
Log::Error(__func__, "validation failed for " + targetChip.getName());
|
||||
}
|
||||
else {
|
||||
Log::Debug(__func__, "completed successfully for " + targetChip.getName());
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool Application::validateComponent() {
|
||||
Log::Debug(__func__, "validating " + targetChip.getName());
|
||||
bool ok = sendCommand(Update::ValidateComponent, [](double) {}, 0, {}, std::chrono::milliseconds(45000));
|
||||
if(!ok) {
|
||||
Log::Error(__func__, "validation failed for " + targetChip.getName());
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send one SoftwareUpdate sub-command and wait for it to complete.
|
||||
*
|
||||
* The device answers the request with OK when it is already done, or OperationPending when it will
|
||||
* finish later. For a pending command we poll Update::GetProgress (except for Write and
|
||||
* ValidateComponent, which do not report progress) until the device sends a final OK or the timeout
|
||||
* passes. Progress replies are OperationPending with a SoftwareUpdateCommandHeader whose
|
||||
* commandSizeOrProgress holds the progress so far, or a GenericReturn with no progress.
|
||||
*/
|
||||
bool Application::sendCommand(Update command, uint32_t offset, uint32_t length, const StatusHandler& handler, std::chrono::milliseconds timeout, std::vector<uint8_t> args) {
|
||||
bool finishedResponse = false;
|
||||
std::condition_variable finishedResponseCV;
|
||||
std::mutex finishedResponseMutex;
|
||||
|
||||
std::optional<uint32_t> progress;
|
||||
std::condition_variable progressCV;
|
||||
std::mutex progressMutex;
|
||||
|
||||
bool firstResponse = true;
|
||||
// Register the callback before sending the command, so that if it goes from pending to finished quickly we will still catch it
|
||||
const auto callback = std::make_shared<icsneo::MessageCallback>(std::make_shared<icsneo::MessageFilter>(icsneo::Message::Type::ExtendedResponse), [&](std::shared_ptr<icsneo::Message> msg) {
|
||||
if(firstResponse) {
|
||||
firstResponse = false;
|
||||
return true; // let waitForMessageSync handle the first message
|
||||
}
|
||||
auto extMsg = std::static_pointer_cast<ExtendedResponseMessage>(msg);
|
||||
if(extMsg->command != ExtendedCommand::SoftwareUpdate) {
|
||||
Log::Error(__func__, "Got an extended response for a command other than SoftwareUpdate");
|
||||
return false;
|
||||
}
|
||||
if(extMsg->response == ExtendedResponse::OK) {
|
||||
{
|
||||
std::scoped_lock lk(finishedResponseMutex);
|
||||
finishedResponse = true;
|
||||
}
|
||||
finishedResponseCV.notify_one();
|
||||
} else if(extMsg->response == ExtendedResponse::OperationPending) {
|
||||
if(extMsg->data.size() < sizeof(ExtendedResponseMessage::ResponseHeader)) {
|
||||
Log::Error(__func__, "The pending response is too short to contain a header");
|
||||
return false;
|
||||
}
|
||||
ExtendedResponseMessage::ResponseHeader respHeader;
|
||||
std::memcpy(&respHeader, extMsg->data.data(), sizeof(respHeader));
|
||||
if(respHeader.command == ExtendedCommand::SoftwareUpdate) {
|
||||
if(respHeader.length != sizeof(SoftwareUpdateCommandHeader) ||
|
||||
extMsg->data.size() < sizeof(ExtendedResponseMessage::ResponseHeader) + sizeof(SoftwareUpdateCommandHeader)) {
|
||||
Log::Error(__func__, "The progress response does not contain a SoftwareUpdate header");
|
||||
return false;
|
||||
}
|
||||
SoftwareUpdateCommandHeader resp;
|
||||
std::memcpy(&resp, extMsg->data.data() + sizeof(ExtendedResponseMessage::ResponseHeader), sizeof(resp));
|
||||
{
|
||||
std::scoped_lock lk(progressMutex);
|
||||
progress.emplace(resp.commandSizeOrProgress);
|
||||
}
|
||||
progressCV.notify_one();
|
||||
} else if(respHeader.command == ExtendedCommand::GenericReturn) {
|
||||
// No progress information, the final OK comes later
|
||||
{
|
||||
std::scoped_lock lk(progressMutex);
|
||||
progress.emplace(0);
|
||||
}
|
||||
progressCV.notify_one();
|
||||
} else {
|
||||
Log::Error(__func__, "The pending response is for an unexpected command");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
Log::Error(__func__, "The device reported an error for the SoftwareUpdate command");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const auto finishedCallbackHandle = device.com->addMessageCallback(callback);
|
||||
Lifetime statusCallbackCleanup([&] {
|
||||
device.com->removeMessageCallback(finishedCallbackHandle);
|
||||
});
|
||||
|
||||
SoftwareUpdateCommandHeader header = {};
|
||||
header.componentIdentifier = static_cast<uint32_t>(targetChip.getID());
|
||||
header.commandType = command;
|
||||
header.offset = offset;
|
||||
header.commandSizeOrProgress = length;
|
||||
header.expansionSlot = targetChip.expansionSlot;
|
||||
const auto headerBytes = reinterpret_cast<const uint8_t*>(&header);
|
||||
args.insert(args.begin(), headerBytes, headerBytes + sizeof(header));
|
||||
|
||||
{
|
||||
auto msg = device.com->waitForMessageSync([&] {
|
||||
return device.com->sendCommand(ExtendedCommand::SoftwareUpdate, args);
|
||||
}, std::make_shared<icsneo::MessageFilter>(icsneo::Message::Type::ExtendedResponse), timeout);
|
||||
|
||||
if(!msg) {
|
||||
Log::Error(__func__, "No response to the SoftwareUpdate command");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto extMsg = std::static_pointer_cast<ExtendedResponseMessage>(msg);
|
||||
if(extMsg->command != ExtendedCommand::SoftwareUpdate) {
|
||||
Log::Error(__func__, "Got an extended response for a command other than SoftwareUpdate");
|
||||
return false;
|
||||
}
|
||||
if(extMsg->response == ExtendedResponse::OK) {
|
||||
return true;
|
||||
}
|
||||
if(extMsg->response != ExtendedResponse::OperationPending) {
|
||||
Log::Error(__func__, "The device rejected the SoftwareUpdate command");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
SoftwareUpdateCommandHeader progressHeader = {};
|
||||
progressHeader.componentIdentifier = static_cast<uint32_t>(targetChip.getID());
|
||||
progressHeader.commandType = Update::GetProgress;
|
||||
progressHeader.expansionSlot = targetChip.expansionSlot;
|
||||
const auto progressHeaderBytes = reinterpret_cast<const uint8_t*>(&progressHeader);
|
||||
const std::vector<uint8_t> progressArgs(progressHeaderBytes, progressHeaderBytes + sizeof(progressHeader));
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
// Write and ValidateComponent do not report progress, just wait for the final OK
|
||||
if(command != Update::Write && command != Update::ValidateComponent) {
|
||||
while(std::chrono::steady_clock::now() < deadline) {
|
||||
{
|
||||
std::unique_lock lk(progressMutex);
|
||||
progress.reset();
|
||||
if(!device.com->sendCommand(ExtendedCommand::SoftwareUpdate, progressArgs)) {
|
||||
Log::Error(__func__, "Failed to send progress request to the device");
|
||||
return false;
|
||||
}
|
||||
if(!progressCV.wait_for(lk, std::chrono::milliseconds(5000), [&]{ return progress.has_value(); })) {
|
||||
Log::Error(__func__, "No progress response from device");
|
||||
return false;
|
||||
}
|
||||
handler(*progress / double(length));
|
||||
}
|
||||
{
|
||||
std::scoped_lock lk(finishedResponseMutex);
|
||||
if(finishedResponse) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock lk(finishedResponseMutex);
|
||||
return finishedResponseCV.wait_until(lk, deadline, [&]{ return finishedResponse; });
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,14 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/communication.h"
|
||||
|
||||
using namespace icsneo::Bootloader;
|
||||
|
||||
uint32_t Communication::readLE32(const uint8_t* buf) {
|
||||
return (uint32_t)buf[0] | ((uint32_t)buf[1] << 8) | ((uint32_t)buf[2] << 16) | ((uint32_t)buf[3] << 24);
|
||||
}
|
||||
|
||||
void Communication::writeLE32(uint8_t* buf, uint32_t num) {
|
||||
buf[0] = num & 0xFFu;
|
||||
buf[1] = (num >> 8) & 0xFFu;
|
||||
buf[2] = (num >> 16) & 0xFFu;
|
||||
buf[3] = (num >> 24) & 0xFFu;
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/radcommunication.h"
|
||||
#include "icsneo/device/extensions/bootloader/communication/bootloaderversion.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwzip.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwrepo.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
|
||||
#include <icsbl/icsbl.h>
|
||||
|
||||
using namespace icsneo::Bootloader;
|
||||
|
||||
RADCommunication::RADCommunication(icsneo::Device& dev, const ChipInfo& info)
|
||||
: Communication(dev), targetChip(info) {}
|
||||
|
||||
bool RADCommunication::supportsFlashBuffer() const {
|
||||
switch(targetChip.getID()) {
|
||||
case icsneo::ChipID::RADGigastar_USBZ_ZYNQ:
|
||||
case icsneo::ChipID::RADGigastar_USBZ_Z7007S_ZYNQ:
|
||||
case icsneo::ChipID::RADGigastar_USBZ_Z7010_ZYNQ: {
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
RADCommunication::Request RADCommunication::makeRequest(Request::Type type, size_t payloadSize, size_t expectedResponseLen) {
|
||||
const size_t headerSize = supportsZynqBinaryFlasher ? ZynqFlasherHeaderSize : 0;
|
||||
const size_t packetSize = headerSize + 1 + payloadSize; // Header + command + payload
|
||||
|
||||
// This shouldn't cause any re-allocations since we already reserved the MaxMessageLength in initialize()
|
||||
txBuffer.resize(packetSize, 0);
|
||||
|
||||
if(supportsZynqBinaryFlasher) {
|
||||
std::copy(std::begin(ZynqFlasherSync), std::end(ZynqFlasherSync), txBuffer.begin());
|
||||
|
||||
// The length covers the command byte and the payload
|
||||
const uint16_t payloadPlusCmd = static_cast<uint16_t>(payloadSize) + 1;
|
||||
txBuffer[4] = payloadPlusCmd & 0xFFu;
|
||||
txBuffer[5] = (payloadPlusCmd >> 8) & 0xFFu;
|
||||
}
|
||||
|
||||
txBuffer[headerSize] = static_cast<uint8_t>(type);
|
||||
|
||||
Request newRequest;
|
||||
newRequest.type = type;
|
||||
newRequest.expectedResponseLen = expectedResponseLen;
|
||||
if(payloadSize > 0) {
|
||||
newRequest.payload = &txBuffer[headerSize + 1]; // First byte right after the command
|
||||
}
|
||||
|
||||
return newRequest;
|
||||
}
|
||||
|
||||
bool RADCommunication::sendRequestNoResponse() {
|
||||
/**
|
||||
* Send our current packet, the payload was written to it if the user
|
||||
* of this function wrote to request.payload. The remaining details were
|
||||
* written when makeRequest() was called
|
||||
*/
|
||||
return device.com->sendPacket(txBuffer);
|
||||
}
|
||||
|
||||
RADCommunication::Response& RADCommunication::sendRequest(const Request& request, std::chrono::milliseconds timeout) {
|
||||
static constexpr size_t ResponseHeaderSize = 2;
|
||||
const size_t rxSize = ResponseHeaderSize + request.expectedResponseLen;
|
||||
/**
|
||||
* Clear previous response
|
||||
*/
|
||||
lastResponse = Response();
|
||||
|
||||
if(!sendRequestNoResponse()) {
|
||||
Log::Error(__func__, "Failed to send request " + std::to_string(static_cast<uint8_t>(request.type)));
|
||||
return lastResponse;
|
||||
}
|
||||
|
||||
auto& rb = device.com->driver->getReadBuffer();
|
||||
rb.clear();
|
||||
auto result = device.com->driver->waitForRx(rxSize, timeout);
|
||||
|
||||
if(!result) {
|
||||
Log::Error(__func__, "No response to request " + std::to_string(static_cast<uint8_t>(request.type)));
|
||||
return lastResponse;
|
||||
}
|
||||
|
||||
rb.read(rxBuffer.data(), 0, rxSize);
|
||||
rb.clear();
|
||||
|
||||
lastResponse.done = true;
|
||||
|
||||
/**
|
||||
* Second byte is success/failure byte
|
||||
*/
|
||||
lastResponse.type = static_cast<Response::Type>(rxBuffer[1]);
|
||||
|
||||
/**
|
||||
* The rest is the payload, if we requested any
|
||||
*/
|
||||
if(request.expectedResponseLen > 0) {
|
||||
lastResponse.payload = &rxBuffer[2];
|
||||
lastResponse.size = request.expectedResponseLen;
|
||||
}
|
||||
|
||||
return lastResponse;
|
||||
}
|
||||
|
||||
bool RADCommunication::enterApplication() {
|
||||
Log::Info(__func__, "sending EnterApplication request");
|
||||
makeRequest(Request::Type::EnterApplication);
|
||||
bool ok = sendRequestNoResponse();
|
||||
if(!ok) {
|
||||
Log::Error(__func__, "EnterApplication request failed");
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool RADCommunication::close() {
|
||||
device.com->resumeReads();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADCommunication::open() {
|
||||
device.com->pauseReads();
|
||||
|
||||
if(!initialize()) {
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!sanityCheck()) {
|
||||
// Note: RAD-Gigastar on low power USB flash fails here for some reason, try another sanity check
|
||||
if(!sanityCheck()) {
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if(!getBootloaderVersion()) {
|
||||
// Try again, just like the sanity checks
|
||||
if(!getBootloaderVersion()) {
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if(!sanityCheck()) {
|
||||
// Note: RAD-Gigastar on low power USB flash fails here for some reason, try another sanity check
|
||||
if(!sanityCheck()) {
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if(!authenticate()) {
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADCommunication::initialize() {
|
||||
auto& rb = device.com->driver->getReadBuffer();
|
||||
|
||||
rxBuffer = std::vector<uint8_t>(MaxMessageLength, 0);
|
||||
txBuffer.reserve(MaxMessageLength);
|
||||
|
||||
// An EnterBootloader command on Main51, as a framed short packet (0xAA, then length << 4 | netid)
|
||||
// with a trailing 0xAF, followed by the same command without the 0xAA framing
|
||||
const uint8_t lengthAndNetID = (1 << 4) | static_cast<uint8_t>(icsneo::Network::NetID::Main51);
|
||||
std::vector<uint8_t> pkt = {
|
||||
0xAA,
|
||||
lengthAndNetID,
|
||||
static_cast<uint8_t>(icsneo::Command::EnterBootloader),
|
||||
0xAF
|
||||
};
|
||||
|
||||
rb.clear();
|
||||
if(!device.com->sendPacket(pkt)) {
|
||||
Log::Error(__func__, "Failed to send the framed enter bootloader command");
|
||||
return false;
|
||||
}
|
||||
|
||||
pkt = {
|
||||
lengthAndNetID,
|
||||
static_cast<uint8_t>(icsneo::Command::EnterBootloader)
|
||||
};
|
||||
|
||||
if(!device.com->sendPacket(pkt)) {
|
||||
Log::Error(__func__, "Failed to send the unframed enter bootloader command");
|
||||
return false;
|
||||
}
|
||||
|
||||
// The Zynq binary flasher answers with the command, Success, then ZynqFlasherSync
|
||||
static constexpr size_t ZynqFlasherReplySize = 2 + sizeof(ZynqFlasherSync);
|
||||
if(!device.com->driver->waitForRx(ZynqFlasherReplySize, std::chrono::milliseconds(1000))) {
|
||||
Log::Error(__func__, "No response to the enter bootloader command");
|
||||
return false;
|
||||
}
|
||||
|
||||
const size_t rxLen = rb.size();
|
||||
if(rxLen == ZynqFlasherReplySize) {
|
||||
rb.read(rxBuffer.data(), 0, rxLen);
|
||||
}
|
||||
rb.clear();
|
||||
supportsZynqBinaryFlasher =
|
||||
rxLen == ZynqFlasherReplySize &&
|
||||
rxBuffer[0] == static_cast<uint8_t>(icsneo::Command::EnterBootloader) &&
|
||||
rxBuffer[1] == static_cast<uint8_t>(Response::Type::Success) &&
|
||||
std::equal(std::begin(ZynqFlasherSync), std::end(ZynqFlasherSync), rxBuffer.begin() + 2);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADCommunication::finalize() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADCommunication::hasFinalizationStep() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RADCommunication::sanityCheck() {
|
||||
if(!supportsZynqBinaryFlasher) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Two numbered test patterns the bootloader must accept, the 8 byte replies are not checked
|
||||
constexpr uint8_t PatternA[8] = {0xAA, 0x55, 0xAA, 0x55, 0xAA, 0xAA, 0x55, 0x55};
|
||||
constexpr uint8_t PatternB[8] = {0x12, 0x21, 0x34, 0x43, 0x56, 0x65, 0x78, 0x87};
|
||||
|
||||
auto request = makeRequest(Request::Type::SanityCheck, 1 + sizeof(PatternA), sizeof(PatternA));
|
||||
|
||||
request.payload[0] = 0x01u;
|
||||
std::copy(std::begin(PatternA), std::end(PatternA), request.payload + 1);
|
||||
|
||||
if(!sendRequest(request, std::chrono::milliseconds(1000))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
request.payload[0] = 0x02u;
|
||||
std::copy(std::begin(PatternB), std::end(PatternB), request.payload + 1);
|
||||
|
||||
return sendRequest(request, std::chrono::milliseconds(1000));
|
||||
}
|
||||
|
||||
bool RADCommunication::getBootloaderVersion() {
|
||||
auto request = makeRequest(Request::Type::BootloaderVersion, 0, sizeof(BootloaderVersionResponse));
|
||||
auto response = sendRequest(request, std::chrono::milliseconds(1000));
|
||||
|
||||
if(!response) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(response.size < sizeof(BootloaderVersionResponse)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BootloaderVersionResponse version;
|
||||
std::memcpy(&version, response.payload, sizeof(version));
|
||||
targetChip.info.id = static_cast<ChipID>(version.zynqId);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADCommunication::validateChipVersion(const icsneo::DeviceAppVersion& chipSrcVer) {
|
||||
if(!supportsZynqBinaryFlasher) {
|
||||
return true;
|
||||
}
|
||||
|
||||
auto request = makeRequest(Request::Type::ValidateVersion, 2, 2);
|
||||
|
||||
request.payload[0] = chipSrcVer.major;
|
||||
request.payload[1] = chipSrcVer.minor;
|
||||
|
||||
return sendRequest(request, std::chrono::milliseconds(1000));
|
||||
}
|
||||
|
||||
bool RADCommunication::authenticate() {
|
||||
icsbl_seed_v1 seed = {};
|
||||
if(!icsbl_generate_seed_v1(device.getSerialNumber(), &seed)) {
|
||||
Log::Error(__func__, "libicsbl could not generate an authentication challenge");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto request = makeRequest(Request::Type::Authenticate, sizeof(seed.a), sizeof(seed.b));
|
||||
|
||||
writeLE32(&request.payload[0], seed.a[0]);
|
||||
writeLE32(&request.payload[4], seed.a[1]);
|
||||
|
||||
auto response = sendRequest(request, std::chrono::milliseconds(2000));
|
||||
|
||||
if(!response) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return seed.b[0] == readLE32(&response.payload[0]) && seed.b[1] == readLE32(&response.payload[4]);
|
||||
}
|
||||
|
||||
bool RADCommunication::sendSoftware(const std::vector<uint8_t>& chipSoftware) {
|
||||
Log::Debug(__func__, "starting for " + targetChip.getName() + " (" + std::to_string(chipSoftware.size()) + " bytes)");
|
||||
static constexpr size_t MaxEthernetPayload = 1487;
|
||||
|
||||
if(supportsZynqBinaryFlasher && chipSoftware.size() < sizeof(uint32_t)) {
|
||||
Log::Error(__func__, "firmware too short to contain a CRC for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
Log::Trace(__func__, "sending BeginTransfer for " + targetChip.getName());
|
||||
auto request = makeRequest(Request::Type::BeginTransfer, 0, 0);
|
||||
auto response = sendRequest(request, std::chrono::milliseconds(10000));
|
||||
|
||||
if(!response) {
|
||||
Log::Error(__func__, "BeginTransfer failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
const size_t headerSize = 1 + (supportsZynqBinaryFlasher ? ZynqFlasherHeaderSize : 0); // Command byte plus the optional Zynq flasher header
|
||||
const size_t maxPayloadSize = MaxEthernetPayload - headerSize;
|
||||
|
||||
size_t remainingBytes = chipSoftware.size();
|
||||
size_t currentlyReading = 0;
|
||||
|
||||
logger(
|
||||
icsneo::Device::OpenStatusType::Progress,
|
||||
"Flashing " + targetChip.getName() + "...",
|
||||
std::nullopt
|
||||
);
|
||||
|
||||
while(remainingBytes > 0) {
|
||||
const double progress = static_cast<double>(currentlyReading) / static_cast<double>(chipSoftware.size());
|
||||
|
||||
logger(
|
||||
icsneo::Device::OpenStatusType::Progress,
|
||||
"Flashing " + targetChip.getName() + "...",
|
||||
progress
|
||||
);
|
||||
|
||||
size_t numToSend = std::min<size_t>(maxPayloadSize, remainingBytes);
|
||||
request = makeRequest(Request::Type::FWPayload, numToSend, supportsZynqBinaryFlasher ? 2 : 0);
|
||||
|
||||
std::copy(
|
||||
chipSoftware.begin() + currentlyReading,
|
||||
chipSoftware.begin() + currentlyReading + numToSend,
|
||||
request.payload
|
||||
);
|
||||
|
||||
if(supportsFlashBuffer()) {
|
||||
if(!sendRequest(request, std::chrono::milliseconds(2000))) {
|
||||
return false;
|
||||
}
|
||||
} else if(!sendRequestNoResponse()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
currentlyReading += numToSend;
|
||||
remainingBytes -= numToSend;
|
||||
if(device.com->driver->isEthernet()) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
}
|
||||
|
||||
Log::Trace(__func__, "sending EndTransfer for " + targetChip.getName());
|
||||
request = makeRequest(Request::Type::EndTransfer, 0, 0);
|
||||
response = sendRequest(request, std::chrono::milliseconds(10000));
|
||||
|
||||
if(!response) {
|
||||
Log::Error(__func__, "EndTransfer failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
request = makeRequest(Request::Type::DownloadedBinInfo, 0, 4);
|
||||
response = sendRequest(request, std::chrono::milliseconds(6000));
|
||||
|
||||
if(!response) {
|
||||
Log::Error(__func__, "DownloadedBinInfo failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint32_t numDownloaded = readLE32(response.payload);
|
||||
|
||||
if(numDownloaded != static_cast<uint32_t>(chipSoftware.size())) {
|
||||
Log::Error(__func__, "downloaded size mismatch for " + targetChip.getName() + ": expected " + std::to_string(chipSoftware.size()) + ", got " + std::to_string(numDownloaded));
|
||||
return false;
|
||||
}
|
||||
|
||||
if(supportsZynqBinaryFlasher) {
|
||||
request = makeRequest(Request::Type::VerifyCRC, sizeof(uint32_t), 2);
|
||||
|
||||
/**
|
||||
* Copy CRC from end of the binary
|
||||
*/
|
||||
std::copy(chipSoftware.end() - sizeof(uint32_t), chipSoftware.end(), request.payload);
|
||||
|
||||
response = sendRequest(request, std::chrono::milliseconds(2000));
|
||||
|
||||
if(!response) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The first response byte is 1 when the CRC matched
|
||||
if(response.payload[0] != 0x01) {
|
||||
Log::Error(__func__, "CRC mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
logger(
|
||||
icsneo::Device::OpenStatusType::Progress,
|
||||
"Flashing " + targetChip.getName() + "...",
|
||||
1.0
|
||||
);
|
||||
|
||||
Log::Debug(__func__, "completed successfully for " + targetChip.getName());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADCommunication::getProgrammingStatus(size_t sizeToValidate) {
|
||||
Log::Debug(__func__, "starting for " + targetChip.getName());
|
||||
auto request = makeRequest(Request::Type::ProgramFlash, 0, supportsZynqBinaryFlasher ? 2 : 0);
|
||||
|
||||
if(!sendRequest(request, std::chrono::milliseconds(2000))) {
|
||||
Log::Error(__func__, "ProgramFlash failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
request = makeRequest(Request::Type::ProgrammingStatus, 0, 4);
|
||||
|
||||
uint32_t status = 0;
|
||||
const auto beginTime = std::chrono::steady_clock::now();
|
||||
|
||||
logger(
|
||||
icsneo::Device::OpenStatusType::Progress,
|
||||
"Programming " + targetChip.getName() + "...",
|
||||
std::nullopt
|
||||
);
|
||||
|
||||
while(status < static_cast<uint32_t>(sizeToValidate)) {
|
||||
const double progress = static_cast<double>(status) / static_cast<double>(sizeToValidate);
|
||||
|
||||
logger(
|
||||
icsneo::Device::OpenStatusType::Progress,
|
||||
"Programming " + targetChip.getName() + "...",
|
||||
progress
|
||||
);
|
||||
|
||||
const auto& response = sendRequest(request, std::chrono::milliseconds(60000));
|
||||
if(!response) {
|
||||
return false;
|
||||
}
|
||||
status = readLE32(response.payload);
|
||||
|
||||
if(std::chrono::steady_clock::now() - beginTime >= std::chrono::milliseconds(180000)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
logger(
|
||||
icsneo::Device::OpenStatusType::Progress,
|
||||
"Programming " + targetChip.getName() + "...",
|
||||
1.0
|
||||
);
|
||||
|
||||
Log::Debug(__func__, "completed successfully for " + targetChip.getName());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADCommunication::loadZips(const FWRepo& fw, std::vector<uint8_t>& chipSoftware) {
|
||||
if(const auto& segmentNames = targetChip.getMultiIEFName(); !segmentNames.empty()) {
|
||||
std::vector<std::unique_ptr<FWZip>> zips;
|
||||
zips.reserve(segmentNames.size());
|
||||
|
||||
size_t totalSize = 0;
|
||||
for(const auto& name : segmentNames) {
|
||||
std::vector<uint8_t> segment;
|
||||
if(!fw.getFW(name, segment)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
zips.push_back(std::make_unique<FWZip>(std::move(segment)));
|
||||
auto& zip = zips.back();
|
||||
if(!zip->size()) {
|
||||
return false;
|
||||
}
|
||||
totalSize += *zip->size();
|
||||
}
|
||||
chipSoftware.resize(totalSize, 0);
|
||||
size_t offset = 0;
|
||||
for(auto& zip : zips) {
|
||||
if(!zip->readAll(chipSoftware.data() + offset)) {
|
||||
return false;
|
||||
}
|
||||
offset += *(zip->size());
|
||||
}
|
||||
return true;
|
||||
} else if(!targetChip.getIEFName().empty()) {
|
||||
std::vector<uint8_t> bin;
|
||||
if(!fw.getFW(targetChip.getIEFName(), bin)) {
|
||||
return false;
|
||||
}
|
||||
FWZip fwZip(std::move(bin));
|
||||
if(!fwZip.readAll(chipSoftware)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Should never happen
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RADCommunication::flash(const FWRepo& fw, const icsneo::Device::OpenStatusHandler& handler) {
|
||||
Log::Info(__func__, "starting flash for " + targetChip.getName());
|
||||
auto chipSrcVer = fw.getChipVersion(targetChip.getIEFName());
|
||||
if(!chipSrcVer) {
|
||||
Log::Error(__func__, "no chip version found for " + targetChip.getIEFName());
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> chipSoftware;
|
||||
if(!loadZips(fw, chipSoftware)) {
|
||||
Log::Error(__func__, "loadZips failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
logger = handler;
|
||||
if(!validateChipVersion(*chipSrcVer)) {
|
||||
Log::Error(__func__, "validateChipVersion failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!sendSoftware(chipSoftware)) {
|
||||
Log::Error(__func__, "sendSoftware failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!supportsFlashBuffer()) {
|
||||
if(!getProgrammingStatus(chipSoftware.size())) {
|
||||
Log::Error(__func__, "getProgrammingStatus failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Log::Info(__func__, "completed successfully for " + targetChip.getName());
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/radmultichipcommunication.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwrepo.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/ief.h"
|
||||
#include "icsneo/device/extensions/bootloader/api.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <thread>
|
||||
|
||||
using namespace icsneo::Bootloader;
|
||||
|
||||
RADMultiChipCommunication::RADMultiChipCommunication(icsneo::Device& dev, const ChipInfo& chipToFlash, bool auth, uint8_t slot)
|
||||
: RADCommunication(dev, chipToFlash), doAuthChecks(auth), slot(slot) {}
|
||||
|
||||
bool RADMultiChipCommunication::authenticate() {
|
||||
if(!doAuthChecks) {
|
||||
Log::Trace(__func__, "auth checks disabled, skipping");
|
||||
return true;
|
||||
}
|
||||
Log::Debug(__func__, "starting authentication");
|
||||
if(!standardComm->authenticate()) {
|
||||
Log::Warning(__func__, "standardComm auth failed, retrying with sanity check");
|
||||
device.com->pauseReads();
|
||||
if(!sanityCheck()) {
|
||||
if(!sanityCheck()) {
|
||||
device.com->resumeReads();
|
||||
Log::Error(__func__, "sanity check failed after retries");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if(!RADCommunication::authenticate()) {
|
||||
device.com->resumeReads();
|
||||
Log::Error(__func__, "RADCommunication auth failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
device.com->resumeReads();
|
||||
}
|
||||
Log::Debug(__func__, "authentication successful");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADMultiChipCommunication::flash(const FWRepo& fw, const icsneo::Device::OpenStatusHandler& handler) {
|
||||
Log::Info(__func__, "starting flash for " + targetChip.getName());
|
||||
auto chipSrcVer = fw.getChipVersion(targetChip.getIEFName());
|
||||
if(!chipSrcVer) {
|
||||
Log::Error(__func__, "no chip version found for " + targetChip.getIEFName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!authenticate()) {
|
||||
Log::Error(__func__, "authentication failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!standardComm->validateFirmware(*chipSrcVer)) {
|
||||
Log::Error(__func__, "firmware validation failed for " + targetChip.getName());
|
||||
handler(icsneo::Device::OpenStatusType::Failed, "Failed to validate firmware", std::nullopt);
|
||||
return false;
|
||||
}
|
||||
|
||||
if(targetChip.getFirmwareType() == FirmwareType::Zip) {
|
||||
std::vector<uint8_t> chipSoftware;
|
||||
if(!loadZips(fw, chipSoftware)) {
|
||||
Log::Error(__func__, "loadZips failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!standardComm->sendSoftware(chipSoftware, handler)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
std::vector<uint8_t> bin;
|
||||
if(!fw.getFW(targetChip.getIEFName(), bin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
IEF ief;
|
||||
if(!ief.load(std::move(bin))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The supplied IEF is not for this product
|
||||
if(ief.getVersion().prodId != static_cast<uint8_t>(device.getProductID()) && !isSFPIEF(ief)) {
|
||||
Log::Error(__func__, "IEF product ID mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// The supplied IEF is for this product, but not for this chip
|
||||
if(ief.getVersion().chipId != static_cast<uint8_t>(targetChip.getID())) {
|
||||
Log::Error(__func__, "IEF chip ID mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!standardComm->sendSoftware(ief.getSectors(), ief.getBlockSize(), handler)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Log::Debug(__func__, "calling finalize");
|
||||
if(!standardComm->finalize()) {
|
||||
Log::Error(__func__, "finalize failed");
|
||||
return false;
|
||||
}
|
||||
Log::Debug(__func__, "finalize successful, proceeding to reboot");
|
||||
handler(icsneo::Device::OpenStatusType::Progress, "Rebooting device...", std::nullopt);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADMultiChipCommunication::enterApplication() {
|
||||
Log::Info(__func__, "starting");
|
||||
if(!standardComm->enterApplication()) {
|
||||
Log::Error(__func__, "reboot failed");
|
||||
return false;
|
||||
}
|
||||
Log::Debug(__func__, "reboot sent, waiting 5000ms");
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADMultiChipCommunication::open() {
|
||||
const auto& components = device.getComponentVersions();
|
||||
auto component = std::find_if(components.begin(), components.end(), [this](const auto& candidate) {
|
||||
if(slot != UINT8_MAX && slot != candidate.expansionSlot) {
|
||||
return false;
|
||||
}
|
||||
return targetChip.getID() == (ChipID)candidate.identifier;
|
||||
});
|
||||
if(component == components.end()) {
|
||||
Log::Error(__func__, "no component found for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
standardComm = std::make_unique<Application>(device, targetChip.info);
|
||||
standardComm->setExpansionSlot(component->expansionSlot);
|
||||
// Pause the read thread so it doesn't consume any responses
|
||||
device.com->pauseReads();
|
||||
const bool res = initialize();
|
||||
device.com->resumeReads();
|
||||
return res;
|
||||
}
|
||||
|
||||
bool RADMultiChipCommunication::close() {
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/radperiphcommunication.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwrepo.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <thread>
|
||||
|
||||
#include <icsbl/icsbl.h>
|
||||
|
||||
using namespace icsneo::Bootloader;
|
||||
|
||||
RADPeriphCommunication::RADPeriphCommunication(icsneo::Device& dev, const ChipInfo& chipToFlash)
|
||||
: Communication(dev), targetChip(chipToFlash) {}
|
||||
|
||||
RADPeriphCommunication::~RADPeriphCommunication() {
|
||||
if(device.com->readsArePaused()) {
|
||||
device.com->resumeReads();
|
||||
}
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::sendRequestNoResponse(Request req, std::vector<uint8_t>&& args) {
|
||||
return sendRequestNoResponse(req, targetChip.getID(), std::move(args));
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::sendRequestNoResponse(Request req, ChipID id, std::vector<uint8_t>&& args) {
|
||||
args.insert(args.begin(), {
|
||||
(uint8_t)id,
|
||||
(uint8_t)req,
|
||||
});
|
||||
return device.com->sendCommand(icsneo::Command::PeripheralBootloader, args);
|
||||
}
|
||||
|
||||
RADPeriphCommunication::Response RADPeriphCommunication::sendRequest(Request req, std::vector<uint8_t>&& args, std::chrono::milliseconds timeout) {
|
||||
return sendRequest(req, targetChip.getID(), std::move(args), timeout);
|
||||
}
|
||||
|
||||
RADPeriphCommunication::Response RADPeriphCommunication::sendRequest(Request req, ChipID id, std::vector<uint8_t>&& args, std::chrono::milliseconds timeout) {
|
||||
// Total reply sizes, including the header bytes
|
||||
size_t expectedResponseLength = 0;
|
||||
bool checkBlAccepted = false;
|
||||
switch(req) {
|
||||
case Request::Mode:
|
||||
expectedResponseLength = 6;
|
||||
break;
|
||||
case Request::Version:
|
||||
expectedResponseLength = 24;
|
||||
checkBlAccepted = true;
|
||||
break;
|
||||
case Request::Authenticate:
|
||||
expectedResponseLength = 13;
|
||||
checkBlAccepted = true;
|
||||
break;
|
||||
case Request::Echo:
|
||||
expectedResponseLength = 3;
|
||||
break;
|
||||
case Request::Erase:
|
||||
case Request::FirmwareValidate:
|
||||
case Request::FlashSector:
|
||||
expectedResponseLength = 3;
|
||||
checkBlAccepted = true;
|
||||
break;
|
||||
default:
|
||||
expectedResponseLength = 3;
|
||||
break;
|
||||
}
|
||||
|
||||
auto& rb = device.com->driver->getReadBuffer();
|
||||
rb.clear();
|
||||
if(!sendRequestNoResponse(req, id, std::move(args))) {
|
||||
Log::Error(__func__, "Failed to send request " + std::to_string(static_cast<uint8_t>(req)));
|
||||
return {};
|
||||
}
|
||||
|
||||
auto result = device.com->driver->waitForRx(expectedResponseLength, timeout);
|
||||
if(!result) {
|
||||
Log::Error(__func__, "No response to request " + std::to_string(static_cast<uint8_t>(req)));
|
||||
return {};
|
||||
}
|
||||
|
||||
Response resp;
|
||||
resp.data.resize(expectedResponseLength, 0);
|
||||
rb.read(resp.data.data(), 0, expectedResponseLength);
|
||||
resp.success = resp.data[ReplySuccessOffset] == ReplySuccess;
|
||||
if(!resp.success) {
|
||||
Log::Error(__func__, "The peripheral reported failure for request " + std::to_string(static_cast<uint8_t>(req)));
|
||||
return resp;
|
||||
}
|
||||
if(checkBlAccepted && resp.data[ReplyAcceptedOffset] != ReplyAccepted) {
|
||||
Log::Error(__func__, "The bootloader rejected request " + std::to_string(static_cast<uint8_t>(req)));
|
||||
return {};
|
||||
}
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
RADPeriphCommunication::Mode RADPeriphCommunication::getMode() {
|
||||
auto resp = sendRequest(Request::Mode, {}, std::chrono::milliseconds(2000));
|
||||
|
||||
if(!resp) {
|
||||
return Mode::NoAnswer;
|
||||
}
|
||||
static constexpr size_t ModeOffset = 4;
|
||||
return (Mode)resp.data[ModeOffset];
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::sendPeriphTest() {
|
||||
// Echo is sent to chip id 0, the reply carries the bitwise inverse of the test byte
|
||||
const uint8_t testByte = 0x00;
|
||||
auto resp = sendRequest(Request::Echo, (ChipID)0x00, {testByte}, std::chrono::milliseconds(2000));
|
||||
|
||||
if(!resp) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(resp.data[2] != static_cast<uint8_t>(~testByte)) {
|
||||
Log::Error(__func__, "The peripheral echo reply did not match");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::readSerialNumber() {
|
||||
auto resp = sendRequest(Request::Version, {0x00}, std::chrono::milliseconds(2000));
|
||||
if(!resp) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The reply payload is the start of a BootloaderVersionResponse
|
||||
static constexpr size_t SerialOffset = ReplyHeaderSize + offsetof(BootloaderVersionResponse, serialNum);
|
||||
serialNumber = readLE32(resp.data.data() + SerialOffset);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::authenticate() {
|
||||
icsbl_seed_v1 seed = {};
|
||||
if(!icsbl_generate_seed_v1(serialNumber, &seed)) {
|
||||
Log::Error(__func__, "libicsbl could not generate an authentication challenge");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> args(BootloaderArgsOffset + sizeof(seed.a), 0);
|
||||
writeLE32(args.data() + BootloaderArgsOffset, seed.a[0]);
|
||||
writeLE32(args.data() + BootloaderArgsOffset + 4, seed.a[1]);
|
||||
|
||||
auto resp = sendRequest(Request::Authenticate, std::move(args), std::chrono::milliseconds(3000));
|
||||
if(!resp) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// seed.b follows the header and one more byte
|
||||
static constexpr size_t ReplyOffset = ReplyHeaderSize + 1;
|
||||
return readLE32(resp.data.data() + ReplyOffset) == seed.b[0] &&
|
||||
readLE32(resp.data.data() + ReplyOffset + 4) == seed.b[1];
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::validateFirmware() {
|
||||
return sendRequest(Request::FirmwareValidate, {0x00u}, std::chrono::milliseconds(2000));
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::flashSector(const IEF::Sector& sector) {
|
||||
if(sector.second.size() < FlashSectorFirstChunkSize) {
|
||||
Log::Error(__func__, "Invalid sector length");
|
||||
return false;
|
||||
}
|
||||
|
||||
// The first request is the 32-bit little-endian address followed by the first chunk, encrypted
|
||||
std::vector<uint8_t> args(BootloaderArgsOffset + sizeof(uint32_t) + FlashSectorFirstChunkSize, 0);
|
||||
writeLE32(args.data() + BootloaderArgsOffset, sector.first);
|
||||
icsbl_encrypt_v1(serialNumber, sector.second.begin(), FlashSectorFirstChunkSize, args.data() + BootloaderArgsOffset + sizeof(uint32_t));
|
||||
if(!sendRequestNoResponse(Request::FlashSector, std::move(args))) {
|
||||
return false;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(400));
|
||||
|
||||
// The second request is the rest of the sector, encrypted
|
||||
const size_t bytesLeft = sector.second.size() - FlashSectorFirstChunkSize;
|
||||
args = std::vector<uint8_t>(bytesLeft, 0);
|
||||
icsbl_encrypt_v1(serialNumber, sector.second.begin() + FlashSectorFirstChunkSize, bytesLeft, args.data());
|
||||
return sendRequest(Request::FlashSector, std::move(args), std::chrono::milliseconds(3000));
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::flash(const FWRepo& fw, const icsneo::Device::OpenStatusHandler& handler) {
|
||||
// Validate the firmware before touching the device so a bad file can not leave it erased
|
||||
std::vector<uint8_t> bin;
|
||||
if(!fw.getFW(targetChip.getIEFName(), bin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
IEF ief;
|
||||
if(!ief.load(std::move(bin))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The supplied IEF is not for this product
|
||||
if(ief.getVersion().prodId != static_cast<uint8_t>(device.getProductID())) {
|
||||
Log::Error(__func__, "IEF product ID mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// The supplied IEF is for this product, but not for this chip
|
||||
if(ief.getVersion().chipId != static_cast<uint8_t>(targetChip.getID())) {
|
||||
Log::Error(__func__, "IEF chip ID mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto& sectors = ief.getSectors();
|
||||
uint32_t totalSize = 0;
|
||||
for(const auto& sector : sectors) {
|
||||
if(sector.second.size() < FlashSectorFirstChunkSize) {
|
||||
Log::Error(__func__, "Invalid sector length in IEF for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
totalSize += static_cast<uint32_t>(sector.second.size());
|
||||
}
|
||||
|
||||
if(!readSerialNumber()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!authenticate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!sendRequest(Request::Erase)) {
|
||||
Log::Error(__func__, "Failed to erase firmware");
|
||||
return false;
|
||||
}
|
||||
|
||||
handler(
|
||||
icsneo::Device::OpenStatusType::Progress,
|
||||
"Flashing " + targetChip.getName() + "...",
|
||||
std::nullopt
|
||||
);
|
||||
|
||||
uint32_t sizeFlashed = 0;
|
||||
|
||||
for(const auto& sector : sectors) {
|
||||
if(!flashSector(sector)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
sizeFlashed += static_cast<uint32_t>(sector.second.size());
|
||||
handler(
|
||||
icsneo::Device::OpenStatusType::Progress,
|
||||
"Flashing " + targetChip.getName() + "...",
|
||||
(double)sizeFlashed / (double)totalSize
|
||||
);
|
||||
}
|
||||
|
||||
return validateFirmware();
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::waitForConnect(std::chrono::milliseconds timeout) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
while(std::chrono::steady_clock::now() < deadline) {
|
||||
if(sendPeriphTest()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::open() {
|
||||
device.com->pauseReads();
|
||||
|
||||
int attempts = 3;
|
||||
do {
|
||||
mode = getMode();
|
||||
if(mode == Mode::NoAnswer) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
mode = getMode();
|
||||
if(mode == Mode::NoAnswer) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if(mode == Mode::MainApplication) {
|
||||
if(!sendRequestNoResponse(Request::SwitchToBootloader)) {
|
||||
return false;
|
||||
}
|
||||
if(!device.reconnect(std::chrono::seconds(30))) {
|
||||
return false;
|
||||
}
|
||||
if(!waitForConnect(std::chrono::seconds(30))) {
|
||||
return false;
|
||||
}
|
||||
} else if(mode == Mode::Bootloader) {
|
||||
return true;
|
||||
}
|
||||
} while(attempts--);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::close() {
|
||||
if(mode != Mode::Bootloader) {
|
||||
device.com->resumeReads();
|
||||
return true;
|
||||
}
|
||||
if(!sendRequestNoResponse(Request::SwitchToApp)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5)); // measured at 2s, 5s for buffer, yes this is needed
|
||||
|
||||
if(!device.reconnect(std::chrono::seconds(30))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!waitForConnect()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mode = getMode();
|
||||
if(mode == Mode::MainApplication) {
|
||||
device.com->resumeReads();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::enterApplication() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::finalize() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RADPeriphCommunication::hasFinalizationStep() const {
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/red.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/ief.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwrepo.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <optional>
|
||||
|
||||
#include <icsbl/icsbl.h>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
REDCommunication::REDCommunication(icsneo::Device& dev, const ChipInfo& chip, bool auth, bool encryptWithDeviceKey)
|
||||
: REDCommunicationBase(dev, chip), doAuthChecks(auth), encryptFirmwareWithDeviceKey(encryptWithDeviceKey) {}
|
||||
|
||||
bool REDCommunication::open() {
|
||||
device.com->pauseReads();
|
||||
|
||||
if(doAuthChecks) {
|
||||
if(!authenticate()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return getVersion();
|
||||
}
|
||||
|
||||
bool REDCommunication::authenticate(bool firstTime) {
|
||||
icsbl_seed_v1 seed = {};
|
||||
if(!icsbl_generate_seed_v1(device.getSerialNumber(), &seed)) {
|
||||
Log::Error(__func__, "libicsbl could not generate an authentication challenge");
|
||||
return false;
|
||||
}
|
||||
|
||||
// The challenge is sent as: uint8_t 0x09, uint16_t 0 (a length on top of the protocol length, always zero here),
|
||||
// one padding byte, then seed.a
|
||||
std::vector<uint8_t> challenge(3 + sizeof(seed.a));
|
||||
challenge[0] = 0x09;
|
||||
std::memcpy(&challenge[3], &seed.a, sizeof(seed.a));
|
||||
|
||||
// Ask the bootloader to decode the seed
|
||||
Log::Debug(__func__, "Authenticating");
|
||||
if(!sendCommand(uint8_t(Command::Authenticate), challenge, std::chrono::seconds(1), false)) {
|
||||
if(firstTime) {
|
||||
// Attempt to flush out any buffers
|
||||
Log::Debug(__func__, "Authentication failed, flushing buffers");
|
||||
std::vector<uint8_t> flush(4096, PaddingByte);
|
||||
device.com->sendPacket(flush);
|
||||
|
||||
// Allow any failure messages to come back
|
||||
const bool any = waitForRx(std::chrono::milliseconds(100));
|
||||
Log::Trace(__func__, any ? "A message came back" : "No communication came back");
|
||||
|
||||
lastData.clear();
|
||||
|
||||
// Now try again
|
||||
return authenticate(false); // Either way, we don't need to continue authenticating
|
||||
} else {
|
||||
Log::Error(__func__, "The bootloader rejected the authentication challenge twice");
|
||||
enterApplication();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// The reply is one byte followed by seed.b
|
||||
if(lastData.back().data.size() < 1 + sizeof(seed.b)) {
|
||||
Log::Error(__func__, "The authentication reply is too short");
|
||||
enterApplication();
|
||||
return false;
|
||||
}
|
||||
if(std::memcmp(&lastData.back().data[1], &seed.b, sizeof(seed.b)) != 0) {
|
||||
Log::Error(__func__, "The authentication reply does not match, the device did not authenticate");
|
||||
enterApplication();
|
||||
return false;
|
||||
}
|
||||
lastData.clear();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool REDCommunication::getVersion() {
|
||||
if(!sendCommand(uint8_t(Command::GetVersion), std::chrono::seconds(1), false)) {
|
||||
Log::Error(__func__, "The bootloader did not answer the version request");
|
||||
enterApplication();
|
||||
return false;
|
||||
}
|
||||
|
||||
if(lastData.front().data.size() < VersionResponse::EncodedSize) {
|
||||
Log::Error(__func__, "The bootloader version reply is too short");
|
||||
enterApplication();
|
||||
return false;
|
||||
}
|
||||
|
||||
currentVersion = VersionResponse(lastData.front());
|
||||
lastData.clear();
|
||||
|
||||
if(doAuthChecks) {
|
||||
// Check that the serial number the bootloader reports is correct
|
||||
uint8_t correctSerial[sizeof(VersionResponse::serial_num)] = {};
|
||||
uint32_t devSerial = device.getSerialNumber();
|
||||
std::memcpy(correctSerial, &devSerial, sizeof(devSerial));
|
||||
if(std::memcmp(correctSerial, currentVersion.serial_num, sizeof(correctSerial))) {
|
||||
Log::Error(__func__, "The serial number reported by the bootloader does not match the device");
|
||||
enterApplication();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
blockSize = currentVersion.block_size;
|
||||
device.setBootloaderVersion({currentVersion.bl_major, currentVersion.bl_minor});
|
||||
return true;
|
||||
}
|
||||
|
||||
bool REDCommunication::flash(const FWRepo& fw, const icsneo::Device::OpenStatusHandler& handler) {
|
||||
const auto& srcVer = fw.getVersion();
|
||||
|
||||
std::vector<uint8_t> bin;
|
||||
if(!fw.getFW(targetChip.getIEFName(), bin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
IEF ief;
|
||||
if(!ief.load(std::move(bin))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The supplied IEF is not for this product
|
||||
if(ief.getVersion().prodId != static_cast<uint8_t>(device.getProductID())) {
|
||||
Log::Error(__func__, "IEF product ID mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// The supplied IEF is for this product, but not for this chip
|
||||
if(ief.getVersion().chipId != static_cast<uint8_t>(targetChip.getID())) {
|
||||
Log::Error(__func__, "IEF chip ID mismatch for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
Log::Debug(__func__, "IEF version " + std::to_string(ief.getVersion().appMajor) + "." + std::to_string(ief.getVersion().appMinor)
|
||||
+ ", " + std::to_string(ief.getSectors().size()) + " sectors");
|
||||
|
||||
if(doAuthChecks && device.supportsSwVersionValidate()) {
|
||||
// Tell the bootloader what version of Vehicle Spy 3 this firmware is from.
|
||||
// We check to make sure it approves, but also, some devices will not accept
|
||||
// new firmware if we have not sent this.
|
||||
// Sometimes new hardware revisions can not accept firmware which is too old.
|
||||
if(!sendCommand(uint8_t(Command::ValidateSWVersion), {srcVer.major, srcVer.minor, srcVer.release, srcVer.build})) {
|
||||
Log::Error(__func__, "SW version validation failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
handler(icsneo::Device::OpenStatusType::Progress,
|
||||
"Preparing to update " + targetChip.getName() + "...", std::nullopt);
|
||||
Log::Debug(__func__, "Erasing " + targetChip.getName());
|
||||
if(!sendCommand(uint8_t(Command::Erase), std::chrono::seconds(45))) {
|
||||
Log::Error(__func__, "Erase failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto& sectorPairs = ief.getSectors();
|
||||
size_t sectorsFlashed = 0;
|
||||
for(const auto& [id, sector] : sectorPairs) {
|
||||
Log::Trace(__func__, "Flashing sector " + std::to_string(id));
|
||||
handler(icsneo::Device::OpenStatusType::Progress,
|
||||
"Updating " + targetChip.getName() + "...",
|
||||
double(sectorsFlashed++) / sectorPairs.size());
|
||||
|
||||
if(sector.size() > blockSize) {
|
||||
Log::Error(__func__, "Sector " + std::to_string(id) + " too large");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Sectors smaller than the block size are padded out with zeros
|
||||
std::vector<uint8_t> padded(sector.begin(), sector.end());
|
||||
padded.resize(blockSize, 0);
|
||||
|
||||
std::vector<uint8_t> encrypted(padded.size());
|
||||
if(encryptFirmwareWithDeviceKey)
|
||||
icsbl_encrypt_v1(device.getSerialNumber(), padded.data(), padded.size(), encrypted.data());
|
||||
else
|
||||
encrypted = std::move(padded);
|
||||
|
||||
encrypted.insert(encrypted.begin(), {
|
||||
0x00, 0x00, 0x00, // Padding bytes
|
||||
// Address
|
||||
uint8_t((id >> 0x00) & 0xFF),
|
||||
uint8_t((id >> 0x08) & 0xFF),
|
||||
uint8_t((id >> 0x10) & 0xFF),
|
||||
uint8_t((id >> 0x18) & 0xFF),
|
||||
});
|
||||
|
||||
// Unencrypted firmware is used for FIRE2 Zynq (and VNET) which also uses the top bit of the ID
|
||||
// to denote whether the sector is flashed to chip A or chip B. That is indicated
|
||||
// with a 1 (for chip B) or a 0 as the first byte of the flash packet payload.
|
||||
if(!encryptFirmwareWithDeviceKey)
|
||||
encrypted.insert(encrypted.begin(), uint8_t(id & (1u << 31) ? 1 : 0));
|
||||
|
||||
if(!sendCommand(uint8_t(Command::Flash), encrypted)) {
|
||||
Log::Error(__func__, "Flash failed at sector " + std::to_string(id) + " for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Tell the application that we flashed 100%
|
||||
handler(icsneo::Device::OpenStatusType::Progress,
|
||||
"Updating " + targetChip.getName() + "...",
|
||||
1.0);
|
||||
|
||||
handler(icsneo::Device::OpenStatusType::Progress, "Finalizing update...", std::nullopt);
|
||||
if(!sendCommand(uint8_t(Command::ValidateFirmware))) {
|
||||
Log::Error(__func__, "Firmware validation failed for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
REDCommunication::VersionResponse::VersionResponse(const REDPacketizer::RxFrame& r) {
|
||||
auto i = r.data.begin();
|
||||
bl_major = *i++;
|
||||
bl_minor = *i++;
|
||||
app_major = *i++;
|
||||
app_minor = *i++;
|
||||
hardware_rev_major = *i++;
|
||||
hardware_rev_minor = *i++;
|
||||
flags = *i++;
|
||||
block_size = *i++;
|
||||
block_size |= uint16_t(*i++) << 8;
|
||||
man_day = *i++;
|
||||
man_month = *i++;
|
||||
man_year = *i++;
|
||||
man_year |= uint16_t(*i++) << 8;
|
||||
for(size_t x = 0; x != sizeof(serial_num); ++x)
|
||||
serial_num[x] = *i++;
|
||||
prod_id = *i++;
|
||||
last_error_code = *i++;
|
||||
pad_byte = *i++;
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,86 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/redbase.h"
|
||||
|
||||
#include <limits>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
REDCommunicationBase::REDCommunicationBase(icsneo::Device& dev, const ChipInfo& chip)
|
||||
: Communication(dev), targetChip(chip) {}
|
||||
|
||||
bool REDCommunicationBase::open() {
|
||||
device.com->pauseReads();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool REDCommunicationBase::close() {
|
||||
device.com->resumeReads();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool REDCommunicationBase::handleData() {
|
||||
auto& rb = device.com->driver->getReadBuffer();
|
||||
|
||||
if(rp.input(rb)) {
|
||||
lastData = rp.output();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool REDCommunicationBase::waitForRx(std::chrono::milliseconds timeout) {
|
||||
return device.com->driver->waitForRx([this]() { return handleData(); }, timeout);
|
||||
}
|
||||
|
||||
bool REDCommunicationBase::sendCommand(uint8_t cmd, std::vector<uint8_t> args, std::chrono::seconds timeout, bool clearLastResponse) {
|
||||
lastData.clear();
|
||||
device.com->driver->getReadBuffer().clear();
|
||||
|
||||
if(!sendCommandRaw(cmd, std::move(args)))
|
||||
return false;
|
||||
|
||||
if(!waitForRx(std::chrono::duration_cast<std::chrono::milliseconds>(timeout)))
|
||||
return false;
|
||||
|
||||
const bool ret = lastData.front().resp == REDPacketizer::Response::Accepted;
|
||||
|
||||
if(clearLastResponse) {
|
||||
lastData.clear();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool REDCommunicationBase::sendCommandRaw(uint8_t cmd, std::vector<uint8_t> args) {
|
||||
// For some reason, some devices need it padded to even total bytes, and some to odd total bytes
|
||||
const bool padEven = device.getType() == DeviceType::FIRE2;
|
||||
|
||||
args.insert(args.begin(), uint8_t(cmd)); // Prepend the command byte to the arguments
|
||||
if(args.size() > std::numeric_limits<uint16_t>::max())
|
||||
return false;
|
||||
|
||||
uint16_t size = uint16_t(args.size());
|
||||
// The header counts, and the header is 5 bytes, so we're checking for even inner size here
|
||||
const bool padding = size % 2 != (padEven ? 0 : 1);
|
||||
if(padding) // We will add padding, so make space for it
|
||||
size++;
|
||||
|
||||
// Prepend the magic, 16-bit little-endian chip ID, and 16-bit little-endian size
|
||||
const uint16_t chipID = uint16_t(targetChip.getID());
|
||||
args.insert(args.begin(), {
|
||||
REDPacketizer::Magic,
|
||||
uint8_t(chipID & 0xFF), uint8_t(chipID >> 8),
|
||||
uint8_t(size & 0xFF), uint8_t(size >> 8)
|
||||
});
|
||||
|
||||
if(padding)
|
||||
args.push_back(PaddingByte); // Ignored by the firmware
|
||||
|
||||
// Write it to the device
|
||||
return device.com->sendPacket(args);
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,111 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/redcore.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwrepo.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
bool REDCoreCommunication::flash(const FWRepo& fw, const icsneo::Device::OpenStatusHandler& handler) {
|
||||
constexpr const size_t MaxSectorSize = 0x600;
|
||||
|
||||
std::vector<uint8_t> bin;
|
||||
if(!fw.getFW(targetChip.getIEFName(), bin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(bin.size() > std::numeric_limits<uint32_t>::max()) {
|
||||
Log::Error(__func__, "Firmware too large for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string message = "Updating " + targetChip.getName() + "...";
|
||||
|
||||
// First send the firmware
|
||||
const uint32_t fileSize = uint32_t(bin.size());
|
||||
size_t sectorsFlashed = 0;
|
||||
const size_t sectorCount = (fileSize / MaxSectorSize) + (fileSize % MaxSectorSize ? 1 : 0);
|
||||
std::vector<uint8_t> sector;
|
||||
for(size_t i = 0; i < fileSize; i += MaxSectorSize) {
|
||||
Log::Trace(__func__, "Sending sector " + std::to_string(sectorsFlashed));
|
||||
handler(icsneo::Device::OpenStatusType::Progress, message, double(sectorsFlashed++) / sectorCount);
|
||||
|
||||
sector.assign(bin.begin() + i, bin.begin() + i + std::min<size_t>(MaxSectorSize, fileSize - i));
|
||||
if(!sendCommand(uint8_t(Command::SendFirmware), sector)) {
|
||||
Log::Error(__func__, "Failed to send sector " + std::to_string(sectorsFlashed - 1) + " for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Then flash it
|
||||
Log::Debug(__func__, "Starting core flash for " + targetChip.getName());
|
||||
handler(icsneo::Device::OpenStatusType::Progress, message, std::nullopt);
|
||||
|
||||
// There is a long timeout on the StartFirmwareFlash because the bootloader may block here,
|
||||
// potentially for the entire duration of the flash
|
||||
if(!sendCommand(uint8_t(Command::StartFirmwareFlash), {
|
||||
uint8_t(fileSize & 0xFF), uint8_t((fileSize >> 8) & 0xFF),
|
||||
uint8_t((fileSize >> 16) & 0xFF), uint8_t((fileSize >> 24) & 0xFF),
|
||||
}, std::chrono::seconds(60))) {
|
||||
Log::Error(__func__, "Failed to start core flash for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Watch the responses to know when it's done
|
||||
const auto endTime = std::chrono::steady_clock::now() + std::chrono::seconds(60);
|
||||
uint32_t flashed = 0;
|
||||
while(flashed < fileSize && std::chrono::steady_clock::now() < endTime) {
|
||||
if(!sendCommandRaw(uint8_t(Command::GetFlashProgress))) {
|
||||
Log::Error(__func__, "Failed to request flash progress for " + targetChip.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!waitForRx(std::chrono::milliseconds(3000))) {
|
||||
Log::Trace(__func__, "No flash progress packet within 3 seconds");
|
||||
continue;
|
||||
}
|
||||
|
||||
const uint32_t oldFlashed = flashed;
|
||||
for(const auto& packet : lastData) {
|
||||
if(packet.resp != REDPacketizer::Response::Accepted)
|
||||
return false;
|
||||
if(packet.data.size() != 4) {
|
||||
Log::Trace(__func__, "Got a flash progress packet of length " + std::to_string(packet.data.size()));
|
||||
continue;
|
||||
}
|
||||
const uint32_t newFlashed = readLE32(packet.data.data());
|
||||
if(newFlashed >= flashed)
|
||||
flashed = newFlashed;
|
||||
else
|
||||
Log::Trace(__func__, "Got a flash progress packet which went backwards " + std::to_string(newFlashed) + " " + std::to_string(flashed));
|
||||
|
||||
// After sending us the packet that confirms the flash, the flash position is cleared and will send us zeros.
|
||||
// We don't need any of these other packets, in that case.
|
||||
if(flashed >= fileSize)
|
||||
break;
|
||||
}
|
||||
lastData.clear();
|
||||
|
||||
Log::Trace(__func__, "Flashed " + std::to_string(flashed) + " of " + std::to_string(fileSize));
|
||||
|
||||
if(flashed != oldFlashed)
|
||||
handler(icsneo::Device::OpenStatusType::Progress, message, std::min(double(flashed) / fileSize, 1.0));
|
||||
}
|
||||
|
||||
return flashed == fileSize;
|
||||
}
|
||||
|
||||
bool REDCoreCommunication::sendCommandRaw(uint8_t cmd, std::vector<uint8_t> args) {
|
||||
if(args.size() > std::numeric_limits<uint16_t>::max())
|
||||
return false;
|
||||
const uint16_t size = static_cast<uint16_t>(args.size());
|
||||
args.insert(args.begin(), { CoreFlasherMagic, uint8_t(size & 0xFF), uint8_t((size >> 8) & 0xFF), cmd });
|
||||
return REDCommunicationBase::sendCommandRaw(CoreFlasherCommand, std::move(args));
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,85 @@
|
||||
#include "icsneo/device/extensions/bootloader/communication/redpacketizer.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
bool REDPacketizer::input(icsneo::RingBuffer& bytes) {
|
||||
while(bytes.size() > 0) {
|
||||
switch(state) {
|
||||
case HEADER:
|
||||
if(bytes[0] == Magic) {
|
||||
working.emplace_back();
|
||||
state = CMD;
|
||||
} else {
|
||||
Log::Trace(__func__, "Got bootloader unknown byte: " + std::to_string(bytes[0]));
|
||||
}
|
||||
bytes.pop_front();
|
||||
break;
|
||||
case CMD:
|
||||
working.back().resp = Response(bytes[0]);
|
||||
if(working.back().resp != Response::Accepted && working.back().resp != Response::Rejected) {
|
||||
Log::Trace(__func__, "Got bootloader unknown response: " + std::to_string(bytes[0]));
|
||||
working.pop_back();
|
||||
state = HEADER;
|
||||
} else {
|
||||
state = LENGTH_LOWER;
|
||||
}
|
||||
bytes.pop_front();
|
||||
break;
|
||||
case LENGTH_LOWER:
|
||||
working.back().len = bytes[0];
|
||||
state = LENGTH_UPPER;
|
||||
bytes.pop_front();
|
||||
break;
|
||||
case LENGTH_UPPER:
|
||||
working.back().len |= uint16_t(bytes[0]) << 8;
|
||||
if(working.back().len == 0) {
|
||||
working.back().done = true;
|
||||
state = HEADER;
|
||||
} else {
|
||||
state = DATA;
|
||||
}
|
||||
bytes.pop_front();
|
||||
break;
|
||||
case DATA: {
|
||||
// The RingBuffer is not contiguous, so copy out with read() rather than taking a pointer
|
||||
auto& frame = working.back();
|
||||
const size_t dataToGo = frame.len - frame.data.size();
|
||||
const size_t toCopy = std::min(bytes.size(), dataToGo);
|
||||
const size_t oldSize = frame.data.size();
|
||||
frame.data.resize(oldSize + toCopy);
|
||||
bytes.read(frame.data.data() + oldSize, 0, toCopy);
|
||||
bytes.pop(toCopy);
|
||||
if(toCopy == dataToGo) {
|
||||
frame.done = true;
|
||||
state = HEADER;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return std::any_of(working.begin(), working.end(), [](const RxFrame& rx) { return rx.done; });
|
||||
}
|
||||
|
||||
std::vector<REDPacketizer::RxFrame> REDPacketizer::output() {
|
||||
// Hand back the completed frames, anything still in progress stays in working
|
||||
std::vector<RxFrame> done;
|
||||
std::vector<RxFrame> pending;
|
||||
for(auto& rx : working) {
|
||||
if(rx.done)
|
||||
done.push_back(std::move(rx));
|
||||
else
|
||||
pending.push_back(std::move(rx));
|
||||
}
|
||||
working = std::move(pending);
|
||||
return done;
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,249 @@
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwbin.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/ief.h"
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
/**
|
||||
* fw.bin file format (all integers little-endian):
|
||||
*
|
||||
* uint8_t versionLength
|
||||
* char version[versionLength] Vehicle Spy 3 version, "major.minor.release.build"
|
||||
* uint8_t hashLength
|
||||
* char hash[hashLength] Build hash, unused
|
||||
* Then tags until the end of the file:
|
||||
* uint32_t nameHash HashDjb2() of the tag name, e.g. "fire2_core"
|
||||
* uint8_t type TagData::Type
|
||||
* uint32_t length
|
||||
* uint8_t data[length]
|
||||
*
|
||||
* Exactly one Signature tag is required, it uses the reserved name hash 0.
|
||||
*/
|
||||
|
||||
uint32_t FWBin::HashDjb2(const std::string& tag) {
|
||||
uint32_t retv = 5381;
|
||||
for(char c : tag)
|
||||
retv = ((retv << 5) + retv) + c;
|
||||
return retv;
|
||||
}
|
||||
|
||||
bool FWBin::load(const std::string& path) {
|
||||
file.open(path, std::ios::binary);
|
||||
if(!file.is_open() || file.fail() || file.eof()) {
|
||||
Log::Error(__func__, "Could not open file at " + path);
|
||||
return false;
|
||||
}
|
||||
// Read out the version string, it is a single byte length followed by a string
|
||||
uint8_t size;
|
||||
file.read((char*)&size, 1);
|
||||
if(file.fail() || file.eof()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, could not read the version length");
|
||||
return false;
|
||||
}
|
||||
std::string unparsedVersion;
|
||||
unparsedVersion.resize(size);
|
||||
file.read(unparsedVersion.data(), size);
|
||||
if(file.fail() || file.eof()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, could not read the version string");
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!version.load(unparsedVersion)) {
|
||||
Log::Error(__func__, "The fw.bin version string is invalid: " + unparsedVersion);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read out the hash string, it is a single byte length followed by a string
|
||||
file.read((char*)&size, 1);
|
||||
if(file.fail() || file.eof()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, could not read the hash length");
|
||||
return false;
|
||||
}
|
||||
|
||||
// The hash string is not used, skip over it
|
||||
file.seekg(size, file.cur);
|
||||
if(file.fail() || file.eof()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, could not read the hash string");
|
||||
return false;
|
||||
}
|
||||
|
||||
while(true) {
|
||||
uint32_t tagHash;
|
||||
file.read((char*)&tagHash, sizeof(uint32_t));
|
||||
if(file.eof()) {
|
||||
break;
|
||||
}
|
||||
if(file.fail()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, could not read a tag name hash");
|
||||
return false;
|
||||
}
|
||||
|
||||
if(tags.count(tagHash)) {
|
||||
// Duplicate tag
|
||||
Log::Error(__func__, "The fw.bin contains a duplicate tag");
|
||||
return false;
|
||||
}
|
||||
TagData& current = tags[tagHash];
|
||||
|
||||
// Read the type field
|
||||
file.read((char*)¤t.type, sizeof(TagData::Type));
|
||||
if(file.fail() || file.eof()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, could not read a tag type");
|
||||
return false;
|
||||
}
|
||||
|
||||
switch(current.type) {
|
||||
case TagData::Type::DataBytes:
|
||||
case TagData::Type::DataLength:
|
||||
case TagData::Type::IEFVersion:
|
||||
if(tagHash == SignatureHash) {
|
||||
Log::Error(__func__, "The fw.bin contains a data tag using the reserved signature name hash");
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case TagData::Type::Signature:
|
||||
if(tagHash != SignatureHash) {
|
||||
Log::Error(__func__, "The fw.bin contains a signature tag with a non-signature name hash");
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
default: // Unknown type
|
||||
Log::Error(__func__, "The fw.bin contains a tag of unknown type " + std::to_string(static_cast<int>(current.type)));
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read the length field
|
||||
file.read((char*)¤t.arrayLength, sizeof(uint32_t));
|
||||
if(file.fail() || file.eof()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, could not read a tag length");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Note the current position so we can jump back to it and read it later
|
||||
current.arrayPosition = file.tellg();
|
||||
file.seekg(current.arrayLength, file.cur);
|
||||
if(file.fail()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, a tag extends past the end of the file");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
file.clear();
|
||||
|
||||
// The signature tag is required to be present, but it is not verified
|
||||
if(tags.count(SignatureHash) == 0) {
|
||||
Log::Error(__func__, "The fw.bin is missing its signature tag");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FWBin::readTag(const std::string& tag, std::vector<uint8_t>& out) const {
|
||||
const auto hash = HashDjb2(tag);
|
||||
if(hash == SignatureHash) {
|
||||
Log::Error(__func__, "The signature tag can not be read as data");
|
||||
return false;
|
||||
}
|
||||
const auto it = tags.find(hash);
|
||||
if(it == tags.end()) {
|
||||
Log::Error(__func__, "The fw.bin does not contain the tag " + tag);
|
||||
return false;
|
||||
}
|
||||
return it->second.read(file, out);
|
||||
}
|
||||
|
||||
bool FWBin::TagData::read(std::ifstream& stream, std::vector<uint8_t>& out) const {
|
||||
stream.clear();
|
||||
stream.seekg(arrayPosition, stream.beg);
|
||||
out.resize(arrayLength);
|
||||
stream.read((char*)out.data(), arrayLength);
|
||||
if(stream.fail()) {
|
||||
Log::Error(__func__, "The fw.bin is truncated, could not read tag data");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FWBin::getFW(const std::string& iefName, std::vector<uint8_t>& fw) const {
|
||||
return readTag(iefName, fw);
|
||||
}
|
||||
|
||||
FWBin::VersionTags FWBin::GetVersionTags(const std::string& iefName) {
|
||||
static const std::unordered_map<std::string, VersionTags> VersionTable = {
|
||||
{"fire2_core", {"fire2_core_version_major", "fire2_core_version_minor"}},
|
||||
{"fire2_core_sg4", {"fire2_core_sg4_version_major", "fire2_core_sg4_version_minor"}},
|
||||
{"RADA2B_SW_bin", {"RADA2B_SW_Version_Major", "RADA2B_SW_Version_Minor"}},
|
||||
{"RADA2B_REVB_SW_bin", {"RADA2B_SW_Version_Major", "RADA2B_SW_Version_Minor"}},
|
||||
{"RADComet_SW_bin", {"RADComet_SW_Version_Major", "RADComet_SW_Version_Minor"}},
|
||||
{"RADComet3_SW_bin", {"RADComet3_SW_Version_Major", "RADComet3_SW_Version_Minor"}},
|
||||
{"RADGalaxy_SG2_SW_bin", {"RADGalaxy_SG2_SW_Version_Major", "RADGalaxy_SG2_SW_Version_Minor"}},
|
||||
{"RADGalaxy_SG2_FFG_SW_bin", {"RADGalaxy_SG2_FFG_SW_Version_Major", "RADGalaxy_SG2_SW_Version_Minor"}},
|
||||
{"RADGalaxy2_SW_bin_p1", {"RADGalaxy2_SW_Version_Major", "RADGalaxy2_SW_Version_Minor"}},
|
||||
{"RADGalaxy2_SW_bin_p2", {"RADGalaxy2_SW_Version_Major", "RADGalaxy2_SW_Version_Minor"}},
|
||||
{"RADGigastar_SW_bin", {"RADGigastar_SW_Version_Major", "RADGigastar_SW_Version_Minor"}},
|
||||
{"RADGigastar_FFG_SW_bin", {"RADGigastar_SW_Version_Major", "RADGigastar_SW_Version_Minor"}},
|
||||
{"RADGigastar_USBz_SW_bin", {"RADGigastar_USBz_SW_Version_Major", "RADGigastar_USBz_SW_Version_Minor"}},
|
||||
{"RADGigastar_USBz_Z7010_SW_bin", {"RADGigastar_USBz_SW_Version_Major", "RADGigastar_USBz_SW_Version_Minor"}},
|
||||
{"RADGigastar_USBz_Z7007s_SW_bin", {"RADGigastar_USBz_SW_Version_Major", "RADGigastar_USBz_SW_Version_Minor"}},
|
||||
{"RADGigastar2_T1S_LIN_SW_bin", {"RADGigastar2_T1S_LIN_SW_Version_Major", "RADGigastar2_T1S_LIN_SW_Version_Minor"}},
|
||||
{"RADGigastar2_T1S_CAN_SW_bin", {"RADGigastar2_T1S_CAN_SW_Version_Major", "RADGigastar2_T1S_CAN_SW_Version_Minor"}},
|
||||
{"RADMoon2_SW_bin", {"RADMoon2_SW_Version_Major", "RADMoon2_SW_Version_Minor"}},
|
||||
{"RADMoon2_Z7010_SW_bin", {"RADMoon2_SW_Version_Major", "RADMoon2_SW_Version_Minor"}},
|
||||
{"RADMoonT1S_SW_bin", {"RADMoonT1S_SW_Version_Major", "RADMoonT1S_SW_Version_Minor"}},
|
||||
{"vcan44_core_ief", {"vcan44_core_version_major", "vcan44_core_version_minor"}}
|
||||
};
|
||||
auto iter = VersionTable.find(iefName);
|
||||
return iter != VersionTable.end() ? iter->second : VersionTags();
|
||||
}
|
||||
|
||||
std::optional<icsneo::DeviceAppVersion> FWBin::getChipVersion(const std::string& iefName) const {
|
||||
auto versionTags = GetVersionTags(iefName);
|
||||
|
||||
if(versionTags) {
|
||||
std::vector<uint8_t> majData;
|
||||
std::vector<uint8_t> minData;
|
||||
|
||||
if(!readTag(versionTags.majorTag, majData)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
if(!readTag(versionTags.minorTag, minData)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
if(majData.size() != 1)
|
||||
return std::nullopt;
|
||||
|
||||
if(minData.size() != 1)
|
||||
return std::nullopt;
|
||||
|
||||
icsneo::DeviceAppVersion chipVersion;
|
||||
chipVersion.major = majData[0];
|
||||
chipVersion.minor = minData[0];
|
||||
return chipVersion;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> buf;
|
||||
|
||||
if(!readTag(iefName, buf)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
IEF ief;
|
||||
|
||||
if(!ief.load(std::move(buf))) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
icsneo::DeviceAppVersion chipVersion;
|
||||
chipVersion.major = ief.getVersion().appMajor;
|
||||
chipVersion.minor = ief.getVersion().appMinor;
|
||||
return chipVersion;
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,142 @@
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwbundle.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwbin.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
#include "icsneo/core/crc32.h"
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
/**
|
||||
* Firmware bundle file format (all integers little-endian):
|
||||
*
|
||||
* FWBundleHeader
|
||||
* Then chips until the end of the file:
|
||||
* FWBundleChip
|
||||
* uint8_t data[FWBundleChip::length]
|
||||
*
|
||||
* The CRC32 covers the whole file with the crc field set to zero.
|
||||
*/
|
||||
#pragma pack(push, 1)
|
||||
struct FWBundleHeader {
|
||||
char magic[2]; // "FW"
|
||||
uint16_t fmtVersion;
|
||||
uint32_t crc;
|
||||
uint8_t build;
|
||||
uint8_t maintenance;
|
||||
uint8_t minor;
|
||||
uint8_t major;
|
||||
uint8_t type; // Build type, unused
|
||||
};
|
||||
|
||||
struct FWBundleChip {
|
||||
uint32_t hash; // FWBin::HashDjb2() of the chip's IEF name
|
||||
uint8_t build;
|
||||
uint8_t maintenance;
|
||||
uint8_t minor;
|
||||
uint8_t major;
|
||||
uint32_t length;
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
bool FWBundle::IsFWBundle(const std::string& path) {
|
||||
std::ifstream file(path, std::ios::binary);
|
||||
if(!file.is_open())
|
||||
return false;
|
||||
// Only check the magic, so a truncated bundle is still reported as a bundle error by load()
|
||||
char magic[sizeof(FWBundleHeader::magic)];
|
||||
file.read(magic, sizeof(magic));
|
||||
if(file.fail())
|
||||
return false;
|
||||
return magic[0] == 'F' && magic[1] == 'W';
|
||||
}
|
||||
|
||||
bool FWBundle::load(const std::string& path) {
|
||||
std::ifstream file(path, std::ios::binary);
|
||||
if(!file.is_open()) {
|
||||
Log::Error(__func__, "Could not open file at " + path);
|
||||
return false;
|
||||
}
|
||||
std::vector<uint8_t> bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
|
||||
if(file.bad()) {
|
||||
Log::Error(__func__, "Could not read file at " + path);
|
||||
return false;
|
||||
}
|
||||
|
||||
if(bytes.size() < sizeof(FWBundleHeader) || bytes.size() > std::numeric_limits<uint32_t>::max()) {
|
||||
Log::Error(__func__, "The firmware bundle is smaller than its header or larger than 4 GiB");
|
||||
return false;
|
||||
}
|
||||
|
||||
FWBundleHeader header;
|
||||
std::memcpy(&header, bytes.data(), sizeof(header));
|
||||
if(header.magic[0] != 'F' || header.magic[1] != 'W') {
|
||||
Log::Error(__func__, "The file is not a firmware bundle, bad magic");
|
||||
return false;
|
||||
}
|
||||
|
||||
// The CRC is computed with the CRC field zeroed
|
||||
std::memset(bytes.data() + offsetof(FWBundleHeader, crc), 0, sizeof(header.crc));
|
||||
if(icsneo::crc32(0, bytes.data(), static_cast<uint32_t>(bytes.size())) != header.crc) {
|
||||
Log::Error(__func__, "The firmware bundle failed CRC validation");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::unordered_map<uint32_t, ChipBinary> parsed;
|
||||
size_t offset = sizeof(FWBundleHeader);
|
||||
while(offset < bytes.size()) {
|
||||
if(bytes.size() - offset < sizeof(FWBundleChip)) {
|
||||
Log::Error(__func__, "The firmware bundle is truncated, could not read a chip header");
|
||||
return false;
|
||||
}
|
||||
FWBundleChip chip;
|
||||
std::memcpy(&chip, bytes.data() + offset, sizeof(chip));
|
||||
offset += sizeof(FWBundleChip);
|
||||
|
||||
if(bytes.size() - offset < chip.length) {
|
||||
Log::Error(__func__, "The firmware bundle is truncated, a chip binary extends past the end of the file");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto& bin = parsed[chip.hash];
|
||||
bin.data.assign(bytes.begin() + offset, bytes.begin() + offset + chip.length);
|
||||
bin.version.major = chip.major;
|
||||
bin.version.minor = chip.minor;
|
||||
bin.version.release = chip.maintenance;
|
||||
bin.version.build = chip.build;
|
||||
offset += chip.length;
|
||||
}
|
||||
|
||||
version.major = header.major;
|
||||
version.minor = header.minor;
|
||||
version.release = header.maintenance;
|
||||
version.build = header.build;
|
||||
binaries = std::move(parsed);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FWBundle::getFW(const std::string& iefName, std::vector<uint8_t>& fw) const {
|
||||
const auto it = binaries.find(FWBin::HashDjb2(iefName));
|
||||
if(it == binaries.end()) {
|
||||
Log::Error(__func__, "The chip binary could not be found");
|
||||
return false;
|
||||
}
|
||||
fw = it->second.data;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<icsneo::DeviceAppVersion> FWBundle::getChipVersion(const std::string& iefName) const {
|
||||
const auto it = binaries.find(FWBin::HashDjb2(iefName));
|
||||
if(it == binaries.end())
|
||||
return std::nullopt;
|
||||
return icsneo::DeviceAppVersion(it->second.version.major, it->second.version.minor);
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,25 @@
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwloader.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwbin.h"
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwbundle.h"
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
std::unique_ptr<FWRepo> FWLoader::Load(const std::string& path) {
|
||||
if(FWBundle::IsFWBundle(path)) {
|
||||
auto bundle = std::make_unique<FWBundle>();
|
||||
if(!bundle->load(path))
|
||||
return nullptr;
|
||||
return bundle;
|
||||
}
|
||||
|
||||
auto bin = std::make_unique<FWBin>();
|
||||
if(!bin->load(path))
|
||||
return nullptr;
|
||||
return bin;
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "icsneo/device/extensions/bootloader/parser/fwzip.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <miniz.h>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
class ZipHandle {
|
||||
public:
|
||||
ZipHandle() {
|
||||
mz_zip_zero_struct(&handle);
|
||||
}
|
||||
~ZipHandle() {
|
||||
mz_zip_reader_end(&handle);
|
||||
}
|
||||
|
||||
operator mz_zip_archive*() {
|
||||
return &handle;
|
||||
}
|
||||
|
||||
private:
|
||||
mz_zip_archive handle;
|
||||
};
|
||||
|
||||
// A zip firmware image holds a single entry, the raw binary to send to the device
|
||||
FWZip::FWZip(std::vector<uint8_t>&& tagData)
|
||||
: handle(std::make_unique<ZipHandle>()), zipData(std::move(tagData)) {
|
||||
|
||||
if(!mz_zip_reader_init_mem(*handle, zipData.data(), zipData.size(), 0)) {
|
||||
Log::Error(__func__, "The firmware zip could not be opened");
|
||||
return;
|
||||
}
|
||||
|
||||
mz_zip_archive_file_stat file;
|
||||
if(!mz_zip_reader_file_stat(*handle, 0, &file)) {
|
||||
Log::Error(__func__, "The firmware zip is empty or its first entry could not be read");
|
||||
} else {
|
||||
uncompressedSize = static_cast<size_t>(file.m_uncomp_size);
|
||||
}
|
||||
}
|
||||
|
||||
FWZip::~FWZip() = default;
|
||||
|
||||
bool FWZip::readAll(uint8_t* out) {
|
||||
if(!uncompressedSize) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!out) {
|
||||
Log::Error(__func__, "No output buffer for the firmware zip");
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!mz_zip_reader_extract_to_mem(*handle, 0, out, *uncompressedSize, 0)) {
|
||||
Log::Error(__func__, "The firmware zip could not be decompressed");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FWZip::readAll(std::vector<uint8_t>& out) {
|
||||
if(!uncompressedSize) {
|
||||
return false;
|
||||
}
|
||||
out = std::vector<uint8_t>(*uncompressedSize, 0);
|
||||
return readAll(out.data());
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,74 @@
|
||||
#include "icsneo/device/extensions/bootloader/parser/ief.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
/**
|
||||
* IEF file format (all integers little-endian):
|
||||
*
|
||||
* uint8_t magic 0xAA
|
||||
* Version version
|
||||
* uint8_t configLength
|
||||
* uint8_t config[configLength] Unused
|
||||
* Then sectors until the end of the file:
|
||||
* uint8_t magic 0xAA
|
||||
* uint32_t index Sector index, see the communication for how this maps to an address
|
||||
* uint32_t length
|
||||
* uint8_t data[length]
|
||||
*/
|
||||
bool IEF::load(std::vector<uint8_t>&& bytes) {
|
||||
static constexpr uint8_t Magic = 0xAA;
|
||||
// Magic, version, config byte count
|
||||
static constexpr size_t FixedHeaderSize = 1 + sizeof(Version) + 1;
|
||||
// Magic, index, size
|
||||
static constexpr size_t SectorHeaderSize = 1 + sizeof(uint32_t) + sizeof(uint32_t);
|
||||
|
||||
data = std::move(bytes);
|
||||
sectors.clear();
|
||||
if(data.size() < FixedHeaderSize) {
|
||||
Log::Error(__func__, "IEF too short");
|
||||
return false;
|
||||
}
|
||||
|
||||
if(data.front() != Magic) {
|
||||
Log::Error(__func__, "Invalid IEF magic");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::memcpy(&version, data.data() + 1, sizeof(Version));
|
||||
|
||||
const size_t headerSize = FixedHeaderSize + data[FixedHeaderSize - 1];
|
||||
if(data.size() <= headerSize) {
|
||||
Log::Error(__func__, "Invalid IEF config bytes");
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t offset = headerSize;
|
||||
while(data.size() - offset >= SectorHeaderSize) {
|
||||
if(data[offset] != Magic) {
|
||||
Log::Error(__func__, "Invalid IEF sector magic");
|
||||
return false;
|
||||
}
|
||||
uint32_t index;
|
||||
uint32_t size;
|
||||
std::memcpy(&index, data.data() + offset + 1, sizeof(index));
|
||||
std::memcpy(&size, data.data() + offset + 1 + sizeof(index), sizeof(size));
|
||||
offset += SectorHeaderSize;
|
||||
if(data.size() - offset < size) {
|
||||
Log::Error(__func__, "Invalid IEF sector");
|
||||
return false;
|
||||
}
|
||||
|
||||
sectors.emplace_back(index, BytesView(data.data() + offset, size));
|
||||
offset += size;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,57 @@
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
namespace Log {
|
||||
|
||||
// Set ICS_BOOTLOADER_LOG_LEVEL to 1 (error) through 5 (trace) to enable logging to stderr
|
||||
static int GetLogLevel() {
|
||||
static const int level = [] {
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable: 4996) // getenv
|
||||
#endif
|
||||
const char* env = std::getenv("ICS_BOOTLOADER_LOG_LEVEL");
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
return env ? std::atoi(env) : 0;
|
||||
}();
|
||||
return level;
|
||||
}
|
||||
|
||||
static void Write(int level, const char* prefix, const std::string& subject, const std::string& msg) {
|
||||
if(GetLogLevel() >= level)
|
||||
std::cerr << prefix << subject << " - " << msg << std::endl;
|
||||
}
|
||||
|
||||
void Trace(const std::string& subject, const std::string& msg) {
|
||||
Write(5, "[TRACE] ", subject, msg);
|
||||
}
|
||||
|
||||
void Debug(const std::string& subject, const std::string& msg) {
|
||||
Write(4, "[DEBUG] ", subject, msg);
|
||||
}
|
||||
|
||||
void Info(const std::string& subject, const std::string& msg) {
|
||||
Write(3, "[INFO] ", subject, msg);
|
||||
}
|
||||
|
||||
void Warning(const std::string& subject, const std::string& msg) {
|
||||
Write(2, "[WARN] ", subject, msg);
|
||||
}
|
||||
|
||||
void Error(const std::string& subject, const std::string& msg) {
|
||||
Write(1, "[ERROR] ", subject, msg);
|
||||
}
|
||||
|
||||
} // namespace Log
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
@@ -0,0 +1,50 @@
|
||||
#include "icsneo/device/extensions/bootloader/version.h"
|
||||
#include "icsneo/device/extensions/bootloader/platform/logging.h"
|
||||
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <regex>
|
||||
|
||||
namespace icsneo {
|
||||
|
||||
namespace Bootloader {
|
||||
|
||||
bool FirmwareSourceVersion::load(const std::string& toParse) {
|
||||
static const std::regex VersionRegex{"(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)"};
|
||||
std::smatch match;
|
||||
if(!std::regex_match(toParse, match, VersionRegex)) {
|
||||
Log::Error(__func__, "Failed to parse version");
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto parse = [](const std::string& input) -> std::optional<ValueType> {
|
||||
// The regex guarantees only digits, limit the length so stoul can not overflow
|
||||
if(input.size() > 3) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto value = std::stoul(input);
|
||||
if(value > std::numeric_limits<ValueType>::max()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<ValueType>(value);
|
||||
};
|
||||
|
||||
const auto parsedMajor = parse(match[1]);
|
||||
const auto parsedMinor = parse(match[2]);
|
||||
const auto parsedRelease = parse(match[3]);
|
||||
const auto parsedBuild = parse(match[4]);
|
||||
if(!parsedMajor || !parsedMinor || !parsedRelease || !parsedBuild) {
|
||||
Log::Error(__func__, "Invalid sized version number");
|
||||
return false;
|
||||
}
|
||||
|
||||
major = *parsedMajor;
|
||||
minor = *parsedMinor;
|
||||
release = *parsedRelease;
|
||||
build = *parsedBuild;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Bootloader
|
||||
|
||||
} // namespace icsneo
|
||||
+345
-18
@@ -1,9 +1,16 @@
|
||||
#include "icsneo/device/device.h"
|
||||
#include "icsneo/device/idevicesettings.h"
|
||||
#include "icsneo/communication/message/filter/main51messagefilter.h"
|
||||
#include <cstring>
|
||||
|
||||
using namespace icsneo;
|
||||
|
||||
IDeviceSettings::IDeviceSettings(Device* device, size_t size)
|
||||
: device(device), report(device->report), structSize(size) {}
|
||||
|
||||
IDeviceSettings::IDeviceSettings(warn_t createInoperableSettings, Device* device)
|
||||
: disabled(true), readonly(true), report(device->report), structSize(0) { (void)createInoperableSettings; }
|
||||
|
||||
std::optional<uint16_t> IDeviceSettings::CalculateGSChecksum(const std::vector<uint8_t>& settings) {
|
||||
const uint16_t* p = reinterpret_cast<const uint16_t*>(settings.data());
|
||||
size_t words = settings.size();
|
||||
@@ -166,7 +173,7 @@ bool IDeviceSettings::refresh() {
|
||||
}
|
||||
|
||||
std::vector<uint8_t> rxSettings;
|
||||
bool ret = com->getSettingsSync(rxSettings);
|
||||
bool ret = device->com->getSettingsSync(rxSettings);
|
||||
if(!ret) {
|
||||
report(APIEvent::Type::SettingsReadError, APIEvent::Severity::Error);
|
||||
return false;
|
||||
@@ -231,10 +238,10 @@ bool IDeviceSettings::apply(bool temporary) {
|
||||
memcpy(bytestream.data() + 7, getMutableRawStructurePointer(), settings.size());
|
||||
|
||||
// Pause I/O with the device while the settings are applied
|
||||
applyingSettings = true;
|
||||
device->stopHeartbeat();
|
||||
|
||||
std::shared_ptr<Main51Message> msg = std::dynamic_pointer_cast<Main51Message>(com->waitForMessageSync([this, &bytestream]() {
|
||||
return com->sendCommand(Command::SetSettings, bytestream);
|
||||
std::shared_ptr<Main51Message> msg = std::dynamic_pointer_cast<Main51Message>(device->com->waitForMessageSync([this, &bytestream]() {
|
||||
return device->com->sendCommand(Command::SetSettings, bytestream);
|
||||
}, std::make_shared<Main51MessageFilter>(Command::SetSettings), std::chrono::milliseconds(5000)));
|
||||
|
||||
if(!msg || msg->data[0] != 1) { // We did not receive a response
|
||||
@@ -259,8 +266,8 @@ bool IDeviceSettings::apply(bool temporary) {
|
||||
bytestream[6] = (uint8_t)(*gsChecksum >> 8);
|
||||
memcpy(bytestream.data() + 7, getMutableRawStructurePointer(), settings.size());
|
||||
|
||||
msg = std::dynamic_pointer_cast<Main51Message>(com->waitForMessageSync([this, &bytestream]() {
|
||||
return com->sendCommand(Command::SetSettings, bytestream);
|
||||
msg = std::dynamic_pointer_cast<Main51Message>(device->com->waitForMessageSync([this, &bytestream]() {
|
||||
return device->com->sendCommand(Command::SetSettings, bytestream);
|
||||
}, std::make_shared<Main51MessageFilter>(Command::SetSettings), std::chrono::milliseconds(5000)));
|
||||
if(!msg || msg->data[0] != 1) {
|
||||
// Attempt to get the settings from the device so we're up to date if possible
|
||||
@@ -272,12 +279,12 @@ bool IDeviceSettings::apply(bool temporary) {
|
||||
}
|
||||
|
||||
if(!temporary) {
|
||||
msg = std::dynamic_pointer_cast<Main51Message>(com->waitForMessageSync([this]() {
|
||||
return com->sendCommand(Command::SaveSettings);
|
||||
msg = std::dynamic_pointer_cast<Main51Message>(device->com->waitForMessageSync([this]() {
|
||||
return device->com->sendCommand(Command::SaveSettings);
|
||||
}, std::make_shared<Main51MessageFilter>(Command::SaveSettings), std::chrono::milliseconds(5000)));
|
||||
}
|
||||
|
||||
applyingSettings = false;
|
||||
device->startHeartbeat();
|
||||
|
||||
refresh(); // Refresh our buffer with what the device has, whether we were successful or not
|
||||
|
||||
@@ -299,10 +306,10 @@ bool IDeviceSettings::applyDefaults(bool temporary) {
|
||||
return false;
|
||||
}
|
||||
|
||||
applyingSettings = true;
|
||||
device->stopHeartbeat();
|
||||
|
||||
std::shared_ptr<Main51Message> msg = std::dynamic_pointer_cast<Main51Message>(com->waitForMessageSync([this]() {
|
||||
return com->sendCommand(Command::SetDefaultSettings);
|
||||
std::shared_ptr<Main51Message> msg = std::dynamic_pointer_cast<Main51Message>(device->com->waitForMessageSync([this]() {
|
||||
return device->com->sendCommand(Command::SetDefaultSettings);
|
||||
}, std::make_shared<Main51MessageFilter>(Command::SetDefaultSettings), std::chrono::milliseconds(5000)));
|
||||
if(!msg || msg->data[0] != 1) {
|
||||
// Attempt to get the settings from the device so we're up to date if possible
|
||||
@@ -336,8 +343,8 @@ bool IDeviceSettings::applyDefaults(bool temporary) {
|
||||
bytestream[6] = (uint8_t)(*gsChecksum >> 8);
|
||||
memcpy(bytestream.data() + 7, getMutableRawStructurePointer(), settings.size());
|
||||
|
||||
msg = std::dynamic_pointer_cast<Main51Message>(com->waitForMessageSync([this, &bytestream]() {
|
||||
return com->sendCommand(Command::SetSettings, bytestream);
|
||||
msg = std::dynamic_pointer_cast<Main51Message>(device->com->waitForMessageSync([this, &bytestream]() {
|
||||
return device->com->sendCommand(Command::SetSettings, bytestream);
|
||||
}, std::make_shared<Main51MessageFilter>(Command::SetSettings), std::chrono::milliseconds(5000)));
|
||||
if(!msg || msg->data[0] != 1) {
|
||||
// Attempt to get the settings from the device so we're up to date if possible
|
||||
@@ -349,12 +356,12 @@ bool IDeviceSettings::applyDefaults(bool temporary) {
|
||||
}
|
||||
|
||||
if(!temporary) {
|
||||
msg = std::dynamic_pointer_cast<Main51Message>(com->waitForMessageSync([this]() {
|
||||
return com->sendCommand(Command::SaveSettings);
|
||||
msg = std::dynamic_pointer_cast<Main51Message>(device->com->waitForMessageSync([this]() {
|
||||
return device->com->sendCommand(Command::SaveSettings);
|
||||
}, std::make_shared<Main51MessageFilter>(Command::SaveSettings), std::chrono::milliseconds(5000)));
|
||||
}
|
||||
|
||||
applyingSettings = false;
|
||||
device->startHeartbeat();
|
||||
|
||||
refresh(); // Refresh our buffer with what the device has, whether we were successful or not
|
||||
|
||||
@@ -959,4 +966,324 @@ bool IDeviceSettings::setMiscIOAnalogOutput(uint8_t pin, MiscIOAnalogVoltage vol
|
||||
(void)voltage;
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::optional<RADGPTPProfile> IDeviceSettings::getGPTPProfile() const {
|
||||
const auto* gptp = getGPTPSettings();
|
||||
if(!gptp) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<RADGPTPProfile>(gptp->profile);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setGPTPProfile(RADGPTPProfile profile) {
|
||||
auto* gptp = getMutableGPTPSettings();
|
||||
if(!gptp) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return false;
|
||||
}
|
||||
gptp->profile = static_cast<uint8_t>(profile);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<RADGPTPRole> IDeviceSettings::getGPTPRole() const {
|
||||
const auto* gptp = getGPTPSettings();
|
||||
if(!gptp) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<RADGPTPRole>(gptp->gptpPortRole);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setGPTPRole(RADGPTPRole role) {
|
||||
auto* gptp = getMutableGPTPSettings();
|
||||
if(!gptp) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return false;
|
||||
}
|
||||
gptp->gptpPortRole = static_cast<uint8_t>(role);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getGPTPEnabledPort() const {
|
||||
const auto* gptp = getGPTPSettings();
|
||||
if(!gptp) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return std::nullopt;
|
||||
}
|
||||
return gptp->gptpEnabledPort;
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setGPTPEnabledPort(uint8_t port) {
|
||||
auto* gptp = getMutableGPTPSettings();
|
||||
if(!gptp) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return false;
|
||||
}
|
||||
gptp->gptpEnabledPort = port;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<bool> IDeviceSettings::isGPTPClockSyntonizationEnabled() const {
|
||||
const auto* gptp = getGPTPSettings();
|
||||
if(!gptp) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return std::nullopt;
|
||||
}
|
||||
return gptp->enableClockSyntonization != 0;
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setGPTPClockSyntonizationEnabled(bool enable) {
|
||||
auto* gptp = getMutableGPTPSettings();
|
||||
if(!gptp) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return false;
|
||||
}
|
||||
gptp->enableClockSyntonization = enable ? 1 : 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<bool> IDeviceSettings::getLinuxBootEnabled() {
|
||||
const auto* os = getLinuxSettings();
|
||||
if(os == nullptr) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return std::nullopt;
|
||||
}
|
||||
return os->allowBoot != 0;
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setLinuxBootEnabled(bool enabled) {
|
||||
auto os = getMutableLinuxSettings();
|
||||
if(!os) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
(*os)->allowBoot = enabled ? 1 : 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<bool> IDeviceSettings::getExternalWifiAntennaEnabled() {
|
||||
const auto* os = getLinuxSettings();
|
||||
if(os == nullptr) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return std::nullopt;
|
||||
}
|
||||
return os->useExternalWifiAntenna != 0;
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setExternalWifiAntennaEnabled(bool enabled) {
|
||||
auto os = getMutableLinuxSettings();
|
||||
if(!os) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
(*os)->useExternalWifiAntenna = enabled ? 1 : 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<LinuxConfigurationPort> IDeviceSettings::getLinuxConfigurationPort() {
|
||||
const auto* os = getLinuxSettings();
|
||||
if(os == nullptr) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
return std::nullopt;
|
||||
}
|
||||
switch(static_cast<LinuxConfigurationPort>(os->ethConfigurationPort)) {
|
||||
case LinuxConfigurationPort::ETH01:
|
||||
return LinuxConfigurationPort::ETH01;
|
||||
case LinuxConfigurationPort::USB:
|
||||
default: // Any other value means the configuration interface is over USB
|
||||
return LinuxConfigurationPort::USB;
|
||||
}
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setLinuxConfigurationPort(LinuxConfigurationPort port) {
|
||||
switch(port) {
|
||||
case LinuxConfigurationPort::USB:
|
||||
case LinuxConfigurationPort::ETH01:
|
||||
break;
|
||||
default:
|
||||
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
auto os = getMutableLinuxSettings();
|
||||
if(!os) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
(*os)->ethConfigurationPort = static_cast<uint8_t>(port);
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
void reportT1SUnavailable(const icsneo::device_eventhandler_t& report) {
|
||||
report(APIEvent::Type::SettingNotAvaiableDevice, APIEvent::Severity::EventWarning);
|
||||
}
|
||||
|
||||
std::optional<bool> t1sFlag(const ETHERNET10T1S_SETTINGS* t1s, uint8_t flag, const icsneo::device_eventhandler_t& report) {
|
||||
if(t1s == nullptr) {
|
||||
reportT1SUnavailable(report);
|
||||
return std::nullopt;
|
||||
}
|
||||
return (t1s->flags & flag) != 0;
|
||||
}
|
||||
|
||||
bool setT1SFlag(ETHERNET10T1S_SETTINGS* t1s, uint8_t flag, bool enable, const icsneo::device_eventhandler_t& report) {
|
||||
if(t1s == nullptr) {
|
||||
reportT1SUnavailable(report);
|
||||
return false;
|
||||
}
|
||||
if(enable)
|
||||
t1s->flags |= flag;
|
||||
else
|
||||
t1s->flags = static_cast<uint8_t>(t1s->flags & ~flag);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<uint8_t> t1sByte(const uint8_t* field, const icsneo::device_eventhandler_t& report) {
|
||||
if(field == nullptr) {
|
||||
reportT1SUnavailable(report);
|
||||
return std::nullopt;
|
||||
}
|
||||
return *field;
|
||||
}
|
||||
|
||||
bool setT1SByte(uint8_t* field, uint8_t value, const icsneo::device_eventhandler_t& report) {
|
||||
if(field == nullptr) {
|
||||
reportT1SUnavailable(report);
|
||||
return false;
|
||||
}
|
||||
*field = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<bool> IDeviceSettings::isT1SPLCAEnabledFor(Network net) const {
|
||||
return t1sFlag(getT1SSettingsFor(net), ETHERNET10T1S_SETTINGS_FLAG_ENABLE_PLCA, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SPLCAFor(Network net, bool enable) {
|
||||
return setT1SFlag(getMutableT1SSettingsFor(net), ETHERNET10T1S_SETTINGS_FLAG_ENABLE_PLCA, enable, report);
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getT1SLocalIDFor(Network net) const {
|
||||
const auto* t1s = getT1SSettingsFor(net);
|
||||
return t1sByte(t1s == nullptr ? nullptr : &t1s->local_id, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SLocalIDFor(Network net, uint8_t id) {
|
||||
auto* t1s = getMutableT1SSettingsFor(net);
|
||||
return setT1SByte(t1s == nullptr ? nullptr : &t1s->local_id, id, report);
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getT1SMaxNodesFor(Network net) const {
|
||||
const auto* t1s = getT1SSettingsFor(net);
|
||||
return t1sByte(t1s == nullptr ? nullptr : &t1s->max_num_nodes, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SMaxNodesFor(Network net, uint8_t nodes) {
|
||||
auto* t1s = getMutableT1SSettingsFor(net);
|
||||
return setT1SByte(t1s == nullptr ? nullptr : &t1s->max_num_nodes, nodes, report);
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getT1STxOppTimerFor(Network net) const {
|
||||
const auto* t1s = getT1SSettingsFor(net);
|
||||
return t1sByte(t1s == nullptr ? nullptr : &t1s->to_timer, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1STxOppTimerFor(Network net, uint8_t timer) {
|
||||
auto* t1s = getMutableT1SSettingsFor(net);
|
||||
return setT1SByte(t1s == nullptr ? nullptr : &t1s->to_timer, timer, report);
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getT1SMaxBurstFor(Network net) const {
|
||||
const auto* t1s = getT1SSettingsFor(net);
|
||||
return t1sByte(t1s == nullptr ? nullptr : &t1s->max_burst_count, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SMaxBurstFor(Network net, uint8_t burst) {
|
||||
auto* t1s = getMutableT1SSettingsFor(net);
|
||||
return setT1SByte(t1s == nullptr ? nullptr : &t1s->max_burst_count, burst, report);
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getT1SBurstTimerFor(Network net) const {
|
||||
const auto* t1s = getT1SSettingsFor(net);
|
||||
return t1sByte(t1s == nullptr ? nullptr : &t1s->burst_timer, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SBurstTimerFor(Network net, uint8_t timer) {
|
||||
auto* t1s = getMutableT1SSettingsFor(net);
|
||||
return setT1SByte(t1s == nullptr ? nullptr : &t1s->burst_timer, timer, report);
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getT1SLocalIDAlternateFor(Network net) const {
|
||||
const auto* t1s = getT1SSettingsFor(net);
|
||||
return t1sByte(t1s == nullptr ? nullptr : &t1s->local_id_alternate, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SLocalIDAlternateFor(Network net, uint8_t id) {
|
||||
auto* t1s = getMutableT1SSettingsFor(net);
|
||||
return setT1SByte(t1s == nullptr ? nullptr : &t1s->local_id_alternate, id, report);
|
||||
}
|
||||
|
||||
std::optional<bool> IDeviceSettings::isT1STerminationEnabledFor(Network net) const {
|
||||
return t1sFlag(getT1SSettingsFor(net), ETHERNET10T1S_SETTINGS_FLAG_TERMINATION, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1STerminationFor(Network net, bool enable) {
|
||||
return setT1SFlag(getMutableT1SSettingsFor(net), ETHERNET10T1S_SETTINGS_FLAG_TERMINATION, enable, report);
|
||||
}
|
||||
|
||||
std::optional<bool> IDeviceSettings::isT1SBusDecodingBeaconsEnabledFor(Network net) const {
|
||||
return t1sFlag(getT1SSettingsFor(net), ETHERNET10T1S_SETTINGS_FLAG_BUS_DECODING_BEACONS, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SBusDecodingBeaconsFor(Network net, bool enable) {
|
||||
return setT1SFlag(getMutableT1SSettingsFor(net), ETHERNET10T1S_SETTINGS_FLAG_BUS_DECODING_BEACONS, enable, report);
|
||||
}
|
||||
|
||||
std::optional<bool> IDeviceSettings::isT1SBusDecodingAllEnabledFor(Network net) const {
|
||||
return t1sFlag(getT1SSettingsFor(net), ETHERNET10T1S_SETTINGS_FLAG_BUS_DECODING_ALL, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SBusDecodingAllFor(Network net, bool enable) {
|
||||
return setT1SFlag(getMutableT1SSettingsFor(net), ETHERNET10T1S_SETTINGS_FLAG_BUS_DECODING_ALL, enable, report);
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getT1SMultiIDEnableMaskFor(Network net) const {
|
||||
const auto* ext = getT1SSettingsExtFor(net);
|
||||
return t1sByte(ext == nullptr ? nullptr : &ext->enable_multi_id, report);
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SMultiIDEnableMaskFor(Network net, uint8_t mask) {
|
||||
auto* ext = getMutableT1SSettingsExtFor(net);
|
||||
return setT1SByte(ext == nullptr ? nullptr : &ext->enable_multi_id, mask, report);
|
||||
}
|
||||
|
||||
std::optional<uint8_t> IDeviceSettings::getT1SMultiIDFor(Network net, uint8_t index) const {
|
||||
const auto* ext = getT1SSettingsExtFor(net);
|
||||
if(ext == nullptr) {
|
||||
reportT1SUnavailable(report);
|
||||
return std::nullopt;
|
||||
}
|
||||
if(index >= sizeof(ext->multi_id)) {
|
||||
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
|
||||
return std::nullopt;
|
||||
}
|
||||
return ext->multi_id[index];
|
||||
}
|
||||
|
||||
bool IDeviceSettings::setT1SMultiIDFor(Network net, uint8_t index, uint8_t id) {
|
||||
auto* ext = getMutableT1SSettingsExtFor(net);
|
||||
if(ext == nullptr) {
|
||||
reportT1SUnavailable(report);
|
||||
return false;
|
||||
}
|
||||
if(index >= sizeof(ext->multi_id)) {
|
||||
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
|
||||
return false;
|
||||
}
|
||||
ext->multi_id[index] = id;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,14 @@ Simple
|
||||
.. literalinclude:: ../../examples/c2/simple/src/main.c
|
||||
:language: c
|
||||
|
||||
Supported Devices
|
||||
=================
|
||||
|
||||
:download:`Download example <../../examples/c2/supported_devices/src/main.c>`
|
||||
|
||||
.. literalinclude:: ../../examples/c2/supported_devices/src/main.c
|
||||
:language: c
|
||||
|
||||
Disk Format
|
||||
===========
|
||||
|
||||
@@ -66,6 +74,14 @@ Ethernet Receive
|
||||
.. literalinclude:: ../../examples/c2/ethernet_receive/src/main.c
|
||||
:language: c
|
||||
|
||||
Ethernet Status
|
||||
===============
|
||||
|
||||
:download:`Download example <../../examples/c2/ethernet_status/src/main.c>`
|
||||
|
||||
.. literalinclude:: ../../examples/c2/ethernet_status/src/main.c
|
||||
:language: c
|
||||
|
||||
T1S Loopback
|
||||
============
|
||||
|
||||
@@ -82,3 +98,27 @@ TC10
|
||||
.. literalinclude:: ../../examples/c2/tc10/src/main.c
|
||||
:language: c
|
||||
|
||||
gPTP
|
||||
====
|
||||
|
||||
:download:`Download example <../../examples/c2/gptp/src/main.c>`
|
||||
|
||||
.. literalinclude:: ../../examples/c2/gptp/src/main.c
|
||||
:language: c
|
||||
|
||||
PerfTest
|
||||
========
|
||||
|
||||
:download:`Download example <../../examples/c2/perf_test/src/main.c>`
|
||||
|
||||
.. literalinclude:: ../../examples/c2/perf_test/src/main.c
|
||||
:language: c
|
||||
|
||||
Termination Groups
|
||||
==================
|
||||
|
||||
:download:`Download example <../../examples/c2/termination/src/main.c>`
|
||||
|
||||
.. literalinclude:: ../../examples/c2/termination/src/main.c
|
||||
:language: c
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ Dependencies
|
||||
The minimum requirements to build libicsneo are:
|
||||
- CMake version 3.12 or newer
|
||||
- A C++17 compiler
|
||||
- libpcap on Linux and macOS
|
||||
|
||||
|
||||
Building library & examples
|
||||
@@ -30,10 +29,3 @@ libicsneo supports being added as a sub-projects with CMake's
|
||||
#. Clone libicsneo into the desired location within the project
|
||||
#. Add ``add_subdirectory(path/to/libicsneo)`` to ``CMakeLists.txt``
|
||||
#. Link the project to libicsneo with ``target_link_libraries(app icsneocpp)``
|
||||
|
||||
Linux udev Rules
|
||||
================
|
||||
|
||||
Linux users may want to install the included udev rules to run libicsneo based
|
||||
applications without root, this can be done with:
|
||||
``cp 99-intrepidcs.rules /etc/udev/rules.d/``
|
||||
|
||||
@@ -107,3 +107,25 @@ Analog Output Control
|
||||
|
||||
.. literalinclude:: ../../examples/python/analog_out/analog_out_basic.py
|
||||
:language: python
|
||||
|
||||
ISO-TP CAN1 Loopback
|
||||
====================
|
||||
|
||||
Two devices, CAN1 wired together. ``--raw`` checks the cable, ``--sf`` sends one
|
||||
firmware single frame, ``--both`` sends a segmented payload with firmware flow control.
|
||||
|
||||
:download:`Download example <../../examples/python/iso15765/iso15765_loopback.py>`
|
||||
|
||||
.. literalinclude:: ../../examples/python/iso15765/iso15765_loopback.py
|
||||
:language: python
|
||||
|
||||
Firmware Update
|
||||
===============
|
||||
|
||||
Updates the first device found from a ``fw.bin`` or firmware bundle, see
|
||||
:doc:`firmware_update`.
|
||||
|
||||
:download:`Download example <../../examples/python/bootloader/update.py>`
|
||||
|
||||
.. literalinclude:: ../../examples/python/bootloader/update.py
|
||||
:language: python
|
||||
|
||||
@@ -25,14 +25,3 @@ To upgrade an existing installation:
|
||||
.. code-block:: bash
|
||||
|
||||
pip install --pre --upgrade icsneopy
|
||||
|
||||
Linux udev Rules
|
||||
================
|
||||
|
||||
Linux users may want to install the included udev rules to run icsneopy-based
|
||||
applications without root. The rules file can be found in the libicsneo source
|
||||
repository at https://github.com/intrepidcs/libicsneo/.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
sudo cp 99-intrepidcs.rules /etc/udev/rules.d/
|
||||
|
||||
@@ -15,17 +15,3 @@ communication library. The source code for libicsneo can be found on GitHub:
|
||||
icsneoc/index
|
||||
icsneoc2/index
|
||||
|
||||
Linux Installation
|
||||
==================
|
||||
|
||||
Applications that use raw Ethernet device discovery, such as PCAP-backed
|
||||
discovery, need permission to open raw network sockets. Instead of running your
|
||||
application with ``sudo``, grant the installed executable the required Linux
|
||||
capabilities:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
sudo setcap cap_net_raw,cap_net_admin=eip /usr/bin/your-app
|
||||
|
||||
Replace ``/usr/bin/your-app`` with the full path to the application executable.
|
||||
|
||||
|
||||
@@ -2,17 +2,24 @@ option(LIBICSNEO_BUILD_C_INTERACTIVE_EXAMPLE "Build the command-line interactive
|
||||
option(LIBICSNEO_BUILD_C_SIMPLE_EXAMPLE "Build the command-line simple C example." ON)
|
||||
option(LIBICSNEO_BUILD_C_LEGACY_EXAMPLE "Build the command-line simple C example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_SIMPLE_EXAMPLE "Build the simple C2 example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_SUPPORTED_DEVICES_EXAMPLE "Build the C2 supported devices example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_READ_MESSAGES_EXAMPLE "Build the C2 read messages example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_DISKFORMAT_EXAMPLE "Build the C2 disk format example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_RECONNECT_EXAMPLE "Build the C2 reconnect example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_DEVICE_INFO_EXAMPLE "Build the C2 device info example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_CHIP_VERSIONS_EXAMPLE "Build the C2 chip versions example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_TERMINATION_EXAMPLE "Build the C2 termination groups example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_LIN_EXAMPLE "Build the C2 LIN example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_LIN_TRANSMIT_EXAMPLE "Build the C2 LIN transmit example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_ETHERNET_TRANSMIT_EXAMPLE "Build the C2 ethernet transmit example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_ETHERNET_RECEIVE_EXAMPLE "Build the C2 ethernet receive example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_ETHERNET_STATUS_EXAMPLE "Build the C2 ethernet status example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_T1S_LOOPBACK_EXAMPLE "Build the C2 RAD-Comet3 T1S loopback example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_TC10_EXAMPLE "Build the C2 TC10 example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_GPTP_EXAMPLE "Build the C2 gPTP settings example." ON)
|
||||
option(LIBICSNEO_BUILD_C2_PERF_TEST_EXAMPLE "Build the C2 PerfTest setting example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_SIMPLE_EXAMPLE "Build the simple C++ example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_DEVICE_INFO_EXAMPLE "Build the C++ device info example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_INTERACTIVE_EXAMPLE "Build the command-line interactive C++ example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_A2B_EXAMPLE "Build the A2B example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_LIN_EXAMPLE "Build the LIN example." ON)
|
||||
@@ -28,6 +35,8 @@ option(LIBICSNEO_BUILD_CPP_MUTEX_EXAMPLE "Build the NetworkMutex example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_ANALOG_OUT_EXAMPLE "Build the analog output example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_DISKFORMAT_EXAMPLE "Build the disk format example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_T1S_EXAMPLE "Build the T1S example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_GPTP_EXAMPLE "Build the C++ gPTP settings example." ON)
|
||||
option(LIBICSNEO_BUILD_CPP_ISO15765_LOOPBACK_EXAMPLE "Build the C++ ISO15765 two-device CAN1 loopback example." ON)
|
||||
|
||||
add_compile_options(${LIBICSNEO_COMPILER_WARNINGS})
|
||||
|
||||
@@ -47,6 +56,10 @@ if(LIBICSNEO_BUILD_C2_SIMPLE_EXAMPLE)
|
||||
add_subdirectory(c2/simple)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_SUPPORTED_DEVICES_EXAMPLE)
|
||||
add_subdirectory(c2/supported_devices)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_READ_MESSAGES_EXAMPLE)
|
||||
add_subdirectory(c2/read_messages)
|
||||
endif()
|
||||
@@ -63,6 +76,14 @@ if(LIBICSNEO_BUILD_C2_DEVICE_INFO_EXAMPLE)
|
||||
add_subdirectory(c2/device_info)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_CHIP_VERSIONS_EXAMPLE)
|
||||
add_subdirectory(c2/chip_versions)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_TERMINATION_EXAMPLE)
|
||||
add_subdirectory(c2/termination)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_LIN_EXAMPLE)
|
||||
add_subdirectory(c2/lin)
|
||||
endif()
|
||||
@@ -79,6 +100,10 @@ if(LIBICSNEO_BUILD_C2_ETHERNET_RECEIVE_EXAMPLE)
|
||||
add_subdirectory(c2/ethernet_receive)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_ETHERNET_STATUS_EXAMPLE)
|
||||
add_subdirectory(c2/ethernet_status)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_T1S_LOOPBACK_EXAMPLE)
|
||||
add_subdirectory(c2/t1s_loopback)
|
||||
endif()
|
||||
@@ -87,10 +112,22 @@ if(LIBICSNEO_BUILD_C2_TC10_EXAMPLE)
|
||||
add_subdirectory(c2/tc10)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_GPTP_EXAMPLE)
|
||||
add_subdirectory(c2/gptp)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_C2_PERF_TEST_EXAMPLE)
|
||||
add_subdirectory(c2/perf_test)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_CPP_SIMPLE_EXAMPLE)
|
||||
add_subdirectory(cpp/simple)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_CPP_DEVICE_INFO_EXAMPLE)
|
||||
add_subdirectory(cpp/device_info)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_CPP_INTERACTIVE_EXAMPLE)
|
||||
add_subdirectory(cpp/interactive)
|
||||
endif()
|
||||
@@ -150,3 +187,11 @@ endif()
|
||||
if(LIBICSNEO_BUILD_CPP_T1S_EXAMPLE)
|
||||
add_subdirectory(cpp/t1s)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_CPP_GPTP_EXAMPLE)
|
||||
add_subdirectory(cpp/gptp)
|
||||
endif()
|
||||
|
||||
if(LIBICSNEO_BUILD_CPP_ISO15765_LOOPBACK_EXAMPLE)
|
||||
add_subdirectory(cpp/iso15765_loopback)
|
||||
endif()
|
||||
|
||||
@@ -52,7 +52,7 @@ Although the example program will build without successfully completing the step
|
||||
|
||||
First, we are going to build the icsneoc library into a .so file that we can later use in order to access the library functions.
|
||||
|
||||
1. Install dependencies with `sudo apt update` then `sudo apt install build-essential cmake libpcap0.8-dev`
|
||||
1. Install dependencies with `sudo apt update` then `sudo apt install build-essential cmake`
|
||||
2. Change directories to `libicsneo-examples/third-party/libicsneo` and create a build directory by running `mkdir -p build`
|
||||
3. Enter the build directory with `cd build`
|
||||
4. Run `cmake ..` to generate your Makefile.
|
||||
@@ -72,8 +72,7 @@ Although the example program will build without successfully completing the step
|
||||
* Hint! Running `cmake -DCMAKE_BUILD_TYPE=Debug ..` will generate the proper scripts to build debug, and `cmake -DCMAKE_BUILD_TYPE=Release ..` will generate the proper scripts to build with all optimizations on.
|
||||
5. Run `make` to build the library.
|
||||
* Hint! Speed up your build by using multiple processors! Use `make -j#` where `#` is the number of cores/threads your system has plus one. For instance, on a standard 8 thread Intel i7, you might use `-j9` for an ~8x speedup.
|
||||
6. Run `sudo ./libicsneoc-example` to run the example.
|
||||
* Hint! In order to run without sudo, you will need to set up the udev rules. Copy `libicsneo-examples/third-party/libicsneo/99-intrepidcs.rules` to `/etc/udev/rules.d`, then run `udevadm control --reload-rules && udevadm trigger` afterwards. While the program will still run without setting up these rules, it will fail to open any devices.
|
||||
6. Run `./libicsneoc-example` to run the example.
|
||||
|
||||
## macOS
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ Although the example program will build without successfully completing the step
|
||||
|
||||
First, we are going to build the icsneoc library into a .so file that we can later use in order to access the library functions.
|
||||
|
||||
1. Install dependencies with `sudo apt update` then `sudo apt install build-essential cmake libpcap0.8-dev`
|
||||
1. Install dependencies with `sudo apt update` then `sudo apt install build-essential cmake`
|
||||
2. Change directories to `libicsneo-examples/third-party/libicsneo` and create a build directory by running `mkdir -p build`
|
||||
3. Enter the build directory with `cd build`
|
||||
4. Run `cmake ..` to generate your Makefile.
|
||||
@@ -72,8 +72,7 @@ Although the example program will build without successfully completing the step
|
||||
* Hint! Running `cmake -DCMAKE_BUILD_TYPE=Debug ..` will generate the proper scripts to build debug, and `cmake -DCMAKE_BUILD_TYPE=Release ..` will generate the proper scripts to build with all optimizations on.
|
||||
5. Run `make` to build the library.
|
||||
* Hint! Speed up your build by using multiple processors! Use `make -j#` where `#` is the number of cores/threads your system has plus one. For instance, on a standard 8 thread Intel i7, you might use `-j9` for an ~8x speedup.
|
||||
6. Run `sudo ./libicsneoc-example` to run the example.
|
||||
* Hint! In order to run without sudo, you will need to set up the udev rules. Copy `libicsneo-examples/third-party/libicsneo/99-intrepidcs.rules` to `/etc/udev/rules.d`, then run `udevadm control --reload-rules && udevadm trigger` afterwards. While the program will still run without setting up these rules, it will fail to open any devices.
|
||||
6. Run `./libicsneoc-example` to run the example.
|
||||
|
||||
## macOS
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ int main() {
|
||||
msg1.Protocol = SPY_PROTOCOL_LIN;
|
||||
msg1.StatusBitField = 0;
|
||||
msg1.StatusBitField2 = 0;
|
||||
lNetworkID = NETID_LIN_02;
|
||||
lNetworkID = NETID_LIN2;
|
||||
msg1.Header[0] = 0x11; //protected ID
|
||||
msg1.Header[1] = 0xaa;
|
||||
msg1.Header[2] = 0xbb;
|
||||
@@ -80,7 +80,7 @@ int main() {
|
||||
icsSpyMessageJ1850 msg2 = {0};
|
||||
msg2.Protocol = SPY_PROTOCOL_LIN;
|
||||
msg2.StatusBitField = SPY_STATUS_INIT_MESSAGE;
|
||||
lNetworkID = NETID_LIN_01;
|
||||
lNetworkID = NETID_LIN;
|
||||
msg2.Header[0] = 0x11; //protected ID
|
||||
msg2.NumberBytesData = 0;
|
||||
msg2.NumberBytesHeader = 1;
|
||||
@@ -96,7 +96,7 @@ int main() {
|
||||
msg3.Protocol = SPY_PROTOCOL_LIN;
|
||||
msg3.StatusBitField = SPY_STATUS_INIT_MESSAGE;
|
||||
msg3.StatusBitField2 = 0;
|
||||
lNetworkID = NETID_LIN_01;
|
||||
lNetworkID = NETID_LIN;
|
||||
msg3.Header[0] = 0xe2; //protected ID
|
||||
msg3.Header[1] = 0x44;
|
||||
msg3.Header[2] = 0x33;
|
||||
@@ -131,10 +131,10 @@ int main() {
|
||||
const icsSpyMessageJ1850* linMsg = (icsSpyMessageJ1850*)&rxMsg[idx];
|
||||
size_t frameLen = (linMsg->NumberBytesHeader + linMsg->NumberBytesData);
|
||||
size_t dataLen = (frameLen > 2) ? (frameLen - 2) : 0;
|
||||
if(linMsg->NetworkID == NETID_LIN_01) {
|
||||
if(linMsg->NetworkID == NETID_LIN) {
|
||||
printf("LIN 1 | ID: 0x%02x [%zu] ", linMsg->Header[0], dataLen);
|
||||
}
|
||||
else if (linMsg->NetworkID == NETID_LIN_02) {
|
||||
else if (linMsg->NetworkID == NETID_LIN2) {
|
||||
printf("LIN 2 | ID: 0x%02x [%zu] ", linMsg->Header[0], dataLen);
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ Although the example program will build without successfully completing the step
|
||||
|
||||
First, we are going to build the icsneoc library into a .so file that we can later use in order to access the library functions.
|
||||
|
||||
1. Install dependencies with `sudo apt update` then `sudo apt install build-essential cmake libpcap0.8-dev`
|
||||
1. Install dependencies with `sudo apt update` then `sudo apt install build-essential cmake`
|
||||
2. Change directories to `libicsneo-examples/third-party/libicsneo` and create a build directory by running `mkdir -p build`
|
||||
3. Enter the build directory with `cd build`
|
||||
4. Run `cmake ..` to generate your Makefile.
|
||||
@@ -72,8 +72,7 @@ Although the example program will build without successfully completing the step
|
||||
* Hint! Running `cmake -DCMAKE_BUILD_TYPE=Debug ..` will generate the proper scripts to build debug, and `cmake -DCMAKE_BUILD_TYPE=Release ..` will generate the proper scripts to build with all optimizations on.
|
||||
5. Run `make` to build the library.
|
||||
* Hint! Speed up your build by using multiple processors! Use `make -j#` where `#` is the number of cores/threads your system has plus one. For instance, on a standard 8 thread Intel i7, you might use `-j9` for an ~8x speedup.
|
||||
6. Run `sudo ./libicsneoc-example` to run the example.
|
||||
* Hint! In order to run without sudo, you will need to set up the udev rules. Copy `libicsneo-examples/third-party/libicsneo/99-intrepidcs.rules` to `/etc/udev/rules.d`, then run `udevadm control --reload-rules && udevadm trigger` afterwards. While the program will still run without setting up these rules, it will fail to open any devices.
|
||||
6. Run `./libicsneoc-example` to run the example.
|
||||
|
||||
## macOS
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(libicsneoc2-chip-versions-example src/main.c)
|
||||
target_link_libraries(libicsneoc2-chip-versions-example icsneoc2-static)
|
||||
|
||||
if(WIN32)
|
||||
target_compile_definitions(libicsneoc2-chip-versions-example PRIVATE _CRT_SECURE_NO_WARNINGS)
|
||||
endif()
|
||||
@@ -0,0 +1,59 @@
|
||||
#include <icsneo/icsneoc2.h>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
int print_error_code(const char* message, icsneoc2_error_t error) {
|
||||
char error_str[64];
|
||||
size_t error_str_len = sizeof(error_str);
|
||||
icsneoc2_error_t res = icsneoc2_error_code_get(error, error_str, &error_str_len);
|
||||
if(res != icsneoc2_error_success) {
|
||||
printf("%s: Failed to get string for error code %u with error code %u\n", message, error, res);
|
||||
return (int)res;
|
||||
}
|
||||
printf("%s: \"%s\" (%u)\n", message, error_str, error);
|
||||
return (int)error;
|
||||
}
|
||||
|
||||
int main() {
|
||||
icsneoc2_error_t res;
|
||||
|
||||
icsneoc2_device_t* device = NULL;
|
||||
res = icsneoc2_device_open_first(0, icsneoc2_open_options_default, &device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("Failed to open first device", res);
|
||||
}
|
||||
|
||||
char description[128] = {0};
|
||||
size_t description_length = sizeof(description);
|
||||
icsneoc2_device_description_get(device, description, &description_length);
|
||||
printf("Opened device: %s\n\n", description);
|
||||
|
||||
size_t count = 0;
|
||||
icsneoc2_chip_versions_t* chip_versions = NULL;
|
||||
res = icsneoc2_device_chip_versions_enumerate(device, &chip_versions, true, &count);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_error_code("Failed to enumerate chip versions", res);
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("Found %zu chip version(s):\n", count);
|
||||
for(icsneoc2_chip_versions_t* cur = chip_versions; cur; cur = icsneoc2_chip_versions_next(cur)) {
|
||||
char name[64] = {0};
|
||||
size_t name_length = sizeof(name);
|
||||
uint8_t major = 0, minor = 0, maintenance = 0, build = 0;
|
||||
res = icsneoc2_chip_versions_props_get(cur, name, &name_length, &major, &minor, &maintenance, &build);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_error_code("Failed to get chip version properties", res);
|
||||
continue;
|
||||
}
|
||||
printf(" %s: %u.%u.%u.%u\n", name, major, minor, maintenance, build);
|
||||
}
|
||||
|
||||
icsneoc2_chip_versions_free(chip_versions);
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return 0;
|
||||
}
|
||||
@@ -102,19 +102,31 @@ int main() {
|
||||
print_error_code("Failed to get PCB serial (device may not support it)", res);
|
||||
}
|
||||
|
||||
/* ===== MAC Address ===== */
|
||||
uint8_t mac[6] = {0};
|
||||
size_t mac_len = sizeof(mac);
|
||||
res = icsneoc2_device_mac_address_get(device, mac, &mac_len);
|
||||
/* ===== MAC Addresses ===== */
|
||||
icsneoc2_mac_addr_entry_t* macs = NULL;
|
||||
res = icsneoc2_device_mac_addresses_enumerate(device, &macs);
|
||||
if(res == icsneoc2_error_success) {
|
||||
printf("MAC: ");
|
||||
for(size_t i = 0; i < mac_len; i++) {
|
||||
if(i > 0) printf(":");
|
||||
printf("%02X", mac[i]);
|
||||
uint16_t mac_count = 0;
|
||||
for(icsneoc2_mac_addr_entry_t* cur = macs; cur; cur = icsneoc2_mac_addresses_next(cur)) {
|
||||
mac_count++;
|
||||
}
|
||||
printf("\n");
|
||||
printf("MACs: %u entr%s\n", mac_count, mac_count == 1 ? "y" : "ies");
|
||||
for(icsneoc2_mac_addr_entry_t* cur = macs; cur; cur = icsneoc2_mac_addresses_next(cur)) {
|
||||
icsneoc2_netid_t network_id;
|
||||
icsneoc2_mac_network_id_get(cur, &network_id);
|
||||
printf(" Network %-5u ", (unsigned)network_id);
|
||||
uint8_t address[6];
|
||||
size_t address_size = 6;
|
||||
icsneoc2_mac_address_get(cur, address, &address_size);
|
||||
for(int j = 0; j < 6; j++) {
|
||||
if(j > 0) printf(":");
|
||||
printf("%02X", (unsigned)address[j]);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
icsneoc2_mac_addresses_free(macs);
|
||||
} else {
|
||||
print_error_code("Failed to get MAC address (device may not support it)", res);
|
||||
print_error_code("Failed to get MAC addresses (device may not support it)", res);
|
||||
}
|
||||
|
||||
/* Cleanup */
|
||||
|
||||
@@ -109,6 +109,85 @@ int main() {
|
||||
}
|
||||
}
|
||||
|
||||
/* Choose operation */
|
||||
printf("\n\tChoose operation:\n");
|
||||
printf("\t [f] Format the disk(s)\n");
|
||||
printf("\t [u] Update the disk configuration without formatting\n");
|
||||
printf("\t [q] Quit\n");
|
||||
printf("\tSelection [f/u/q]: ");
|
||||
char choice[8] = {0};
|
||||
if(scanf("%7s", choice) != 1) {
|
||||
choice[0] = 'q';
|
||||
}
|
||||
|
||||
if(choice[0] == 'u' || choice[0] == 'U') {
|
||||
/* Force a disk config update (e.g. changing the disk layout) without formatting.
|
||||
* Unlike a format, this preserves the existing data on the disk(s). */
|
||||
printf("\n\tChoose disk layout:\n");
|
||||
printf("\t [s] Spanned\n");
|
||||
printf("\t [r] RAID0\n");
|
||||
printf("\tSelection [s/r] (current: %s): ", layout == icsneoc2_disk_layout_raid0 ? "RAID0" : "Spanned");
|
||||
char layout_choice[8] = {0};
|
||||
if(scanf("%7s", layout_choice) != 1) {
|
||||
layout_choice[0] = '\0';
|
||||
}
|
||||
if(layout_choice[0] == 'r' || layout_choice[0] == 'R') {
|
||||
icsneoc2_disk_details_layout_set(details, icsneoc2_disk_layout_raid0);
|
||||
} else if(layout_choice[0] == 's' || layout_choice[0] == 'S') {
|
||||
icsneoc2_disk_details_layout_set(details, icsneoc2_disk_layout_spanned);
|
||||
} else {
|
||||
printf("\tKeeping current layout.\n");
|
||||
}
|
||||
|
||||
/* Enable/disable individual disks in the configuration. A disk's enabled
|
||||
* state is carried by the FORMATTED flag; only present disks can be enabled. */
|
||||
for(size_t i = 0; i < detail_count; i++) {
|
||||
icsneoc2_disk_format_flags_t flags = 0;
|
||||
icsneoc2_disk_details_flags_get(details, i, &flags);
|
||||
if(!(flags & ICSNEOC2_DISK_FORMAT_FLAGS_PRESENT)) {
|
||||
continue; /* Can't enable a disk that isn't present */
|
||||
}
|
||||
printf("\tEnable disk [%zu]? [y/N] (currently %s): ", i,
|
||||
(flags & ICSNEOC2_DISK_FORMAT_FLAGS_FORMATTED) ? "enabled" : "disabled");
|
||||
char disk_choice[8] = {0};
|
||||
if(scanf("%7s", disk_choice) != 1) {
|
||||
disk_choice[0] = '\0';
|
||||
}
|
||||
if(disk_choice[0] == 'y' || disk_choice[0] == 'Y') {
|
||||
flags |= ICSNEOC2_DISK_FORMAT_FLAGS_FORMATTED;
|
||||
} else {
|
||||
flags &= ~(icsneoc2_disk_format_flags_t)ICSNEOC2_DISK_FORMAT_FLAGS_FORMATTED;
|
||||
}
|
||||
icsneoc2_disk_details_flags_set(details, i, flags);
|
||||
}
|
||||
|
||||
icsneoc2_disk_layout_t new_layout = 0;
|
||||
icsneoc2_disk_details_layout_get(details, &new_layout);
|
||||
printf("\n\tForcing disk config update on %s to %s layout (no data will be erased)...\n",
|
||||
description, new_layout == icsneoc2_disk_layout_raid0 ? "RAID0" : "Spanned");
|
||||
res = icsneoc2_device_force_disk_config_update(device, details);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_error_code("\tForce disk config update failed", res);
|
||||
icsneoc2_disk_details_free(details);
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return -1;
|
||||
}
|
||||
printf("\tDisk config update complete!\n");
|
||||
icsneoc2_disk_details_free(details);
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(choice[0] != 'f' && choice[0] != 'F') {
|
||||
printf("\tAborted.\n");
|
||||
icsneoc2_disk_details_free(details);
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Build format config: mark present disks for formatting */
|
||||
bool any_present = false;
|
||||
for(size_t i = 0; i < detail_count; i++) {
|
||||
|
||||
@@ -68,6 +68,7 @@ void print_mac(const char* label, const uint8_t* mac) {
|
||||
|
||||
int process_ethernet_message(icsneoc2_message_t* message, size_t index) {
|
||||
icsneoc2_netid_t netid = 0;
|
||||
uint64_t timestamp = 0;
|
||||
char netid_name[128] = {0};
|
||||
size_t netid_name_length = 128;
|
||||
|
||||
@@ -79,6 +80,10 @@ int process_ethernet_message(icsneoc2_message_t* message, size_t index) {
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to get netid name", res);
|
||||
}
|
||||
res = icsneoc2_message_timestamp_get(message, ×tamp);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to get timestamp", res);
|
||||
}
|
||||
|
||||
/* Get data length first */
|
||||
size_t data_length = 0;
|
||||
@@ -88,6 +93,7 @@ int process_ethernet_message(icsneoc2_message_t* message, size_t index) {
|
||||
}
|
||||
|
||||
printf("\t%zu) Ethernet Frame on %s (0x%x) - %zu bytes\n", index, netid_name, netid, data_length);
|
||||
printf("\t Timestamp: %" PRIu64 " ns since 2007-01-01 UTC\n", timestamp);
|
||||
|
||||
/* Get MAC addresses and EtherType if we have enough data */
|
||||
uint8_t dst_mac[6] = {0};
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(libicsneoc2-ethernet-status-example src/main.c)
|
||||
target_link_libraries(libicsneoc2-ethernet-status-example icsneoc2-static)
|
||||
|
||||
if(WIN32)
|
||||
target_compile_definitions(libicsneoc2-ethernet-status-example PRIVATE _CRT_SECURE_NO_WARNINGS)
|
||||
endif()
|
||||
@@ -0,0 +1,228 @@
|
||||
#include <icsneo/icsneoc2.h>
|
||||
#include <icsneo/icsneoc2messages.h>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
void sleep_ms(uint32_t ms) {
|
||||
#ifdef _WIN32
|
||||
Sleep(ms);
|
||||
#else
|
||||
usleep(ms * 1000);
|
||||
#endif
|
||||
}
|
||||
|
||||
int print_error_code(const char* message, icsneoc2_error_t error) {
|
||||
char error_str[64] = {0};
|
||||
size_t error_str_len = sizeof(error_str);
|
||||
icsneoc2_error_t res = icsneoc2_error_code_get(error, error_str, &error_str_len);
|
||||
if(res != icsneoc2_error_success) {
|
||||
printf("%s: Failed to get string for error code %u with error code %u\n", message, error, res);
|
||||
return (int)res;
|
||||
}
|
||||
printf("%s: \"%s\" (%u)\n", message, error_str, error);
|
||||
return (int)error;
|
||||
}
|
||||
|
||||
void print_events(void) {
|
||||
icsneoc2_event_t* events[256] = {0};
|
||||
size_t events_count = 256;
|
||||
for(size_t i = 0; i < events_count; ++i) {
|
||||
icsneoc2_error_t res = icsneoc2_event_get(&events[i], NULL);
|
||||
if(res != icsneoc2_error_success) {
|
||||
(void)print_error_code("\tFailed to get events", res);
|
||||
return;
|
||||
}
|
||||
if(events[i] == NULL) {
|
||||
events_count = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for(size_t i = 0; i < events_count; i++) {
|
||||
char description[255] = {0};
|
||||
size_t description_length = sizeof(description);
|
||||
icsneoc2_error_t res = icsneoc2_event_description_get(events[i], description, &description_length);
|
||||
if(res != icsneoc2_error_success) {
|
||||
(void)print_error_code("\tFailed to get event description", res);
|
||||
continue;
|
||||
}
|
||||
printf("\tEvent %zu: %s\n", i, description);
|
||||
}
|
||||
|
||||
for(size_t i = 0; i < events_count; i++) {
|
||||
icsneoc2_event_free(events[i]);
|
||||
}
|
||||
if(events_count > 0) {
|
||||
printf("\tReceived %zu events\n", events_count);
|
||||
}
|
||||
}
|
||||
|
||||
const char* link_speed_name(icsneoc2_link_speed_t speed) {
|
||||
switch(speed) {
|
||||
case icsneoc2_link_speed_auto:
|
||||
return "Auto";
|
||||
case icsneoc2_link_speed_10mbps:
|
||||
return "10 Mbps";
|
||||
case icsneoc2_link_speed_100mbps:
|
||||
return "100 Mbps";
|
||||
case icsneoc2_link_speed_1000mbps:
|
||||
return "1000 Mbps";
|
||||
case icsneoc2_link_speed_2500mbps:
|
||||
return "2500 Mbps";
|
||||
case icsneoc2_link_speed_5000mbps:
|
||||
return "5000 Mbps";
|
||||
case icsneoc2_link_speed_10000mbps:
|
||||
return "10000 Mbps";
|
||||
default:
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
const char* link_mode_name(icsneoc2_link_mode_t mode) {
|
||||
switch(mode) {
|
||||
case icsneoc2_link_mode_auto:
|
||||
return "Auto";
|
||||
case icsneoc2_link_mode_master:
|
||||
return "Master";
|
||||
case icsneoc2_link_mode_slave:
|
||||
return "Slave";
|
||||
case icsneoc2_link_mode_invalid:
|
||||
return "Invalid";
|
||||
case icsneoc2_link_mode_none:
|
||||
return "None";
|
||||
default:
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
int print_ethernet_status_message(icsneoc2_message_t* message, size_t index) {
|
||||
icsneoc2_netid_t netid = 0;
|
||||
char netid_name[128] = {0};
|
||||
size_t netid_name_length = sizeof(netid_name);
|
||||
bool link_state = false;
|
||||
bool duplex = false;
|
||||
icsneoc2_link_speed_t link_speed = icsneoc2_link_speed_auto;
|
||||
icsneoc2_link_mode_t link_mode = icsneoc2_link_mode_auto;
|
||||
|
||||
icsneoc2_error_t res = icsneoc2_message_netid_get(message, &netid);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to get Ethernet status netid", res);
|
||||
}
|
||||
|
||||
res = icsneoc2_netid_name_get(netid, netid_name, &netid_name_length);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to get Ethernet status netid name", res);
|
||||
}
|
||||
|
||||
res = icsneoc2_message_eth_status_props_get(message, &link_state, &duplex, &link_speed, &link_mode);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to get Ethernet status properties", res);
|
||||
}
|
||||
|
||||
printf("\t%zu) Ethernet status on %s (0x%x)\n", index, netid_name, netid);
|
||||
printf("\t Link: %s\n", link_state ? "Up" : "Down");
|
||||
printf("\t Duplex: %s\n", duplex ? "Full" : "Half");
|
||||
printf("\t Speed: %s (%u)\n", link_speed_name(link_speed), link_speed);
|
||||
printf("\t Mode: %s (%u)\n", link_mode_name(link_mode), link_mode);
|
||||
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
printf("Opening first available device offline...\n");
|
||||
icsneoc2_device_t* device = NULL;
|
||||
icsneoc2_open_options_t options = icsneoc2_open_options_default & ~ICSNEOC2_OPEN_OPTIONS_GO_ONLINE;
|
||||
icsneoc2_error_t res = icsneoc2_device_open_first(0, options, &device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("Failed to open first device", res);
|
||||
}
|
||||
|
||||
char description[255] = {0};
|
||||
size_t description_length = sizeof(description);
|
||||
res = icsneoc2_device_description_get(device, description, &description_length);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return print_error_code("Failed to get device description", res);
|
||||
}
|
||||
printf("Opened device: %s\n", description);
|
||||
|
||||
printf("Going online to trigger Ethernet status broadcast...\n");
|
||||
res = icsneoc2_device_go_online(device, true);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_events();
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return print_error_code("Failed to go online", res);
|
||||
}
|
||||
|
||||
const int listen_seconds = 6;
|
||||
time_t start_time = time(NULL);
|
||||
size_t status_count = 0;
|
||||
size_t total_count = 0;
|
||||
printf("Listening for Ethernet status messages for %d seconds...\n", listen_seconds);
|
||||
|
||||
while(time(NULL) - start_time < listen_seconds) {
|
||||
icsneoc2_message_t* message = NULL;
|
||||
res = icsneoc2_device_message_get(device, &message, 100);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_events();
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return print_error_code("Failed to get message", res);
|
||||
}
|
||||
if(message == NULL) {
|
||||
sleep_ms(10);
|
||||
continue;
|
||||
}
|
||||
|
||||
total_count++;
|
||||
bool is_ethernet_status = false;
|
||||
res = icsneoc2_message_is_ethernet_status(message, &is_ethernet_status);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_message_free(message);
|
||||
print_events();
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return print_error_code("Failed to check for Ethernet status message", res);
|
||||
}
|
||||
|
||||
if(is_ethernet_status) {
|
||||
res = print_ethernet_status_message(message, status_count);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_message_free(message);
|
||||
print_events();
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return (int)res;
|
||||
}
|
||||
status_count++;
|
||||
}
|
||||
|
||||
icsneoc2_message_free(message);
|
||||
}
|
||||
|
||||
printf("Received %zu Ethernet status messages out of %zu total messages.\n", status_count, total_count);
|
||||
if(status_count == 0) {
|
||||
printf("No Ethernet status messages were seen. These messages are broadcast when the device goes online and may depend on device Ethernet support.\n");
|
||||
}
|
||||
|
||||
print_events();
|
||||
|
||||
printf("Closing device...\n");
|
||||
res = icsneoc2_device_close(device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_device_free(device);
|
||||
return print_error_code("Failed to close device", res);
|
||||
}
|
||||
|
||||
icsneoc2_device_free(device);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(libicsneoc2-gptp-example src/main.c)
|
||||
target_link_libraries(libicsneoc2-gptp-example icsneoc2-static)
|
||||
|
||||
if(WIN32)
|
||||
target_compile_definitions(libicsneoc2-gptp-example PRIVATE _CRT_SECURE_NO_WARNINGS)
|
||||
endif()
|
||||
@@ -0,0 +1,330 @@
|
||||
/*
|
||||
* gPTP settings configurator example.
|
||||
*
|
||||
* Lists connected devices and their gPTP support, then lets the user
|
||||
* configure the gPTP profile, role, port, and clock syntonization on any
|
||||
* device that supports it. If --serial is omitted, the first available
|
||||
* gPTP-capable device is used.
|
||||
*/
|
||||
|
||||
#include <icsneo/icsneoc2.h>
|
||||
#include <icsneo/icsneoc2settings.h>
|
||||
#include <icsneo/icsneoc2messages.h>
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct {
|
||||
const char* serial;
|
||||
bool list;
|
||||
} args_t;
|
||||
|
||||
/* Maps an icsneoc2_netid_t to its gPTP port index (0 = not a gPTP port). */
|
||||
static uint8_t netid_to_gptp_port(icsneoc2_netid_t netid) {
|
||||
switch(netid) {
|
||||
case icsneoc2_netid_ae_01: return 1;
|
||||
case icsneoc2_netid_ae_02: return 2;
|
||||
case icsneoc2_netid_ae_03: return 3;
|
||||
case icsneoc2_netid_ae_04: return 4;
|
||||
case icsneoc2_netid_ae_05: return 5;
|
||||
case icsneoc2_netid_ae_06: return 6;
|
||||
case icsneoc2_netid_ae_07: return 7;
|
||||
case icsneoc2_netid_ae_08: return 8;
|
||||
case icsneoc2_netid_ae_09: return 9;
|
||||
case icsneoc2_netid_ae_10: return 10;
|
||||
case icsneoc2_netid_ae_11: return 11;
|
||||
case icsneoc2_netid_ae_12: return 12;
|
||||
case icsneoc2_netid_ethernet_01: return 13;
|
||||
case icsneoc2_netid_ethernet_02: return 14;
|
||||
case icsneoc2_netid_ethernet_03: return 15;
|
||||
case icsneoc2_netid_ae_13: return 16;
|
||||
case icsneoc2_netid_ae_14: return 17;
|
||||
case icsneoc2_netid_ae_15: return 18;
|
||||
case icsneoc2_netid_ae_16: return 19;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static const char* gptp_profile_str(icsneoc2_gptp_profile_t p) {
|
||||
switch(p) {
|
||||
case icsneoc2_gptp_profile_standard: return "Standard";
|
||||
case icsneoc2_gptp_profile_automotive: return "Automotive";
|
||||
default: return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
static const char* gptp_role_str(icsneoc2_gptp_role_t r) {
|
||||
switch(r) {
|
||||
case icsneoc2_gptp_role_disabled: return "Disabled";
|
||||
case icsneoc2_gptp_role_passive: return "Passive";
|
||||
case icsneoc2_gptp_role_master: return "Master";
|
||||
case icsneoc2_gptp_role_slave: return "Slave";
|
||||
default: return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
static int print_error_code(const char* message, icsneoc2_error_t error) {
|
||||
char error_str[64] = {0};
|
||||
size_t error_str_len = sizeof(error_str);
|
||||
icsneoc2_error_t res = icsneoc2_error_code_get(error, error_str, &error_str_len);
|
||||
if(res != icsneoc2_error_success) {
|
||||
fprintf(stderr, "%s: failed to get string for error code %u\n", message, error);
|
||||
return (int)res;
|
||||
}
|
||||
fprintf(stderr, "%s: \"%s\" (%u)\n", message, error_str, error);
|
||||
return (int)error;
|
||||
}
|
||||
|
||||
static void print_usage(const char* prog) {
|
||||
printf("Usage:\n");
|
||||
printf(" %s --list\n", prog);
|
||||
printf(" %s [--serial SERIAL]\n", prog);
|
||||
printf("\n");
|
||||
printf(" --list List connected devices and their gPTP support.\n");
|
||||
printf(" --serial SERIAL Serial number of the device to configure.\n");
|
||||
printf(" -h, --help Show this message.\n");
|
||||
}
|
||||
|
||||
static int parse_args(int argc, char** argv, args_t* out) {
|
||||
memset(out, 0, sizeof(*out));
|
||||
for(int i = 1; i < argc; ++i) {
|
||||
const char* a = argv[i];
|
||||
if(strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) {
|
||||
print_usage(argv[0]);
|
||||
exit(0);
|
||||
} else if(strcmp(a, "--list") == 0) {
|
||||
out->list = true;
|
||||
} else if(strcmp(a, "--serial") == 0) {
|
||||
if(i + 1 >= argc) {
|
||||
fprintf(stderr, "error: --serial requires a value\n");
|
||||
return 1;
|
||||
}
|
||||
out->serial = argv[++i];
|
||||
} else {
|
||||
fprintf(stderr, "error: unknown argument '%s'\n", a);
|
||||
print_usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static icsneoc2_device_info_t* find_device(icsneoc2_device_info_t* list, const char* serial) {
|
||||
for(icsneoc2_device_info_t* cur = list; cur != NULL; cur = icsneoc2_device_info_next(cur)) {
|
||||
if(serial == NULL)
|
||||
return cur;
|
||||
char dev_serial[64] = {0};
|
||||
size_t dev_serial_len = sizeof(dev_serial);
|
||||
if(icsneoc2_device_info_serial_get(cur, dev_serial, &dev_serial_len) != icsneoc2_error_success)
|
||||
continue;
|
||||
if(strcmp(dev_serial, serial) == 0)
|
||||
return cur;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Print a list of available Ethernet/AE networks with their gPTP port indices.
|
||||
* Returns the number of ports printed.
|
||||
*/
|
||||
static size_t print_gptp_ports(icsneoc2_device_t* device) {
|
||||
icsneoc2_netid_t nets[128] = {0};
|
||||
size_t count = sizeof(nets) / sizeof(nets[0]);
|
||||
if(icsneoc2_device_supported_tx_networks_get(device, nets, &count) != icsneoc2_error_success)
|
||||
return 0;
|
||||
|
||||
size_t printed = 0;
|
||||
for(size_t i = 0; i < count; ++i) {
|
||||
uint8_t port = netid_to_gptp_port(nets[i]);
|
||||
if(port == 0)
|
||||
continue;
|
||||
char name[64] = {0};
|
||||
size_t name_len = sizeof(name);
|
||||
icsneoc2_netid_name_get(nets[i], name, &name_len);
|
||||
printf(" [%u] %s\n", (unsigned)port, name);
|
||||
++printed;
|
||||
}
|
||||
return printed;
|
||||
}
|
||||
|
||||
static int list_devices(icsneoc2_device_info_t* list) {
|
||||
size_t index = 0;
|
||||
for(icsneoc2_device_info_t* cur = list; cur != NULL; cur = icsneoc2_device_info_next(cur)) {
|
||||
char serial[64] = {0};
|
||||
size_t serial_len = sizeof(serial);
|
||||
char description[256] = {0};
|
||||
size_t description_len = sizeof(description);
|
||||
icsneoc2_device_info_serial_get(cur, serial, &serial_len);
|
||||
icsneoc2_device_info_description_get(cur, description, &description_len);
|
||||
printf("[%zu] %s (%s)\n", index++, description, serial);
|
||||
|
||||
icsneoc2_device_t* device = NULL;
|
||||
if(icsneoc2_device_create(cur, &device) != icsneoc2_error_success)
|
||||
continue;
|
||||
|
||||
icsneoc2_open_options_t opts = icsneoc2_open_options_default;
|
||||
opts &= ~ICSNEOC2_OPEN_OPTIONS_SYNC_RTC;
|
||||
opts &= ~ICSNEOC2_OPEN_OPTIONS_GO_ONLINE;
|
||||
if(icsneoc2_device_open(device, opts) != icsneoc2_error_success) {
|
||||
icsneoc2_device_free(device);
|
||||
continue;
|
||||
}
|
||||
|
||||
bool supported = false;
|
||||
icsneoc2_device_supports_gptp(device, &supported);
|
||||
printf(" gPTP supported: %s\n", supported ? "yes" : "no");
|
||||
if(supported) {
|
||||
printf(" gPTP ports:\n");
|
||||
print_gptp_ports(device);
|
||||
}
|
||||
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void print_current_settings(icsneoc2_device_t* device) {
|
||||
icsneoc2_gptp_profile_t profile = icsneoc2_gptp_profile_standard;
|
||||
icsneoc2_gptp_role_t role = icsneoc2_gptp_role_disabled;
|
||||
uint8_t port = 0;
|
||||
bool clock_syntonization = false;
|
||||
|
||||
printf("\nCurrent gPTP settings:\n");
|
||||
if(icsneoc2_settings_gptp_profile_get(device, &profile) == icsneoc2_error_success)
|
||||
printf(" Profile: %s\n", gptp_profile_str(profile));
|
||||
if(icsneoc2_settings_gptp_role_get(device, &role) == icsneoc2_error_success)
|
||||
printf(" Role: %s\n", gptp_role_str(role));
|
||||
if(icsneoc2_settings_gptp_enabled_port_get(device, &port) == icsneoc2_error_success)
|
||||
printf(" Enabled port: %u%s\n", (unsigned)port, port == 0 ? " (disabled)" : "");
|
||||
if(icsneoc2_settings_gptp_clock_syntonization_enabled_get(device, &clock_syntonization) == icsneoc2_error_success)
|
||||
printf(" Clock syntonization: %s\n", clock_syntonization ? "enabled" : "disabled");
|
||||
}
|
||||
|
||||
static long prompt_long(const char* prompt, long default_val, long min, long max) {
|
||||
char buf[32] = {0};
|
||||
printf("%s [%ld]: ", prompt, default_val);
|
||||
fflush(stdout);
|
||||
if(fgets(buf, sizeof(buf), stdin) == NULL || buf[0] == '\n')
|
||||
return default_val;
|
||||
char* end = NULL;
|
||||
long val = strtol(buf, &end, 10);
|
||||
if(end == buf || val < min || val > max) {
|
||||
printf("Invalid input, using %ld.\n", default_val);
|
||||
return default_val;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
static int configure_device(icsneoc2_device_t* device) {
|
||||
icsneoc2_error_t res;
|
||||
|
||||
res = icsneoc2_settings_refresh(device);
|
||||
if(res != icsneoc2_error_success)
|
||||
return print_error_code("Failed to refresh settings", res);
|
||||
|
||||
print_current_settings(device);
|
||||
|
||||
printf("\nAvailable gPTP ports (0 = disabled):\n");
|
||||
printf(" [0] Disabled\n");
|
||||
print_gptp_ports(device);
|
||||
|
||||
printf("\nConfigure gPTP:\n");
|
||||
|
||||
long profile = prompt_long(" Profile (0=Standard, 1=Automotive)", 1, 0, 1);
|
||||
res = icsneoc2_settings_gptp_profile_set(device, (icsneoc2_gptp_profile_t)profile);
|
||||
if(res != icsneoc2_error_success)
|
||||
return print_error_code("Failed to set profile", res);
|
||||
|
||||
long role = prompt_long(" Role (0=Disabled, 1=Passive, 2=Master, 3=Slave)", 3, 0, 3);
|
||||
res = icsneoc2_settings_gptp_role_set(device, (icsneoc2_gptp_role_t)role);
|
||||
if(res != icsneoc2_error_success)
|
||||
return print_error_code("Failed to set role", res);
|
||||
|
||||
long port = prompt_long(" Enabled port index", 0, 0, 19);
|
||||
res = icsneoc2_settings_gptp_enabled_port_set(device, (uint8_t)port);
|
||||
if(res != icsneoc2_error_success)
|
||||
return print_error_code("Failed to set enabled port", res);
|
||||
|
||||
long syntonization = prompt_long(" Clock syntonization (0=disabled, 1=enabled)", 0, 0, 1);
|
||||
res = icsneoc2_settings_gptp_clock_syntonization_enabled_set(device, syntonization != 0);
|
||||
if(res != icsneoc2_error_success)
|
||||
return print_error_code("Failed to set clock syntonization", res);
|
||||
|
||||
printf("\nNote: icsneoc2_settings_apply() persists settings on the device.\n");
|
||||
res = icsneoc2_settings_apply(device);
|
||||
if(res != icsneoc2_error_success)
|
||||
return print_error_code("Failed to apply settings", res);
|
||||
|
||||
printf("\nUpdated gPTP settings:\n");
|
||||
print_current_settings(device);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
args_t args;
|
||||
if(parse_args(argc, argv, &args) != 0)
|
||||
return 1;
|
||||
|
||||
icsneoc2_device_info_t* found_devices = NULL;
|
||||
icsneoc2_error_t res = icsneoc2_device_enumerate(0, &found_devices);
|
||||
if(res != icsneoc2_error_success)
|
||||
return print_error_code("Failed to enumerate devices", res);
|
||||
if(found_devices == NULL) {
|
||||
fprintf(stderr, "error: no devices found\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if(args.list) {
|
||||
int rc = list_devices(found_devices);
|
||||
icsneoc2_enumeration_free(found_devices);
|
||||
return rc;
|
||||
}
|
||||
|
||||
icsneoc2_device_info_t* info = find_device(found_devices, args.serial);
|
||||
if(info == NULL) {
|
||||
fprintf(stderr, "error: unable to find device %s\n", args.serial ? args.serial : "(any)");
|
||||
icsneoc2_enumeration_free(found_devices);
|
||||
return 1;
|
||||
}
|
||||
|
||||
char description[256] = {0};
|
||||
size_t description_len = sizeof(description);
|
||||
icsneoc2_device_info_description_get(info, description, &description_len);
|
||||
|
||||
icsneoc2_device_t* device = NULL;
|
||||
res = icsneoc2_device_create(info, &device);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_enumeration_free(found_devices);
|
||||
return print_error_code("Failed to create device", res);
|
||||
}
|
||||
|
||||
printf("Opening %s\n", description);
|
||||
res = icsneoc2_device_open(device, icsneoc2_open_options_default);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_device_free(device);
|
||||
icsneoc2_enumeration_free(found_devices);
|
||||
return print_error_code("Failed to open device", res);
|
||||
}
|
||||
|
||||
bool supported = false;
|
||||
icsneoc2_device_supports_gptp(device, &supported);
|
||||
if(!supported) {
|
||||
fprintf(stderr, "error: device does not support gPTP (%s)\n", description);
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
icsneoc2_enumeration_free(found_devices);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int rc = configure_device(device);
|
||||
|
||||
printf("Closing %s\n", description);
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
icsneoc2_enumeration_free(found_devices);
|
||||
return rc;
|
||||
}
|
||||
@@ -86,6 +86,8 @@ void process_lin_messages(icsneoc2_message_t** messages, size_t count) {
|
||||
|
||||
icsneoc2_netid_t netid = 0;
|
||||
icsneoc2_message_netid_get(messages[i], &netid);
|
||||
uint64_t timestamp = 0;
|
||||
icsneoc2_message_timestamp_get(messages[i], ×tamp);
|
||||
char netid_name[128] = {0};
|
||||
size_t netid_name_length = 128;
|
||||
icsneoc2_netid_name_get(netid, netid_name, &netid_name_length);
|
||||
@@ -98,6 +100,7 @@ void process_lin_messages(icsneoc2_message_t** messages, size_t count) {
|
||||
icsneoc2_message_lin_err_flags_get(messages[i], &err_flags);
|
||||
|
||||
printf("\t%s RX | ID: 0x%02x | Protected ID: 0x%02x\n", netid_name, id, protected_id);
|
||||
printf("\tTimestamp: %" PRIu64 " ns since 2007-01-01 UTC\n", timestamp);
|
||||
printf("\tData: [");
|
||||
for(size_t x = 0; x < data_length; x++) {
|
||||
printf(" 0x%02x", data[x]);
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(libicsneoc2-perf_test-example src/main.c)
|
||||
target_link_libraries(libicsneoc2-perf_test-example icsneoc2-static)
|
||||
|
||||
if(WIN32)
|
||||
target_compile_definitions(libicsneoc2-perf_test-example PRIVATE _CRT_SECURE_NO_WARNINGS)
|
||||
endif()
|
||||
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* PerfTest setting example.
|
||||
*
|
||||
* Opens the first available device, enables the device-global PerfTest mode
|
||||
* via icsneoc2_settings_perf_test_enabled_set(), reads messages for a few
|
||||
* seconds while PerfTest is active, then disables PerfTest again. Each step
|
||||
* reads the value back with icsneoc2_settings_perf_test_enabled_get() to
|
||||
* confirm the change took effect.
|
||||
*/
|
||||
|
||||
#include <icsneo/icsneoc2.h>
|
||||
#include <icsneo/icsneoc2settings.h>
|
||||
#include <icsneo/icsneoc2messages.h>
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
|
||||
static int print_error_code(const char* message, icsneoc2_error_t error) {
|
||||
char error_str[64] = {0};
|
||||
size_t error_str_len = sizeof(error_str);
|
||||
icsneoc2_error_t res = icsneoc2_error_code_get(error, error_str, &error_str_len);
|
||||
if(res != icsneoc2_error_success) {
|
||||
fprintf(stderr, "%s: failed to get string for error code %u\n", message, error);
|
||||
return (int)res;
|
||||
}
|
||||
fprintf(stderr, "%s: \"%s\" (%u)\n", message, error_str, error);
|
||||
return (int)error;
|
||||
}
|
||||
|
||||
/* Sets PerfTest, applies it to the device, then reads it back to confirm. */
|
||||
static icsneoc2_error_t set_and_verify_perf_test(icsneoc2_device_t* device, bool enable) {
|
||||
icsneoc2_error_t res = icsneoc2_settings_perf_test_enabled_set(device, enable);
|
||||
if(res != icsneoc2_error_success)
|
||||
return res;
|
||||
|
||||
res = icsneoc2_settings_apply(device);
|
||||
if(res != icsneoc2_error_success)
|
||||
return res;
|
||||
|
||||
/* Re-read settings from the device so the read-back reflects what was
|
||||
* actually persisted, not just the local settings buffer. */
|
||||
res = icsneoc2_settings_refresh(device);
|
||||
if(res != icsneoc2_error_success)
|
||||
return res;
|
||||
|
||||
bool value = !enable;
|
||||
res = icsneoc2_settings_perf_test_enabled_get(device, &value);
|
||||
if(res != icsneoc2_error_success)
|
||||
return res;
|
||||
|
||||
printf("\tPerfTest now reads back as: %s\n", value ? "enabled" : "disabled");
|
||||
if(value != enable) {
|
||||
fprintf(stderr, "\tERROR: expected PerfTest %s but device reports %s\n",
|
||||
enable ? "enabled" : "disabled", value ? "enabled" : "disabled");
|
||||
return icsneoc2_error_get_settings_failure;
|
||||
}
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
/* Continuously drains and counts messages for the given wall-clock duration. */
|
||||
static icsneoc2_error_t read_messages_for(icsneoc2_device_t* device, unsigned seconds) {
|
||||
size_t total = 0;
|
||||
printf("\tReading messages for %u seconds...\n", seconds);
|
||||
time_t start = time(NULL);
|
||||
while((time_t)(time(NULL) - start) < (time_t)seconds) {
|
||||
/* Short timeout so an idle bus still lets us re-check the clock,
|
||||
* while a flooding bus is drained as fast as messages arrive. */
|
||||
icsneoc2_message_t* message = NULL;
|
||||
icsneoc2_error_t res = icsneoc2_device_message_get(device, &message, 50);
|
||||
if(res != icsneoc2_error_success)
|
||||
return res;
|
||||
if(message == NULL)
|
||||
continue;
|
||||
++total;
|
||||
icsneoc2_message_free(message);
|
||||
}
|
||||
printf("\tReceived %zu messages in %u seconds.\n", total, seconds);
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
printf("Opening first available device...\n");
|
||||
icsneoc2_device_t* device = NULL;
|
||||
icsneoc2_error_t res = icsneoc2_device_open_first(0, icsneoc2_open_options_default, &device);
|
||||
if(res != icsneoc2_error_success)
|
||||
return print_error_code("\tFailed to open first device", res);
|
||||
|
||||
char description[255] = {0};
|
||||
size_t description_length = sizeof(description);
|
||||
res = icsneoc2_device_description_get(device, description, &description_length);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_device_free(device);
|
||||
return print_error_code("\tFailed to get device description", res);
|
||||
}
|
||||
printf("\tOpened device: %s\n", description);
|
||||
|
||||
/* Pull the current settings down from the device before reading/modifying them. */
|
||||
res = icsneoc2_settings_refresh(device);
|
||||
if(res != icsneoc2_error_success)
|
||||
goto cleanup;
|
||||
|
||||
bool initial = false;
|
||||
res = icsneoc2_settings_perf_test_enabled_get(device, &initial);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_error_code("\tFailed to read initial PerfTest state (device may not support it)", res);
|
||||
goto cleanup;
|
||||
}
|
||||
printf("\tInitial PerfTest state: %s\n", initial ? "enabled" : "disabled");
|
||||
|
||||
printf("Enabling PerfTest...\n");
|
||||
res = set_and_verify_perf_test(device, true);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_error_code("\tFailed to enable PerfTest", res);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
res = read_messages_for(device, 3);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_error_code("\tFailed while reading messages", res);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
printf("Disabling PerfTest...\n");
|
||||
res = set_and_verify_perf_test(device, false);
|
||||
if(res != icsneoc2_error_success) {
|
||||
print_error_code("\tFailed to disable PerfTest", res);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
printf("PerfTest enable/read/disable cycle completed successfully.\n");
|
||||
|
||||
cleanup:
|
||||
icsneoc2_device_close(device);
|
||||
icsneoc2_device_free(device);
|
||||
return (int)res;
|
||||
}
|
||||
@@ -176,6 +176,7 @@ int process_message(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
// Print the type and bus type of each message
|
||||
size_t tx_count = 0;
|
||||
size_t can_error_count = 0;
|
||||
size_t internal_count = 0;
|
||||
icsneoc2_error_t res = icsneoc2_error_success;
|
||||
for(size_t i = 0; i < messages_count; i++) {
|
||||
icsneoc2_message_t* message = messages[i];
|
||||
@@ -216,13 +217,21 @@ int process_message(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// This example only cares about bus traffic, so skip internal
|
||||
// device/status messages.
|
||||
icsneoc2_network_type_t internal_check = icsneoc2_network_type_invalid;
|
||||
res = icsneoc2_message_network_type_get(message, &internal_check);
|
||||
if(res == icsneoc2_error_success && internal_check == icsneoc2_network_type_internal) {
|
||||
internal_count++;
|
||||
continue;
|
||||
}
|
||||
|
||||
bool is_frame = false;
|
||||
res = icsneoc2_message_is_frame(message, &is_frame);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to check if message is a frame", res);
|
||||
}
|
||||
if(!is_frame) {
|
||||
printf("Ignoring non-frame message at index %zu\n", i);
|
||||
continue;
|
||||
}
|
||||
icsneoc2_network_type_t network_type;
|
||||
@@ -244,6 +253,7 @@ int process_message(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
|
||||
printf("\t%zd) network type: %s (%u)\n", i, network_type_name, network_type);
|
||||
if(network_type == icsneoc2_network_type_can) {
|
||||
uint64_t timestamp = 0;
|
||||
uint64_t arbid = 0;
|
||||
int32_t dlc = 0;
|
||||
icsneoc2_netid_t netid = 0;
|
||||
@@ -256,6 +266,7 @@ int process_message(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
bool is_tx = false;
|
||||
icsneoc2_error_t result = icsneoc2_message_netid_get(message, &netid);
|
||||
result += icsneoc2_netid_name_get(netid, netid_name, &netid_name_length);
|
||||
result += icsneoc2_message_timestamp_get(message, ×tamp);
|
||||
result += icsneoc2_message_can_props_get(message, &arbid, &can_flags);
|
||||
result += icsneoc2_message_data_get(message, data, &data_length);
|
||||
result += icsneoc2_message_is_transmit(message, &is_tx);
|
||||
@@ -276,6 +287,7 @@ int process_message(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
dlc = (int32_t)data_length;
|
||||
|
||||
printf("\t %s%s\n", is_tx ? "TX" : "RX", is_error ? " [Error]" : "");
|
||||
printf("\t Timestamp: %" PRIu64 " ns since 2007-01-01 UTC\n", timestamp);
|
||||
printf("\t NetID: %s (0x%x)\tArbID: 0x%llx\tDLC: %u\tLen: %zu\n", netid_name, netid, (unsigned long long)arbid, dlc, data_length);
|
||||
printf("\t Flags:%s%s%s%s%s%s%s%s\n",
|
||||
is_remote ? " RTR" : "",
|
||||
@@ -293,7 +305,7 @@ int process_message(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
printf(" ]\n");
|
||||
}
|
||||
}
|
||||
printf("\tReceived %zu messages total, %zu were TX messages, %zu were CAN errors\n", messages_count, tx_count, can_error_count);
|
||||
printf("\tReceived %zu messages total, %zu were TX messages, %zu were CAN errors, %zu internal (skipped)\n", messages_count, tx_count, can_error_count, internal_count);
|
||||
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
@@ -359,6 +359,8 @@ int process_messages(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
// Print the type and bus type of each message
|
||||
size_t tx_count = 0;
|
||||
size_t can_error_count = 0;
|
||||
size_t app_error_count = 0;
|
||||
size_t internal_count = 0;
|
||||
for(size_t i = 0; i < messages_count; i++) {
|
||||
icsneoc2_message_t* message = messages[i];
|
||||
|
||||
@@ -392,13 +394,42 @@ int process_messages(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for application error messages
|
||||
bool is_app_error = false;
|
||||
res = icsneoc2_message_is_app_error(message, &is_app_error);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to check if message is an app error", res);
|
||||
}
|
||||
if(is_app_error) {
|
||||
icsneoc2_app_error_type_t error_type = icsneoc2_app_error_type_no_error;
|
||||
icsneoc2_netid_t error_netid = 0;
|
||||
char description[256] = {0};
|
||||
size_t description_length = sizeof(description);
|
||||
res = icsneoc2_message_app_error_props_get(message, &error_type, &error_netid);
|
||||
res += icsneoc2_message_app_error_string_get(message, description, &description_length);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to get app error properties", res);
|
||||
}
|
||||
printf("\t%zd) App Error (type %u) on netid 0x%x: %s\n", i, error_type, error_netid, description);
|
||||
app_error_count++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// This example only cares about bus traffic, so skip internal
|
||||
// device/status messages.
|
||||
icsneoc2_network_type_t internal_check = icsneoc2_network_type_invalid;
|
||||
res = icsneoc2_message_network_type_get(message, &internal_check);
|
||||
if(res == icsneoc2_error_success && internal_check == icsneoc2_network_type_internal) {
|
||||
internal_count++;
|
||||
continue;
|
||||
}
|
||||
|
||||
bool is_frame = false;
|
||||
res = icsneoc2_message_is_frame(message, &is_frame);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("\tFailed to check if message is a frame", res);
|
||||
}
|
||||
if(!is_frame) {
|
||||
printf("Ignoring non-frame message at index %zu\n", i);
|
||||
continue;
|
||||
}
|
||||
icsneoc2_network_type_t network_type;
|
||||
@@ -426,6 +457,7 @@ int process_messages(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
printf("\t%zd) network type: %s (%u)\n", i, network_type_name, network_type);
|
||||
|
||||
if(network_type == icsneoc2_network_type_can) {
|
||||
uint64_t timestamp = 0;
|
||||
uint64_t arbid = 0;
|
||||
int32_t dlc = 0;
|
||||
icsneoc2_netid_t netid = 0;
|
||||
@@ -436,6 +468,7 @@ int process_messages(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
size_t netid_name_length = 128;
|
||||
icsneoc2_error_t result = icsneoc2_message_netid_get(message, &netid);
|
||||
result += icsneoc2_netid_name_get(netid, netid_name, &netid_name_length);
|
||||
result += icsneoc2_message_timestamp_get(message, ×tamp);
|
||||
result += icsneoc2_message_can_props_get(message, &arbid, &can_flags);
|
||||
result += icsneoc2_message_data_get(message, data, &data_length);
|
||||
if(result != icsneoc2_error_success) {
|
||||
@@ -452,6 +485,7 @@ int process_messages(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
bool tx_error = (can_flags & ICSNEOC2_MESSAGE_CAN_FLAGS_TX_ERROR) != 0;
|
||||
dlc = (int32_t)data_length;
|
||||
|
||||
printf("\t Timestamp: %" PRIu64 " ns since 2007-01-01 UTC\n", timestamp);
|
||||
printf("\t NetID: %s (0x%x)\tArbID: 0x%llx\tDLC: %u\tLen: %zu\n", netid_name, netid, (unsigned long long)arbid, dlc, data_length);
|
||||
printf("\t Flags:%s%s%s%s%s%s%s%s\n",
|
||||
is_remote ? " RTR" : "",
|
||||
@@ -469,7 +503,7 @@ int process_messages(icsneoc2_message_t** messages, size_t messages_count) {
|
||||
printf(" ]\n");
|
||||
}
|
||||
}
|
||||
printf("\tReceived %zu messages total, %zu were TX messages, %zu were CAN errors\n", messages_count, tx_count, can_error_count);
|
||||
printf("\tReceived %zu messages total, %zu were TX messages, %zu were CAN errors, %zu were app errors, %zu internal (skipped)\n", messages_count, tx_count, can_error_count, app_error_count, internal_count);
|
||||
|
||||
return icsneoc2_error_success;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(libicsneoc2-supported-devices-example src/main.c)
|
||||
target_link_libraries(libicsneoc2-supported-devices-example icsneoc2-static)
|
||||
|
||||
if(WIN32)
|
||||
target_compile_definitions(libicsneoc2-supported-devices-example PRIVATE _CRT_SECURE_NO_WARNINGS)
|
||||
endif()
|
||||
@@ -0,0 +1,55 @@
|
||||
#include <icsneo/icsneoc2.h>
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
static int print_error_code(const char* message, icsneoc2_error_t error) {
|
||||
char error_str[64] = {0};
|
||||
size_t error_str_len = sizeof(error_str);
|
||||
icsneoc2_error_t res = icsneoc2_error_code_get(error, error_str, &error_str_len);
|
||||
if(res != icsneoc2_error_success) {
|
||||
printf("%s: failed to get string for error code %u\n", message, error);
|
||||
return (int)res;
|
||||
}
|
||||
printf("%s: %s (%u)\n", message, error_str, error);
|
||||
return (int)error;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
icsneoc2_supported_device_t* supported_devices = NULL;
|
||||
icsneoc2_error_t res = icsneoc2_supported_devices_enumerate(&supported_devices);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("Failed to enumerate supported devices", res);
|
||||
}
|
||||
|
||||
if(!supported_devices) {
|
||||
printf("No supported devices found.\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
printf("Supported devices:\n");
|
||||
for(icsneoc2_supported_device_t* cur = supported_devices; cur != NULL; cur = icsneoc2_supported_devices_next(cur)) {
|
||||
icsneoc2_devicetype_t device_type = 0;
|
||||
res = icsneoc2_supported_device_get(cur, &device_type);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_supported_devices_free(supported_devices);
|
||||
return print_error_code("Failed to get supported device type", res);
|
||||
}
|
||||
|
||||
char name[128] = {0};
|
||||
size_t name_len = sizeof(name);
|
||||
res = icsneoc2_device_type_name_get(device_type, name, &name_len);
|
||||
if(res != icsneoc2_error_success) {
|
||||
icsneoc2_supported_devices_free(supported_devices);
|
||||
return print_error_code("Failed to get supported device type name", res);
|
||||
}
|
||||
|
||||
printf(" %s (%u)\n", name, (unsigned int)device_type);
|
||||
}
|
||||
|
||||
res = icsneoc2_supported_devices_free(supported_devices);
|
||||
if(res != icsneoc2_error_success) {
|
||||
return print_error_code("Failed to free supported device list", res);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user