资讯专栏INFORMATION COLUMN

php实现mqtt发布/发送 消息到主题

eechen / 2205人阅读

摘要:实现发布发送消息到主题是啥我的博客有写这个东西传送门想要实现需要使用到中的函数函数是什么此次使用的是网上开源案例其中使用的是系列函数什么是系列函数大概意思是正如你所指出的,是核心内置的,始终可用,而套接字是很少包含的扩展的一部分。

php实现mqtt发布/发送 消息到主题

mqtt是啥?我的博客有写这个东西:传送门

php想要实现mqtt需要使用到php中的socket函数;

socket函数是什么?

此次使用的是网上开源mqtt案例:其中使用的是 stream_socket_xxxx 系列函数

什么是stream_socket_xxxx系列函数

大概意思是:

</>复制代码

  1. 正如你所指出的,"stream"是PHP核心(内置的,始终可用),而"套接字"是很少包含的扩展的一部分。除此之外,它们几乎完全相同。您可以同时使用TCP和UDP两种流,也可以使用阻塞和非阻塞模式,这些模式涵盖了所有用例的99%。

    我能想到的唯一常见的例外是ICMP。例如,"ping"。但是,看起来目前还没有一种安全的方式来从PHP执行ICMP。这种调用需要通过套接字扩展来实现SOCK_RAW,这需要执行“root”权限。此外,并非所有路由器都会在TCP,UDP和ICMP之外路由其他数据包类型。这限制了套接字扩展的实用性。

MQTT类代码:

</>复制代码

  1. /* phpMQTT */
  2. class Mqtt {
  3. private $socket; /* holds the socket */
  4. private $msgid = 1; /* counter for message id */
  5. public $keepalive = 10; /* default keepalive timmer */
  6. public $timesinceping; /* host unix time, used to detect disconects */
  7. public $topics = array(); /* used to store currently subscribed topics */
  8. public $debug = false; /* should output debug messages */
  9. public $address; /* broker address */
  10. public $port; /* broker port */
  11. public $clientid; /* client id sent to brocker */
  12. public $will; /* stores the will of the client */
  13. private $username; /* stores username */
  14. private $password; /* stores password */
  15. public $cafile;
  16. function __construct($address, $port, $clientid, $cafile = NULL){
  17. $this->broker($address, $port, $clientid, $cafile);
  18. }
  19. /* sets the broker details */
  20. function broker($address, $port, $clientid, $cafile = NULL){
  21. $this->address = $address;
  22. $this->port = $port;
  23. $this->clientid = $clientid;
  24. $this->cafile = $cafile;
  25. }
  26. function connect_auto($clean = true, $will = NULL, $username = NULL, $password = NULL){
  27. while($this->connect($clean, $will, $username, $password)==false){
  28. sleep(10);
  29. }
  30. return true;
  31. }
  32. /* connects to the broker
  33. inputs: $clean: should the client send a clean session flag */
  34. function connect($clean = true, $will = NULL, $username = NULL, $password = NULL){
  35. if($will) $this->will = $will;
  36. if($username) $this->username = $username;
  37. if($password) $this->password = $password;
  38. if ($this->cafile) {
  39. $socketContext = stream_context_create(["ssl" => [
  40. "verify_peer_name" => true,
  41. "cafile" => $this->cafile
  42. ]]);
  43. $this->socket = stream_socket_client("tls://" . $this->address . ":" . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT, $socketContext);
  44. } else {
  45. $this->socket = stream_socket_client("tcp://" . $this->address . ":" . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT);
  46. }
  47. if (!$this->socket ) {
  48. if($this->debug) error_log("stream_socket_create() $errno, $errstr
  49. ");
  50. return false;
  51. }
  52. stream_set_timeout($this->socket, 5);
  53. stream_set_blocking($this->socket, 0);
  54. $i = 0;
  55. $buffer = "";
  56. $buffer .= chr(0x00); $i++;
  57. $buffer .= chr(0x06); $i++;
  58. $buffer .= chr(0x4d); $i++;
  59. $buffer .= chr(0x51); $i++;
  60. $buffer .= chr(0x49); $i++;
  61. $buffer .= chr(0x73); $i++;
  62. $buffer .= chr(0x64); $i++;
  63. $buffer .= chr(0x70); $i++;
  64. $buffer .= chr(0x03); $i++;
  65. //No Will
  66. $var = 0;
  67. if($clean) $var+=2;
  68. //Add will info to header
  69. if($this->will != NULL){
  70. $var += 4; // Set will flag
  71. $var += ($this->will["qos"] << 3); //Set will qos
  72. if($this->will["retain"]) $var += 32; //Set will retain
  73. }
  74. if($this->username != NULL) $var += 128; //Add username to header
  75. if($this->password != NULL) $var += 64; //Add password to header
  76. $buffer .= chr($var); $i++;
  77. //Keep alive
  78. $buffer .= chr($this->keepalive >> 8); $i++;
  79. $buffer .= chr($this->keepalive & 0xff); $i++;
  80. $buffer .= $this->strwritestring($this->clientid,$i);
  81. //Adding will to payload
  82. if($this->will != NULL){
  83. $buffer .= $this->strwritestring($this->will["topic"],$i);
  84. $buffer .= $this->strwritestring($this->will["content"],$i);
  85. }
  86. if($this->username) $buffer .= $this->strwritestring($this->username,$i);
  87. if($this->password) $buffer .= $this->strwritestring($this->password,$i);
  88. $head = " ";
  89. $head{0} = chr(0x10);
  90. $head{1} = chr($i);
  91. fwrite($this->socket, $head, 2);
  92. fwrite($this->socket, $buffer);
  93. $string = $this->read(4);
  94. if(ord($string{0})>>4 == 2 && $string{3} == chr(0)){
  95. if($this->debug) echo "Connected to Broker
  96. ";
  97. }else{
  98. error_log(sprintf("Connection failed! (Error: 0x%02x 0x%02x)
  99. ",
  100. ord($string{0}),ord($string{3})));
  101. return false;
  102. }
  103. $this->timesinceping = time();
  104. return true;
  105. }
  106. /* read: reads in so many bytes */
  107. function read($int = 8192, $nb = false){
  108. // print_r(socket_get_status($this->socket));
  109. $string="";
  110. $togo = $int;
  111. if($nb){
  112. return fread($this->socket, $togo);
  113. }
  114. while (!feof($this->socket) && $togo>0) {
  115. $fread = fread($this->socket, $togo);
  116. $string .= $fread;
  117. $togo = $int - strlen($string);
  118. }
  119. return $string;
  120. }
  121. /* subscribe: subscribes to topics */
  122. function subscribe($topics, $qos = 0){
  123. $i = 0;
  124. $buffer = "";
  125. $id = $this->msgid;
  126. $buffer .= chr($id >> 8); $i++;
  127. $buffer .= chr($id % 256); $i++;
  128. foreach($topics as $key => $topic){
  129. $buffer .= $this->strwritestring($key,$i);
  130. $buffer .= chr($topic["qos"]); $i++;
  131. $this->topics[$key] = $topic;
  132. }
  133. $cmd = 0x80;
  134. //$qos
  135. $cmd += ($qos << 1);
  136. $head = chr($cmd);
  137. $head .= chr($i);
  138. fwrite($this->socket, $head, 2);
  139. fwrite($this->socket, $buffer, $i);
  140. $string = $this->read(2);
  141. $bytes = ord(substr($string,1,1));
  142. $string = $this->read($bytes);
  143. }
  144. /* ping: sends a keep alive ping */
  145. function ping(){
  146. $head = " ";
  147. $head = chr(0xc0);
  148. $head .= chr(0x00);
  149. fwrite($this->socket, $head, 2);
  150. if($this->debug) echo "ping sent
  151. ";
  152. }
  153. /* disconnect: sends a proper disconect cmd */
  154. function disconnect(){
  155. $head = " ";
  156. $head{0} = chr(0xe0);
  157. $head{1} = chr(0x00);
  158. fwrite($this->socket, $head, 2);
  159. }
  160. /* close: sends a proper disconect, then closes the socket */
  161. function close(){
  162. $this->disconnect();
  163. stream_socket_shutdown($this->socket, STREAM_SHUT_WR);
  164. }
  165. /* publish: publishes $content on a $topic */
  166. function publish($topic, $content, $qos = 0, $retain = 0){
  167. $i = 0;
  168. $buffer = "";
  169. $buffer .= $this->strwritestring($topic,$i);
  170. //$buffer .= $this->strwritestring($content,$i);
  171. if($qos){
  172. $id = $this->msgid++;
  173. $buffer .= chr($id >> 8); $i++;
  174. $buffer .= chr($id % 256); $i++;
  175. }
  176. $buffer .= $content;
  177. $i+=strlen($content);
  178. $head = " ";
  179. $cmd = 0x30;
  180. if($qos) $cmd += $qos << 1;
  181. if($retain) $cmd += 1;
  182. $head{0} = chr($cmd);
  183. $head .= $this->setmsglength($i);
  184. fwrite($this->socket, $head, strlen($head));
  185. fwrite($this->socket, $buffer, $i);
  186. }
  187. /* message: processes a recieved topic */
  188. function message($msg){
  189. $tlen = (ord($msg{0})<<8) + ord($msg{1});
  190. $topic = substr($msg,2,$tlen);
  191. $msg = substr($msg,($tlen+2));
  192. $found = 0;
  193. foreach($this->topics as $key=>$top){
  194. if( preg_match("/^".str_replace("#",".*",
  195. str_replace("+","[^/]*",
  196. str_replace("/","/",
  197. str_replace("$","$",
  198. $key))))."$/",$topic) ){
  199. if(is_callable($top["function"])){
  200. call_user_func($top["function"],$topic,$msg);
  201. $found = 1;
  202. }
  203. }
  204. }
  205. if($this->debug && !$found) echo "msg recieved but no match in subscriptions
  206. ";
  207. }
  208. /* proc: the processing loop for an "allways on" client
  209. set true when you are doing other stuff in the loop good for watching something else at the same time */
  210. function proc( $loop = true){
  211. if(1){
  212. $sockets = array($this->socket);
  213. $w = $e = NULL;
  214. $cmd = 0;
  215. //$byte = fgetc($this->socket);
  216. if(feof($this->socket)){
  217. if($this->debug) echo "eof receive going to reconnect for good measure
  218. ";
  219. fclose($this->socket);
  220. $this->connect_auto(false);
  221. if(count($this->topics))
  222. $this->subscribe($this->topics);
  223. }
  224. $byte = $this->read(1, true);
  225. if(!strlen($byte)){
  226. if($loop){
  227. usleep(100000);
  228. }
  229. }else{
  230. $cmd = (int)(ord($byte)/16);
  231. if($this->debug) echo "Recevid: $cmd
  232. ";
  233. $multiplier = 1;
  234. $value = 0;
  235. do{
  236. $digit = ord($this->read(1));
  237. $value += ($digit & 127) * $multiplier;
  238. $multiplier *= 128;
  239. }while (($digit & 128) != 0);
  240. if($this->debug) echo "Fetching: $value
  241. ";
  242. if($value)
  243. $string = $this->read($value);
  244. if($cmd){
  245. switch($cmd){
  246. case 3:
  247. $this->message($string);
  248. break;
  249. }
  250. $this->timesinceping = time();
  251. }
  252. }
  253. if($this->timesinceping < (time() - $this->keepalive )){
  254. if($this->debug) echo "not found something so ping
  255. ";
  256. $this->ping();
  257. }
  258. if($this->timesinceping<(time()-($this->keepalive*2))){
  259. if($this->debug) echo "not seen a package in a while, disconnecting
  260. ";
  261. fclose($this->socket);
  262. $this->connect_auto(false);
  263. if(count($this->topics))
  264. $this->subscribe($this->topics);
  265. }
  266. }
  267. return 1;
  268. }
  269. /* getmsglength: */
  270. function getmsglength(&$msg, &$i){
  271. $multiplier = 1;
  272. $value = 0 ;
  273. do{
  274. $digit = ord($msg{$i});
  275. $value += ($digit & 127) * $multiplier;
  276. $multiplier *= 128;
  277. $i++;
  278. }while (($digit & 128) != 0);
  279. return $value;
  280. }
  281. /* setmsglength: */
  282. function setmsglength($len){
  283. $string = "";
  284. do{
  285. $digit = $len % 128;
  286. $len = $len >> 7;
  287. // if there are more digits to encode, set the top bit of this digit
  288. if ( $len > 0 )
  289. $digit = ($digit | 0x80);
  290. $string .= chr($digit);
  291. }while ( $len > 0 );
  292. return $string;
  293. }
  294. /* strwritestring: writes a string to a buffer */
  295. function strwritestring($str, &$i){
  296. $ret = " ";
  297. $len = strlen($str);
  298. $msb = $len >> 8;
  299. $lsb = $len % 256;
  300. $ret = chr($msb);
  301. $ret .= chr($lsb);
  302. $ret .= $str;
  303. $i += ($len+2);
  304. return $ret;
  305. }
  306. function printstr($string){
  307. $strlen = strlen($string);
  308. for($j=0;$j<$strlen;$j++){
  309. $num = ord($string{$j});
  310. if($num > 31)
  311. $chr = $string{$j}; else $chr = " ";
  312. printf("%4d: %08b : 0x%02x : %s
  313. ",$j,$num,$num,$chr);
  314. }
  315. }
  316. }
实现部分 发送到主题

</>复制代码

  1. // 发送给订阅号信息,创建socket,无sam队列
  2. $server = "127.0.0.1"; // 服务代理地址(mqtt服务端地址)
  3. $port = 1883; // 通信端口
  4. $username = ""; // 用户名(如果需要)
  5. $password = ""; // 密码(如果需要
  6. $client_id = "clientx9293670xxctr"; // 设置你的连接客户端id
  7. $mqtt = new Mqtt($server, $port, $client_id); //实例化MQTT类
  8. if ($mqtt->connect(true, NULL, $username, $password)) {
  9. //如果创建链接成功
  10. $mqtt->publish("xxx3809293670ctr", "setr=3xxxxxxxxx", 0);
  11. // 发送到 xxx3809293670ctr 的主题 一个信息 内容为 setr=3xxxxxxxxx Qos 为 0
  12. $mqtt->close(); //发送后关闭链接
  13. } else {
  14. echo "Time out!
  15. ";
  16. }
订阅主题

</>复制代码

  1. /*// 订阅信息,接收一个信息后退出
  2. $server = "127.0.0.1"; // 服务代理地址(mqtt服务端地址)
  3. $port = 1883; // 通信端口
  4. $username = ""; // 用户名(如果需要)
  5. $password = ""; // 密码(如果需要
  6. $client_id = "clientx9293670xxctr"; // 设置你的连接客户端id
  7. $mqtt = new Mqtt($server, $port, $client_id);
  8. if(!$mqtt->connect(true, NULL, $username, $password)) { //链接不成功再重复执行监听连接
  9. exit(1);
  10. }
  11. $topics["SN69143809293670state"] = array("qos" => 0, "function" => "procmsg");
  12. // 订阅主题为 SN69143809293670state qos为0
  13. $mqtt->subscribe($topics, 0);
  14. while($mqtt->proc()){
  15. }
  16. //死循环监听
  17. $mqtt->close();
  18. function procmsg($topic, $msg){ //信息回调函数 打印信息
  19. echo "Msg Recieved: " . date("r") . "
  20. ";
  21. echo "Topic: {$topic}
  22. ";
  23. echo "
  24. $msg
  25. ";
  26. $xxx = json_decode($msg);
  27. var_dump($xxxxxx->aa);
  28. die;
  29. }

这是php实现方法,如果用php做发送端还是不错的.但是

我被这个图片打击了,区块链应用还真提莫的是js写起来跟简单;

我最终写出的mqtt api 使用的是node;为什么?

node.js实现mqtt

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/28481.html

相关文章

  • MQTT协议(1)-简介

    摘要:,消息队列遥测传输是开发的一个即时通讯协议,有可能成为物联网的重要组成部分。会发生消息丢失或重复。只有一次,确保消息到达一次。此外,国内很多企业都广泛使用作为手机客户端与服务器端推送消息的协议。 前几天写了一下MQTT协议实现推送数据传输,所以我会不定期的更新一下关注MQTT的知识。 MQTT: MQTT(Message Queuing Telemetry Transport,消息队列...

    objc94 评论0 收藏0
  • MQTT

    摘要:协议版本介绍互联网的基础网络协议是协议消息队列遥测传输是基于协议栈而构建的已成为通信的标准为什么选择有多好多好多么牛逼我就不说了说的再多不如一个一个试试完了做比对剩下的那个就是要选择的实在不想这样搞技术就跟着一线走发布和订阅模型协议在网络中 mqtt 协议版本: 3.1.1 MQTT 介绍 互联网的基础网络协议是 TCP/IP协议. MQTT(消息队列遥测传输)是基于 TCP/IP 协...

    lastSeries 评论0 收藏0
  • MQTT协议介绍

    摘要:协议简介,消息队列遥测传输是一个轻量的发布订阅模式消息传输协议,是专门针对低带宽和不稳定网络环境的物联网应用设计的。它是等级协议交换的第二个报文。 1.MQTT协议简介 MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是一个轻量的发布/订...

    lewinlee 评论0 收藏0
  • MQTT如何快速助你产品化

    摘要:时间就是金钱,效率就是生命本教程助力开发者使用协议快速产品化。摘要借助具备及联网功能的,快速部署到客户产品上,助力开发,缩短开发周期,快速实现产品商业化。 时间就是金钱,效率就是生命 本教程助力开发者使用MQTT协议快速产品化。 摘要 借助具备MQTT及联网功能的DTU,快速部署到客户产品...

    sutaking 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<