Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- header('Content-Type: application/json');
- // Koneksi ke MQTT Broker
- require 'vendor/phpMQTT.php';
- $server = '192.168.155.4'; // Alamat broker MQTT
- $port = 1883; // Port broker MQTT
- $username = 'localmech'; // Username MQTT
- $password = '1234'; // Password MQTT
- $client_id = 'MyIoT';
- // Variabel untuk menyimpan data dari topik MQTT
- $sensorData = [
- 'temperature' => '-',
- 'humidity' => '-',
- 'ldr' => '-',
- 'mq2' => '-',
- 'pir' => '-'
- ];
- // Callback untuk data sensor
- function procSensor($topic, $message) {
- global $sensorData;
- $data = json_decode($message, true); // Decode payload JSON
- if (is_array($data)) {
- $sensorData = array_merge($sensorData, $data); // Update variabel global
- }
- }
- $mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id);
- if ($mqtt->connect(true, NULL, $username, $password)) {
- $topics = [
- 'smarthome/sensor' => ['qos' => 0, 'function' => 'procSensor'] // Topik untuk data sensor
- ];
- $mqtt->subscribe($topics, 0);
- // Beri waktu untuk menerima pesan
- $start_time = time();
- while (time() - $start_time < 5) { // Tunggu hingga 5 detik
- $mqtt->proc();
- usleep(100000); // Delay 100ms untuk menghindari CPU usage tinggi
- }
- $mqtt->close();
- // Kirim data sensor sebagai JSON
- echo json_encode($sensorData);
- } else {
- echo json_encode(['error' => 'Unable to connect to MQTT broker']);
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement