Advertisement
Painlover

get_data.php

Jan 20th, 2025
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.47 KB | None | 0 0
  1. <?php
  2. header('Content-Type: application/json');
  3.  
  4. // Koneksi ke MQTT Broker
  5. require 'vendor/phpMQTT.php';
  6.  
  7. $server = '192.168.155.4';  // Alamat broker MQTT
  8. $port = 1883;               // Port broker MQTT
  9. $username = 'localmech';    // Username MQTT
  10. $password = '1234';         // Password MQTT
  11. $client_id = 'MyIoT';
  12.  
  13. // Variabel untuk menyimpan data dari topik MQTT
  14. $sensorData = [
  15.     'temperature' => '-',
  16.     'humidity' => '-',
  17.     'ldr' => '-',
  18.     'mq2' => '-',
  19.     'pir' => '-'
  20. ];
  21.  
  22. // Callback untuk data sensor
  23. function procSensor($topic, $message) {
  24.     global $sensorData;
  25.  
  26.     $data = json_decode($message, true); // Decode payload JSON
  27.     if (is_array($data)) {
  28.         $sensorData = array_merge($sensorData, $data); // Update variabel global
  29.     }
  30. }
  31.  
  32. $mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id);
  33.  
  34. if ($mqtt->connect(true, NULL, $username, $password)) {
  35.     $topics = [
  36.         'smarthome/sensor' => ['qos' => 0, 'function' => 'procSensor'] // Topik untuk data sensor
  37.     ];
  38.     $mqtt->subscribe($topics, 0);
  39.  
  40.     // Beri waktu untuk menerima pesan
  41.     $start_time = time();
  42.     while (time() - $start_time < 5) { // Tunggu hingga 5 detik
  43.         $mqtt->proc();
  44.         usleep(100000); // Delay 100ms untuk menghindari CPU usage tinggi
  45.     }
  46.  
  47.     $mqtt->close();
  48.  
  49.     // Kirim data sensor sebagai JSON
  50.     echo json_encode($sensorData);
  51. } else {
  52.     echo json_encode(['error' => 'Unable to connect to MQTT broker']);
  53. }
  54. ?>
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement