<?php/* Phpmqtt */class phpmqtt {private $socket; /* Holds the socket */private $msgid = 1; /* counter for Message ID */Public $keepalive = 10; /* Default KeepAlive Timmer */public $timesinceping; /* Host Unix time, used to detect disconects */Public $topics = Array (); /* Used to store currently subscribed topics */public $debug = false; /* Should output DEBUG messages */public $address; /* Broker Address */public $port; /* Broker Port */public $clientid; /* Client ID sent to Brocker */public $will; /* Stores the'll of the client */private $username; /* Stores username */Private $password; /* Stores Password */function __construct ($address, $port, $clientid) {$this->broker ($address, $port, $clie NTID); }/* Sets the broker Details */function broker ($address, $port, $clientid) {$this->address = $adDress $this->port = $port; $this->clientid = $clientid; }/* connects to the broker inputs: $clean: Should the client, send a clean session flag */function Connect ( $clean = true, $will = null, $username = NULL, $password = null) {if ($will) $this->will = $will; if ($username) $this->username = $username; if ($password) $this->password = $password; $address = gethostbyname ($this->address); $this->socket = Fsockopen ($address, $this->port, $errno, $ERRSTR, 60); if (! $this->socket) {error_log ("fsockopen () $errno, $ERRSTR \ n"); return false; } stream_set_timeout ($this->socket, 5); Stream_set_blocking ($this->socket, 0); $i = 0; $buffer = ""; $buffer. = Chr (0x00); $i + +; $buffer. = Chr (0x06); $i + +; $buffer. = Chr (0x4d); $i + +; $buffer. = Chr (0x51); $i + +; $buffer. = Chr (0x49); $i + +; $buffer. = Chr (0x73); $i + +; $buffer. = Chr (0x64); $i + +; $buffer. = Chr (0x70); $i + +; $buffer. = Chr (0x03); $i + +; No would $var = 0; if ($clean) $var +=2; ADD would info to header if ($this->will! = NULL) {$var + = 4;//Set would flag $var + = ($t His->will[' QoS '] << 3); Set would QoS if ($this->will[' retain ')) $var + = 32; Set would retain} if ($this->username! = NULL) $var + = 128; ADD username to Header if ($this->password! = NULL) $var + = 64; Add password to header $buffer. = Chr ($var); $i + +; Keep Alive $buffer. = Chr ($this->keepalive >> 8); $i + +; $buffer. = Chr ($this->keepalive & 0xff); $i + +; $buffer. = $this->strwritestring ($this->clientid, $i); Adding would to payload if ($this->will! = NULL) {$buffer. = $this->strwritestring ($this->will[ ' Topic '], $i); $buffer. = $this->strwritestring ($this->will[' content '), $i); if ($this->username) $buffer. = $this->strwritestring ($this->username, $i); if ($this->password) $buffer. = $this->strwritestring ($this->password, $i); $head = ""; $head {0} = Chr (0x10); $head {1} = Chr ($i); Fwrite ($this->socket, $head, 2); Fwrite ($this->socket, $buffer); $string = $this->read (4); if (Ord ($string {0}) >>4 = = 2 && $string {3} = Chr (0)) {if ($this->debug) echo "Connected to broke r\n "; }else{Error_log (sprintf ("Connection failed! (error:0x%02x 0x%02x) \ n ", Ord ($string {0}), Ord ($string {3})); return false; } $this->timesinceping = time (); return true; }/* Read:reads in so many bytes * * Function Read ($int = 8192, $nb = False) {//Print_r (Socket_get_status ($this->socket)); $string = ""; $togo = $int; if ($NB) {return fread ($this->socket, $togo); } while (!feof ($this->socket) && $togo >0) {$fread = Fread ($this->socket, $togo); $string. = $fread; $togo = $int-strlen ($string); } return $string; }/* Subscribe:subscribes to Topics */function Subscribe ($topics, $qos = 0) {$i = 0; $buffer = ""; $id = $this->msgid; $buffer. = Chr ($id >> 8); $i + +; $buffer. = chr ($id% 256); $i + +; foreach ($topics as $key = = $topic) {$buffer. = $this->strwritestring ($key, $i); $buffer. = Chr ($topic ["QoS"]); $i + +; $this->topics[$key] = $topic; } $cmd = 0x80; $qos $cmd + = ($qos << 1); $head = Chr ($cmd); $head. = Chr ($i); Fwrite ($this->socket, $head, 2); Fwrite ($this->socket,$buffer, $i); $string = $this->read (2); $bytes = Ord (substr ($string, 1, 1)); $string = $this->read ($bytes); }/* Ping:sends a Keep alive ping */function ping () {$head = ""; $head = Chr (0xc0); $head. = Chr (0x00); Fwrite ($this->socket, $head, 2); if ($this->debug) echo "Ping sent\n"; }/* Disconnect:sends a proper disconect cmd */function disconnect () {$head = ""; $head {0} = Chr (0XE0); $head {1} = Chr (0x00); Fwrite ($this->socket, $head, 2); }/* Close:sends a proper disconect, then closes the socket */function Close () {$this->disconnect (); Fclose ($this->socket); }/* Publish:publishes $content on a $topic */function Publish ($topic, $content, $qos = 0, $retain = 0) { $i = 0; $buffer = ""; $buffer. = $this->strwritestring ($topic, $i); $buffer. = $this->strwritestring ($content, $i); if ($qos) {$id = $this->msgid++; $buffer. = Chr ($id >> 8); $i + +; $buffer. = chr ($id% 256); $i + +; } $buffer. = $content; $i +=strlen ($content); $head = ""; $cmd = 0x30; if ($qos) $cmd + = $qos << 1; if ($retain) $cmd + = 1; $head {0} = Chr ($cmd); $head. = $this->setmsglength ($i); Fwrite ($this->socket, $head, strlen ($head)); Fwrite ($this->socket, $buffer, $i); }/* Message:processes a recieved topic */function message ($msg) {$tlen = (ord ($msg {0}) <<8) + or D ($msg {1}); $topic = substr ($msg, 2, $tlen); $msg = substr ($msg, ($tlen +2)); $found = 0; foreach ($this->topics as $key = + $top) {if (Preg_match ("/^". Str_replace ("#", ". *", Str_replace ("+", "[^\/]*", Str_replace ("/", "\ ", Str_replace (" $ ", ' \$ ', $key))))." $/", $topic)) {if (Function_exists ($top [' function ')]) {Call_user_func ($top [' Funct Ion '], $topic, $msg); $found = 1; }}} if ($this->debug &&! $found) echo "msg recieved but no match in subs Criptions\n "; }/* Proc:the processing loop for a "allways on" client set true if you were doing other stuff in the loop g Ood for watching something else at the same time * * function proc ($loop = True) {if (1) {$sockets = Array ($this->socket); $w = $e = NULL; $cmd = 0; $byte = fgetc ($this->socket); if (feof ($this->socket)) {if ($this->debug) echo "EOF receive going to reconnect for good measure\n"; Fclose ($this->socket); $thIs->connect (FALSE); if (count ($this->topics)) $this->subscribe ($this->topics); } $byte = $this->read (1, true); if (!strlen ($byte)) {if ($loop) {usleep (100000); }}else{$cmd = (int) (ORD ($byte)/16); if ($this->debug) echo "Recevid: $cmd \ n"; $multiplier = 1; $value = 0; do{$digit = Ord ($this->read (1)); $value + = ($digit & 127) * $multiplier; $multiplier *= 128; }while (($digit & 128)! = 0); if ($this->debug) echo "fetching: $value \ n"; if ($value) $string = $this->read ($value, "fetch"); if ($cmd) {switch ($cmd) {case 3: $this->message ($st Ring); Break } $this->timesinceping = time (); }} if ($this->timesinceping < (time ()-$this->keepalive)) {if ($this->d Ebug) echo "not found something so ping\n"; $this->ping (); if ($this->timesinceping< () ($this->keepalive*2)) {if ($this->debug) echo "No T seen a package in a while, disconnecting\n "; Fclose ($this->socket); $this->connect (FALSE); if (count ($this->topics)) $this->subscribe ($this->topics); }} return 1; }/* Getmsglength: */function Getmsglength (& $msg, & $i) {$multiplier = 1; $value = 0; do{$digit = Ord ($msg {$i}); $value + = ($digit & 127) * $multiplier; $multiplier *= 128; $i + +; }while (($Digit & 128)! = 0); return $value; }/* Setmsglength: */function Setmsglength ($len) {$string = ""; do{$digit = $len% 128; $len = $len >> 7; If there is more digits-encode, set the top bit of this digit if ($len > 0) $digit = ($dig it | 0x80); $string. = Chr ($digit); }while ($len > 0); return $string; }/* Strwritestring:writes A string to a buffer */function strwritestring ($STR, & $i) {$ret = ""; $len = strlen ($STR); $MSB = $len >> 8; $LSB = $len% 256; $ret = Chr ($MSB); $ret. = Chr ($LSB); $ret. = $str; $i + = ($len +2); return $ret; } function Printstr ($string) {$strlen = strlen ($string); for ($j =0; $j < $strlen; $j + +) {$num = Ord ($string {$j}); if ($num >) $chr = $string {$j}; else $CHR = ""; printf ("%4D:%08b:0x%02x:%s \ n", $j, $num, $num, $CHR); }}}?>
publish.php
<?php require ("./phpmqtt.php"); $mqtt = new Phpmqtt ("localhost", 1883, "Hacker"); if ($mqtt->connect ()) { $mqtt->publish ("Hello", "Hello world! at". Date ("R"), 0); $mqtt->close ();} ?>
subscribe.php
<?php require ("./phpmqtt.php"); $mqtt = new Phpmqtt ("localhost", 1883, "Musikar"); if (! $mqtt->connect ()) { exit (1);} $topics [' hello '] = Array ("QoS" =>0, "function" = "procmsg"); $mqtt Subscribe ($topics, 0); while ($mqtt->proc ()) {} $mqtt->close (); function procmsg ($topic, $msg) { echo "msg recieved:". Date ("R"). " \ntopic:{$topic}\n$msg\n ";} ?>
MQTT Client PHP