这儿演示的php使用了两个类, 一个是 telnet_class,一个是 mqtt的class。具体两个class可以到网上search。 代码如下:
代码: 全选
#!/usr/bin/php -q
<?php
// run this program , must do
// linux command line
// $ composer require brandonhudson/lightning
// $ ## just wait to download package
require dirname(__FILE__)."/vendor/autoload.php";
include "telnet_class.php"; // install at /usr/share/php
// Step 1: Get router tempera
$telnet=new telnet;
$telnet->set_host('更换为你的路由器的IP');
$telnet->connect();
$telnet->set_prompt('ogin: '); $telnet->wait_prompt(); $telnet->write('登陆用户名');
$telnet->set_prompt('word: '); $telnet->wait_prompt(); $telnet->write('登陆密码');
$telnet->set_prompt('# '); $telnet->wait_prompt();
$telnet->write('cat /proc/dmu/temperature'); # 我用的是梅林,其他请参考相关命令
$telnet->wait_prompt();
$output= $telnet->get_buffer();
$telnet->write('exit');
$telnet->disconnect();
unset($telnet);
// get last line from output, and delete last char
$retStr=preg_split("/:/",$output);
$temp=trim(substr($retStr[1],0,-2));
$fp=popen("cat /sys/class/thermal/thermal_zone0/temp","r");
$temp2=fread($fp,32);
pclose($fp);
echo "temp2=".trim($temp2)."\n";
$temp2=intval($temp2)/1000;
echo "temp2=".$temp2."\n";
// Step 2: Build json data
// IDX=12 # 这个12是你在 domoticz 中定义设备的 idx 编号
$message=array( "idx"=>12, "nvalue"=>0, "svalue"=>"$temp");
$message=json_encode($message);
var_dump($message);
// Step 3: send data # 发送数据
$host = "更换为你的mqtt服务器地址";
$port = 1883; #mqtt服务器端口
$clientID = 'php'.md5(uniqid()); // use a unique client id for each connection
$username = 'spender'; // username is optional
$password = 'mqtt_access_password' ; // password is optional
$mqtt = new \Lightning\App($host, $port, $clientID, $username, $password);
if (!$mqtt->connect()) {
echo "Failed to connect.\n";
}
$mqtt->publish("domoticz/in", $message, 1);
$mqtt->publish("domoticz/in", $message, 1);
$mqtt->close();
unset($mqtt);
?>