temperature.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* See LICENSE file for copyright and license details. */
  2. #include <stddef.h>
  3. #include "../util.h"
  4. #if defined(__linux__)
  5. #include <stdint.h>
  6. const char *
  7. temp(const char *file)
  8. {
  9. uintmax_t temp;
  10. if (pscanf(file, "%ju", &temp) != 1) {
  11. return NULL;
  12. }
  13. return bprintf("%ju", temp / 1000);
  14. }
  15. #elif defined(__OpenBSD__)
  16. #include <stdio.h>
  17. #include <sys/time.h> /* before <sys/sensors.h> for struct timeval */
  18. #include <sys/sensors.h>
  19. #include <sys/sysctl.h>
  20. const char *
  21. temp(const char *unused)
  22. {
  23. int mib[5];
  24. size_t size;
  25. struct sensor temp;
  26. mib[0] = CTL_HW;
  27. mib[1] = HW_SENSORS;
  28. mib[2] = 0; /* cpu0 */
  29. mib[3] = SENSOR_TEMP;
  30. mib[4] = 0; /* temp0 */
  31. size = sizeof(temp);
  32. if (sysctl(mib, 5, &temp, &size, NULL, 0) < 0) {
  33. warn("sysctl 'SENSOR_TEMP':");
  34. return NULL;
  35. }
  36. /* kelvin to celsius */
  37. return bprintf("%d", (temp.value - 273150000) / 1E6);
  38. }
  39. #elif defined(__FreeBSD__)
  40. #include <stdio.h>
  41. #include <stdlib.h>
  42. #include <sys/sysctl.h>
  43. const char *
  44. temp(const char *zone)
  45. {
  46. char buf[256];
  47. int temp;
  48. size_t len;
  49. len = sizeof(temp);
  50. snprintf(buf, sizeof(buf), "hw.acpi.thermal.%s.temperature", zone);
  51. if (sysctlbyname(buf, &temp, &len, NULL, 0) == -1
  52. || !len)
  53. return NULL;
  54. /* kelvin to decimal celcius */
  55. return bprintf("%d.%d", (temp - 2731) / 10, abs((temp - 2731) % 10));
  56. }
  57. #endif