Remove sensors
These got their own repo, so delete it from here.
Change-Id: I97496393509b9a1dd69981b0995d915cc3529bef
Signed-off-by: James Feist <james.feist@linux.intel.com>
diff --git a/sensors/.clang-format b/sensors/.clang-format
deleted file mode 100644
index dd27708..0000000
--- a/sensors/.clang-format
+++ /dev/null
@@ -1,98 +0,0 @@
----
-Language: Cpp
-# BasedOnStyle: LLVM
-AccessModifierOffset: -2
-AlignAfterOpenBracket: Align
-AlignConsecutiveAssignments: false
-AlignConsecutiveDeclarations: false
-AlignEscapedNewlinesLeft: false
-AlignOperands: true
-AlignTrailingComments: true
-AllowAllParametersOfDeclarationOnNextLine: true
-AllowShortBlocksOnASingleLine: false
-AllowShortCaseLabelsOnASingleLine: false
-AllowShortFunctionsOnASingleLine: None
-AllowShortIfStatementsOnASingleLine: false
-AllowShortLoopsOnASingleLine: false
-AlwaysBreakAfterDefinitionReturnType: None
-AlwaysBreakAfterReturnType: None
-AlwaysBreakBeforeMultilineStrings: false
-AlwaysBreakTemplateDeclarations: false
-BinPackArguments: true
-BinPackParameters: true
-BraceWrapping:
- AfterClass: true
- AfterControlStatement: true
- AfterEnum: true
- AfterFunction: true
- AfterNamespace: true
- AfterObjCDeclaration: true
- AfterStruct: true
- AfterUnion: true
- BeforeCatch: true
- BeforeElse: true
- IndentBraces: false
-BreakBeforeBinaryOperators: None
-BreakBeforeBraces: Custom
-BreakBeforeTernaryOperators: true
-BreakConstructorInitializers: AfterColon
-ColumnLimit: 80
-CommentPragmas: '^ IWYU pragma:'
-ConstructorInitializerAllOnOneLineOrOnePerLine: false
-ConstructorInitializerIndentWidth: 4
-ContinuationIndentWidth: 4
-Cpp11BracedListStyle: true
-DerivePointerAlignment: true
-PointerAlignment: Left
-DisableFormat: false
-ExperimentalAutoDetectBinPacking: false
-FixNamespaceComments: true
-ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
-IncludeBlocks: Regroup
-IncludeCategories:
- - Regex: '^[<"](gtest|gmock)'
- Priority: 5
- - Regex: '^"config.h"'
- Priority: -1
- - Regex: '^".*\.hpp"'
- Priority: 1
- - Regex: '^<.*\.h>'
- Priority: 2
- - Regex: '^<.*'
- Priority: 3
- - Regex: '.*'
- Priority: 4
-IndentCaseLabels: true
-IndentWidth: 4
-IndentWrappedFunctionNames: true
-KeepEmptyLinesAtTheStartOfBlocks: true
-MacroBlockBegin: ''
-MacroBlockEnd: ''
-MaxEmptyLinesToKeep: 1
-NamespaceIndentation: None
-ObjCBlockIndentWidth: 2
-ObjCSpaceAfterProperty: false
-ObjCSpaceBeforeProtocolList: true
-PenaltyBreakBeforeFirstCallParameter: 19
-PenaltyBreakComment: 300
-PenaltyBreakFirstLessLess: 120
-PenaltyBreakString: 1000
-PenaltyExcessCharacter: 1000000
-PenaltyReturnTypeOnItsOwnLine: 60
-PointerAlignment: Right
-ReflowComments: true
-SortIncludes: true
-SpaceAfterCStyleCast: false
-SpaceBeforeAssignmentOperators: true
-SpaceBeforeParens: ControlStatements
-SpaceInEmptyParentheses: false
-SpacesBeforeTrailingComments: 1
-SpacesInAngles: false
-SpacesInContainerLiterals: true
-SpacesInCStyleCastParentheses: false
-SpacesInParentheses: false
-SpacesInSquareBrackets: false
-Standard: Cpp11
-TabWidth: 4
-UseTab: Never
-...
diff --git a/sensors/.gitignore b/sensors/.gitignore
deleted file mode 100644
index 4fa6dc2..0000000
--- a/sensors/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-build
-.vscode
-toolchain.cmake
diff --git a/sensors/CMakeLists.txt b/sensors/CMakeLists.txt
deleted file mode 100644
index a1c80e4..0000000
--- a/sensors/CMakeLists.txt
+++ /dev/null
@@ -1,125 +0,0 @@
-cmake_minimum_required (VERSION 2.8.10 FATAL_ERROR)
-set (BUILD_SHARED_LIBRARIES OFF)
-include (ExternalProject)
-set (CMAKE_CXX_STANDARD 17)
-set (CMAKE_CXX_STANDARD_REQUIRED ON)
-set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lstdc++fs")
-set (CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH})
-
-option (HUNTER_ENABLED "Enable hunter package pulling" OFF)
-include ("cmake/HunterGate.cmake")
-
-huntergate (URL "https://github.com/ruslo/hunter/archive/v0.18.64.tar.gz" SHA1
- "baf9c8cc4f65306f0e442b5419967b4c4c04589a")
-
-project (sensors CXX)
-
-set (FAN_SRC_FILES src/TachSensor.cpp src/PwmSensor.cpp src/Utils.cpp
- src/Thresholds.cpp)
-
-set (HWMON_TEMP_SRC_FILES src/Utils.cpp src/HwmonTempSensor.cpp
- src/Thresholds.cpp)
-
-set (CPU_SRC_FILES src/Utils.cpp src/CPUSensor.cpp src/Thresholds.cpp)
-
-set (ADC_SRC_FILES src/Utils.cpp src/ADCSensor.cpp src/Thresholds.cpp)
-
-set (EXTERNAL_PACKAGES Boost sdbusplus-project nlohmann-json)
-set (SENSOR_LINK_LIBS -lsystemd stdc++fs sdbusplus)
-
-option (EXTERNAL_PROJECT "Enable Cloning External Projects" OFF)
-if (EXTERNAL_PROJECT)
- option (ENABLE_TEST "Enable Google Test" OFF)
- include_directories (${CMAKE_CURRENT_SOURCE_DIR}/include/non-yocto)
-
- externalproject_add (
- Boost URL
- https://dl.bintray.com/boostorg/release/1.66.0/source/boost_1_66_0.tar.gz
- URL_MD5 d275cd85b00022313c171f602db59fc5 SOURCE_DIR
- "${CMAKE_BINARY_DIR}/boost-src" BINARY_DIR
- "${CMAKE_BINARY_DIR}/boost-build" CONFIGURE_COMMAND "" BUILD_COMMAND ""
- INSTALL_COMMAND ""
- )
- include_directories (${CMAKE_BINARY_DIR}/boost-src)
- set (CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR}/boost-src ${CMAKE_PREFIX_PATH})
-
- # requires apt install autoconf-archive and autoconf
- externalproject_add (sdbusplus-project PREFIX
- ${CMAKE_BINARY_DIR}/sdbusplus-project GIT_REPOSITORY
- https://github.com/openbmc/sdbusplus.git SOURCE_DIR
- ${CMAKE_BINARY_DIR}/sdbusplus-src BINARY_DIR
- ${CMAKE_BINARY_DIR}/sdbusplus-build CONFIGURE_COMMAND
- "" BUILD_COMMAND cd ${CMAKE_BINARY_DIR}/sdbusplus-src
- && ./bootstrap.sh && ./configure --enable-transaction
- && make -j libsdbusplus.la INSTALL_COMMAND ""
- LOG_DOWNLOAD ON)
- include_directories (${CMAKE_BINARY_DIR}/sdbusplus-src)
- link_directories (${CMAKE_BINARY_DIR}/sdbusplus-src/.libs)
-
- externalproject_add (nlohmann-json PREFIX
- ${CMAKE_CURRENT_BINARY_DIR}/nlohmann-json
- GIT_REPOSITORY https://github.com/nlohmann/json.git
- SOURCE_DIR ${CMAKE_BINARY_DIR}/nlohmann-json-src
- BINARY_DIR ${CMAKE_BINARY_DIR}/nlohmann-json-build
- CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND
- "" LOG_DOWNLOAD ON)
- include_directories (${CMAKE_BINARY_DIR}/nlohmann-json-src/include)
- if (ENABLE_TEST)
- option (HUNTER_ENABLED "Enable hunter package pulling" ON)
- hunter_add_package (GTest)
-
- find_package (GTest CONFIG REQUIRED)
-
- enable_testing ()
-
- add_executable (runTachTests tests/test_TachSensor.cpp ${FAN_SRC_FILES})
- add_test (NAME test_fansensor COMMAND runTachTests)
- target_link_libraries (runTachTests GTest::main GTest::gtest pthread
- ${DBUS_LIBRARIES} stdc++fs)
- add_dependencies (runTachTests nlohmann-json)
-
- add_executable (runHwmonTempTests tests/test_HwmonTempSensor.cpp
- ${HWMON_TEMP_SRC_FILES})
- add_test (NAME test_hwmontempsensor COMMAND runHwmonTempTests)
- target_link_libraries (runHwmonTempTests GTest::main GTest::gtest
- pthread ${DBUS_LIBRARIES} stdc++fs)
- add_dependencies (runHwmonTempTests nlohmann-json)
- endif ()
-
-endif ()
-
-add_definitions (-DBOOST_ERROR_CODE_HEADER_ONLY)
-add_definitions (-DBOOST_SYSTEM_NO_DEPRECATED)
-add_definitions (-DBOOST_ALL_NO_LIB)
-add_definitions (-DBOOST_NO_RTTI)
-add_definitions (-DBOOST_NO_TYPEID)
-add_definitions (-DBOOST_ASIO_DISABLE_THREADS)
-
-link_directories (${EXTERNAL_INSTALL_LOCATION}/lib)
-
-include_directories (${CMAKE_CURRENT_SOURCE_DIR}/include)
-
-add_executable (fansensor src/FanMain.cpp ${FAN_SRC_FILES})
-add_dependencies (fansensor sdbusplus)
-target_link_libraries (fansensor ${SENSOR_LINK_LIBS})
-
-add_executable (hwmontempsensor src/HwmonTempMain.cpp ${HWMON_TEMP_SRC_FILES})
-add_dependencies (hwmontempsensor sdbusplus)
-target_link_libraries (hwmontempsensor ${SENSOR_LINK_LIBS})
-
-add_executable (cpusensor src/CPUSensorMain.cpp ${CPU_SRC_FILES})
-add_dependencies (cpusensor sdbusplus)
-target_link_libraries (cpusensor ${SENSOR_LINK_LIBS})
-
-add_executable (adcsensor src/ADCSensorMain.cpp ${ADC_SRC_FILES})
-add_dependencies (adcsensor sdbusplus)
-target_link_libraries (adcsensor ${SENSOR_LINK_LIBS})
-
-if (EXTERNAL_PROJECT)
- add_dependencies (fansensor ${EXTERNAL_PACKAGES})
- add_dependencies (hwmontempsensor ${EXTERNAL_PACKAGES})
- add_dependencies (adcsensor ${EXTERNAL_PACKAGES})
- add_dependencies (cpusensor ${EXTERNAL_PACKAGES})
-endif ()
-
-install (TARGETS fansensor hwmontempsensor cpusensor adcsensor DESTINATION bin)
diff --git a/sensors/Jenkinsfile b/sensors/Jenkinsfile
deleted file mode 100644
index c4f6c7a..0000000
--- a/sensors/Jenkinsfile
+++ /dev/null
@@ -1,26 +0,0 @@
-#!groovy
-
-
-stage 'Debug Build'
- sh '''
- rm -rf build_debug
- mkdir build_debug
- cd build_debug
- cmake .. -DCMAKE_BUILD_TYPE="Debug" -DHUNTER_ENABLED=1 -DEXTERNAL_PROJECT=1
- cmake --build .'''
-
-stage 'Debug Test'
- sh '''cd build_debug
- dbus-launch ctest -V --output-on-failure'''
-
-stage 'Release Build'
- sh '''
- rm -rf build_release
- mkdir build_release
- cd build_release
- cmake .. -DCMAKE_BUILD_TYPE="Release" -DHUNTER_ENABLED=1 -DEXTERNAL_PROJECT=1
- cmake --build .'''
-
-stage 'Release Test'
- sh '''cd build_release
- dbus-launch ctest -V --output-on-failure'''
diff --git a/sensors/cmake-format.json b/sensors/cmake-format.json
deleted file mode 100644
index 4a68fb7..0000000
--- a/sensors/cmake-format.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "enum_char": ".",
- "line_ending": "unix",
- "bullet_char": "*",
- "max_subargs_per_line": 99,
- "command_case": "lower",
- "tab_size": 4,
- "line_width": 80,
- "separate_fn_name_with_space": true,
- "dangle_parens": true,
- "separate_ctrl_name_with_space": true
-}
-
diff --git a/sensors/cmake/Finddbus.cmake b/sensors/cmake/Finddbus.cmake
deleted file mode 100644
index 2d8eea2..0000000
--- a/sensors/cmake/Finddbus.cmake
+++ /dev/null
@@ -1,61 +0,0 @@
-# - Try to find DBus
-# Once done, this will define
-#
-# DBUS_FOUND - system has DBus
-# DBUS_INCLUDE_DIRS - the DBus include directories
-# DBUS_LIBRARIES - link these to use DBus
-#
-# Copyright (C) 2012 Raphael Kubo da Costa <rakuco@webkit.org>
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-# 1. Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# 2. Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND ITS CONTRIBUTORS ``AS
-# IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
-# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ITS
-# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-FIND_PACKAGE(PkgConfig)
-PKG_CHECK_MODULES(PC_DBUS QUIET dbus-1)
-
-FIND_LIBRARY(DBUS_LIBRARIES
- NAMES dbus-1
- HINTS ${PC_DBUS_LIBDIR}
- ${PC_DBUS_LIBRARY_DIRS}
-)
-
-message("DBUS_LIBRARIES = ${DBUS_LIBRARIES}")
-
-FIND_PATH(DBUS_INCLUDE_DIR
- NAMES dbus/dbus.h
- HINTS ${PC_DBUS_INCLUDEDIR}
- ${PC_DBUS_INCLUDE_DIRS}
-)
-
-GET_FILENAME_COMPONENT(_DBUS_LIBRARY_DIR ${DBUS_LIBRARIES} PATH)
-FIND_PATH(DBUS_ARCH_INCLUDE_DIR
- NAMES dbus/dbus-arch-deps.h
- HINTS ${PC_DBUS_INCLUDEDIR}
- ${PC_DBUS_INCLUDE_DIRS}
- ${_DBUS_LIBRARY_DIR}
- ${DBUS_INCLUDE_DIR}
- PATH_SUFFIXES include
-)
-
-SET(DBUS_INCLUDE_DIRS ${DBUS_INCLUDE_DIR} ${DBUS_ARCH_INCLUDE_DIR})
-
-INCLUDE(FindPackageHandleStandardArgs)
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(DBUS REQUIRED_VARS DBUS_INCLUDE_DIRS DBUS_LIBRARIES)
diff --git a/sensors/cmake/HunterGate.cmake b/sensors/cmake/HunterGate.cmake
deleted file mode 100644
index 97f69cc..0000000
--- a/sensors/cmake/HunterGate.cmake
+++ /dev/null
@@ -1,514 +0,0 @@
-# Copyright (c) 2013-2015, Ruslan Baratov
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following disclaimer in the documentation
-# and/or other materials provided with the distribution.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-# This is a gate file to Hunter package manager.
-# Include this file using `include` command and add package you need, example:
-#
-# cmake_minimum_required(VERSION 3.0)
-#
-# include("cmake/HunterGate.cmake")
-# HunterGate(
-# URL "https://github.com/path/to/hunter/archive.tar.gz"
-# SHA1 "798501e983f14b28b10cda16afa4de69eee1da1d"
-# )
-#
-# project(MyProject)
-#
-# hunter_add_package(Foo)
-# hunter_add_package(Boo COMPONENTS Bar Baz)
-#
-# Projects:
-# * https://github.com/hunter-packages/gate/
-# * https://github.com/ruslo/hunter
-
-option(HUNTER_ENABLED "Enable Hunter package manager support" ON)
-if(HUNTER_ENABLED)
- if(CMAKE_VERSION VERSION_LESS "3.0")
- message(FATAL_ERROR "At least CMake version 3.0 required for hunter dependency management."
- " Update CMake or set HUNTER_ENABLED to OFF.")
- endif()
-endif()
-
-include(CMakeParseArguments) # cmake_parse_arguments
-
-option(HUNTER_STATUS_PRINT "Print working status" ON)
-option(HUNTER_STATUS_DEBUG "Print a lot info" OFF)
-
-set(HUNTER_WIKI "https://github.com/ruslo/hunter/wiki")
-
-function(hunter_gate_status_print)
- foreach(print_message ${ARGV})
- if(HUNTER_STATUS_PRINT OR HUNTER_STATUS_DEBUG)
- message(STATUS "[hunter] ${print_message}")
- endif()
- endforeach()
-endfunction()
-
-function(hunter_gate_status_debug)
- foreach(print_message ${ARGV})
- if(HUNTER_STATUS_DEBUG)
- string(TIMESTAMP timestamp)
- message(STATUS "[hunter *** DEBUG *** ${timestamp}] ${print_message}")
- endif()
- endforeach()
-endfunction()
-
-function(hunter_gate_wiki wiki_page)
- message("------------------------------ WIKI -------------------------------")
- message(" ${HUNTER_WIKI}/${wiki_page}")
- message("-------------------------------------------------------------------")
- message("")
- message(FATAL_ERROR "")
-endfunction()
-
-function(hunter_gate_internal_error)
- message("")
- foreach(print_message ${ARGV})
- message("[hunter ** INTERNAL **] ${print_message}")
- endforeach()
- message("[hunter ** INTERNAL **] [Directory:${CMAKE_CURRENT_LIST_DIR}]")
- message("")
- hunter_gate_wiki("error.internal")
-endfunction()
-
-function(hunter_gate_fatal_error)
- cmake_parse_arguments(hunter "" "WIKI" "" "${ARGV}")
- string(COMPARE EQUAL "${hunter_WIKI}" "" have_no_wiki)
- if(have_no_wiki)
- hunter_gate_internal_error("Expected wiki")
- endif()
- message("")
- foreach(x ${hunter_UNPARSED_ARGUMENTS})
- message("[hunter ** FATAL ERROR **] ${x}")
- endforeach()
- message("[hunter ** FATAL ERROR **] [Directory:${CMAKE_CURRENT_LIST_DIR}]")
- message("")
- hunter_gate_wiki("${hunter_WIKI}")
-endfunction()
-
-function(hunter_gate_user_error)
- hunter_gate_fatal_error(${ARGV} WIKI "error.incorrect.input.data")
-endfunction()
-
-function(hunter_gate_self root version sha1 result)
- string(COMPARE EQUAL "${root}" "" is_bad)
- if(is_bad)
- hunter_gate_internal_error("root is empty")
- endif()
-
- string(COMPARE EQUAL "${version}" "" is_bad)
- if(is_bad)
- hunter_gate_internal_error("version is empty")
- endif()
-
- string(COMPARE EQUAL "${sha1}" "" is_bad)
- if(is_bad)
- hunter_gate_internal_error("sha1 is empty")
- endif()
-
- string(SUBSTRING "${sha1}" 0 7 archive_id)
-
- if(EXISTS "${root}/cmake/Hunter")
- set(hunter_self "${root}")
- else()
- set(
- hunter_self
- "${root}/_Base/Download/Hunter/${version}/${archive_id}/Unpacked"
- )
- endif()
-
- set("${result}" "${hunter_self}" PARENT_SCOPE)
-endfunction()
-
-# Set HUNTER_GATE_ROOT cmake variable to suitable value.
-function(hunter_gate_detect_root)
- # Check CMake variable
- string(COMPARE NOTEQUAL "${HUNTER_ROOT}" "" not_empty)
- if(not_empty)
- set(HUNTER_GATE_ROOT "${HUNTER_ROOT}" PARENT_SCOPE)
- hunter_gate_status_debug("HUNTER_ROOT detected by cmake variable")
- return()
- endif()
-
- # Check environment variable
- string(COMPARE NOTEQUAL "$ENV{HUNTER_ROOT}" "" not_empty)
- if(not_empty)
- set(HUNTER_GATE_ROOT "$ENV{HUNTER_ROOT}" PARENT_SCOPE)
- hunter_gate_status_debug("HUNTER_ROOT detected by environment variable")
- return()
- endif()
-
- # Check HOME environment variable
- string(COMPARE NOTEQUAL "$ENV{HOME}" "" result)
- if(result)
- set(HUNTER_GATE_ROOT "$ENV{HOME}/.hunter" PARENT_SCOPE)
- hunter_gate_status_debug("HUNTER_ROOT set using HOME environment variable")
- return()
- endif()
-
- # Check SYSTEMDRIVE and USERPROFILE environment variable (windows only)
- if(WIN32)
- string(COMPARE NOTEQUAL "$ENV{SYSTEMDRIVE}" "" result)
- if(result)
- set(HUNTER_GATE_ROOT "$ENV{SYSTEMDRIVE}/.hunter" PARENT_SCOPE)
- hunter_gate_status_debug(
- "HUNTER_ROOT set using SYSTEMDRIVE environment variable"
- )
- return()
- endif()
-
- string(COMPARE NOTEQUAL "$ENV{USERPROFILE}" "" result)
- if(result)
- set(HUNTER_GATE_ROOT "$ENV{USERPROFILE}/.hunter" PARENT_SCOPE)
- hunter_gate_status_debug(
- "HUNTER_ROOT set using USERPROFILE environment variable"
- )
- return()
- endif()
- endif()
-
- hunter_gate_fatal_error(
- "Can't detect HUNTER_ROOT"
- WIKI "error.detect.hunter.root"
- )
-endfunction()
-
-macro(hunter_gate_lock dir)
- if(NOT HUNTER_SKIP_LOCK)
- if("${CMAKE_VERSION}" VERSION_LESS "3.2")
- hunter_gate_fatal_error(
- "Can't lock, upgrade to CMake 3.2 or use HUNTER_SKIP_LOCK"
- WIKI "error.can.not.lock"
- )
- endif()
- hunter_gate_status_debug("Locking directory: ${dir}")
- file(LOCK "${dir}" DIRECTORY GUARD FUNCTION)
- hunter_gate_status_debug("Lock done")
- endif()
-endmacro()
-
-function(hunter_gate_download dir)
- string(
- COMPARE
- NOTEQUAL
- "$ENV{HUNTER_DISABLE_AUTOINSTALL}"
- ""
- disable_autoinstall
- )
- if(disable_autoinstall AND NOT HUNTER_RUN_INSTALL)
- hunter_gate_fatal_error(
- "Hunter not found in '${dir}'"
- "Set HUNTER_RUN_INSTALL=ON to auto-install it from '${HUNTER_GATE_URL}'"
- "Settings:"
- " HUNTER_ROOT: ${HUNTER_GATE_ROOT}"
- " HUNTER_SHA1: ${HUNTER_GATE_SHA1}"
- WIKI "error.run.install"
- )
- endif()
- string(COMPARE EQUAL "${dir}" "" is_bad)
- if(is_bad)
- hunter_gate_internal_error("Empty 'dir' argument")
- endif()
-
- string(COMPARE EQUAL "${HUNTER_GATE_SHA1}" "" is_bad)
- if(is_bad)
- hunter_gate_internal_error("HUNTER_GATE_SHA1 empty")
- endif()
-
- string(COMPARE EQUAL "${HUNTER_GATE_URL}" "" is_bad)
- if(is_bad)
- hunter_gate_internal_error("HUNTER_GATE_URL empty")
- endif()
-
- set(done_location "${dir}/DONE")
- set(sha1_location "${dir}/SHA1")
-
- set(build_dir "${dir}/Build")
- set(cmakelists "${dir}/CMakeLists.txt")
-
- hunter_gate_lock("${dir}")
- if(EXISTS "${done_location}")
- # while waiting for lock other instance can do all the job
- hunter_gate_status_debug("File '${done_location}' found, skip install")
- return()
- endif()
-
- file(REMOVE_RECURSE "${build_dir}")
- file(REMOVE_RECURSE "${cmakelists}")
-
- file(MAKE_DIRECTORY "${build_dir}") # check directory permissions
-
- # Disabling languages speeds up a little bit, reduces noise in the output
- # and avoids path too long windows error
- file(
- WRITE
- "${cmakelists}"
- "cmake_minimum_required(VERSION 3.0)\n"
- "project(HunterDownload LANGUAGES NONE)\n"
- "include(ExternalProject)\n"
- "ExternalProject_Add(\n"
- " Hunter\n"
- " URL\n"
- " \"${HUNTER_GATE_URL}\"\n"
- " URL_HASH\n"
- " SHA1=${HUNTER_GATE_SHA1}\n"
- " DOWNLOAD_DIR\n"
- " \"${dir}\"\n"
- " SOURCE_DIR\n"
- " \"${dir}/Unpacked\"\n"
- " CONFIGURE_COMMAND\n"
- " \"\"\n"
- " BUILD_COMMAND\n"
- " \"\"\n"
- " INSTALL_COMMAND\n"
- " \"\"\n"
- ")\n"
- )
-
- if(HUNTER_STATUS_DEBUG)
- set(logging_params "")
- else()
- set(logging_params OUTPUT_QUIET)
- endif()
-
- hunter_gate_status_debug("Run generate")
-
- # Need to add toolchain file too.
- # Otherwise on Visual Studio + MDD this will fail with error:
- # "Could not find an appropriate version of the Windows 10 SDK installed on this machine"
- if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
- set(toolchain_arg "-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}")
- else()
- # 'toolchain_arg' can't be empty
- set(toolchain_arg "-DCMAKE_TOOLCHAIN_FILE=")
- endif()
-
- execute_process(
- COMMAND "${CMAKE_COMMAND}" "-H${dir}" "-B${build_dir}" "-G${CMAKE_GENERATOR}" "${toolchain_arg}"
- WORKING_DIRECTORY "${dir}"
- RESULT_VARIABLE download_result
- ${logging_params}
- )
-
- if(NOT download_result EQUAL 0)
- hunter_gate_internal_error("Configure project failed")
- endif()
-
- hunter_gate_status_print(
- "Initializing Hunter workspace (${HUNTER_GATE_SHA1})"
- " ${HUNTER_GATE_URL}"
- " -> ${dir}"
- )
- execute_process(
- COMMAND "${CMAKE_COMMAND}" --build "${build_dir}"
- WORKING_DIRECTORY "${dir}"
- RESULT_VARIABLE download_result
- ${logging_params}
- )
-
- if(NOT download_result EQUAL 0)
- hunter_gate_internal_error("Build project failed")
- endif()
-
- file(REMOVE_RECURSE "${build_dir}")
- file(REMOVE_RECURSE "${cmakelists}")
-
- file(WRITE "${sha1_location}" "${HUNTER_GATE_SHA1}")
- file(WRITE "${done_location}" "DONE")
-
- hunter_gate_status_debug("Finished")
-endfunction()
-
-# Must be a macro so master file 'cmake/Hunter' can
-# apply all variables easily just by 'include' command
-# (otherwise PARENT_SCOPE magic needed)
-macro(HunterGate)
- if(HUNTER_GATE_DONE)
- # variable HUNTER_GATE_DONE set explicitly for external project
- # (see `hunter_download`)
- set_property(GLOBAL PROPERTY HUNTER_GATE_DONE YES)
- endif()
-
- # First HunterGate command will init Hunter, others will be ignored
- get_property(_hunter_gate_done GLOBAL PROPERTY HUNTER_GATE_DONE SET)
-
- if(NOT HUNTER_ENABLED)
- # Empty function to avoid error "unknown function"
- function(hunter_add_package)
- endfunction()
- elseif(_hunter_gate_done)
- hunter_gate_status_debug("Secondary HunterGate (use old settings)")
- hunter_gate_self(
- "${HUNTER_CACHED_ROOT}"
- "${HUNTER_VERSION}"
- "${HUNTER_SHA1}"
- _hunter_self
- )
- include("${_hunter_self}/cmake/Hunter")
- else()
- set(HUNTER_GATE_LOCATION "${CMAKE_CURRENT_LIST_DIR}")
-
- string(COMPARE NOTEQUAL "${PROJECT_NAME}" "" _have_project_name)
- if(_have_project_name)
- hunter_gate_fatal_error(
- "Please set HunterGate *before* 'project' command. "
- "Detected project: ${PROJECT_NAME}"
- WIKI "error.huntergate.before.project"
- )
- endif()
-
- cmake_parse_arguments(
- HUNTER_GATE "LOCAL" "URL;SHA1;GLOBAL;FILEPATH" "" ${ARGV}
- )
-
- string(COMPARE EQUAL "${HUNTER_GATE_SHA1}" "" _empty_sha1)
- string(COMPARE EQUAL "${HUNTER_GATE_URL}" "" _empty_url)
- string(
- COMPARE
- NOTEQUAL
- "${HUNTER_GATE_UNPARSED_ARGUMENTS}"
- ""
- _have_unparsed
- )
- string(COMPARE NOTEQUAL "${HUNTER_GATE_GLOBAL}" "" _have_global)
- string(COMPARE NOTEQUAL "${HUNTER_GATE_FILEPATH}" "" _have_filepath)
-
- if(_have_unparsed)
- hunter_gate_user_error(
- "HunterGate unparsed arguments: ${HUNTER_GATE_UNPARSED_ARGUMENTS}"
- )
- endif()
- if(_empty_sha1)
- hunter_gate_user_error("SHA1 suboption of HunterGate is mandatory")
- endif()
- if(_empty_url)
- hunter_gate_user_error("URL suboption of HunterGate is mandatory")
- endif()
- if(_have_global)
- if(HUNTER_GATE_LOCAL)
- hunter_gate_user_error("Unexpected LOCAL (already has GLOBAL)")
- endif()
- if(_have_filepath)
- hunter_gate_user_error("Unexpected FILEPATH (already has GLOBAL)")
- endif()
- endif()
- if(HUNTER_GATE_LOCAL)
- if(_have_global)
- hunter_gate_user_error("Unexpected GLOBAL (already has LOCAL)")
- endif()
- if(_have_filepath)
- hunter_gate_user_error("Unexpected FILEPATH (already has LOCAL)")
- endif()
- endif()
- if(_have_filepath)
- if(_have_global)
- hunter_gate_user_error("Unexpected GLOBAL (already has FILEPATH)")
- endif()
- if(HUNTER_GATE_LOCAL)
- hunter_gate_user_error("Unexpected LOCAL (already has FILEPATH)")
- endif()
- endif()
-
- hunter_gate_detect_root() # set HUNTER_GATE_ROOT
-
- # Beautify path, fix probable problems with windows path slashes
- get_filename_component(
- HUNTER_GATE_ROOT "${HUNTER_GATE_ROOT}" ABSOLUTE
- )
- hunter_gate_status_debug("HUNTER_ROOT: ${HUNTER_GATE_ROOT}")
- if(NOT HUNTER_ALLOW_SPACES_IN_PATH)
- string(FIND "${HUNTER_GATE_ROOT}" " " _contain_spaces)
- if(NOT _contain_spaces EQUAL -1)
- hunter_gate_fatal_error(
- "HUNTER_ROOT (${HUNTER_GATE_ROOT}) contains spaces."
- "Set HUNTER_ALLOW_SPACES_IN_PATH=ON to skip this error"
- "(Use at your own risk!)"
- WIKI "error.spaces.in.hunter.root"
- )
- endif()
- endif()
-
- string(
- REGEX
- MATCH
- "[0-9]+\\.[0-9]+\\.[0-9]+[-_a-z0-9]*"
- HUNTER_GATE_VERSION
- "${HUNTER_GATE_URL}"
- )
- string(COMPARE EQUAL "${HUNTER_GATE_VERSION}" "" _is_empty)
- if(_is_empty)
- set(HUNTER_GATE_VERSION "unknown")
- endif()
-
- hunter_gate_self(
- "${HUNTER_GATE_ROOT}"
- "${HUNTER_GATE_VERSION}"
- "${HUNTER_GATE_SHA1}"
- _hunter_self
- )
-
- set(_master_location "${_hunter_self}/cmake/Hunter")
- if(EXISTS "${HUNTER_GATE_ROOT}/cmake/Hunter")
- # Hunter downloaded manually (e.g. by 'git clone')
- set(_unused "xxxxxxxxxx")
- set(HUNTER_GATE_SHA1 "${_unused}")
- set(HUNTER_GATE_VERSION "${_unused}")
- else()
- get_filename_component(_archive_id_location "${_hunter_self}/.." ABSOLUTE)
- set(_done_location "${_archive_id_location}/DONE")
- set(_sha1_location "${_archive_id_location}/SHA1")
-
- # Check Hunter already downloaded by HunterGate
- if(NOT EXISTS "${_done_location}")
- hunter_gate_download("${_archive_id_location}")
- endif()
-
- if(NOT EXISTS "${_done_location}")
- hunter_gate_internal_error("hunter_gate_download failed")
- endif()
-
- if(NOT EXISTS "${_sha1_location}")
- hunter_gate_internal_error("${_sha1_location} not found")
- endif()
- file(READ "${_sha1_location}" _sha1_value)
- string(COMPARE EQUAL "${_sha1_value}" "${HUNTER_GATE_SHA1}" _is_equal)
- if(NOT _is_equal)
- hunter_gate_internal_error(
- "Short SHA1 collision:"
- " ${_sha1_value} (from ${_sha1_location})"
- " ${HUNTER_GATE_SHA1} (HunterGate)"
- )
- endif()
- if(NOT EXISTS "${_master_location}")
- hunter_gate_user_error(
- "Master file not found:"
- " ${_master_location}"
- "try to update Hunter/HunterGate"
- )
- endif()
- endif()
- include("${_master_location}")
- set_property(GLOBAL PROPERTY HUNTER_GATE_DONE YES)
- endif()
-endmacro()
\ No newline at end of file
diff --git a/sensors/include/ADCSensor.hpp b/sensors/include/ADCSensor.hpp
deleted file mode 100644
index 59b4450..0000000
--- a/sensors/include/ADCSensor.hpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#pragma once
-
-#include <Thresholds.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-#include <sensor.hpp>
-
-class ADCSensor : public Sensor
-{
- public:
- std::string configuration;
- ADCSensor(const std::string &path,
- sdbusplus::asio::object_server &objectServer,
- std::shared_ptr<sdbusplus::asio::connection> &conn,
- boost::asio::io_service &io, const std::string &sensorName,
- std::vector<thresholds::Threshold> &&thresholds,
- const double scaleFactor, const std::string &sensorConfiguration);
- ~ADCSensor();
-
- private:
- sdbusplus::asio::object_server &objServer;
- boost::asio::posix::stream_descriptor inputDev;
- boost::asio::deadline_timer waitTimer;
- boost::asio::streambuf readBuf;
- int errCount;
- double maxValue;
- double minValue;
- double scaleFactor;
- void setupRead(void);
- void handleResponse(const boost::system::error_code &err);
- void checkThresholds(void);
- void updateValue(const double &newValue);
-
- void setInitialProperties(
- std::shared_ptr<sdbusplus::asio::connection> &conn);
-};
diff --git a/sensors/include/CPUSensor.hpp b/sensors/include/CPUSensor.hpp
deleted file mode 100644
index 41cc02f..0000000
--- a/sensors/include/CPUSensor.hpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#pragma once
-
-#include <Thresholds.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-#include <sensor.hpp>
-
-class CPUSensor : public Sensor
-{
- public:
- std::string configuration;
- CPUSensor(const std::string &path, const std::string &objectType,
- sdbusplus::asio::object_server &objectServer,
- std::shared_ptr<sdbusplus::asio::connection> &conn,
- boost::asio::io_service &io, const std::string &fanName,
- std::vector<thresholds::Threshold> &&thresholds,
- const std::string &configuration);
- ~CPUSensor();
- static constexpr unsigned int sensorScaleFactor = 1000;
- static constexpr unsigned int sensorPollMs = 1000;
-
- private:
- std::string objectType;
- sdbusplus::asio::object_server &objServer;
- std::shared_ptr<sdbusplus::asio::connection> dbusConnection;
- boost::asio::posix::stream_descriptor inputDev;
- boost::asio::deadline_timer waitTimer;
- boost::asio::streambuf readBuf;
- int errCount;
- double maxValue;
- double minValue;
- void setupRead(void);
- void handleResponse(const boost::system::error_code &err);
- void checkThresholds(void);
- void updateValue(const double &newValue);
-
- void setInitialProperties(
- std::shared_ptr<sdbusplus::asio::connection> &conn);
-};
diff --git a/sensors/include/HwmonTempSensor.hpp b/sensors/include/HwmonTempSensor.hpp
deleted file mode 100644
index 117f286..0000000
--- a/sensors/include/HwmonTempSensor.hpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#pragma once
-
-#include <Thresholds.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-#include <sensor.hpp>
-
-class HwmonTempSensor : public Sensor
-{
- public:
- std::string configuration;
- HwmonTempSensor(const std::string &path, const std::string &objectType,
- sdbusplus::asio::object_server &objectServer,
- std::shared_ptr<sdbusplus::asio::connection> &conn,
- boost::asio::io_service &io, const std::string &fanName,
- std::vector<thresholds::Threshold> &&thresholds,
- const std::string &sensorConfiguration);
- ~HwmonTempSensor();
-
- private:
- std::string objectType;
- sdbusplus::asio::object_server &objServer;
- boost::asio::posix::stream_descriptor inputDev;
- boost::asio::deadline_timer waitTimer;
- boost::asio::streambuf readBuf;
- int errCount;
- double maxValue;
- double minValue;
- void setupRead(void);
- void handleResponse(const boost::system::error_code &err);
- void checkThresholds(void);
- void updateValue(const double &newValue);
-
- void setInitialProperties(
- std::shared_ptr<sdbusplus::asio::connection> &conn);
-};
\ No newline at end of file
diff --git a/sensors/include/PwmSensor.hpp b/sensors/include/PwmSensor.hpp
deleted file mode 100644
index 0a712fb..0000000
--- a/sensors/include/PwmSensor.hpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#pragma once
-
-#include <sdbusplus/asio/object_server.hpp>
-
-class PwmSensor
-{
- public:
- PwmSensor(const std::string& sysPath,
- sdbusplus::asio::object_server& objectServer);
- ~PwmSensor();
-
- private:
- std::string sysPath;
- sdbusplus::asio::object_server& objectServer;
- std::string name;
- std::shared_ptr<sdbusplus::asio::dbus_interface> sensorInterface;
- std::shared_ptr<sdbusplus::asio::dbus_interface> controlInterface;
- void setValue(uint32_t value);
- uint32_t getValue(bool errThrow = true);
-};
diff --git a/sensors/include/TachSensor.hpp b/sensors/include/TachSensor.hpp
deleted file mode 100644
index 36e3eaa..0000000
--- a/sensors/include/TachSensor.hpp
+++ /dev/null
@@ -1,77 +0,0 @@
-#pragma once
-
-#include <Thresholds.hpp>
-#include <boost/container/flat_map.hpp>
-#include <boost/container/flat_set.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-#include <sensor.hpp>
-
-constexpr const char *gpioPath = "/sys/class/gpio/";
-class PresenceSensor
-{
-
- public:
- PresenceSensor(const size_t index, bool inverted,
- boost::asio::io_service &io);
- ~PresenceSensor();
-
- void monitorPresence(void);
- void read(void);
- bool getValue(void);
-
- private:
- bool status = true;
- bool inverted;
- boost::asio::ip::tcp::socket inputDev;
- int fd;
-};
-
-class RedundancySensor
-{
- public:
- RedundancySensor(size_t count, const std::vector<std::string> &children,
- sdbusplus::asio::object_server &objectServer);
- ~RedundancySensor();
-
- void update(const std::string &name, bool failed);
-
- private:
- size_t count;
- std::shared_ptr<sdbusplus::asio::dbus_interface> iface;
- sdbusplus::asio::object_server &objectServer;
- boost::container::flat_map<std::string, bool> statuses;
-};
-
-class TachSensor : public Sensor
-{
- public:
- std::string configuration;
- TachSensor(const std::string &path,
- sdbusplus::asio::object_server &objectServer,
- std::shared_ptr<sdbusplus::asio::connection> &conn,
- std::unique_ptr<PresenceSensor> &&presence,
- std::unique_ptr<RedundancySensor> &redundancy,
- boost::asio::io_service &io, const std::string &fanName,
- std::vector<thresholds::Threshold> &&thresholds,
- const std::string &sensorConfiguration);
- ~TachSensor();
-
- private:
- sdbusplus::asio::object_server &objServer;
- std::unique_ptr<RedundancySensor> &redundancy;
- std::shared_ptr<sdbusplus::asio::connection> dbusConnection;
- std::unique_ptr<PresenceSensor> presence;
- boost::asio::posix::stream_descriptor inputDev;
- boost::asio::deadline_timer waitTimer;
- boost::asio::streambuf readBuf;
- int errCount;
- double maxValue;
- double minValue;
- void setupRead(void);
- void handleResponse(const boost::system::error_code &err);
- void checkThresholds(void);
- void updateValue(const double &newValue);
-
- void setInitialProperties(
- std::shared_ptr<sdbusplus::asio::connection> &conn);
-};
diff --git a/sensors/include/Thresholds.hpp b/sensors/include/Thresholds.hpp
deleted file mode 100644
index 3f9aa79..0000000
--- a/sensors/include/Thresholds.hpp
+++ /dev/null
@@ -1,55 +0,0 @@
-#pragma once
-#include <Utils.hpp>
-#include <nlohmann/json.hpp>
-
-struct Sensor;
-namespace thresholds
-{
-enum Level
-{
- WARNING,
- CRITICAL
-};
-enum Direction
-{
- HIGH,
- LOW
-};
-struct Threshold
-{
- Threshold(const Level &lev, const Direction &dir, const double &val,
- bool write = true) :
- level(lev),
- direction(dir), value(val), writeable(write)
- {
- }
- Level level;
- Direction direction;
- double value;
- bool writeable;
- bool asserted = false;
-};
-
-bool parseThresholdsFromConfig(
- const SensorData &sensorData,
- std::vector<thresholds::Threshold> &thresholdVector,
- const std::string *matchLabel = nullptr);
-
-bool parseThresholdsFromAttr(std::vector<thresholds::Threshold> &thresholds,
- const std::string &inputPath,
- const double &scaleFactor);
-bool hasCriticalInterface(
- const std::vector<thresholds::Threshold> &thresholdVector);
-
-bool hasWarningInterface(
- const std::vector<thresholds::Threshold> &thresholdVector);
-
-void persistThreshold(const std::string &baseInterface, const std::string &path,
- const thresholds::Threshold &threshold,
- std::shared_ptr<sdbusplus::asio::connection> &conn);
-
-// returns false if a critical threshold has been crossed, true otherwise
-bool checkThresholds(Sensor *sensor);
-void assertThresholds(Sensor *sensor, thresholds::Level level,
- thresholds::Direction direction, bool assert);
-} // namespace thresholds
diff --git a/sensors/include/Utils.hpp b/sensors/include/Utils.hpp
deleted file mode 100644
index 8d9eac5..0000000
--- a/sensors/include/Utils.hpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#pragma once
-#include <boost/container/flat_map.hpp>
-#include <experimental/filesystem>
-#include <iostream>
-#include <regex>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/message/types.hpp>
-
-const constexpr char* jsonStore = "/var/configuration/flattened.json";
-const constexpr char* inventoryPath = "/xyz/openbmc_project/inventory";
-const constexpr char* entityManagerName = "xyz.openbmc_project.EntityManager";
-const std::regex illegalDbusRegex("[^A-Za-z0-9_]");
-
-using BasicVariantType =
- sdbusplus::message::variant<std::string, int64_t, uint64_t, double, int32_t,
- uint32_t, int16_t, uint16_t, uint8_t, bool>;
-
-using ManagedObjectType = boost::container::flat_map<
- sdbusplus::message::object_path,
- boost::container::flat_map<
- std::string,
- boost::container::flat_map<std::string, BasicVariantType>>>;
-using SensorData = boost::container::flat_map<
- std::string, boost::container::flat_map<std::string, BasicVariantType>>;
-
-bool findFiles(const std::experimental::filesystem::path dirPath,
- const std::string& matchString,
- std::vector<std::experimental::filesystem::path>& foundPaths,
- unsigned int symlinkDepth = 1);
-bool isPowerOn(const std::shared_ptr<sdbusplus::asio::connection>& conn);
-bool getSensorConfiguration(
- const std::string& type,
- const std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
- ManagedObjectType& resp, bool useCache = false);
\ No newline at end of file
diff --git a/sensors/include/VariantVisitors.hpp b/sensors/include/VariantVisitors.hpp
deleted file mode 100644
index 8d4b004..0000000
--- a/sensors/include/VariantVisitors.hpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
-// Copyright (c) 2018 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#pragma once
-#include <boost/variant.hpp>
-#include <string>
-
-struct VariantToFloatVisitor : public boost::static_visitor<float>
-{
- template <typename T> float operator()(const T &t) const
- {
- return static_cast<float>(t);
- }
-};
-template <>
-inline float VariantToFloatVisitor::
- operator()<std::string>(const std::string &s) const
-{
- throw std::invalid_argument("Cannot translate string to float");
-}
-
-struct VariantToIntVisitor : public boost::static_visitor<int>
-{
- template <typename T> int operator()(const T &t) const
- {
- return static_cast<int>(t);
- }
-};
-template <>
-inline int VariantToIntVisitor::
- operator()<std::string>(const std::string &s) const
-{
- throw std::invalid_argument("Cannot translate string to int");
-}
-
-struct VariantToUnsignedIntVisitor : public boost::static_visitor<unsigned int>
-{
- template <typename T> unsigned int operator()(const T &t) const
- {
- return static_cast<int>(t);
- }
-};
-template <>
-inline unsigned int VariantToUnsignedIntVisitor::
- operator()<std::string>(const std::string &s) const
-{
- throw std::invalid_argument("Cannot translate string to unsigned int");
-}
-
-struct VariantToStringVisitor : public boost::static_visitor<std::string>
-{
- template <typename T> std::string operator()(const T &t) const
- {
- return std::to_string(t);
- }
-};
-template <>
-inline std::string VariantToStringVisitor::
- operator()<std::string>(const std::string &s) const
-{
- return s;
-}
\ No newline at end of file
diff --git a/sensors/include/non-yocto/linux/peci-ioctl.h b/sensors/include/non-yocto/linux/peci-ioctl.h
deleted file mode 100644
index 9cddb8b..0000000
--- a/sensors/include/non-yocto/linux/peci-ioctl.h
+++ /dev/null
@@ -1,247 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0 */
-/* Copyright (c) 2018 Intel Corporation */
-
-#ifndef __PECI_IOCTL_H
-#define __PECI_IOCTL_H
-
-#include <linux/ioctl.h>
-#include <linux/types.h>
-
-/* Base Address of 48d */
-#define PECI_BASE_ADDR 0x30 /* The PECI client's default address of 0x30 */
-#define PECI_OFFSET_MAX 8 /* Max numver of CPU clients */
-
-/* PCI Access */
-#define MAX_PCI_READ_LEN 24 /* Number of bytes of the PCI Space read */
-
-#define PCI_BUS0_CPU0 0x00
-#define PCI_BUS0_CPU1 0x80
-#define PCI_CPUBUSNO_BUS 0x00
-#define PCI_CPUBUSNO_DEV 0x08
-#define PCI_CPUBUSNO_FUNC 0x02
-#define PCI_CPUBUSNO 0xcc
-#define PCI_CPUBUSNO_1 0xd0
-#define PCI_CPUBUSNO_VALID 0xd4
-
-/* Package Identifier Read Parameter Value */
-#define PKG_ID_CPU_ID 0x0000 /* CPUID Info */
-#define PKG_ID_PLATFORM_ID 0x0001 /* Platform ID */
-#define PKG_ID_UNCORE_ID 0x0002 /* Uncore Device ID */
-#define PKG_ID_MAX_THREAD_ID 0x0003 /* Max Thread ID */
-#define PKG_ID_MICROCODE_REV 0x0004 /* CPU Microcode Update Revision */
-#define PKG_ID_MACHINE_CHECK_STATUS 0x0005 /* Machine Check Status */
-
-/* Crashdump Parameters */
-enum crashdump_agent {
- CRASHDUMP_CORE = 0x00,
- CRASHDUMP_TOR = 0x01,
-};
-enum crashdump_discovery_sub_opcode {
- CRASHDUMP_ENABLED = 0x00,
- CRASHDUMP_NUM_AGENTS = 0x01,
- CRASHDUMP_AGENT_DATA = 0x02,
-};
-enum crashdump_agent_data_param {
- CRASHDUMP_AGENT_ID = 0x00,
- CRASHDUMP_AGENT_PARAM = 0x01,
-};
-enum crashdump_agent_param {
- CRASHDUMP_PAYLOAD_SIZE = 0x00,
-};
-
-/* RdPkgConfig Index */
-#define MBX_INDEX_CPU_ID 0 /* Package Identifier Read */
-#define MBX_INDEX_VR_DEBUG 1 /* VR Debug */
-#define MBX_INDEX_PKG_TEMP_READ 2 /* Package Temperature Read */
-#define MBX_INDEX_ENERGY_COUNTER 3 /* Energy counter */
-#define MBX_INDEX_ENERGY_STATUS 4 /* DDR Energy Status */
-#define MBX_INDEX_WAKE_MODE_BIT 5 /* "Wake on PECI" Mode bit */
-#define MBX_INDEX_EPI 6 /* Efficient Performance Indication */
-#define MBX_INDEX_PKG_RAPL_PERF 8 /* Pkg RAPL Performance Status Read */
-#define MBX_INDEX_PER_CORE_DTS_TEMP 9 /* Per Core DTS Temperature Read */
-#define MBX_INDEX_DTS_MARGIN 10 /* DTS thermal margin */
-#define MBX_INDEX_SKT_PWR_THRTL_DUR 11 /* Socket Power Throttled Duration */
-#define MBX_INDEX_CFG_TDP_CONTROL 12 /* TDP Config Control */
-#define MBX_INDEX_CFG_TDP_LEVELS 13 /* TDP Config Levels */
-#define MBX_INDEX_DDR_DIMM_TEMP 14 /* DDR DIMM Temperature */
-#define MBX_INDEX_CFG_ICCMAX 15 /* Configurable ICCMAX */
-#define MBX_INDEX_TEMP_TARGET 16 /* Temperature Target Read */
-#define MBX_INDEX_CURR_CFG_LIMIT 17 /* Current Config Limit */
-#define MBX_INDEX_DIMM_TEMP_READ 20 /* Package Thermal Status Read */
-#define MBX_INDEX_DRAM_IMC_TMP_READ 22 /* DRAM IMC Temperature Read */
-#define MBX_INDEX_DDR_CH_THERM_STAT 23 /* DDR Channel Thermal Status */
-#define MBX_INDEX_PKG_POWER_LIMIT1 26 /* Package Power Limit1 */
-#define MBX_INDEX_PKG_POWER_LIMIT2 27 /* Package Power Limit2 */
-#define MBX_INDEX_TDP 28 /* Thermal design power minimum */
-#define MBX_INDEX_TDP_HIGH 29 /* Thermal design power maximum */
-#define MBX_INDEX_TDP_UNITS 30 /* Units for power/energy registers */
-#define MBX_INDEX_RUN_TIME 31 /* Accumulated Run Time */
-#define MBX_INDEX_CONSTRAINED_TIME 32 /* Thermally Constrained Time Read */
-#define MBX_INDEX_TURBO_RATIO 33 /* Turbo Activation Ratio */
-#define MBX_INDEX_DDR_RAPL_PL1 34 /* DDR RAPL PL1 */
-#define MBX_INDEX_DDR_PWR_INFO_HIGH 35 /* DRAM Power Info Read (high) */
-#define MBX_INDEX_DDR_PWR_INFO_LOW 36 /* DRAM Power Info Read (low) */
-#define MBX_INDEX_DDR_RAPL_PL2 37 /* DDR RAPL PL2 */
-#define MBX_INDEX_DDR_RAPL_STATUS 38 /* DDR RAPL Performance Status */
-#define MBX_INDEX_DDR_HOT_ABSOLUTE 43 /* DDR Hottest Dimm Absolute Temp */
-#define MBX_INDEX_DDR_HOT_RELATIVE 44 /* DDR Hottest Dimm Relative Temp */
-#define MBX_INDEX_DDR_THROTTLE_TIME 45 /* DDR Throttle Time */
-#define MBX_INDEX_DDR_THERM_STATUS 46 /* DDR Thermal Status */
-#define MBX_INDEX_TIME_AVG_TEMP 47 /* Package time-averaged temperature */
-#define MBX_INDEX_TURBO_RATIO_LIMIT 49 /* Turbo Ratio Limit Read */
-#define MBX_INDEX_HWP_AUTO_OOB 53 /* HWP Autonomous Out-of-band */
-#define MBX_INDEX_DDR_WARM_BUDGET 55 /* DDR Warm Power Budget */
-#define MBX_INDEX_DDR_HOT_BUDGET 56 /* DDR Hot Power Budget */
-#define MBX_INDEX_PKG_PSYS_PWR_LIM3 57 /* Package/Psys Power Limit3 */
-#define MBX_INDEX_PKG_PSYS_PWR_LIM1 58 /* Package/Psys Power Limit1 */
-#define MBX_INDEX_PKG_PSYS_PWR_LIM2 59 /* Package/Psys Power Limit2 */
-#define MBX_INDEX_PKG_PSYS_PWR_LIM4 60 /* Package/Psys Power Limit4 */
-#define MBX_INDEX_PERF_LIMIT_REASON 65 /* Performance Limit Reasons */
-
-/* WrPkgConfig Index */
-#define MBX_INDEX_DIMM_AMBIENT 19
-#define MBX_INDEX_DIMM_TEMP 24
-
-enum peci_cmd {
- PECI_CMD_XFER = 0,
- PECI_CMD_PING,
- PECI_CMD_GET_DIB,
- PECI_CMD_GET_TEMP,
- PECI_CMD_RD_PKG_CFG,
- PECI_CMD_WR_PKG_CFG,
- PECI_CMD_RD_IA_MSR,
- PECI_CMD_WR_IA_MSR,
- PECI_CMD_RD_PCI_CFG,
- PECI_CMD_WR_PCI_CFG,
- PECI_CMD_RD_PCI_CFG_LOCAL,
- PECI_CMD_WR_PCI_CFG_LOCAL,
- PECI_CMD_CRASHDUMP_DISC,
- PECI_CMD_CRASHDUMP_GET_FRAME,
- PECI_CMD_MAX
-};
-
-struct peci_ping_msg {
- __u8 addr;
-} __attribute__((__packed__));
-
-struct peci_get_dib_msg {
- __u8 addr;
- __u32 dib;
-} __attribute__((__packed__));
-
-struct peci_get_temp_msg {
- __u8 addr;
- __s16 temp_raw;
-} __attribute__((__packed__));
-
-struct peci_rd_pkg_cfg_msg {
- __u8 addr;
- __u8 index;
- __u16 param;
- __u8 rx_len;
- __u8 pkg_config[4];
-} __attribute__((__packed__));
-
-struct peci_wr_pkg_cfg_msg {
- __u8 addr;
- __u8 index;
- __u16 param;
- __u8 tx_len;
- __u32 value;
-} __attribute__((__packed__));
-
-struct peci_rd_ia_msr_msg {
- __u8 addr;
- __u8 thread_id;
- __u16 address;
- __u64 value;
-} __attribute__((__packed__));
-
-struct peci_rd_pci_cfg_msg {
- __u8 addr;
- __u8 bus;
- __u8 device;
- __u8 function;
- __u16 reg;
- __u8 pci_config[4];
-} __attribute__((__packed__));
-
-struct peci_rd_pci_cfg_local_msg {
- __u8 addr;
- __u8 bus;
- __u8 device;
- __u8 function;
- __u16 reg;
- __u8 rx_len;
- __u8 pci_config[4];
-} __attribute__((__packed__));
-
-struct peci_wr_pci_cfg_local_msg {
- __u8 addr;
- __u8 bus;
- __u8 device;
- __u8 function;
- __u16 reg;
- __u8 tx_len;
- __u32 value;
-} __attribute__((__packed__));
-
-struct peci_crashdump_disc_msg {
- __u8 addr;
- __u8 subopcode;
- __u8 param0;
- __u16 param1;
- __u8 param2;
- __u8 rx_len;
- __u8 data[8];
-} __attribute__((__packed__));
-
-struct peci_crashdump_get_frame_msg {
- __u8 addr;
- __u16 param0;
- __u16 param1;
- __u16 param2;
- __u8 rx_len;
- __u8 data[16];
-} __attribute__((__packed__));
-
-#define PECI_IOC_BASE 0xb6
-
-#define PECI_IOC_PING \
- _IOWR(PECI_IOC_BASE, PECI_CMD_PING, struct peci_ping_msg)
-
-#define PECI_IOC_GET_DIB \
- _IOWR(PECI_IOC_BASE, PECI_CMD_GET_DIB, struct peci_get_dib_msg)
-
-#define PECI_IOC_GET_TEMP \
- _IOWR(PECI_IOC_BASE, PECI_CMD_GET_TEMP, struct peci_get_temp_msg)
-
-#define PECI_IOC_RD_PKG_CFG \
- _IOWR(PECI_IOC_BASE, PECI_CMD_RD_PKG_CFG, struct peci_rd_pkg_cfg_msg)
-
-#define PECI_IOC_WR_PKG_CFG \
- _IOWR(PECI_IOC_BASE, PECI_CMD_WR_PKG_CFG, struct peci_wr_pkg_cfg_msg)
-
-#define PECI_IOC_RD_IA_MSR \
- _IOWR(PECI_IOC_BASE, PECI_CMD_RD_IA_MSR, struct peci_rd_ia_msr_msg)
-
-#define PECI_IOC_RD_PCI_CFG \
- _IOWR(PECI_IOC_BASE, PECI_CMD_RD_PCI_CFG, struct peci_rd_pci_cfg_msg)
-
-#define PECI_IOC_RD_PCI_CFG_LOCAL \
- _IOWR(PECI_IOC_BASE, PECI_CMD_RD_PCI_CFG_LOCAL, \
- struct peci_rd_pci_cfg_local_msg)
-
-#define PECI_IOC_WR_PCI_CFG_LOCAL \
- _IOWR(PECI_IOC_BASE, PECI_CMD_WR_PCI_CFG_LOCAL, \
- struct peci_wr_pci_cfg_local_msg)
-
-#define PECI_IOC_CRASHDUMP_DISC \
- _IOWR(PECI_IOC_BASE, PECI_CMD_CRASHDUMP_DISC, \
- struct peci_crashdump_disc_msg)
-
-#define PECI_IOC_CRASHDUMP_GET_FRAME \
- _IOWR(PECI_IOC_BASE, PECI_CMD_CRASHDUMP_GET_FRAME, \
- struct peci_crashdump_get_frame_msg)
-
-#endif /* __PECI_IOCTL_H */
diff --git a/sensors/include/sensor.hpp b/sensors/include/sensor.hpp
deleted file mode 100644
index 62eec62..0000000
--- a/sensors/include/sensor.hpp
+++ /dev/null
@@ -1,36 +0,0 @@
-#pragma once
-
-#include <Thresholds.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-
-constexpr size_t sensorFailedPollTimeMs = 5000;
-struct Sensor
-{
- Sensor(const std::string& name, const std::string& path,
- std::vector<thresholds::Threshold>&& thresholdData) :
- name(name),
- path(path), thresholds(std::move(thresholdData))
- {
- }
- virtual ~Sensor() = default;
- std::string name;
- std::string path;
- std::vector<thresholds::Threshold> thresholds;
- std::shared_ptr<sdbusplus::asio::dbus_interface> sensorInterface;
- std::shared_ptr<sdbusplus::asio::dbus_interface> thresholdInterfaceWarning;
- std::shared_ptr<sdbusplus::asio::dbus_interface> thresholdInterfaceCritical;
- double value = std::numeric_limits<double>::quiet_NaN();
- double overriddenValue = std::numeric_limits<double>::quiet_NaN();
- bool internalSet = false;
- int setSensorValue(const double& newValue, double& oldValue)
- {
- if (internalSet)
- {
- internalSet = false;
- oldValue = newValue;
- return 1;
- }
- overriddenValue = newValue;
- return 1;
- }
-};
\ No newline at end of file
diff --git a/sensors/src/ADCSensor.cpp b/sensors/src/ADCSensor.cpp
deleted file mode 100644
index 4ce6dda..0000000
--- a/sensors/src/ADCSensor.cpp
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <unistd.h>
-
-#include <ADCSensor.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
-#include <iostream>
-#include <limits>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-#include <string>
-
-static constexpr unsigned int sensorPollMs = 500;
-static constexpr size_t warnAfterErrorCount = 10;
-
-// scaling factor from hwmon
-static constexpr unsigned int sensorScaleFactor = 1000;
-
-ADCSensor::ADCSensor(const std::string &path,
- sdbusplus::asio::object_server &objectServer,
- std::shared_ptr<sdbusplus::asio::connection> &conn,
- boost::asio::io_service &io, const std::string &sensorName,
- std::vector<thresholds::Threshold> &&_thresholds,
- const double scaleFactor,
- const std::string &sensorConfiguration) :
- Sensor(boost::replace_all_copy(sensorName, " ", "_"), path,
- std::move(_thresholds)),
- objServer(objectServer), configuration(sensorConfiguration),
- scaleFactor(scaleFactor), inputDev(io, open(path.c_str(), O_RDONLY)),
- waitTimer(io), errCount(0),
- // todo, get these from config
- maxValue(20), minValue(0)
-{
- sensorInterface = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/voltage/" + name,
- "xyz.openbmc_project.Sensor.Value");
- if (thresholds::hasWarningInterface(thresholds))
- {
- thresholdInterfaceWarning = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/voltage/" + name,
- "xyz.openbmc_project.Sensor.Threshold.Warning");
- }
- if (thresholds::hasCriticalInterface(thresholds))
- {
- thresholdInterfaceCritical = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/voltage/" + name,
- "xyz.openbmc_project.Sensor.Threshold.Critical");
- }
- setInitialProperties(conn);
- setupRead();
-}
-
-ADCSensor::~ADCSensor()
-{
- // close the input dev to cancel async operations
- inputDev.close();
- waitTimer.cancel();
- objServer.remove_interface(thresholdInterfaceWarning);
- objServer.remove_interface(thresholdInterfaceCritical);
- objServer.remove_interface(sensorInterface);
-}
-
-void ADCSensor::setupRead(void)
-{
- boost::asio::async_read_until(
- inputDev, readBuf, '\n',
- [&](const boost::system::error_code &ec,
- std::size_t /*bytes_transfered*/) { handleResponse(ec); });
-}
-
-void ADCSensor::handleResponse(const boost::system::error_code &err)
-{
- if (err == boost::system::errc::bad_file_descriptor)
- {
- return; // we're being destroyed
- }
- std::istream responseStream(&readBuf);
-
- if (!err)
- {
- std::string response;
- std::getline(responseStream, response);
-
- // todo read scaling factors from configuration
- try
- {
- float nvalue = std::stof(response);
- nvalue = (nvalue / sensorScaleFactor) / scaleFactor;
- if (!isnan(overriddenValue))
- {
- nvalue = overriddenValue;
- }
- if (nvalue != value)
- {
- updateValue(nvalue);
- }
- errCount = 0;
- }
- catch (std::invalid_argument)
- {
- errCount++;
- }
- }
- else
- {
-
- errCount++;
- }
- // only print once
- if (errCount == warnAfterErrorCount)
- {
- std::cerr << "Failure to read sensor " << name << " at " << path
- << " ec:" << err << "\n";
- }
-
- if (errCount >= warnAfterErrorCount)
- {
- updateValue(0);
- }
-
- responseStream.clear();
- inputDev.close();
- int fd = open(path.c_str(), O_RDONLY);
- if (fd <= 0)
- {
- return; // we're no longer valid
- }
- inputDev.assign(fd);
- waitTimer.expires_from_now(boost::posix_time::milliseconds(sensorPollMs));
- waitTimer.async_wait([&](const boost::system::error_code &ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- return; // we're being canceled
- }
- setupRead();
- });
-}
-
-void ADCSensor::checkThresholds(void)
-{
- thresholds::checkThresholds(this);
-}
-
-void ADCSensor::updateValue(const double &newValue)
-{
- // Indicate that it is internal set call
- internalSet = true;
- bool ret = sensorInterface->set_property("Value", newValue);
- internalSet = false;
- value = newValue;
- checkThresholds();
-}
-
-void ADCSensor::setInitialProperties(
- std::shared_ptr<sdbusplus::asio::connection> &conn)
-{
- // todo, get max and min from configuration
- sensorInterface->register_property("MaxValue", maxValue);
- sensorInterface->register_property("MinValue", minValue);
- sensorInterface->register_property(
- "Value", value, [&](const double &newValue, double &oldValue) {
- return setSensorValue(newValue, oldValue);
- });
-
- for (auto &threshold : thresholds)
- {
- std::shared_ptr<sdbusplus::asio::dbus_interface> iface;
- std::string level;
- std::string alarm;
- if (threshold.level == thresholds::Level::CRITICAL)
- {
- iface = thresholdInterfaceCritical;
- if (threshold.direction == thresholds::Direction::HIGH)
- {
- level = "CriticalHigh";
- alarm = "CriticalAlarmHigh";
- }
- else
- {
- level = "CriticalLow";
- alarm = "CriticalAlarmLow";
- }
- }
- else if (threshold.level == thresholds::Level::WARNING)
- {
- iface = thresholdInterfaceWarning;
- if (threshold.direction == thresholds::Direction::HIGH)
- {
- level = "WarningHigh";
- alarm = "WarningAlarmHigh";
- }
- else
- {
- level = "WarningLow";
- alarm = "WarningAlarmLow";
- }
- }
- else
- {
- std::cerr << "Unknown threshold level" << threshold.level << "\n";
- continue;
- }
- if (!iface)
- {
- std::cout << "trying to set uninitialized interface\n";
- continue;
- }
- iface->register_property(
- level, threshold.value,
- [&](const double &request, double &oldValue) {
- oldValue = request; // todo, just let the config do this?
- threshold.value = request;
- thresholds::persistThreshold(
- configuration, "xyz.openbmc_project.Configuration.ADC",
- threshold, conn);
- return 1;
- });
- iface->register_property(alarm, false);
- }
- if (!sensorInterface->initialize())
- {
- std::cerr << "error initializing value interface\n";
- }
- if (thresholdInterfaceWarning && !thresholdInterfaceWarning->initialize())
- {
- std::cerr << "error initializing warning threshold interface\n";
- }
-
- if (thresholdInterfaceCritical && !thresholdInterfaceCritical->initialize())
- {
- std::cerr << "error initializing critical threshold interface\n";
- }
-}
diff --git a/sensors/src/ADCSensorMain.cpp b/sensors/src/ADCSensorMain.cpp
deleted file mode 100644
index 4fff81a..0000000
--- a/sensors/src/ADCSensorMain.cpp
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <ADCSensor.hpp>
-#include <Utils.hpp>
-#include <VariantVisitors.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/container/flat_set.hpp>
-#include <experimental/filesystem>
-#include <fstream>
-#include <regex>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-
-static constexpr bool DEBUG = false;
-
-namespace fs = std::experimental::filesystem;
-namespace variant_ns = sdbusplus::message::variant_ns;
-static constexpr std::array<const char*, 1> sensorTypes = {
- "xyz.openbmc_project.Configuration.ADC"};
-static std::regex inputRegex(R"(in(\d+)_input)");
-
-void createSensors(
- boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
- boost::container::flat_map<std::string, std::unique_ptr<ADCSensor>>&
- sensors,
- std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
- const std::unique_ptr<boost::container::flat_set<std::string>>&
- sensorsChanged)
-{
- bool firstScan = sensorsChanged == nullptr;
- // use new data the first time, then refresh
- ManagedObjectType sensorConfigurations;
- bool useCache = false;
- for (const char* type : sensorTypes)
- {
- if (!getSensorConfiguration(type, dbusConnection, sensorConfigurations,
- useCache))
- {
- std::cerr << "error communicating to entity manager\n";
- return;
- }
- useCache = true;
- }
- std::vector<fs::path> paths;
- if (!findFiles(fs::path("/sys/class/hwmon"), R"(in\d+_input)", paths))
- {
- std::cerr << "No temperature sensors in system\n";
- return;
- }
-
- // iterate through all found adc sensors, and try to match them with
- // configuration
- for (auto& path : paths)
- {
- std::smatch match;
- std::string pathStr = path.string();
-
- std::regex_search(pathStr, match, inputRegex);
- std::string indexStr = *(match.begin() + 1);
-
- auto directory = path.parent_path();
- // convert to 0 based
- size_t index = std::stoul(indexStr) - 1;
- auto oemNamePath =
- directory.string() + R"(/of_node/oemname)" + std::to_string(index);
-
- if (DEBUG)
- {
- std::cout << "Checking path " << oemNamePath << "\n";
- }
- std::ifstream nameFile(oemNamePath);
- if (!nameFile.good())
- {
- std::cerr << "Failure reading " << oemNamePath << "\n";
- continue;
- }
- std::string oemName;
- std::getline(nameFile, oemName);
- nameFile.close();
- if (!oemName.size())
- {
- // shouldn't have an empty name file
- continue;
- }
- oemName.pop_back(); // remove trailing null
-
- const SensorData* sensorData = nullptr;
- const std::string* interfacePath = nullptr;
- for (const std::pair<sdbusplus::message::object_path, SensorData>&
- sensor : sensorConfigurations)
- {
- if (!boost::ends_with(sensor.first.str, oemName))
- {
- continue;
- }
- sensorData = &(sensor.second);
- interfacePath = &(sensor.first.str);
- break;
- }
- if (sensorData == nullptr)
- {
- std::cerr << "failed to find match for " << oemName << "\n";
- continue;
- }
- const std::pair<std::string, boost::container::flat_map<
- std::string, BasicVariantType>>*
- baseConfiguration = nullptr;
- for (const char* type : sensorTypes)
- {
- auto sensorBase = sensorData->find(type);
- if (sensorBase != sensorData->end())
- {
- baseConfiguration = &(*sensorBase);
- break;
- }
- }
-
- if (baseConfiguration == nullptr)
- {
- std::cerr << "error finding base configuration for" << oemName
- << "\n";
- continue;
- }
-
- auto findSensorName = baseConfiguration->second.find("Name");
- if (findSensorName == baseConfiguration->second.end())
- {
- std::cerr << "could not determine configuration name for "
- << oemName << "\n";
- continue;
- }
- std::string sensorName =
- sdbusplus::message::variant_ns::get<std::string>(
- findSensorName->second);
-
- // on rescans, only update sensors we were signaled by
- auto findSensor = sensors.find(sensorName);
- if (!firstScan && findSensor != sensors.end())
- {
- bool found = false;
- for (auto it = sensorsChanged->begin(); it != sensorsChanged->end();
- it++)
- {
- if (boost::ends_with(*it, findSensor->second->name))
- {
- sensorsChanged->erase(it);
- findSensor->second = nullptr;
- found = true;
- break;
- }
- }
- if (!found)
- {
- continue;
- }
- }
- std::vector<thresholds::Threshold> sensorThresholds;
- if (!parseThresholdsFromConfig(*sensorData, sensorThresholds))
- {
- std::cerr << "error populating thresholds for " << sensorName
- << "\n";
- }
-
- auto findScaleFactor = baseConfiguration->second.find("ScaleFactor");
- float scaleFactor = 1.0;
- if (findScaleFactor != baseConfiguration->second.end())
- {
- scaleFactor = variant_ns::visit(VariantToFloatVisitor(),
- findScaleFactor->second);
- }
- sensors[sensorName] = std::make_unique<ADCSensor>(
- path.string(), objectServer, dbusConnection, io, sensorName,
- std::move(sensorThresholds), scaleFactor, *interfacePath);
- }
-}
-
-int main(int argc, char** argv)
-{
- boost::asio::io_service io;
- auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
- systemBus->request_name("xyz.openbmc_project.ADCSensor");
- sdbusplus::asio::object_server objectServer(systemBus);
- boost::container::flat_map<std::string, std::unique_ptr<ADCSensor>> sensors;
- std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
- std::unique_ptr<boost::container::flat_set<std::string>> sensorsChanged =
- std::make_unique<boost::container::flat_set<std::string>>();
-
- io.post([&]() {
- createSensors(io, objectServer, sensors, systemBus, nullptr);
- });
-
- boost::asio::deadline_timer filterTimer(io);
- std::function<void(sdbusplus::message::message&)> eventHandler =
- [&](sdbusplus::message::message& message) {
- if (message.is_method_error())
- {
- std::cerr << "callback method error\n";
- return;
- }
- sensorsChanged->insert(message.get_path());
- // this implicitly cancels the timer
- filterTimer.expires_from_now(boost::posix_time::seconds(1));
-
- filterTimer.async_wait([&](const boost::system::error_code& ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- /* we were canceled*/
- return;
- }
- else if (ec)
- {
- std::cerr << "timer error\n";
- return;
- }
- createSensors(io, objectServer, sensors, systemBus,
- sensorsChanged);
- });
- };
-
- for (const char* type : sensorTypes)
- {
- auto match = std::make_unique<sdbusplus::bus::match::match>(
- static_cast<sdbusplus::bus::bus&>(*systemBus),
- "type='signal',member='PropertiesChanged',path_namespace='" +
- std::string(inventoryPath) + "',arg0namespace='" + type + "'",
- eventHandler);
- matches.emplace_back(std::move(match));
- }
-
- io.run();
-}
diff --git a/sensors/src/CPUSensor.cpp b/sensors/src/CPUSensor.cpp
deleted file mode 100644
index 24e30c8..0000000
--- a/sensors/src/CPUSensor.cpp
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
-// Copyright (c) 2018 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <unistd.h>
-
-#include <CPUSensor.hpp>
-#include <Utils.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
-#include <iostream>
-#include <limits>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-#include <string>
-
-static constexpr size_t warnAfterErrorCount = 10;
-
-CPUSensor::CPUSensor(const std::string &path, const std::string &objectType,
- sdbusplus::asio::object_server &objectServer,
- std::shared_ptr<sdbusplus::asio::connection> &conn,
- boost::asio::io_service &io, const std::string &sensorName,
- std::vector<thresholds::Threshold> &&_thresholds,
- const std::string &sensorConfiguration) :
- Sensor(boost::replace_all_copy(sensorName, " ", "_"), path,
- std::move(_thresholds)),
- objectType(objectType), objServer(objectServer), dbusConnection(conn),
- configuration(sensorConfiguration),
-
- inputDev(io, open(path.c_str(), O_RDONLY)), waitTimer(io), errCount(0),
- // todo, get these from config
- maxValue(127), minValue(-128)
-{
- sensorInterface = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/temperature/" + name,
- "xyz.openbmc_project.Sensor.Value");
- if (thresholds::hasWarningInterface(thresholds))
- {
- thresholdInterfaceWarning = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/temperature/" + name,
- "xyz.openbmc_project.Sensor.Threshold.Warning");
- }
- if (thresholds::hasCriticalInterface(thresholds))
- {
- thresholdInterfaceCritical = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/temperature/" + name,
- "xyz.openbmc_project.Sensor.Threshold.Critical");
- }
- setInitialProperties(conn);
- isPowerOn(dbusConnection); // first call initializes
- setupRead();
-}
-
-CPUSensor::~CPUSensor()
-{
- // close the input dev to cancel async operations
- inputDev.close();
- waitTimer.cancel();
- objServer.remove_interface(thresholdInterfaceWarning);
- objServer.remove_interface(thresholdInterfaceCritical);
- objServer.remove_interface(sensorInterface);
-}
-
-void CPUSensor::setupRead(void)
-{
- boost::asio::async_read_until(
- inputDev, readBuf, '\n',
- [&](const boost::system::error_code &ec,
- std::size_t /*bytes_transfered*/) { handleResponse(ec); });
-}
-
-void CPUSensor::handleResponse(const boost::system::error_code &err)
-{
- if (err == boost::system::errc::bad_file_descriptor)
- {
- return; // we're being destroyed
- }
- size_t pollTime = CPUSensor::sensorPollMs;
- std::istream responseStream(&readBuf);
- if (!err)
- {
- std::string response;
- try
- {
- std::getline(responseStream, response);
- float nvalue = std::stof(response);
- responseStream.clear();
- nvalue /= CPUSensor::sensorScaleFactor;
- if (!isnan(overriddenValue))
- {
- nvalue = overriddenValue;
- }
- if (nvalue != value)
- {
- updateValue(nvalue);
- }
- errCount = 0;
- }
- catch (const std::invalid_argument &)
- {
- errCount++;
- }
- }
- else
- {
- pollTime = sensorFailedPollTimeMs;
- errCount++;
- }
-
- if (errCount >= warnAfterErrorCount)
- {
- // only an error if power is on
- if (isPowerOn(dbusConnection))
- {
- // only print once
- if (errCount == warnAfterErrorCount)
- {
- std::cerr << "Failure to read sensor " << name << " at " << path
- << "\n";
- }
- updateValue(0);
- errCount++;
- }
- else
- {
- errCount = 0; // check power again in 10 cycles
- updateValue(std::numeric_limits<double>::quiet_NaN());
- }
- }
-
- responseStream.clear();
- inputDev.close();
- int fd = open(path.c_str(), O_RDONLY);
- if (fd <= 0)
- {
- return; // we're no longer valid
- }
- inputDev.assign(fd);
- waitTimer.expires_from_now(boost::posix_time::milliseconds(pollTime));
- waitTimer.async_wait([&](const boost::system::error_code &ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- return; // we're being canceled
- }
- setupRead();
- });
-}
-
-void CPUSensor::checkThresholds(void)
-{
- thresholds::checkThresholds(this);
-}
-
-void CPUSensor::updateValue(const double &newValue)
-{
- // Indicate that it is internal set call
- internalSet = true;
- sensorInterface->set_property("Value", newValue);
- internalSet = false;
- value = newValue;
- checkThresholds();
-}
-
-void CPUSensor::setInitialProperties(
- std::shared_ptr<sdbusplus::asio::connection> &conn)
-{
- // todo, get max and min from configuration
- sensorInterface->register_property("MaxValue", maxValue);
- sensorInterface->register_property("MinValue", minValue);
- sensorInterface->register_property(
- "Value", value, [&](const double &newValue, double &oldValue) {
- return setSensorValue(newValue, oldValue);
- });
-
- for (auto &threshold : thresholds)
- {
- std::shared_ptr<sdbusplus::asio::dbus_interface> iface;
- std::string level;
- std::string alarm;
- if (threshold.level == thresholds::Level::CRITICAL)
- {
- iface = thresholdInterfaceCritical;
- if (threshold.direction == thresholds::Direction::HIGH)
- {
- level = "CriticalHigh";
- alarm = "CriticalAlarmHigh";
- }
- else
- {
- level = "CriticalLow";
- alarm = "CriticalAlarmLow";
- }
- }
- else if (threshold.level == thresholds::Level::WARNING)
- {
- iface = thresholdInterfaceWarning;
- if (threshold.direction == thresholds::Direction::HIGH)
- {
- level = "WarningHigh";
- alarm = "WarningAlarmHigh";
- }
- else
- {
- level = "WarningLow";
- alarm = "WarningAlarmLow";
- }
- }
- else
- {
- std::cerr << "Unknown threshold level" << threshold.level << "\n";
- continue;
- }
- if (!iface)
- {
- std::cout << "trying to set uninitialized interface\n";
- continue;
- }
- if (threshold.writeable)
- {
- iface->register_property(
- level, threshold.value,
- [&](const double &request, double &oldValue) {
- oldValue = request; // todo, just let the config do this?
- threshold.value = request;
- thresholds::persistThreshold(configuration, objectType,
- threshold, conn);
- return 1;
- });
- }
- else
- {
- iface->register_property(level, threshold.value);
- }
- iface->register_property(alarm, false);
- }
- if (!sensorInterface->initialize())
- {
- std::cerr << "error initializing value interface\n";
- }
- if (thresholdInterfaceWarning && !thresholdInterfaceWarning->initialize())
- {
- std::cerr << "error initializing warning threshold interface\n";
- }
-
- if (thresholdInterfaceCritical && !thresholdInterfaceCritical->initialize())
- {
- std::cerr << "error initializing critical threshold interface\n";
- }
-}
diff --git a/sensors/src/CPUSensorMain.cpp b/sensors/src/CPUSensorMain.cpp
deleted file mode 100644
index a356d5c..0000000
--- a/sensors/src/CPUSensorMain.cpp
+++ /dev/null
@@ -1,667 +0,0 @@
-/*
-// Copyright (c) 2018 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <fcntl.h>
-#include <linux/peci-ioctl.h>
-
-#include <CPUSensor.hpp>
-#include <Utils.hpp>
-#include <VariantVisitors.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/container/flat_set.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
-#include <boost/process/child.hpp>
-#include <experimental/filesystem>
-#include <fstream>
-#include <regex>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-
-static constexpr bool DEBUG = false;
-
-enum State
-{
- OFF, // host powered down
- ON, // host powered on
- READY // host powered on and mem test passed - fully ready
-};
-
-struct CPUConfig
-{
- CPUConfig(const uint64_t& bus, const uint64_t& addr,
- const std::string& name, const State& state) :
- bus(bus),
- addr(addr), name(name), state(state)
- {
- }
- int bus;
- int addr;
- std::string name;
- State state;
-
- bool operator<(const CPUConfig& rhs) const
- {
- return (name < rhs.name);
- }
-};
-
-static constexpr const char* peciDev = "/dev/peci-";
-static constexpr const unsigned int rankNumMax = 8;
-
-namespace fs = std::experimental::filesystem;
-namespace variant_ns = sdbusplus::message::variant_ns;
-static constexpr const char* configPrefix =
- "xyz.openbmc_project.Configuration.";
-static constexpr std::array<const char*, 3> sensorTypes = {
- "SkylakeCPU", "BroadwellCPU", "HaswellCPU"};
-
-void detectCpuAsync(
- boost::asio::deadline_timer& pingTimer,
- boost::asio::deadline_timer& creationTimer, boost::asio::io_service& io,
- sdbusplus::asio::object_server& objectServer,
- boost::container::flat_map<std::string, std::unique_ptr<CPUSensor>>&
- sensors,
- boost::container::flat_set<CPUConfig>& configs,
- std::shared_ptr<sdbusplus::asio::connection>& dbusConnection);
-
-bool createSensors(
- boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
- boost::container::flat_map<std::string, std::unique_ptr<CPUSensor>>&
- sensors,
- boost::container::flat_set<CPUConfig>& configs,
- std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
-{
- bool available = false;
- for (CPUConfig cpu : configs)
- {
- if (cpu.state != State::OFF)
- {
- available = true;
- break;
- }
- }
- if (!available)
- {
- return false;
- }
-
- // use new data the first time, then refresh
- ManagedObjectType sensorConfigurations;
- bool useCache = false;
- for (const char* type : sensorTypes)
- {
- if (!getSensorConfiguration(configPrefix + std::string(type),
- dbusConnection, sensorConfigurations,
- useCache))
- {
- return false;
- }
- useCache = true;
- }
-
- std::vector<fs::path> hwmonNamePaths;
- if (!findFiles(fs::path(R"(/sys/bus/peci/devices)"),
- R"(peci-\d+/\d+-.+/peci-.+/hwmon/hwmon\d+/name$)",
- hwmonNamePaths, 1))
- {
- std::cerr << "No CPU sensors in system\n";
- return true;
- }
-
- boost::container::flat_set<std::string> scannedDirectories;
- boost::container::flat_set<std::string> createdSensors;
-
- for (fs::path& hwmonNamePath : hwmonNamePaths)
- {
- const std::string& pathStr = hwmonNamePath.string();
- auto hwmonDirectory = hwmonNamePath.parent_path();
-
- auto ret = scannedDirectories.insert(hwmonDirectory.string());
- if (!ret.second)
- {
- continue; // already searched this path
- }
-
- fs::path::iterator it = hwmonNamePath.begin();
- std::advance(it, 6); // pick the 6th part for a PECI client device name
- std::string deviceName = *it;
- auto findHyphen = deviceName.find("-");
- if (findHyphen == std::string::npos)
- {
- std::cerr << "found bad device " << deviceName << "\n";
- continue;
- }
- std::string busStr = deviceName.substr(0, findHyphen);
- std::string addrStr = deviceName.substr(findHyphen + 1);
-
- size_t bus = 0;
- size_t addr = 0;
- try
- {
- bus = std::stoi(busStr);
- addr = std::stoi(addrStr, 0, 16);
- }
- catch (std::invalid_argument)
- {
- continue;
- }
-
- std::ifstream nameFile(hwmonNamePath);
- if (!nameFile.good())
- {
- std::cerr << "Failure reading " << hwmonNamePath << "\n";
- continue;
- }
- std::string hwmonName;
- std::getline(nameFile, hwmonName);
- nameFile.close();
- if (!hwmonName.size())
- {
- // shouldn't have an empty name file
- continue;
- }
- if (DEBUG)
- {
- std::cout << "Checking: " << hwmonNamePath << ": " << hwmonName
- << "\n";
- }
-
- std::string sensorType;
- const SensorData* sensorData = nullptr;
- const std::string* interfacePath = nullptr;
- const std::pair<std::string, boost::container::flat_map<
- std::string, BasicVariantType>>*
- baseConfiguration = nullptr;
-
- for (const std::pair<sdbusplus::message::object_path, SensorData>&
- sensor : sensorConfigurations)
- {
- sensorData = &(sensor.second);
- for (const char* type : sensorTypes)
- {
- sensorType = configPrefix + std::string(type);
- auto sensorBase = sensorData->find(sensorType);
- if (sensorBase != sensorData->end())
- {
- baseConfiguration = &(*sensorBase);
- break;
- }
- }
- if (baseConfiguration == nullptr)
- {
- std::cerr << "error finding base configuration for" << hwmonName
- << "\n";
- continue;
- }
- auto configurationBus = baseConfiguration->second.find("Bus");
- auto configurationAddress =
- baseConfiguration->second.find("Address");
-
- if (configurationBus == baseConfiguration->second.end() ||
- configurationAddress == baseConfiguration->second.end())
- {
- std::cerr << "error finding bus or address in configuration";
- continue;
- }
-
- if (sdbusplus::message::variant_ns::get<uint64_t>(
- configurationBus->second) != bus ||
- sdbusplus::message::variant_ns::get<uint64_t>(
- configurationAddress->second) != addr)
- {
- continue;
- }
-
- interfacePath = &(sensor.first.str);
- break;
- }
- if (interfacePath == nullptr)
- {
- std::cerr << "failed to find match for " << hwmonName << "\n";
- continue;
- }
-
- auto findCpuId = baseConfiguration->second.find("CpuID");
- if (findCpuId == baseConfiguration->second.end())
- {
- std::cerr << "could not determine CPU ID for " << hwmonName << "\n";
- continue;
- }
- int cpuId =
- variant_ns::visit(VariantToUnsignedIntVisitor(), findCpuId->second);
-
- auto directory = hwmonNamePath.parent_path();
- std::vector<fs::path> inputPaths;
- if (!findFiles(fs::path(directory), R"(temp\d+_input$)", inputPaths, 0))
- {
- std::cerr << "No temperature sensors in system\n";
- continue;
- }
-
- // iterate through all found temp sensors
- for (auto& inputPath : inputPaths)
- {
- auto inputPathStr = inputPath.string();
- auto labelPath =
- boost::replace_all_copy(inputPathStr, "input", "label");
- std::ifstream labelFile(labelPath);
- if (!labelFile.good())
- {
- std::cerr << "Failure reading " << labelPath << "\n";
- continue;
- }
- std::string label;
- std::getline(labelFile, label);
- labelFile.close();
- std::string sensorName = label + " CPU" + std::to_string(cpuId);
-
- auto findSensor = sensors.find(sensorName);
- if (findSensor != sensors.end())
- {
- if (DEBUG)
- {
- std::cout << "Skipped: " << inputPath << ": " << sensorName
- << " is already created\n";
- }
- continue;
- }
-
- std::vector<thresholds::Threshold> sensorThresholds;
- std::string labelHead = label.substr(0, label.find(" "));
- parseThresholdsFromConfig(*sensorData, sensorThresholds,
- &labelHead);
- if (!sensorThresholds.size())
- {
- if (!parseThresholdsFromAttr(sensorThresholds, inputPathStr,
- CPUSensor::sensorScaleFactor))
- {
- std::cerr << "error populating thresholds for "
- << sensorName << "\n";
- }
- }
- sensors[sensorName] = std::make_unique<CPUSensor>(
- inputPathStr, sensorType, objectServer, dbusConnection, io,
- sensorName, std::move(sensorThresholds), *interfacePath);
- createdSensors.insert(sensorName);
- if (DEBUG)
- {
- std::cout << "Mapped: " << inputPath << " to " << sensorName
- << "\n";
- }
- }
- }
-
- if (createdSensors.size())
- {
- std::cout << "Sensor" << (createdSensors.size() == 1 ? " is" : "s are")
- << " created\n";
- }
-
- return true;
-}
-
-void exportDevice(const CPUConfig& config)
-{
- std::ostringstream hex;
- hex << std::hex << config.addr;
- const std::string& addrHexStr = hex.str();
- std::string busStr = std::to_string(config.bus);
-
- std::string parameters = "peci-client 0x" + addrHexStr;
- std::string device = "/sys/bus/peci/devices/peci-" + busStr + "/new_device";
-
- std::experimental::filesystem::path devicePath(device);
- const std::string& dir = devicePath.parent_path().string();
- for (const auto& path :
- std::experimental::filesystem::directory_iterator(dir))
- {
- if (!std::experimental::filesystem::is_directory(path))
- {
- continue;
- }
-
- const std::string& directoryName = path.path().filename();
- if (boost::starts_with(directoryName, busStr) &&
- boost::ends_with(directoryName, addrHexStr))
- {
- if (DEBUG)
- {
- std::cout << parameters << " on bus " << busStr
- << " is already exported\n";
- }
- return;
- }
- }
-
- std::ofstream deviceFile(device);
- if (!deviceFile.good())
- {
- std::cerr << "Error writing " << device << "\n";
- return;
- }
- deviceFile << parameters;
- deviceFile.close();
-
- std::cout << parameters << " on bus " << busStr << " is exported\n";
-}
-
-void detectCpu(boost::asio::deadline_timer& pingTimer,
- boost::asio::deadline_timer& creationTimer,
- boost::asio::io_service& io,
- sdbusplus::asio::object_server& objectServer,
- boost::container::flat_map<std::string,
- std::unique_ptr<CPUSensor>>& sensors,
- boost::container::flat_set<CPUConfig>& configs,
- std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
-{
- size_t rescanDelaySeconds = 0;
- bool keepPinging = false;
-
- for (CPUConfig& config : configs)
- {
- std::string peciDevPath = peciDev + std::to_string(config.bus);
- auto file = open(peciDevPath.c_str(), O_RDWR | O_CLOEXEC);
- if (file < 0)
- {
- std::cerr << "unable to open " << peciDevPath << "\n";
- std::exit(EXIT_FAILURE);
- }
-
- State state;
- struct peci_ping_msg msg;
- msg.addr = config.addr;
- if (!ioctl(file, PECI_IOC_PING, &msg))
- {
- bool dimmReady = false;
- for (unsigned int rank = 0; rank < rankNumMax; rank++)
- {
- struct peci_rd_pkg_cfg_msg msg;
- msg.addr = config.addr;
- msg.index = MBX_INDEX_DDR_DIMM_TEMP;
- msg.param = rank;
- msg.rx_len = 4;
- if (!ioctl(file, PECI_IOC_RD_PKG_CFG, &msg))
- {
- if (msg.pkg_config[0] || msg.pkg_config[1] ||
- msg.pkg_config[2])
- {
- dimmReady = true;
- break;
- }
- }
- else
- {
- break;
- }
- }
-
- if (dimmReady)
- {
- state = State::READY;
- }
- else
- {
- state = State::ON;
- }
- }
- else
- {
- state = State::OFF;
- }
-
- close(file);
-
- if (config.state != state)
- {
- if (config.state == State::OFF)
- {
- std::cout << config.name << " is detected\n";
- exportDevice(config);
- }
- if (state == State::READY)
- {
- std::cout << "DIMM(s) on " << config.name
- << " is/are detected\n";
- }
- config.state = state;
- }
-
- if (config.state != State::OFF)
- {
- if (config.state == State::ON)
- {
- rescanDelaySeconds = 1;
- }
- else
- {
- rescanDelaySeconds = 5;
- }
- }
-
- if (config.state != State::READY)
- {
- keepPinging = true;
- }
-
- if (DEBUG)
- {
- std::cout << config.name << ", state: " << config.state << "\n";
- }
- }
-
- if (rescanDelaySeconds)
- {
- creationTimer.expires_from_now(
- boost::posix_time::seconds(rescanDelaySeconds));
- creationTimer.async_wait([&](const boost::system::error_code& ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- return; // we're being canceled
- }
-
- if (!createSensors(io, objectServer, sensors, configs,
- dbusConnection))
- {
- detectCpuAsync(pingTimer, creationTimer, io, objectServer,
- sensors, configs, dbusConnection);
- }
- });
- }
-
- if (keepPinging)
- {
- detectCpuAsync(pingTimer, creationTimer, io, objectServer, sensors,
- configs, dbusConnection);
- }
-}
-
-void detectCpuAsync(
- boost::asio::deadline_timer& pingTimer,
- boost::asio::deadline_timer& creationTimer, boost::asio::io_service& io,
- sdbusplus::asio::object_server& objectServer,
- boost::container::flat_map<std::string, std::unique_ptr<CPUSensor>>&
- sensors,
- boost::container::flat_set<CPUConfig>& configs,
- std::shared_ptr<sdbusplus::asio::connection>& dbusConnection)
-{
- pingTimer.expires_from_now(boost::posix_time::seconds(1));
- pingTimer.async_wait([&](const boost::system::error_code& ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- return; // we're being canceled
- }
-
- detectCpu(pingTimer, creationTimer, io, objectServer, sensors, configs,
- dbusConnection);
- });
-}
-
-bool getCpuConfig(const std::shared_ptr<sdbusplus::asio::connection>& systemBus,
- boost::container::flat_set<CPUConfig>& configs)
-{
- ManagedObjectType sensorConfigurations;
- bool useCache = false;
- // use new data the first time, then refresh
- for (const char* type : sensorTypes)
- {
- if (!getSensorConfiguration(configPrefix + std::string(type), systemBus,
- sensorConfigurations, useCache))
- {
- return false;
- }
- useCache = true;
- }
-
- // check PECI client addresses and DT overlay names from CPU configuration
- // before starting ping operation
- for (const char* type : sensorTypes)
- {
- for (const std::pair<sdbusplus::message::object_path, SensorData>&
- sensor : sensorConfigurations)
- {
- for (const std::pair<
- std::string,
- boost::container::flat_map<std::string, BasicVariantType>>&
- config : sensor.second)
- {
- if ((configPrefix + std::string(type)) != config.first)
- {
- continue;
- }
-
- auto findName = config.second.find("Name");
- if (findName == config.second.end())
- {
- continue;
- }
- std::string nameRaw = variant_ns::visit(
- VariantToStringVisitor(), findName->second);
- std::string name =
- std::regex_replace(nameRaw, illegalDbusRegex, "_");
-
- auto findBus = config.second.find("Bus");
- if (findBus == config.second.end())
- {
- std::cerr << "Can't find 'Bus' setting in " << name << "\n";
- continue;
- }
- uint64_t bus = variant_ns::visit(VariantToUnsignedIntVisitor(),
- findBus->second);
-
- auto findAddress = config.second.find("Address");
- if (findAddress == config.second.end())
- {
- std::cerr << "Can't find 'Address' setting in " << name
- << "\n";
- continue;
- }
- uint64_t addr = variant_ns::visit(VariantToUnsignedIntVisitor(),
- findAddress->second);
-
- if (DEBUG)
- {
- std::cout << "bus: " << bus << "\n";
- std::cout << "addr: " << addr << "\n";
- std::cout << "name: " << name << "\n";
- std::cout << "type: " << type << "\n";
- }
-
- configs.emplace(bus, addr, name, State::OFF);
- }
- }
- }
-
- if (configs.size())
- {
- std::cout << "CPU config" << (configs.size() == 1 ? " is" : "s are")
- << " parsed\n";
- return true;
- }
-
- return false;
-}
-
-int main(int argc, char** argv)
-{
- boost::asio::io_service io;
- auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
- boost::container::flat_set<CPUConfig> configs;
-
- systemBus->request_name("xyz.openbmc_project.CPUSensor");
- sdbusplus::asio::object_server objectServer(systemBus);
- boost::container::flat_map<std::string, std::unique_ptr<CPUSensor>> sensors;
- std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
- boost::asio::deadline_timer pingTimer(io);
- boost::asio::deadline_timer creationTimer(io);
- boost::asio::deadline_timer filterTimer(io);
-
- filterTimer.expires_from_now(boost::posix_time::seconds(1));
- filterTimer.async_wait([&](const boost::system::error_code& ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- return; // we're being canceled
- }
-
- if (getCpuConfig(systemBus, configs))
- {
- detectCpuAsync(pingTimer, creationTimer, io, objectServer, sensors,
- configs, systemBus);
- }
- });
-
- std::function<void(sdbusplus::message::message&)> eventHandler =
- [&](sdbusplus::message::message& message) {
- if (message.is_method_error())
- {
- std::cerr << "callback method error\n";
- return;
- }
-
- if (DEBUG)
- {
- std::cout << message.get_path() << " is changed\n";
- }
-
- // this implicitly cancels the timer
- filterTimer.expires_from_now(boost::posix_time::seconds(1));
- filterTimer.async_wait([&](const boost::system::error_code& ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- return; // we're being canceled
- }
-
- if (getCpuConfig(systemBus, configs))
- {
- detectCpuAsync(pingTimer, creationTimer, io, objectServer,
- sensors, configs, systemBus);
- }
- });
- };
-
- for (const char* type : sensorTypes)
- {
- auto match = std::make_unique<sdbusplus::bus::match::match>(
- static_cast<sdbusplus::bus::bus&>(*systemBus),
- "type='signal',member='PropertiesChanged',path_namespace='" +
- std::string(inventoryPath) + "',arg0namespace='" +
- configPrefix + type + "'",
- eventHandler);
- matches.emplace_back(std::move(match));
- }
-
- io.run();
-}
diff --git a/sensors/src/FanMain.cpp b/sensors/src/FanMain.cpp
deleted file mode 100644
index 8401343..0000000
--- a/sensors/src/FanMain.cpp
+++ /dev/null
@@ -1,390 +0,0 @@
-/*
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <PwmSensor.hpp>
-#include <TachSensor.hpp>
-#include <Utils.hpp>
-#include <VariantVisitors.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/container/flat_set.hpp>
-#include <boost/lexical_cast.hpp>
-#include <experimental/filesystem>
-#include <fstream>
-#include <regex>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-
-static constexpr bool DEBUG = false;
-
-namespace fs = std::experimental::filesystem;
-namespace variant_ns = sdbusplus::message::variant_ns;
-static constexpr std::array<const char*, 1> sensorTypes = {
- "xyz.openbmc_project.Configuration.AspeedFan"};
-constexpr const char* redundancyConfiguration =
- "xyz.openbmc_project.Configuration.FanRedundancy";
-static std::regex inputRegex(R"(fan(\d+)_input)");
-
-// todo: power supply fan redundancy
-std::unique_ptr<RedundancySensor> systemRedundancy = nullptr;
-
-void createSensors(
- boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
- boost::container::flat_map<std::string, std::unique_ptr<TachSensor>>&
- tachSensors,
- boost::container::flat_map<std::string, std::unique_ptr<PwmSensor>>&
- pwmSensors,
- std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
- const std::unique_ptr<boost::container::flat_set<std::string>>&
- sensorsChanged)
-{
- bool firstScan = sensorsChanged == nullptr;
- // use new data the first time, then refresh
- ManagedObjectType sensorConfigurations;
- bool useCache = false;
- for (const char* type : sensorTypes)
- {
- if (!getSensorConfiguration(type, dbusConnection, sensorConfigurations,
- useCache))
- {
- std::cerr << "error communicating to entity manager\n";
- return;
- }
- useCache = true;
- }
- std::vector<fs::path> paths;
- if (!findFiles(fs::path("/sys/class/hwmon"), R"(fan\d+_input)", paths))
- {
- std::cerr << "No temperature sensors in system\n";
- return;
- }
-
- // iterate through all found fan sensors, and try to match them with
- // configuration
- for (auto& path : paths)
- {
- std::smatch match;
- std::string pathStr = path.string();
-
- std::regex_search(pathStr, match, inputRegex);
- std::string indexStr = *(match.begin() + 1);
-
- auto directory = path.parent_path();
- // convert to 0 based
- size_t index = std::stoul(indexStr) - 1;
-
- const char* baseType;
- const SensorData* sensorData = nullptr;
- const std::string* interfacePath = nullptr;
- const std::pair<std::string, boost::container::flat_map<
- std::string, BasicVariantType>>*
- baseConfiguration = nullptr;
- for (const std::pair<sdbusplus::message::object_path, SensorData>&
- sensor : sensorConfigurations)
- {
- // find the base of the configuration to see if indexes match
- for (const char* type : sensorTypes)
- {
- auto sensorBaseFind = sensor.second.find(type);
- if (sensorBaseFind != sensor.second.end())
- {
- baseConfiguration = &(*sensorBaseFind);
- interfacePath = &(sensor.first.str);
- baseType = type;
- break;
- }
- }
- if (baseConfiguration == nullptr)
- {
- continue;
- }
- auto connector =
- sensor.second.find(baseType + std::string(".Connector"));
- if (connector == sensor.second.end())
- {
- std::cerr << baseConfiguration->first << " missing connector\n";
- continue;
- }
- auto findPwmIndex = connector->second.find("Pwm");
- if (findPwmIndex == connector->second.end())
- {
- continue;
- }
- uint16_t pwmIndex = variant_ns::visit(VariantToUnsignedIntVisitor(),
- findPwmIndex->second);
- auto oemNamePath = directory.string() + R"(/of_node/oemname)" +
- std::to_string(pwmIndex);
-
- if (DEBUG)
- {
- std::cout << "Checking path " << oemNamePath << "\n";
- }
- std::ifstream nameFile(oemNamePath);
- if (!nameFile.good())
- {
- continue;
- }
- std::string oemName;
- std::getline(nameFile, oemName);
- nameFile.close();
- if (!oemName.size())
- {
- // shouldn't have an empty name file
- continue;
- }
- oemName.pop_back(); // remove trailing null
- auto findIndex = baseConfiguration->second.find("Index");
- if (findIndex == baseConfiguration->second.end())
- {
- std::cerr << baseConfiguration->first << " missing index\n";
- continue;
- }
- unsigned int configIndex = variant_ns::visit(
- VariantToUnsignedIntVisitor(), findIndex->second);
-
- if (configIndex != index)
- {
- continue;
- }
- // now that the indexes match, verify the connector
- auto findConnectorName = connector->second.find("Name");
- if (findConnectorName == connector->second.end())
- {
- continue;
- }
- std::string connectorName = variant_ns::visit(
- VariantToStringVisitor(), findConnectorName->second);
- boost::replace_all(connectorName, " ", "_");
- if (connectorName == oemName)
- {
- sensorData = &(sensor.second);
- break;
- }
- }
- if (sensorData == nullptr)
- {
- std::cerr << "failed to find match for " << path.string() << "\n";
- continue;
- }
-
- auto findSensorName = baseConfiguration->second.find("Name");
- if (findSensorName == baseConfiguration->second.end())
- {
- std::cerr << "could not determine configuration name for "
- << path.string() << "\n";
- continue;
- }
- std::string sensorName =
- sdbusplus::message::variant_ns::get<std::string>(
- findSensorName->second);
- // on rescans, only update sensors we were signaled by
- auto findSensor = tachSensors.find(sensorName);
- if (!firstScan && findSensor != tachSensors.end())
- {
- bool found = false;
- for (auto it = sensorsChanged->begin(); it != sensorsChanged->end();
- it++)
- {
- if (boost::ends_with(*it, findSensor->second->name))
- {
- sensorsChanged->erase(it);
- findSensor->second = nullptr;
- found = true;
- break;
- }
- }
- if (!found)
- {
- continue;
- }
- }
- std::vector<thresholds::Threshold> sensorThresholds;
- if (!parseThresholdsFromConfig(*sensorData, sensorThresholds))
- {
- std::cerr << "error populating thresholds for " << sensorName
- << "\n";
- }
-
- auto presenceConfig =
- sensorData->find(baseType + std::string(".Presence"));
-
- std::unique_ptr<PresenceSensor> presenceSensor(nullptr);
-
- // presence sensors are optional
- if (presenceConfig != sensorData->end())
- {
- auto findIndex = presenceConfig->second.find("Index");
- auto findPolarity = presenceConfig->second.find("Polarity");
-
- if (findIndex == presenceConfig->second.end() ||
- findPolarity == presenceConfig->second.end())
- {
- std::cerr << "Malformed Presence Configuration\n";
- }
- else
- {
- size_t index = variant_ns::get<uint64_t>(findIndex->second);
- bool inverted =
- variant_ns::get<std::string>(findPolarity->second) == "Low";
- presenceSensor =
- std::make_unique<PresenceSensor>(index, inverted, io);
- }
- }
-
- tachSensors[sensorName] = std::make_unique<TachSensor>(
- path.string(), objectServer, dbusConnection,
- std::move(presenceSensor), systemRedundancy, io, sensorName,
- std::move(sensorThresholds), *interfacePath);
- }
- std::vector<fs::path> pwms;
- if (!findFiles(fs::path("/sys/class/hwmon"), R"(pwm\d+)", pwms))
- {
- std::cerr << "No pwm in system\n";
- return;
- }
- for (const fs::path& pwm : pwms)
- {
- // only add new elements
- pwmSensors.insert(std::pair<std::string, std::unique_ptr<PwmSensor>>(
- pwm.string(),
- std::make_unique<PwmSensor>(pwm.string(), objectServer)));
- }
-}
-
-void createRedundancySensor(
- const boost::container::flat_map<std::string, std::unique_ptr<TachSensor>>&
- sensors,
- std::shared_ptr<sdbusplus::asio::connection> conn,
- sdbusplus::asio::object_server& objectServer)
-{
-
- conn->async_method_call(
- [&objectServer, &sensors](boost::system::error_code& ec,
- const ManagedObjectType managedObj) {
- if (ec)
- {
- std::cerr << "Error calling entity manager \n";
- return;
- }
- for (const auto& pathPair : managedObj)
- {
- for (const auto& interfacePair : pathPair.second)
- {
- if (interfacePair.first == redundancyConfiguration)
- {
- // currently only support one
- auto findCount =
- interfacePair.second.find("AllowedFailures");
- if (findCount == interfacePair.second.end())
- {
- std::cerr << "Malformed redundancy record \n";
- return;
- }
- std::vector<std::string> sensorList;
-
- for (const auto& sensor : sensors)
- {
- sensorList.push_back(
- "/xyz/openbmc_project/sensors/fan_tach/" +
- sensor.second->name);
- }
- systemRedundancy = std::make_unique<RedundancySensor>(
- variant_ns::get<uint64_t>(findCount->second),
- sensorList, objectServer);
-
- return;
- }
- }
- }
- },
- "xyz.openbmc_project.EntityManager", "/",
- "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
-}
-
-int main(int argc, char** argv)
-{
- boost::asio::io_service io;
- auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
- systemBus->request_name("xyz.openbmc_project.FanSensor");
- sdbusplus::asio::object_server objectServer(systemBus);
- boost::container::flat_map<std::string, std::unique_ptr<TachSensor>>
- tachSensors;
- boost::container::flat_map<std::string, std::unique_ptr<PwmSensor>>
- pwmSensors;
- std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
- std::unique_ptr<boost::container::flat_set<std::string>> sensorsChanged =
- std::make_unique<boost::container::flat_set<std::string>>();
-
- io.post([&]() {
- createSensors(io, objectServer, tachSensors, pwmSensors, systemBus,
- nullptr);
- createRedundancySensor(tachSensors, systemBus, objectServer);
- });
-
- boost::asio::deadline_timer filterTimer(io);
- std::function<void(sdbusplus::message::message&)> eventHandler =
- [&](sdbusplus::message::message& message) {
- if (message.is_method_error())
- {
- std::cerr << "callback method error\n";
- return;
- }
- sensorsChanged->insert(message.get_path());
- // this implicitly cancels the timer
- filterTimer.expires_from_now(boost::posix_time::seconds(1));
-
- filterTimer.async_wait([&](const boost::system::error_code& ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- /* we were canceled*/
- return;
- }
- else if (ec)
- {
- std::cerr << "timer error\n";
- return;
- }
- createSensors(io, objectServer, tachSensors, pwmSensors,
- systemBus, sensorsChanged);
- });
- };
-
- for (const char* type : sensorTypes)
- {
- auto match = std::make_unique<sdbusplus::bus::match::match>(
- static_cast<sdbusplus::bus::bus&>(*systemBus),
- "type='signal',member='PropertiesChanged',path_namespace='" +
- std::string(inventoryPath) + "',arg0namespace='" + type + "'",
- eventHandler);
- matches.emplace_back(std::move(match));
- }
-
- // redundancy sensor
- std::function<void(sdbusplus::message::message&)> redundancyHandler =
- [&tachSensors, &systemBus,
- &objectServer](sdbusplus::message::message& message) {
- createRedundancySensor(tachSensors, systemBus, objectServer);
- };
- auto match = std::make_unique<sdbusplus::bus::match::match>(
- static_cast<sdbusplus::bus::bus&>(*systemBus),
- "type='signal',member='PropertiesChanged',path_namespace='" +
- std::string(inventoryPath) + "',arg0namespace='" +
- redundancyConfiguration + "'",
- redundancyHandler);
- matches.emplace_back(std::move(match));
-
- io.run();
-}
diff --git a/sensors/src/HwmonTempMain.cpp b/sensors/src/HwmonTempMain.cpp
deleted file mode 100644
index 70fbb75..0000000
--- a/sensors/src/HwmonTempMain.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <HwmonTempSensor.hpp>
-#include <Utils.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/container/flat_set.hpp>
-#include <experimental/filesystem>
-#include <fstream>
-#include <regex>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-
-static constexpr bool DEBUG = false;
-
-namespace fs = std::experimental::filesystem;
-static constexpr std::array<const char*, 2> sensorTypes = {
- "xyz.openbmc_project.Configuration.TMP75",
- "xyz.openbmc_project.Configuration.TMP421"};
-
-void createSensors(
- boost::asio::io_service& io, sdbusplus::asio::object_server& objectServer,
- boost::container::flat_map<std::string, std::unique_ptr<HwmonTempSensor>>&
- sensors,
- std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
- const std::unique_ptr<boost::container::flat_set<std::string>>&
- sensorsChanged)
-{
- bool firstScan = sensorsChanged == nullptr;
- // use new data the first time, then refresh
- ManagedObjectType sensorConfigurations;
- bool useCache = false;
- for (const char* type : sensorTypes)
- {
- if (!getSensorConfiguration(type, dbusConnection, sensorConfigurations,
- useCache))
- {
- std::cerr << "error communicating to entity manager\n";
- return;
- }
- useCache = true;
- }
- std::vector<fs::path> paths;
- if (!findFiles(fs::path("/sys/class/hwmon"), R"(temp\d+_input)", paths))
- {
- std::cerr << "No temperature sensors in system\n";
- return;
- }
-
- boost::container::flat_set<std::string> directories;
-
- // iterate through all found temp sensors, and try to match them with
- // configuration
- for (auto& path : paths)
- {
- std::smatch match;
- const std::string& pathStr = path.string();
- auto directory = path.parent_path();
-
- auto ret = directories.insert(directory.string());
- if (!ret.second)
- {
- continue; // already searched this path
- }
-
- auto device = fs::path(directory / "device");
- std::string deviceName = fs::canonical(device).stem();
- auto findHyphen = deviceName.find("-");
- if (findHyphen == std::string::npos)
- {
- std::cerr << "found bad device " << deviceName << "\n";
- continue;
- }
- std::string busStr = deviceName.substr(0, findHyphen);
- std::string addrStr = deviceName.substr(findHyphen + 1);
-
- size_t bus = 0;
- size_t addr = 0;
- try
- {
- bus = std::stoi(busStr);
- addr = std::stoi(addrStr, 0, 16);
- }
- catch (std::invalid_argument)
- {
- continue;
- }
- const SensorData* sensorData = nullptr;
- const std::string* interfacePath = nullptr;
- const char* sensorType = nullptr;
- const std::pair<std::string, boost::container::flat_map<
- std::string, BasicVariantType>>*
- baseConfiguration = nullptr;
-
- for (const std::pair<sdbusplus::message::object_path, SensorData>&
- sensor : sensorConfigurations)
- {
- sensorData = &(sensor.second);
- for (const char* type : sensorTypes)
- {
- auto sensorBase = sensorData->find(type);
- if (sensorBase != sensorData->end())
- {
- baseConfiguration = &(*sensorBase);
- sensorType = type;
- break;
- }
- }
- if (baseConfiguration == nullptr)
- {
- std::cerr << "error finding base configuration for "
- << deviceName << "\n";
- continue;
- }
- auto configurationBus = baseConfiguration->second.find("Bus");
- auto configurationAddress =
- baseConfiguration->second.find("Address");
-
- if (configurationBus == baseConfiguration->second.end() ||
- configurationAddress == baseConfiguration->second.end())
- {
- std::cerr << "error finding bus or address in configuration";
- continue;
- }
-
- if (sdbusplus::message::variant_ns::get<uint64_t>(
- configurationBus->second) != bus ||
- sdbusplus::message::variant_ns::get<uint64_t>(
- configurationAddress->second) != addr)
- {
- continue;
- }
-
- interfacePath = &(sensor.first.str);
- break;
- }
- if (interfacePath == nullptr)
- {
- std::cerr << "failed to find match for " << deviceName << "\n";
- continue;
- }
-
- auto findSensorName = baseConfiguration->second.find("Name");
- if (findSensorName == baseConfiguration->second.end())
- {
- std::cerr << "could not determine configuration name for "
- << deviceName << "\n";
- continue;
- }
- std::string sensorName =
- sdbusplus::message::variant_ns::get<std::string>(
- findSensorName->second);
- // on rescans, only update sensors we were signaled by
- auto findSensor = sensors.find(sensorName);
- if (!firstScan && findSensor != sensors.end())
- {
- bool found = false;
- for (auto it = sensorsChanged->begin(); it != sensorsChanged->end();
- it++)
- {
- if (boost::ends_with(*it, findSensor->second->name))
- {
- sensorsChanged->erase(it);
- findSensor->second = nullptr;
- found = true;
- break;
- }
- }
- if (!found)
- {
- continue;
- }
- }
- std::vector<thresholds::Threshold> sensorThresholds;
- if (!parseThresholdsFromConfig(*sensorData, sensorThresholds))
- {
- std::cerr << "error populating thresholds for " << sensorName
- << "\n";
- }
-
- sensors[sensorName] = std::make_unique<HwmonTempSensor>(
- directory.string() + "/temp1_input", sensorType, objectServer,
- dbusConnection, io, sensorName, std::move(sensorThresholds),
- *interfacePath);
- auto findSecondName = baseConfiguration->second.find("Name1");
- if (findSecondName == baseConfiguration->second.end())
- {
- continue;
- }
-
- sensorName = sdbusplus::message::variant_ns::get<std::string>(
- findSecondName->second);
- sensors[sensorName] = std::make_unique<HwmonTempSensor>(
- directory.string() + "/temp2_input", sensorType, objectServer,
- dbusConnection, io, sensorName,
- std::vector<thresholds::Threshold>(), *interfacePath);
- }
-}
-
-int main(int argc, char** argv)
-{
- boost::asio::io_service io;
- auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
- systemBus->request_name("xyz.openbmc_project.HwmonTempSensor");
- sdbusplus::asio::object_server objectServer(systemBus);
- boost::container::flat_map<std::string, std::unique_ptr<HwmonTempSensor>>
- sensors;
- std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
- std::unique_ptr<boost::container::flat_set<std::string>> sensorsChanged =
- std::make_unique<boost::container::flat_set<std::string>>();
-
- io.post([&]() {
- createSensors(io, objectServer, sensors, systemBus, nullptr);
- });
-
- boost::asio::deadline_timer filterTimer(io);
- std::function<void(sdbusplus::message::message&)> eventHandler =
- [&](sdbusplus::message::message& message) {
- if (message.is_method_error())
- {
- std::cerr << "callback method error\n";
- return;
- }
- sensorsChanged->insert(message.get_path());
- // this implicitly cancels the timer
- filterTimer.expires_from_now(boost::posix_time::seconds(1));
-
- filterTimer.async_wait([&](const boost::system::error_code& ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- /* we were canceled*/
- return;
- }
- else if (ec)
- {
- std::cerr << "timer error\n";
- return;
- }
- createSensors(io, objectServer, sensors, systemBus,
- sensorsChanged);
- });
- };
-
- for (const char* type : sensorTypes)
- {
- auto match = std::make_unique<sdbusplus::bus::match::match>(
- static_cast<sdbusplus::bus::bus&>(*systemBus),
- "type='signal',member='PropertiesChanged',path_namespace='" +
- std::string(inventoryPath) + "',arg0namespace='" + type + "'",
- eventHandler);
- matches.emplace_back(std::move(match));
- }
-
- io.run();
-}
diff --git a/sensors/src/HwmonTempSensor.cpp b/sensors/src/HwmonTempSensor.cpp
deleted file mode 100644
index 48e3fa6..0000000
--- a/sensors/src/HwmonTempSensor.cpp
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <unistd.h>
-
-#include <HwmonTempSensor.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
-#include <iostream>
-#include <limits>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-#include <string>
-
-static constexpr unsigned int sensorPollMs = 500;
-static constexpr unsigned int sensorScaleFactor = 1000;
-static constexpr size_t warnAfterErrorCount = 10;
-
-HwmonTempSensor::HwmonTempSensor(
- const std::string &path, const std::string &objectType,
- sdbusplus::asio::object_server &objectServer,
- std::shared_ptr<sdbusplus::asio::connection> &conn,
- boost::asio::io_service &io, const std::string &sensorName,
- std::vector<thresholds::Threshold> &&_thresholds,
- const std::string &sensorConfiguration) :
- Sensor(boost::replace_all_copy(sensorName, " ", "_"), path,
- std::move(_thresholds)),
- objectType(objectType), configuration(sensorConfiguration),
- objServer(objectServer), inputDev(io, open(path.c_str(), O_RDONLY)),
- waitTimer(io), errCount(0),
- // todo, get these from config
- maxValue(127), minValue(-128)
-{
- sensorInterface = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/temperature/" + name,
- "xyz.openbmc_project.Sensor.Value");
-
- if (thresholds::hasWarningInterface(thresholds))
- {
- thresholdInterfaceWarning = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/temperature/" + name,
- "xyz.openbmc_project.Sensor.Threshold.Warning");
- }
- if (thresholds::hasCriticalInterface(thresholds))
- {
- thresholdInterfaceCritical = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/temperature/" + name,
- "xyz.openbmc_project.Sensor.Threshold.Critical");
- }
- setInitialProperties(conn);
- setupRead();
-}
-
-HwmonTempSensor::~HwmonTempSensor()
-{
- // close the input dev to cancel async operations
- inputDev.close();
- waitTimer.cancel();
- objServer.remove_interface(thresholdInterfaceWarning);
- objServer.remove_interface(thresholdInterfaceCritical);
- objServer.remove_interface(sensorInterface);
-}
-
-void HwmonTempSensor::setupRead(void)
-{
- boost::asio::async_read_until(
- inputDev, readBuf, '\n',
- [&](const boost::system::error_code &ec,
- std::size_t /*bytes_transfered*/) { handleResponse(ec); });
-}
-
-void HwmonTempSensor::handleResponse(const boost::system::error_code &err)
-{
- if (err == boost::system::errc::bad_file_descriptor)
- {
- return; // we're being destroyed
- }
- std::istream responseStream(&readBuf);
- if (!err)
- {
- std::string response;
- std::getline(responseStream, response);
- try
- {
- float nvalue = std::stof(response);
- nvalue /= sensorScaleFactor;
- if (!isnan(overriddenValue))
- {
- nvalue = overriddenValue;
- }
- if (nvalue != value)
- {
- updateValue(nvalue);
- }
- errCount = 0;
- }
- catch (const std::invalid_argument &)
- {
- errCount++;
- }
- }
- else
- {
- errCount++;
- }
-
- // only print once
- if (errCount == warnAfterErrorCount)
- {
- std::cerr << "Failure to read sensor " << name << " at " << path
- << " ec:" << err << "\n";
- }
-
- if (errCount >= warnAfterErrorCount)
- {
- updateValue(0);
- }
- responseStream.clear();
- inputDev.close();
- int fd = open(path.c_str(), O_RDONLY);
- if (fd <= 0)
- {
- return; // we're no longer valid
- }
- inputDev.assign(fd);
- waitTimer.expires_from_now(boost::posix_time::milliseconds(sensorPollMs));
- waitTimer.async_wait([&](const boost::system::error_code &ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- return; // we're being canceled
- }
- setupRead();
- });
-}
-
-void HwmonTempSensor::checkThresholds(void)
-{
- thresholds::checkThresholds(this);
-}
-
-void HwmonTempSensor::updateValue(const double &newValue)
-{
- // Indicate that it is internal set call
- internalSet = true;
- sensorInterface->set_property("Value", newValue);
- internalSet = false;
- value = newValue;
- checkThresholds();
-}
-
-void HwmonTempSensor::setInitialProperties(
- std::shared_ptr<sdbusplus::asio::connection> &conn)
-{
- // todo, get max and min from configuration
- sensorInterface->register_property("MaxValue", maxValue);
- sensorInterface->register_property("MinValue", minValue);
- sensorInterface->register_property(
- "Value", value, [&](const double &newValue, double &oldValue) {
- return setSensorValue(newValue, oldValue);
- });
-
- for (auto &threshold : thresholds)
- {
- std::shared_ptr<sdbusplus::asio::dbus_interface> iface;
- std::string level;
- std::string alarm;
- if (threshold.level == thresholds::Level::CRITICAL)
- {
- iface = thresholdInterfaceCritical;
- if (threshold.direction == thresholds::Direction::HIGH)
- {
- level = "CriticalHigh";
- alarm = "CriticalAlarmHigh";
- }
- else
- {
- level = "CriticalLow";
- alarm = "CriticalAlarmLow";
- }
- }
- else if (threshold.level == thresholds::Level::WARNING)
- {
- iface = thresholdInterfaceWarning;
- if (threshold.direction == thresholds::Direction::HIGH)
- {
- level = "WarningHigh";
- alarm = "WarningAlarmHigh";
- }
- else
- {
- level = "WarningLow";
- alarm = "WarningAlarmLow";
- }
- }
- else
- {
- std::cerr << "Unknown threshold level" << threshold.level << "\n";
- continue;
- }
- if (!iface)
- {
- std::cout << "trying to set uninitialized interface\n";
- continue;
- }
- iface->register_property(
- level, threshold.value,
- [&](const double &request, double &oldValue) {
- oldValue = request; // todo, just let the config do this?
- threshold.value = request;
- thresholds::persistThreshold(configuration, objectType,
- threshold, conn);
- return 1;
- });
- iface->register_property(alarm, false);
- }
- if (!sensorInterface->initialize())
- {
- std::cerr << "error initializing value interface\n";
- }
- if (thresholdInterfaceWarning && !thresholdInterfaceWarning->initialize())
- {
- std::cerr << "error initializing warning threshold interface\n";
- }
-
- if (thresholdInterfaceCritical && !thresholdInterfaceCritical->initialize())
- {
- std::cerr << "error initializing critical threshold interface\n";
- }
-}
diff --git a/sensors/src/PwmSensor.cpp b/sensors/src/PwmSensor.cpp
deleted file mode 100644
index dabc2f8..0000000
--- a/sensors/src/PwmSensor.cpp
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-// Copyright (c) 2018 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-#include <PwmSensor.hpp>
-#include <fstream>
-#include <iostream>
-#include <sdbusplus/asio/object_server.hpp>
-
-static constexpr size_t pwmMax = 255;
-static constexpr size_t pwmMin = 0;
-
-PwmSensor::PwmSensor(const std::string& sysPath,
- sdbusplus::asio::object_server& objectServer) :
- sysPath(sysPath),
- objectServer(objectServer)
-{
- // strip off index from path
- name = "Pwm_" + sysPath.substr(sysPath.find_last_of("pwm") + 1);
-
- // add interface under sensor and Control.FanPwm as Control is used
- // in obmc project, also add sensor so it can be viewed as a sensor
- sensorInterface = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/fan_pwm/" + name,
- "xyz.openbmc_project.Sensor.Value");
- uint32_t pwmValue = getValue(false);
- double fValue = 100.0 * (static_cast<float>(pwmValue) / pwmMax);
- sensorInterface->register_property(
- "Value", fValue,
- [this](const double& req, double& resp) {
- if (req > 100 || req < 0)
- {
- throw std::runtime_error("Value out of range");
- return -1;
- }
- double value = (req / 100) * pwmMax;
- setValue(static_cast<int>(value));
- resp = req;
- return 1;
- },
- [this](double& curVal) {
- float value = 100.0 * (static_cast<float>(getValue()) / pwmMax);
- curVal = value;
- return curVal;
- });
- // pwm sensor interface is in percent
- sensorInterface->register_property("MaxValue", static_cast<int64_t>(100));
- sensorInterface->register_property("MinValue", static_cast<int64_t>(0));
-
- controlInterface = objectServer.add_interface(
- "/xyz/openbmc_project/control/fanpwm/" + name,
- "xyz.openbmc_project.Control.FanPwm");
- controlInterface->register_property(
- "Target", static_cast<uint64_t>(pwmValue),
- [this](const uint64_t& req, uint64_t& resp) {
- if (req > pwmMax || req < pwmMin)
- {
- throw std::runtime_error("Value out of range");
- return -1;
- }
- setValue(req);
- resp = req;
- return 1;
- },
- [this](uint64_t& curVal) {
- curVal = getValue();
- return curVal;
- });
- sensorInterface->initialize();
- controlInterface->initialize();
-}
-PwmSensor::~PwmSensor()
-{
- objectServer.remove_interface(sensorInterface);
- objectServer.remove_interface(controlInterface);
-}
-
-void PwmSensor::setValue(uint32_t value)
-{
- std::ofstream ref(sysPath);
- if (!ref.good())
- {
- throw std::runtime_error("Bad Write File");
- return;
- }
- ref << value;
-}
-
-// on success returns pwm, on failure throws except on initialization, where it
-// prints an error and returns 0
-uint32_t PwmSensor::getValue(bool errThrow)
-{
- std::ifstream ref(sysPath);
- if (!ref.good())
- {
- return -1;
- }
- std::string line;
- if (!std::getline(ref, line))
- {
- return -1;
- }
- try
- {
- uint32_t value = std::stoi(line);
- return value;
- }
- catch (std::invalid_argument)
- {
- std::cerr << "Error reading pwm at " << sysPath << "\n";
- // throw if not initial read to be caught by dbus bindings
- if (errThrow)
- {
- throw std::runtime_error("Bad Read");
- }
- }
- return 0;
-}
diff --git a/sensors/src/TachSensor.cpp b/sensors/src/TachSensor.cpp
deleted file mode 100644
index a68c894..0000000
--- a/sensors/src/TachSensor.cpp
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
-// Copyright (c) 2018 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <unistd.h>
-
-#include <TachSensor.hpp>
-#include <Utils.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
-#include <fstream>
-#include <iostream>
-#include <limits>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/asio/object_server.hpp>
-#include <string>
-
-static constexpr unsigned int pwmPollMs = 500;
-static constexpr size_t warnAfterErrorCount = 10;
-
-TachSensor::TachSensor(const std::string &path,
- sdbusplus::asio::object_server &objectServer,
- std::shared_ptr<sdbusplus::asio::connection> &conn,
- std::unique_ptr<PresenceSensor> &&presence,
- std::unique_ptr<RedundancySensor> &redundancy,
- boost::asio::io_service &io, const std::string &fanName,
- std::vector<thresholds::Threshold> &&_thresholds,
- const std::string &sensorConfiguration) :
- Sensor(boost::replace_all_copy(fanName, " ", "_"), path,
- std::move(_thresholds)),
- objServer(objectServer), dbusConnection(conn),
- presence(std::move(presence)), redundancy(redundancy),
- configuration(sensorConfiguration),
- inputDev(io, open(path.c_str(), O_RDONLY)), waitTimer(io), errCount(0),
- // todo, get these from config
- maxValue(25000), minValue(0)
-{
- sensorInterface = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/fan_tach/" + name,
- "xyz.openbmc_project.Sensor.Value");
-
- if (thresholds::hasWarningInterface(thresholds))
- {
- thresholdInterfaceWarning = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/fan_tach/" + name,
- "xyz.openbmc_project.Sensor.Threshold.Warning");
- }
- if (thresholds::hasCriticalInterface(thresholds))
- {
- thresholdInterfaceCritical = objectServer.add_interface(
- "/xyz/openbmc_project/sensors/fan_tach/" + name,
- "xyz.openbmc_project.Sensor.Threshold.Critical");
- }
- setInitialProperties(conn);
- isPowerOn(dbusConnection); // first call initializes
- setupRead();
-}
-
-TachSensor::~TachSensor()
-{
- // close the input dev to cancel async operations
- inputDev.close();
- waitTimer.cancel();
- objServer.remove_interface(thresholdInterfaceWarning);
- objServer.remove_interface(thresholdInterfaceCritical);
- objServer.remove_interface(sensorInterface);
-}
-
-void TachSensor::setupRead(void)
-{
- boost::asio::async_read_until(
- inputDev, readBuf, '\n',
- [&](const boost::system::error_code &ec,
- std::size_t /*bytes_transfered*/) { handleResponse(ec); });
-}
-
-void TachSensor::handleResponse(const boost::system::error_code &err)
-{
- if (err == boost::system::errc::bad_file_descriptor)
- {
- return; // we're being destroyed
- }
- bool missing = false;
- size_t pollTime = pwmPollMs;
- if (presence)
- {
- if (!presence->getValue())
- {
- updateValue(std::numeric_limits<double>::quiet_NaN());
- missing = true;
- pollTime = sensorFailedPollTimeMs;
- }
- }
- std::istream responseStream(&readBuf);
- if (!missing)
- {
- if (!err)
- {
- std::string response;
- try
- {
- std::getline(responseStream, response);
- float nvalue = std::stof(response);
- responseStream.clear();
- if (!isnan(overriddenValue))
- {
- nvalue = overriddenValue;
- }
- if (nvalue != value)
- {
- updateValue(nvalue);
- }
- errCount = 0;
- }
- catch (const std::invalid_argument &)
- {
- errCount++;
- }
- }
- else
- {
- pollTime = sensorFailedPollTimeMs;
- errCount++;
- }
- if (errCount >= warnAfterErrorCount)
- {
- // only an error if power is on
- if (isPowerOn(dbusConnection))
- {
- // only print once
- if (errCount == warnAfterErrorCount)
- {
- std::cerr << "Failure to read sensor " << name << " at "
- << path << " ec:" << err << "\n";
- }
- updateValue(0);
- }
- else
- {
- errCount = 0; // check power again in 10 cycles
- updateValue(std::numeric_limits<double>::quiet_NaN());
- }
- }
- }
- responseStream.clear();
- inputDev.close();
- int fd = open(path.c_str(), O_RDONLY);
- if (fd <= 0)
- {
- return; // we're no longer valid
- }
- inputDev.assign(fd);
- waitTimer.expires_from_now(boost::posix_time::milliseconds(pollTime));
- waitTimer.async_wait([&](const boost::system::error_code &ec) {
- if (ec == boost::asio::error::operation_aborted)
- {
- return; // we're being canceled
- }
- setupRead();
- });
-}
-
-void TachSensor::checkThresholds(void)
-{
- bool status = thresholds::checkThresholds(this);
- if (redundancy)
- {
- redundancy->update("/xyz/openbmc_project/sensors/fan_tach/" + name,
- !status);
- }
-}
-
-void TachSensor::updateValue(const double &newValue)
-{
- // Indicate that it is internal set call
- internalSet = true;
- sensorInterface->set_property("Value", newValue);
- internalSet = false;
- value = newValue;
- checkThresholds();
-}
-
-void TachSensor::setInitialProperties(
- std::shared_ptr<sdbusplus::asio::connection> &conn)
-{
- // todo, get max and min from configuration
- sensorInterface->register_property("MaxValue", maxValue);
- sensorInterface->register_property("MinValue", minValue);
- sensorInterface->register_property(
- "Value", value, [&](const double &newValue, double &oldValue) {
- return setSensorValue(newValue, oldValue);
- });
-
- for (auto &threshold : thresholds)
- {
- std::shared_ptr<sdbusplus::asio::dbus_interface> iface;
- std::string level;
- std::string alarm;
- if (threshold.level == thresholds::Level::CRITICAL)
- {
- iface = thresholdInterfaceCritical;
- if (threshold.direction == thresholds::Direction::HIGH)
- {
- level = "CriticalHigh";
- alarm = "CriticalAlarmHigh";
- }
- else
- {
- level = "CriticalLow";
- alarm = "CriticalAlarmLow";
- }
- }
- else if (threshold.level == thresholds::Level::WARNING)
- {
- iface = thresholdInterfaceWarning;
- if (threshold.direction == thresholds::Direction::HIGH)
- {
- level = "WarningHigh";
- alarm = "WarningAlarmHigh";
- }
- else
- {
- level = "WarningLow";
- alarm = "WarningAlarmLow";
- }
- }
- else
- {
- std::cerr << "Unknown threshold level" << threshold.level << "\n";
- continue;
- }
- if (!iface)
- {
- std::cout << "trying to set uninitialized interface\n";
- continue;
- }
- iface->register_property(
- level, threshold.value,
- [&](const double &request, double &oldValue) {
- oldValue = request; // todo, just let the config do this?
- threshold.value = request;
- thresholds::persistThreshold(
- configuration,
- "xyz.openbmc_project.Configuration.AspeedFan", threshold,
- conn);
- return 1;
- });
- iface->register_property(alarm, false);
- }
- if (!sensorInterface->initialize())
- {
- std::cerr << "error initializing value interface\n";
- }
- if (thresholdInterfaceWarning && !thresholdInterfaceWarning->initialize())
- {
- std::cerr << "error initializing warning threshold interface\n";
- }
-
- if (thresholdInterfaceCritical && !thresholdInterfaceCritical->initialize())
- {
- std::cerr << "error initializing critical threshold interface\n";
- }
-}
-
-PresenceSensor::PresenceSensor(const size_t index, bool inverted,
- boost::asio::io_service &io) :
- inverted(inverted),
- inputDev(io)
-{
- // todo: use gpiodaemon
- std::string device = gpioPath + std::string("gpio") + std::to_string(index);
- fd = open((device + "/value").c_str(), O_RDONLY);
- if (fd < 0)
- {
- std::cerr << "Error opening gpio " << index << "\n";
- return;
- }
-
- std::ofstream deviceFile(device + "/edge");
- if (!deviceFile.good())
- {
- std::cerr << "Error setting edge " << device << "\n";
- return;
- }
- deviceFile << "both";
- deviceFile.close();
-
- inputDev.assign(boost::asio::ip::tcp::v4(), fd);
- monitorPresence();
- read();
-}
-
-PresenceSensor::~PresenceSensor()
-{
- inputDev.close();
- close(fd);
-}
-
-void PresenceSensor::monitorPresence(void)
-{
- inputDev.async_wait(boost::asio::ip::tcp::socket::wait_error,
- [this](const boost::system::error_code &ec) {
- if (ec == boost::system::errc::bad_file_descriptor)
- {
- return; // we're being destroyed
- }
- else if (ec)
- {
- std::cerr
- << "Error on presence sensor socket\n";
- }
- else
- {
- read();
- }
- monitorPresence();
- });
-}
-
-void PresenceSensor::read(void)
-{
- constexpr size_t readSize = sizeof("0");
- std::string readBuf;
- readBuf.resize(readSize);
- lseek(fd, 0, SEEK_SET);
- size_t r = ::read(fd, readBuf.data(), readSize);
- if (r != 1)
- {
- std::cerr << "Error reading gpio\n";
- }
- else
- {
- bool value = std::stoi(readBuf);
- if (inverted)
- {
- value = !value;
- }
- status = value;
- }
-}
-
-bool PresenceSensor::getValue(void)
-{
- return status;
-}
-
-RedundancySensor::RedundancySensor(
- size_t count, const std::vector<std::string> &children,
- sdbusplus::asio::object_server &objectServer) :
- count(count),
- iface(objectServer.add_interface(
- "/xyz/openbmc_project/control/FanRedundancy/Tach",
- "xyz.openbmc_project.control.FanRedundancy")),
- objectServer(objectServer)
-{
- iface->register_property("Collection", children);
- iface->register_property("Status", std::string("Full"));
- iface->register_property("AllowedFailures", static_cast<uint8_t>(count));
- iface->initialize();
-}
-RedundancySensor::~RedundancySensor()
-{
- objectServer.remove_interface(iface);
-}
-void RedundancySensor::update(const std::string &name, bool failed)
-{
- statuses[name] = failed;
- size_t failedCount = 0;
-
- std::string state = "Full";
- for (const auto &status : statuses)
- {
- if (status.second)
- {
- failedCount++;
- }
- if (failedCount > count)
- {
- state = "Failed";
- break;
- }
- else if (failedCount)
- {
- state = "Degraded";
- }
- }
- iface->set_property("Status", state);
-}
diff --git a/sensors/src/Thresholds.cpp b/sensors/src/Thresholds.cpp
deleted file mode 100644
index 10b1674..0000000
--- a/sensors/src/Thresholds.cpp
+++ /dev/null
@@ -1,338 +0,0 @@
-#include <Thresholds.hpp>
-#include <VariantVisitors.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#include <boost/lexical_cast.hpp>
-#include <cmath>
-#include <fstream>
-#include <iostream>
-#include <sensor.hpp>
-
-static constexpr bool DEBUG = false;
-static constexpr size_t maxThresholds = 4;
-
-namespace variant_ns = sdbusplus::message::variant_ns;
-namespace thresholds
-{
-unsigned int toBusValue(const Level &level)
-{
- switch (level)
- {
- case (Level::WARNING):
- {
- return 0;
- }
- case (Level::CRITICAL):
- {
- return 1;
- }
- default:
- {
- return -1;
- }
- }
-}
-
-std::string toBusValue(const Direction &direction)
-{
- switch (direction)
- {
- case (Direction::LOW):
- {
- return "less than";
- }
- case (Direction::HIGH):
- {
- return "greater than";
- }
- default:
- {
- return "err";
- }
- }
-}
-
-bool parseThresholdsFromConfig(
- const SensorData &sensorData,
- std::vector<thresholds::Threshold> &thresholdVector,
- const std::string *matchLabel)
-{
- for (const auto &item : sensorData)
- {
- if (item.first.find("Thresholds") == std::string::npos)
- {
- continue;
- }
- if (matchLabel != nullptr)
- {
- auto labelFind = item.second.find("Label");
- if (labelFind == item.second.end())
- continue;
- if (variant_ns::visit(VariantToStringVisitor(),
- labelFind->second) != *matchLabel)
- continue;
- }
- auto directionFind = item.second.find("Direction");
- auto severityFind = item.second.find("Severity");
- auto valueFind = item.second.find("Value");
- if (valueFind == item.second.end() ||
- severityFind == item.second.end() ||
- directionFind == item.second.end())
- {
- std::cerr << "Malformed threshold in configuration\n";
- return false;
- }
- Level level;
- Direction direction;
- if (variant_ns::visit(VariantToUnsignedIntVisitor(),
- severityFind->second) == 0)
- {
- level = Level::WARNING;
- }
- else
- {
- level = Level::CRITICAL;
- }
- if (variant_ns::visit(VariantToStringVisitor(),
- directionFind->second) == "less than")
- {
- direction = Direction::LOW;
- }
- else
- {
- direction = Direction::HIGH;
- }
- float val =
- variant_ns::visit(VariantToFloatVisitor(), valueFind->second);
-
- thresholdVector.emplace_back(level, direction, val);
- }
- return true;
-}
-
-void persistThreshold(const std::string &path, const std::string &baseInterface,
- const thresholds::Threshold &threshold,
- std::shared_ptr<sdbusplus::asio::connection> &conn)
-{
- for (int ii = 0; ii < maxThresholds; ii++)
- {
- std::string thresholdInterface =
- baseInterface + ".Thresholds" + std::to_string(ii);
- conn->async_method_call(
- [&, path, threshold, thresholdInterface](
- const boost::system::error_code &ec,
- const boost::container::flat_map<std::string, BasicVariantType>
- &result) {
- if (ec)
- {
- return; // threshold not supported
- }
-
- auto directionFind = result.find("Direction");
- auto severityFind = result.find("Severity");
- auto valueFind = result.find("Value");
- if (valueFind == result.end() || severityFind == result.end() ||
- directionFind == result.end())
- {
- std::cerr << "Malformed threshold in configuration\n";
- return;
- }
- unsigned int level = variant_ns::visit(
- VariantToUnsignedIntVisitor(), severityFind->second);
-
- std::string dir = variant_ns::visit(VariantToStringVisitor(),
- directionFind->second);
- if ((toBusValue(threshold.level) != level) ||
- (toBusValue(threshold.direction) != dir))
- {
- return; // not the droid we're looking for
- }
-
- sdbusplus::message::variant<double> value(threshold.value);
- conn->async_method_call(
- [](const boost::system::error_code &ec) {
- if (ec)
- {
- std::cerr << "Error setting threshold " << ec
- << "\n";
- }
- },
- entityManagerName, path, "org.freedesktop.DBus.Properties",
- "Set", thresholdInterface, "Value", value);
- },
- entityManagerName, path, "org.freedesktop.DBus.Properties",
- "GetAll", thresholdInterface);
- }
-}
-
-bool checkThresholds(Sensor *sensor)
-{
- bool status = true;
-
- if (sensor->thresholds.empty())
- {
- return true;
- }
- for (auto &threshold : sensor->thresholds)
- {
- if (std::isnan(sensor->value))
- {
- threshold.asserted = false;
- }
- else if (threshold.direction == thresholds::Direction::HIGH)
- {
- if (sensor->value > threshold.value && !threshold.asserted)
- {
- assertThresholds(sensor, threshold.level, threshold.direction,
- true);
- threshold.asserted = true;
- }
- else if (sensor->value <= threshold.value && threshold.asserted)
- {
- assertThresholds(sensor, threshold.level, threshold.direction,
- false);
- threshold.asserted = false;
- }
- }
- else
- {
- if (sensor->value < threshold.value && !threshold.asserted)
- {
- assertThresholds(sensor, threshold.level, threshold.direction,
- true);
- threshold.asserted = true;
- }
- else if (sensor->value >= threshold.value && threshold.asserted)
- {
- assertThresholds(sensor, threshold.level, threshold.direction,
- false);
- threshold.asserted = false;
- }
- }
- if (threshold.level == thresholds::Level::CRITICAL &&
- threshold.asserted)
- {
- status = false;
- }
- }
- return status;
-}
-
-void assertThresholds(Sensor *sensor, thresholds::Level level,
- thresholds::Direction direction, bool assert)
-{
- std::string property;
- std::shared_ptr<sdbusplus::asio::dbus_interface> interface;
- if (level == thresholds::Level::WARNING &&
- direction == thresholds::Direction::HIGH)
- {
- property = "WarningAlarmHigh";
- interface = sensor->thresholdInterfaceWarning;
- }
- else if (level == thresholds::Level::WARNING &&
- direction == thresholds::Direction::LOW)
- {
- property = "WarningAlarmLow";
- interface = sensor->thresholdInterfaceWarning;
- }
- else if (level == thresholds::Level::CRITICAL &&
- direction == thresholds::Direction::HIGH)
- {
- property = "CriticalAlarmHigh";
- interface = sensor->thresholdInterfaceCritical;
- }
- else if (level == thresholds::Level::CRITICAL &&
- direction == thresholds::Direction::LOW)
- {
- property = "CriticalAlarmLow";
- interface = sensor->thresholdInterfaceCritical;
- }
- else
- {
- std::cerr << "Unknown threshold, level " << level << "direction "
- << direction << "\n";
- return;
- }
- if (!interface)
- {
- std::cout << "trying to set uninitialized interface\n";
- return;
- }
- interface->set_property(property, assert);
-}
-
-static constexpr std::array<const char *, 4> attrTypes = {"lcrit", "min", "max",
- "crit"};
-
-bool parseThresholdsFromAttr(
- std::vector<thresholds::Threshold> &thresholdVector,
- const std::string &inputPath, const double &scaleFactor)
-{
- for (auto &type : attrTypes)
- {
- auto attrPath = boost::replace_all_copy(inputPath, "input", type);
- std::ifstream attrFile(attrPath);
- if (!attrFile.good())
- {
- continue;
- }
- std::string attr;
- std::getline(attrFile, attr);
- attrFile.close();
-
- Level level;
- Direction direction;
- double val = std::stod(attr) / scaleFactor;
- if (type == "min" || type == "max")
- {
- level = Level::WARNING;
- }
- else
- {
- level = Level::CRITICAL;
- }
- if (type == "min" || type == "lcrit")
- {
- direction = Direction::LOW;
- }
- else
- {
- direction = Direction::HIGH;
- }
-
- if (DEBUG)
- {
- std::cout << "Threshold: " << attrPath << ": " << val << "\n";
- }
-
- thresholdVector.emplace_back(level, direction, val);
- }
- // no thresholds is allowed, not an error so return true always
- return true;
-}
-
-bool hasCriticalInterface(
- const std::vector<thresholds::Threshold> &thresholdVector)
-{
- for (auto &threshold : thresholdVector)
- {
- if (threshold.level == Level::CRITICAL)
- {
- return true;
- }
- }
- return false;
-}
-
-bool hasWarningInterface(
- const std::vector<thresholds::Threshold> &thresholdVector)
-{
- for (auto &threshold : thresholdVector)
- {
- if (threshold.level == Level::WARNING)
- {
- return true;
- }
- }
- return false;
-}
-} // namespace thresholds
diff --git a/sensors/src/Utils.cpp b/sensors/src/Utils.cpp
deleted file mode 100644
index a5685d5..0000000
--- a/sensors/src/Utils.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-*/
-
-#include <Utils.hpp>
-#include <boost/algorithm/string/predicate.hpp>
-#include <experimental/filesystem>
-#include <fstream>
-#include <regex>
-#include <sdbusplus/asio/connection.hpp>
-#include <sdbusplus/bus/match.hpp>
-
-namespace fs = std::experimental::filesystem;
-const static constexpr char* powerInterfaceName =
- "xyz.openbmc_project.Chassis.Control.Power";
-const static constexpr char* powerObjectName =
- "/xyz/openbmc_project/Chassis/Control/Power0";
-
-bool getSensorConfiguration(
- const std::string& type,
- const std::shared_ptr<sdbusplus::asio::connection>& dbusConnection,
- ManagedObjectType& resp, bool useCache)
-{
- static ManagedObjectType managedObj;
-
- if (!useCache)
- {
- managedObj.clear();
- sdbusplus::message::message getManagedObjects =
- dbusConnection->new_method_call(
- entityManagerName, "/", "org.freedesktop.DBus.ObjectManager",
- "GetManagedObjects");
- bool err = false;
- try
- {
- sdbusplus::message::message reply =
- dbusConnection->call(getManagedObjects);
- reply.read(managedObj);
- }
- catch (const sdbusplus::exception::exception&)
- {
- err = true;
- }
-
- if (err)
- {
- std::cerr << "Error communicating to entity manager\n";
- return false;
- }
- }
- for (const auto& pathPair : managedObj)
- {
- std::vector<boost::container::flat_map<std::string, BasicVariantType>>
- sensorData;
- bool correctType = false;
- for (const auto& entry : pathPair.second)
- {
- if (boost::starts_with(entry.first, type))
- {
- correctType = true;
- break;
- }
- }
- if (correctType)
- {
- resp.emplace(pathPair);
- }
- }
- return true;
-}
-
-bool findFiles(const fs::path dirPath, const std::string& matchString,
- std::vector<fs::path>& foundPaths, unsigned int symlinkDepth)
-{
- if (!fs::exists(dirPath))
- return false;
-
- std::regex search(matchString);
- std::smatch match;
- for (auto& p : fs::recursive_directory_iterator(dirPath))
- {
- std::string path = p.path().string();
- if (!is_directory(p))
- {
- if (std::regex_search(path, match, search))
- foundPaths.emplace_back(p.path());
- }
- else if (is_symlink(p) && symlinkDepth)
- {
- findFiles(p.path(), matchString, foundPaths, symlinkDepth - 1);
- }
- }
- return true;
-}
-
-// initially returns false, then sets up matches and returns status
-// should be called once first to initialize
-bool isPowerOn(const std::shared_ptr<sdbusplus::asio::connection>& conn)
-{
- static std::unique_ptr<sdbusplus::bus::match::match> powerMatch = nullptr;
- static bool powerStatusOn = false;
-
- if (powerMatch != nullptr)
- {
- return powerStatusOn;
- }
-
- // create a match for powergood changes, first time do a method call to
- // return the correct value
- std::function<void(sdbusplus::message::message & message)> eventHandler =
- [&powerStatusOn](sdbusplus::message::message& message) {
- std::string objectName;
- boost::container::flat_map<std::string,
- sdbusplus::message::variant<int32_t>>
- values;
- message.read(objectName, values);
- auto findPgood = values.find("pgood");
- if (findPgood != values.end())
- {
- powerStatusOn = sdbusplus::message::variant_ns::get<int32_t>(
- findPgood->second);
- }
- };
-
- powerMatch = std::make_unique<sdbusplus::bus::match::match>(
- static_cast<sdbusplus::bus::bus&>(*conn),
- "type='signal',interface='org.freedesktop.DBus.Properties',path_"
- "namespace='/xyz/openbmc_project/Chassis/Control/"
- "power0',arg0='xyz.openbmc_project.Chassis.Control.Power'",
- eventHandler);
-
- conn->async_method_call(
- [&powerStatusOn](boost::system::error_code ec,
- const sdbusplus::message::variant<int32_t>& pgood) {
- if (ec)
- {
- std::cerr << "Error getting initial power status\n";
- return;
- }
- powerStatusOn = sdbusplus::message::variant_ns::get<int32_t>(pgood);
- },
- powerInterfaceName, powerObjectName, "org.freedesktop.DBus.Properties",
- "Get", powerInterfaceName, "pgood");
-
- return powerStatusOn;
-}
\ No newline at end of file
diff --git a/sensors/tests/test_HwmonTempSensor.cpp b/sensors/tests/test_HwmonTempSensor.cpp
deleted file mode 100644
index a618720..0000000
--- a/sensors/tests/test_HwmonTempSensor.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-#include <HwmonTempSensor.hpp>
-#include <dbus/connection.hpp>
-#include <nlohmann/json.hpp>
-#include <fstream>
-#include "gtest/gtest.h"
-
-TEST(HwmonTempSensor, TestTMP75)
-{
- boost::asio::io_service io;
- auto system_bus =
- std::make_shared<dbus::connection>(io, dbus::bus::session);
- dbus::DbusObjectServer object_server(system_bus);
-
- std::vector<thresholds::Threshold> sensor_thresholds;
- auto t = thresholds::Threshold(thresholds::Level::CRITICAL,
- thresholds::Direction::LOW, 80);
- sensor_thresholds.emplace_back(t);
-
- std::ofstream test_file("test0.txt");
- test_file << "28\n";
- test_file.close();
- auto filename = std::string("test0.txt");
- auto tempsensname = std::string("test sensor");
- HwmonTempSensor test(filename, object_server, io, tempsensname,
- std::move(sensor_thresholds));
-
- std::remove("test0.txt");
-}
-
-TEST(HwmonTempSensor, TestTMP421)
-{
- boost::asio::io_service io;
- auto system_bus =
- std::make_shared<dbus::connection>(io, dbus::bus::session);
- dbus::DbusObjectServer object_server(system_bus);
-
- std::vector<thresholds::Threshold> sensor_thresholds;
- auto t = thresholds::Threshold(thresholds::Level::WARNING,
- thresholds::Direction::HIGH, 80);
- sensor_thresholds.emplace_back(t);
-
- std::ofstream test_file("test1.txt");
- test_file << "28\n";
- test_file.close();
- auto filename = std::string("test1.txt");
- auto tempsensname = std::string("test sensor");
- HwmonTempSensor test(filename, object_server, io, tempsensname,
- std::move(sensor_thresholds));
-
- std::remove("test1.txt");
-}
diff --git a/sensors/tests/test_TachSensor.cpp b/sensors/tests/test_TachSensor.cpp
deleted file mode 100644
index 059b18b..0000000
--- a/sensors/tests/test_TachSensor.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include <TachSensor.hpp>
-#include <Thresholds.hpp>
-#include <dbus/connection.hpp>
-#include <nlohmann/json.hpp>
-#include <fstream>
-#include "gtest/gtest.h"
-
-TEST(TachSensor, TestTachSensor)
-{
- boost::asio::io_service io;
- auto system_bus =
- std::make_shared<dbus::connection>(io, dbus::bus::session);
- dbus::DbusObjectServer object_server(system_bus);
-
- std::vector<thresholds::Threshold> sensor_thresholds;
- auto t = thresholds::Threshold(thresholds::Level::CRITICAL,
- thresholds::Direction::LOW, 1000);
- sensor_thresholds.emplace_back(t);
-
- std::ofstream test_file("test.txt");
- test_file << "10000\n";
- test_file.close();
- auto filename = std::string("test.txt");
- auto fanname = std::string("test fan");
- TachSensor test(filename, object_server, system_bus, io, fanname,
- std::move(sensor_thresholds));
- std::remove("test.txt");
-}