phpMQTT.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <?php
  2. /*
  3. phpMQTT
  4. A simple php class to connect/publish/subscribe to an MQTT broker
  5. */
  6. /*
  7. Licence
  8. Copyright (c) 2010 Blue Rhinos Consulting | Andrew Milsted
  9. andrew@bluerhinos.co.uk | http://www.bluerhinos.co.uk
  10. Permission is hereby granted, free of charge, to any person obtaining a copy
  11. of this software and associated documentation files (the "Software"), to deal
  12. in the Software without restriction, including without limitation the rights
  13. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. copies of the Software, and to permit persons to whom the Software is
  15. furnished to do so, subject to the following conditions:
  16. The above copyright notice and this permission notice shall be included in
  17. all copies or substantial portions of the Software.
  18. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. THE SOFTWARE.
  25. */
  26. /* phpMQTT */
  27. class phpMQTT {
  28. private $socket; /* holds the socket */
  29. private $msgid = 1; /* counter for message id */
  30. public $keepalive = 10; /* default keepalive timmer */
  31. public $timesinceping; /* host unix time, used to detect disconects */
  32. public $topics = array(); /* used to store currently subscribed topics */
  33. public $debug = false; /* should output debug messages */
  34. public $address; /* broker address */
  35. public $port; /* broker port */
  36. public $clientid; /* client id sent to brocker */
  37. public $will; /* stores the will of the client */
  38. private $username; /* stores username */
  39. private $password; /* stores password */
  40. function __construct($address, $port, $clientid){
  41. $this->broker($address, $port, $clientid);
  42. }
  43. /* sets the broker details */
  44. function broker($address, $port, $clientid){
  45. $this->address = $address;
  46. $this->port = $port;
  47. $this->clientid = $clientid;
  48. }
  49. function connect_auto($clean = true, $will = NULL, $username = NULL, $password = NULL){
  50. while($this->connect($clean, $will, $username, $password)==false){
  51. sleep(10);
  52. }
  53. return true;
  54. }
  55. /* connects to the broker
  56. inputs: $clean: should the client send a clean session flag */
  57. function connect($clean = true, $will = NULL, $username = NULL, $password = NULL){
  58. if($will) $this->will = $will;
  59. if($username) $this->username = $username;
  60. if($password) $this->password = $password;
  61. $address = gethostbyname($this->address);
  62. $this->socket = fsockopen($address, $this->port, $errno, $errstr, 60);
  63. if (!$this->socket ) {
  64. if($this->debug) error_log("fsockopen() $errno, $errstr \n");
  65. return false;
  66. }
  67. stream_set_timeout($this->socket, 5);
  68. stream_set_blocking($this->socket, 0);
  69. $i = 0;
  70. $buffer = "";
  71. $buffer .= chr(0x00); $i++;
  72. $buffer .= chr(0x06); $i++;
  73. $buffer .= chr(0x4d); $i++;
  74. $buffer .= chr(0x51); $i++;
  75. $buffer .= chr(0x49); $i++;
  76. $buffer .= chr(0x73); $i++;
  77. $buffer .= chr(0x64); $i++;
  78. $buffer .= chr(0x70); $i++;
  79. $buffer .= chr(0x03); $i++;
  80. //No Will
  81. $var = 0;
  82. if($clean) $var+=2;
  83. //Add will info to header
  84. if($this->will != NULL){
  85. $var += 4; // Set will flag
  86. $var += ($this->will['qos'] << 3); //Set will qos
  87. if($this->will['retain']) $var += 32; //Set will retain
  88. }
  89. if($this->username != NULL) $var += 128; //Add username to header
  90. if($this->password != NULL) $var += 64; //Add password to header
  91. $buffer .= chr($var); $i++;
  92. //Keep alive
  93. $buffer .= chr($this->keepalive >> 8); $i++;
  94. $buffer .= chr($this->keepalive & 0xff); $i++;
  95. $buffer .= $this->strwritestring($this->clientid,$i);
  96. //Adding will to payload
  97. if($this->will != NULL){
  98. $buffer .= $this->strwritestring($this->will['topic'],$i);
  99. $buffer .= $this->strwritestring($this->will['content'],$i);
  100. }
  101. if($this->username) $buffer .= $this->strwritestring($this->username,$i);
  102. if($this->password) $buffer .= $this->strwritestring($this->password,$i);
  103. $head = " ";
  104. $head{0} = chr(0x10);
  105. $head{1} = chr($i);
  106. fwrite($this->socket, $head, 2);
  107. fwrite($this->socket, $buffer);
  108. $string = $this->read(4);
  109. if(ord($string{0})>>4 == 2 && $string{3} == chr(0)){
  110. if($this->debug) echo "Connected to Broker\n";
  111. }else{
  112. error_log(sprintf("Connection failed! (Error: 0x%02x 0x%02x)\n",
  113. ord($string{0}),ord($string{3})));
  114. return false;
  115. }
  116. $this->timesinceping = time();
  117. return true;
  118. }
  119. /* read: reads in so many bytes */
  120. function read($int = 8192, $nb = false){
  121. // print_r(socket_get_status($this->socket));
  122. $string="";
  123. $togo = $int;
  124. if($nb){
  125. return fread($this->socket, $togo);
  126. }
  127. while (!feof($this->socket) && $togo>0) {
  128. $fread = fread($this->socket, $togo);
  129. $string .= $fread;
  130. $togo = $int - strlen($string);
  131. }
  132. return $string;
  133. }
  134. /* subscribe: subscribes to topics */
  135. function subscribe($topics, $qos = 0){
  136. $i = 0;
  137. $buffer = "";
  138. $id = $this->msgid;
  139. $buffer .= chr($id >> 8); $i++;
  140. $buffer .= chr($id % 256); $i++;
  141. foreach($topics as $key => $topic){
  142. $buffer .= $this->strwritestring($key,$i);
  143. $buffer .= chr($topic["qos"]); $i++;
  144. $this->topics[$key] = $topic;
  145. }
  146. $cmd = 0x80;
  147. //$qos
  148. $cmd += ($qos << 1);
  149. $head = chr($cmd);
  150. $head .= chr($i);
  151. fwrite($this->socket, $head, 2);
  152. fwrite($this->socket, $buffer, $i);
  153. $string = $this->read(2);
  154. $bytes = ord(substr($string,1,1));
  155. $string = $this->read($bytes);
  156. }
  157. /* ping: sends a keep alive ping */
  158. function ping(){
  159. $head = " ";
  160. $head = chr(0xc0);
  161. $head .= chr(0x00);
  162. fwrite($this->socket, $head, 2);
  163. if($this->debug) echo "ping sent\n";
  164. }
  165. /* disconnect: sends a proper disconect cmd */
  166. function disconnect(){
  167. $head = " ";
  168. $head{0} = chr(0xe0);
  169. $head{1} = chr(0x00);
  170. fwrite($this->socket, $head, 2);
  171. }
  172. /* close: sends a proper disconect, then closes the socket */
  173. function close(){
  174. $this->disconnect();
  175. fclose($this->socket);
  176. }
  177. /* publish: publishes $content on a $topic */
  178. function publish($topic, $content, $qos = 0, $retain = 0){
  179. $i = 0;
  180. $buffer = "";
  181. $buffer .= $this->strwritestring($topic,$i);
  182. //$buffer .= $this->strwritestring($content,$i);
  183. if($qos){
  184. $id = $this->msgid++;
  185. $buffer .= chr($id >> 8); $i++;
  186. $buffer .= chr($id % 256); $i++;
  187. }
  188. $buffer .= $content;
  189. $i+=strlen($content);
  190. $head = " ";
  191. $cmd = 0x30;
  192. if($qos) $cmd += $qos << 1;
  193. if($retain) $cmd += 1;
  194. $head{0} = chr($cmd);
  195. $head .= $this->setmsglength($i);
  196. fwrite($this->socket, $head, strlen($head));
  197. fwrite($this->socket, $buffer, $i);
  198. }
  199. /* message: processes a recieved topic */
  200. function message($msg){
  201. $tlen = (ord($msg{0})<<8) + ord($msg{1});
  202. $topic = substr($msg,2,$tlen);
  203. $msg = substr($msg,($tlen+2));
  204. $found = 0;
  205. foreach($this->topics as $key=>$top){
  206. if( preg_match("/^".str_replace("#",".*",
  207. str_replace("+","[^\/]*",
  208. str_replace("/","\/",
  209. str_replace("$",'\$',
  210. $key))))."$/",$topic) ){
  211. if(is_callable($top['function'])){
  212. call_user_func($top['function'],$topic,$msg);
  213. $found = 1;
  214. }
  215. }
  216. }
  217. if($this->debug && !$found) echo "msg recieved but no match in subscriptions\n";
  218. }
  219. /* proc: the processing loop for an "allways on" client
  220. set true when you are doing other stuff in the loop good for watching something else at the same time */
  221. function proc( $loop = true){
  222. if(1){
  223. $sockets = array($this->socket);
  224. $w = $e = NULL;
  225. $cmd = 0;
  226. //$byte = fgetc($this->socket);
  227. if(feof($this->socket)){
  228. if($this->debug) echo "eof receive going to reconnect for good measure\n";
  229. fclose($this->socket);
  230. $this->connect_auto(false);
  231. if(count($this->topics))
  232. $this->subscribe($this->topics);
  233. }
  234. $byte = $this->read(1, true);
  235. if(!strlen($byte)){
  236. if($loop){
  237. usleep(100000);
  238. }
  239. }else{
  240. $cmd = (int)(ord($byte)/16);
  241. if($this->debug) echo "Recevid: $cmd\n";
  242. $multiplier = 1;
  243. $value = 0;
  244. do{
  245. $digit = ord($this->read(1));
  246. $value += ($digit & 127) * $multiplier;
  247. $multiplier *= 128;
  248. }while (($digit & 128) != 0);
  249. if($this->debug) echo "Fetching: $value\n";
  250. if($value)
  251. $string = $this->read($value,"fetch");
  252. if($cmd){
  253. switch($cmd){
  254. case 3:
  255. $this->message($string);
  256. break;
  257. }
  258. $this->timesinceping = time();
  259. }
  260. }
  261. if($this->timesinceping < (time() - $this->keepalive )){
  262. if($this->debug) echo "not found something so ping\n";
  263. $this->ping();
  264. }
  265. if($this->timesinceping<(time()-($this->keepalive*2))){
  266. if($this->debug) echo "not seen a package in a while, disconnecting\n";
  267. fclose($this->socket);
  268. $this->connect_auto(false);
  269. if(count($this->topics))
  270. $this->subscribe($this->topics);
  271. }
  272. }
  273. return 1;
  274. }
  275. /* getmsglength: */
  276. function getmsglength(&$msg, &$i){
  277. $multiplier = 1;
  278. $value = 0 ;
  279. do{
  280. $digit = ord($msg{$i});
  281. $value += ($digit & 127) * $multiplier;
  282. $multiplier *= 128;
  283. $i++;
  284. }while (($digit & 128) != 0);
  285. return $value;
  286. }
  287. /* setmsglength: */
  288. function setmsglength($len){
  289. $string = "";
  290. do{
  291. $digit = $len % 128;
  292. $len = $len >> 7;
  293. // if there are more digits to encode, set the top bit of this digit
  294. if ( $len > 0 )
  295. $digit = ($digit | 0x80);
  296. $string .= chr($digit);
  297. }while ( $len > 0 );
  298. return $string;
  299. }
  300. /* strwritestring: writes a string to a buffer */
  301. function strwritestring($str, &$i){
  302. $ret = " ";
  303. $len = strlen($str);
  304. $msb = $len >> 8;
  305. $lsb = $len % 256;
  306. $ret = chr($msb);
  307. $ret .= chr($lsb);
  308. $ret .= $str;
  309. $i += ($len+2);
  310. return $ret;
  311. }
  312. function printstr($string){
  313. $strlen = strlen($string);
  314. for($j=0;$j<$strlen;$j++){
  315. $num = ord($string{$j});
  316. if($num > 31)
  317. $chr = $string{$j}; else $chr = " ";
  318. printf("%4d: %08b : 0x%02x : %s \n",$j,$num,$num,$chr);
  319. }
  320. }
  321. }
  322. ?>