ラズパイのCPU温度を測定し値をレンタルサーバーへ格納する

ラズパイのソースコード

requests_post.py

#!/usr/bin/python
import sys
import requests
import json
import os
import commands

gettemp = commands.getoutput("vcgencmd measure_temp").split('=')
print (gettemp[1]);

text = gettemp[1];
tmp = text.replace("'C", "")
print (tmp);

# Request to Server by Post Method
url = 'http://xxxx.jp/yyyy/regist_data.php'
sensorsdata = {'code':'temp', 'v_1':str(tmp), 'v_2':'20'}
headers = {'content-type': 'application/json'}
print (url)
print (headers)

def main():
    res = requests.post(url, sensorsdata)
    print (res.json())


if __name__=='__main__':
    main()

ソースコードの説明

ラズパイのCPU温度を取得し配列の変数gettempへ格納する。
gettempの配列添え字1番目にCPU温度が格納される。
CPU温度は50.5'cの用に'Cが付いているので、'Cを取り除いた値を求めtmpに格納する。

url = 'http://xxxx.jp/yyyy/regist_data.php'
urlにはphpソースのアドレスを指定する。

sensorsdata = {'code':'temp', 'v_1':str(tmp), 'v_2':'20'}
code:,V_1:V_2:に値を編集する。

res = requests.post(url, sensorsdata)
httpリクエストをします。

regist_data.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>データ登録</title>
</head>
<body>

<?php
    // Initialize
    $db = null;
    $sql = null;
    $res = null;

    $code = $_POST['code'];
    $v_0 = $_POST['v_0'];
    $v_1 = $_POST['v_1'];
    $v_2 = $_POST['v_2'];
    $v_3 = $_POST['v_3'];
    $v_4 = $_POST['v_4'];
    $v_5 = $_POST['v_5'];
    $v_6 = $_POST['v_6'];
    $v_7 = $_POST['v_7'];
    $v_8 = $_POST['v_8'];
    $v_9 = $_POST['v_9'];

    switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        print ('GETメソッドでアクセス<br>');
        break; //GETメソッドの終わり

    case 'POST':
        print ('POSTメソッドでアクセス<br>');
        print("code: $code <br>");

        if($code == "temp"){
            print ('code:tempでアクセス<br>');

            $dsn = 'mysql:host=mysql1.php.xdomain.ne.jp;dbname=dbname;charset=utf8';
            $user = 'userid';
            $password = 'password';

            //DBへ接続
            try {
                $db = new PDO($dsn, $user, $password);
                // エラーの場合Exceptionを出す
                $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            } catch (PDOException $e) {
                print 'DBへの接続でエラーが発生しました。<br>';
                print $e->getTraceAsString();
                break;
            }

            // データの追加
            $sql = "INSERT INTO temp_pi(temp) VALUES ($v_1)";
            $res = $db->query($sql);
            print("$sql <br>");

            //接続を終了
            // $db->close();
            print('切断しました。<br>');
        }
        break; //POSTメソッドの終わり
}
?>
</body>
</html>

コメント