訓練家的快寫筆記

The legend of trainer's paper


搜尋:

     關閉     
標題:mqtt 心得
內容:
windows:
https://mosquitto.org/files/binary/win64/mosquitto-2.0.15-install-windows-x64.exe

Server : 
yum install mosquitto mosquitto-devel 
git clone https://github.com/mgdm/Mosquitto-PHP

phpize
./configure
make

cp Mosquitto-PHP/modules/mosquitto.so /usr/lib64/php/modules/
vim /etc/php.d/42-mosquitto.ini

; Enable MQTT extension module
extension=mosquitto.so

systemctl restart httpd
systemctl restart php-fpm

調整 mqtt 設定檔

# vim /etc/mosquitto/mosquitto.conf

port 1883
allow_anonymous false
password_file /etc/mosquitto/passwd

增加驗證帳號
編輯 /etc/mosquitto/passwd
例如:
john:密碼
jade:密碼

然後
mosquitto_passwd -U /etc/mosquitto/passwd

systemctl start mosquitto.service

防火牆要允許 1883
# MQTT
iptables -I INPUT -p tcp -s 0/0 --dport 1883 -j ACCEPT

client.php 語法參考(PUBLISH):

<?php
$c = new Mosquitto\Client;
$c->setCredentials('john', '密碼');
$c->onConnect(function() use ($c) {
  $c->publish('a/a', 'Hasdfasfellasdfadfo', 1);
  // $c->disconnect();
});
$c->connect('localhost',1883);
$c->loopForever();
echo "Finished\n";

server.php 語法參考(subscribe)
subscribe.php
<?php
$c = new Mosquitto\Client;
$c->setCredentials('john', '密碼');
$c->onConnect(function() use ($c) {
  $c->subscribe("#",1);
});
$c->onMessage(function($c){
  print_r($c); // --> 注意,拿到的資料是在 onMessage ,不是 onSubscribe...
  /*
  Mosquitto\Message Object
  (
      [mid] => 0
      [topic] => a/a
      [payload] => asdfasdfqqqef
      [qos] => 0
      [retain] =>
  )
  */
});
//$c->onSubscribe(function($c){
//  print_r($c);
//});
$c->connect('localhost',1883);
$c->loopForever();
//echo "Finished\n";

指令式發送(publish):
mosquitto_pub.exe -h 3wa.tw -t "a/a" -m "asdfasdfqqqef" -u john -P 密碼
發成retained,每次訂都可看到最後一次的 retained 值
mosquitto_pub.exe -h 3wa.tw -t "a/a" -r -m "asdfasdfqqqef" -u john -P 密碼

發 null 可以消除 retained
mosquitto_pub.exe -h 3wa.tw -t "a/a" -r -n -u john -P 密碼
-r 是 retained

指令式訂閱推播(subscribe):
mosquitto_sub -h 3wa.tw -v -t "#" -u john -P 密碼

windows mqtt:
C:\Program Files\mosquitto\mosquitto_pub.exe
https://mosquitto.org/files/binary/win64/mosquitto-2.0.15-install-windows-x64.exe

linux mqtt:
mosquitto_pub -h 3wa.tw -t "ARDUINO/CAT_COMING" -m "asdfasdfqqqef" -u john -P 密碼


以下是精簡的 mosquitto.conf 設定
cat mosquitto.conf
listener 1883 0.0.0.0
protocol mqtt
allow_anonymous false
password_file /etc/mosquitto/passwd

listener 8883 0.0.0.0
protocol websockets
#http_dir /path/to/http/dir

#cafile /path/to/ca.crt
#certfile /path/to/server.crt
#keyfile /path/to/server.key