Core.php 11 KB

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