4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RustでRaspberry PiのCPU温度を取得しSQLiteに保存する

Posted at

リポジトリ:https://github.com/misogihagi/raspberrypi-temperture):https://github.com/misogihagi/raspberrypi-temperture
バイナリ:https://github.com/misogihagi/raspberrypi-temperture/releases/download/v0.1.0/raspberrypi-temperture

Raspberry Piをずっと稼動させていてこれ熱暴走とか大丈夫か?と思いRustの練習も兼ねて作ってみました。

Raspberry Piでハードウェアが固定されているので

/sys/class/thermal/thermal_zone0/temp

を参照すればいいだけです。

もしほかのプロセッサやディストリビューションならどうなったか…

使い方

./raspberrypi-temperture 

で5秒ごとに温度をtemperature.dbに格納します。

やってみる

そこそこ動かすとこんな感じでデータが取れます。

sqlite3 temperture.db "select * from monitor;"

39.008|1682099833
39.008|1682099838
39.546|1682100348
39.008|1682100353
40.084|1682100358
39.008|1682100363
38.47|1682100368
39.546|1682100387
38.47|1682100393
39.008|1682100398
39.008|1682100403
40.084|1682100408
39.008|1682100413
39.008|1682100418
39.546|1682100423

ソース

use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{thread, time};

const DB_PATH: &str = "./temperture.db";
const INTERVAL: u64 = 5000;
const TEMPERATURE_FILE: &str = "/sys/class/thermal/thermal_zone0/temp";

fn init() {
    let query = "
    CREATE TABLE monitor (temperature REAL, timestamp INTEGER);
";

    let path = Path::new(DB_PATH);
    if !path.is_file() {
        let connection = sqlite::open(DB_PATH).unwrap();

        connection.execute(query).unwrap();
    }
}

fn load() {
    let connection = sqlite::open(DB_PATH).unwrap();

    macro_rules! query {
        () => {
            "INSERT INTO monitor VALUES ({temperature}, {timestamp});"
        };
    }

    let mut f = File::open(TEMPERATURE_FILE).unwrap();
    let mut c = String::new();
    f.read_to_string(&mut c).unwrap();

    // 45678 -> 45.678
    let temperature = format!("{}.{}", &c[0..2], &c[2..5]);

    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");

    let timestamp = since_the_epoch.as_secs();

    connection
        .execute(format!(
            query!(),
            temperature = temperature,
            timestamp = timestamp
        ))
        .unwrap()
}

fn main() {
    init();
    let ten_millis = time::Duration::from_millis(INTERVAL);
    loop {
        load();
        thread::sleep(ten_millis);
    }
}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?