-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribe.php
39 lines (31 loc) · 1.09 KB
/
subscribe.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
require("phpMQTT.php");
$conn = mysqli_connect("localhost","db_username","db_password","db_name");
$host = "xxxxx.cloudmqtt.com"; // server cloudmqtt
$port = 123456; // port cloudmqtt
$username = "username_mqtt"; // user cloudmqtt
$password = "password_mqtt"; // password cloudmqtt
$mqtt = new phpMQTT($host, $port, "example_1");
if(!$mqtt->connect(true, NULL, $username, $password)) {
exit(1);
}
$topics['sensor/'] = array("qos" => 0, "function" => "procmsg");
$mqtt->subscribe($topics, 0);
while($mqtt->proc() ){
}
$mqtt->close();
function procmsg($topic, $msg){
//decode json
$obj = json_decode($msg);
$data_1=$obj->array_1;
$data_2=$obj->array_2;
// echo "Msg Recieved: " . date("r") . "\n";
// echo "Topic: {$topic}\n\n";
// echo "\t$msg\n\n";
mysqlinsert($data_1, $data_2);
}
function mysqlinsert($data_1, $data_2) {
global $conn;
$query="INSERT INTO db (data_1, data_2) VALUES ('$data_1', '$data_2')";
mysqli_query($conn,$query) or die(mysqli_error($conn));
}