1+ <?php 
2+ 
3+ namespace  Jzzoo \Laravel \Mqttx ;
4+ 
5+ class  Mqttx
6+ {
7+     public  function  __construct () {
8+         $ this  ->host       = config ('mqtt.host ' );
9+         $ this  ->username   = config ('mqtt.username ' );
10+         $ this  ->password   = config ('mqtt.password ' );
11+         $ this  ->cert_file  = config ('mqtt.certfile ' );
12+         $ this  ->port       = config ('mqtt.port ' );
13+         $ this  ->debug      = config ('mqtt.debug ' );
14+         $ this  ->qos        = config ('mqtt.qos ' );
15+         $ this  ->retain     = config ('mqtt.retain ' );
16+     }
17+ 
18+     /** 
19+      * 发布消息 
20+      * 
21+      * @param $topic 
22+      * @param $msg 
23+      * @param null $client_id 
24+      * @return bool 
25+      */ 
26+     public  function  Publish ($ topic , $ msg , $ client_id  = null ) {
27+ 
28+         empty ($ client_id ) && $ client_id  = rand (10000 , 99999 );
29+ 
30+         $ mqtt  = new  MqttxNear ($ this  ->host ,$ this  ->port , $ client_id , $ this  ->cert_file , $ this  ->debug );
31+ 
32+         if  ( $ mqtt ->connect (true , null , $ this  ->username , $ this  ->password ) )  {
33+             $ mqtt ->publish ($ topic , $ msg , $ this  ->qos , $ this  ->retain );
34+             $ mqtt ->close ();
35+             return  true ;
36+         }
37+ 
38+         return  false ;
39+     }
40+ 
41+     /** 
42+      * 订阅消息 
43+      * 
44+      * @param $topic 
45+      * @param $function 
46+      * @param null $client_id 
47+      * @return bool 
48+      */ 
49+     public  function  Subscribe ($ topic , $ function , $ client_id  = null ) {
50+ 
51+         empty ($ client_id ) && $ client_id  = mt_rand (10000 , 99999 );
52+ 
53+         $ mqtt  = new  MqttxNear ($ this  ->host ,$ this  ->port , $ client_id );
54+         if ( $ mqtt ->connect (true , null , $ this  ->username , $ this  ->password ) ) {
55+ 
56+             $ topics [$ topic ] = [ 'qos '  => 0 , 'function '  => $ function  ];
57+             $ mqtt ->subscribe ($ topics , 0 );
58+ 
59+             do  {
60+                 $ rs  = $ mqtt ->proc ();
61+             } while ($ rs );
62+ 
63+             $ mqtt ->close ();
64+             return  true ;
65+         }
66+         return  false ;
67+     }
68+ }
0 commit comments