Skip to content

Instantly share code, notes, and snippets.

@arthurmco
Created December 9, 2020 00:25
Show Gist options
  • Save arthurmco/cca170e9bbcf866b763db92d02c65926 to your computer and use it in GitHub Desktop.
Save arthurmco/cca170e9bbcf866b763db92d02c65926 to your computer and use it in GitHub Desktop.
read sensor information on linux
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sensors/sensors.h>
#include <sensors/error.h>
/**
* Reads informations of all sensors and print them, a little bit rawish
*
* Compile it with `g++ sensors_test.cpp -o sensors_test -lsensors --std=c++17 -Wall`
*
* Since libsensors is linux-specific, it will only work on Linux
*/
int main(int argc, char* argv[])
{
if (sensors_init(nullptr)) {
puts("Error");
return 1;
}
/**
* This library is organized in the following way
* - Chips
* | - Features, like "groups" of sensors
* | | - Subfeatures, the sensors themselves
*/
int i = 0;
for(auto* chip = sensors_get_detected_chips(nullptr, &i);
chip != nullptr;
chip = sensors_get_detected_chips(nullptr, &i))
{
char orig_name[256] = {};
if (auto e = sensors_snprintf_chip_name(orig_name, 255, chip); e < 0) {
printf("Error while getting chip name: %s\n", sensors_strerror(e));
continue;
}
printf("%d: %s\n", i+1, orig_name);
int feati = 0;
for (auto* feat = sensors_get_features(chip, &feati); feat != nullptr;
feat = sensors_get_features(chip, &feati))
{
// get feature type
const char* ftype;
switch (feat->type) {
case SENSORS_FEATURE_IN: ftype = "in"; break;
case SENSORS_FEATURE_FAN: ftype = "fan"; break;
case SENSORS_FEATURE_TEMP: ftype = "temperature"; break;
case SENSORS_FEATURE_POWER: ftype = "power"; break;
case SENSORS_FEATURE_ENERGY: ftype = "energy"; break;
case SENSORS_FEATURE_CURR: ftype = "current"; break;
case SENSORS_FEATURE_HUMIDITY: ftype = "humidity"; break;
// there are more types, but I will not show them
default: ftype = "other"; break;
}
printf("\tfeature %s, number %d, type %02x (%s)\n",
feat->name, feat->number, feat->type, ftype);
int sfeati = 0;
for (auto* sfeat = sensors_get_all_subfeatures(chip, feat, &sfeati); sfeat != nullptr;
sfeat = sensors_get_all_subfeatures(chip, feat, &sfeati))
{
/// get flags
std::string flagstr = "";
if (sfeat->flags & SENSORS_MODE_R)
flagstr += " readable";
if (sfeat->flags & SENSORS_MODE_W)
flagstr += " writable";
if (sfeat->flags & SENSORS_COMPUTE_MAPPING)
flagstr += " affected-by-main-feature";
// write sensor data
printf("\t\tsubfeature %s, number %d, type %04x, mapping %08x, flags %02x (%s )\n",
sfeat->name, sfeat->number, sfeat->type, sfeat->mapping, sfeat->flags, flagstr.c_str());
double val = 0.0;
if (auto e = sensors_get_value(chip, sfeat->number, &val); e < 0) {
printf("\t\t\terror '%s' while getting value", sensors_strerror(e));
} else {
printf("\t\t\tvalue %.2f", val);
}
puts(")");
}
}
}
sensors_cleanup();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment