示例#1
1
<?php

require __DIR__ . '/../test.inc.php';
use sskaje\mqtt\MQTT;
use sskaje\mqtt\Debug;
use sskaje\mqtt\MessageHandler;
$mqtt = new MQTT($MQTT_SERVER);
$context = stream_context_create();
$mqtt->setSocketContext($context);
Debug::Enable();
//$mqtt->setAuth('sskaje', '123123');
$mqtt->setKeepalive(3600);
$connected = $mqtt->connect();
if (!$connected) {
    die("Not connected\n");
}
$topics['sskaje/#'] = 2;
$mqtt->subscribe($topics);
#$mqtt->unsubscribe(array_keys($topics));
class MySubscribeCallback extends MessageHandler
{
    public function publish($mqtt, sskaje\mqtt\Message\PUBLISH $publish_object)
    {
        printf("I got a message:(msgid=%d, QoS=%d, dup=%d, topic=%s) %s\n", $publish_object->getMsgID(), $publish_object->getQos(), $publish_object->getDup(), $publish_object->getTopic(), $publish_object->getMessage());
    }
}
$callback = new MySubscribeCallback();
$mqtt->setHandler($callback);
$mqtt->loop();
示例#2
0
文件: PUBLISH.php 项目: sskaje/mqtt
 /**
  * Build Payload
  *
  * @return string
  */
 protected function payload()
 {
     $buffer = "";
     # Payload
     $buffer .= $this->message;
     Debug::Log(Debug::DEBUG, 'Message PUBLISH: Message=' . $this->message);
     return $buffer;
 }
示例#3
0
$mqtt->setSocketContext($context);
# Set Connect Will
$mqtt->setWill('sskaje/will', 'Ciao~', 0, 0);
Debug::Enable();
Debug::SetLogPriority(Debug::NOTICE);
#
$mqtt->setKeepalive(30);
//$mqtt->setAuth('sskaje', '123123');
$connected = $mqtt->connect();
if (!$connected) {
    die("Not connected\n");
}
$msg = str_repeat('1234567890', 1);
# Set Retry Timeout for Publish and its following commands
$mqtt->setRetryTimeout(5);
Debug::Log(Debug::INFO, "QoS=1");
$c = 1;
while (true) {
    # Special thanks to @LiuYongShuai for this test case.
    # It is the responsibility of the Client to ensure that the interval between Control Packets
    # being sent does not exceed the Keep Alive value. In the absence of sending any other Control
    # Packets, the Client MUST send a PINGREQ Packet [MQTT-3.1.2-23].
    # If the Keep Alive value is non-zero and the Server does not receive a Control Packet from the Client
    # within one and a half times the Keep Alive time period, it MUST disconnect the Network Connection to
    # the Client as if the network had failed [MQTT-3.1.2-24].
    $mqtt->keepalive();
    # mosquitto_sub -t 'sskaje/#'  -q 1 -h test.mosquitto.org
    $mqtt->publish_sync('sskaje/test', $msg, 1, 0);
    echo "======== QoS=1, Count={$c}\n";
    #sleep(1);
    ++$c;
示例#4
0
文件: Base.php 项目: dethegeek/mqtt
 protected final function packPacketIdentifer()
 {
     if (!$this->msgid) {
         throw new Exception('Invalid Packet Identifier');
     }
     Debug::Log(Debug::DEBUG, 'msgid=' . $this->msgid);
     return pack('n', $this->msgid);
 }
示例#5
0
文件: Base.php 项目: dethegeek/mqtt
 /**
  * Process packet with Fixed Header + Message Identifier only
  *
  * @param string $message
  * @return array|bool
  */
 protected final function processReadFixedHeaderWithMsgID($message)
 {
     $packet_length = 4;
     $name = Message::$name[$this->message_type];
     if (!isset($message[$packet_length - 1])) {
         # error
         Debug::Log(Debug::DEBUG, "Message {$name}: error on reading");
         return false;
     }
     $packet = unpack('Ccmd/Clength/nmsgid', $message);
     $packet['cmd'] = Utility::UnpackCommand($packet['cmd']);
     if ($packet['cmd']['message_type'] != $this->getMessageType()) {
         Debug::Log(Debug::DEBUG, "Message {$name}: type mismatch");
         return false;
     } else {
         Debug::Log(Debug::DEBUG, "Message {$name}: success");
         return $packet;
     }
 }
示例#6
0
文件: qos0.php 项目: dethegeek/mqtt
<?php

require __DIR__ . '/../test.inc.php';
ini_set('error_log', __DIR__ . '/../../logs/examples_publish.log');
use sskaje\mqtt\MQTT;
use sskaje\mqtt\Debug;
$mqtt = new MQTT($MQTT_SERVER);
# Set Socket Context
$context = stream_context_create();
$mqtt->setSocketContext($context);
# Set Connect Will
$mqtt->setWill('sskaje/will', 'Ciao~', 0, 0);
Debug::Enable();
Debug::SetLogPriority(Debug::NOTICE);
//$mqtt->setAuth('sskaje', '123123');
$connected = $mqtt->connect();
if (!$connected) {
    die("Not connected\n");
}
$msg = str_repeat('1234567890', 1);
Debug::Log(Debug::INFO, "QoS=0");
$c = 0;
do {
    # mosquitto_sub -t 'sskaje/#'  -q 1 -h test.mosquitto.org
    $mqtt->publish_sync('sskaje/test', $msg, 0, 0);
    echo "======== QoS=0, Count={$c}\n";
    #sleep(1);
} while (++$c < 100);
示例#7
0
 /**
  * Decode Variable Header
  *
  * @param string & $packet_data
  * @param int    & $pos
  * @return bool
  * @throws Exception
  */
 protected function decodeVariableHeader(&$packet_data, &$pos)
 {
     $this->session_present = ord($packet_data[2]) & 0x1;
     $this->return_code = ord($packet_data[3]);
     if ($this->return_code != 0) {
         $error = isset(self::$connect_errors[$this->return_code]) ? self::$connect_errors[$this->return_code] : 'Unknown error';
         Debug::Log(Debug::ERR, sprintf("Connection failed! (Error: 0x%02x 0x%02x|%s)", ord($packet_data[2]), $this->return_code, $error));
         /*
         If a server sends a CONNACK packet containing a non-zero return code it MUST
         then close the Network Connection [MQTT-3.2.2-5]
         */
         throw new Exception\ConnectError($error);
     }
     if ($this->session_present) {
         Debug::Log(Debug::DEBUG, "CONNACK: Session Present Flag: ON");
     } else {
         Debug::Log(Debug::DEBUG, "CONNACK: Session Present Flag: OFF");
     }
 }
示例#8
0
 /**
  * PUBLISH Variable Header
  *
  * Topic Name, Packet Identifier
  *
  * @return string
  * @throws Exception
  */
 protected function buildVariableHeader()
 {
     $header = '';
     $topic = $this->message->getTopic();
     # Topic
     $header .= Utility::PackStringWithLength($topic);
     Debug::Log(Debug::DEBUG, 'Message PUBLISH: topic=' . $topic);
     Debug::Log(Debug::DEBUG, 'Message PUBLISH: QoS=' . $this->getQos());
     Debug::Log(Debug::DEBUG, 'Message PUBLISH: DUP=' . $this->getDup());
     Debug::Log(Debug::DEBUG, 'Message PUBLISH: RETAIN=' . $this->getRetain());
     # Message ID if QoS > 0
     if ($this->getQos()) {
         if (!$this->msgid) {
             throw new Exception('MsgID MUST be set if QoS is not 0.');
         }
         $header .= $this->packPacketIdentifer();
     }
     return $header;
 }
示例#9
0
文件: MQTT.php 项目: dethegeek/mqtt
 /**
  * Read Message And Create Message Object
  *
  * @return \sskaje\mqtt\Message\Base
  * @throws \sskaje\mqtt\Exception
  */
 protected function message_read()
 {
     if ($this->socket->eof()) {
         if (++$this->count_eof > 5) {
             usleep(pow(2, $this->count_eof));
         }
         Debug::Log(Debug::NOTICE, 'message_read(): EOF ' . $this->count_eof);
         if ($this->count_eof > $this->max_eof) {
             throw new Exception\NetworkError();
         }
         return false;
     }
     # Reset EOF counter
     $this->count_eof = 0;
     # read 2 bytes
     $read_fh_bytes = 2;
     $read_more_length_bytes = 3;
     $read_bytes = 0;
     $read_message = $this->socket->read($read_fh_bytes);
     if (empty($read_message)) {
         throw new Exception('WTFFFFFF!!!! ');
     }
     $read_bytes += $read_fh_bytes;
     $cmd = Utility::ParseCommand(ord($read_message[0]));
     $message_type = $cmd['message_type'];
     $flags = $cmd['flags'];
     Debug::Log(Debug::DEBUG, "message_read(): message_type=" . Message::$name[$message_type] . ", flags={$flags}");
     if (ord($read_message[1]) > 0x7f) {
         # read 3 more bytes
         $read_message .= $this->socket->read($read_more_length_bytes);
         $read_bytes += $read_more_length_bytes;
     }
     $pos = 1;
     $remaining_length = Utility::DecodeLength($read_message, $pos);
     $to_read = 0;
     if ($remaining_length) {
         $to_read = $remaining_length - ($read_bytes - $pos);
     }
     Debug::Log(Debug::DEBUG, 'message_read(): remaining length=' . $remaining_length . ', data to read=' . $to_read);
     if ($to_read) {
         $read_message .= $this->socket->read($to_read);
     }
     Debug::Log(Debug::DEBUG, 'message_read(): Dump', $read_message);
     $message_object = $this->getMessageObject($message_type);
     $message_object->decode($read_message, $remaining_length);
     return $message_object;
 }
示例#10
0
文件: qos2.php 项目: dethegeek/mqtt
ini_set('error_log', __DIR__ . '/../../logs/examples_publish.log');
use sskaje\mqtt\MQTT;
use sskaje\mqtt\Debug;
$mqtt = new MQTT($MQTT_SERVER);
# Set Socket Context
$context = stream_context_create();
$mqtt->setSocketContext($context);
# Set Connect Will
$mqtt->setWill('sskaje/will', 'Ciao~', 0, 0);
Debug::Enable();
Debug::SetLogPriority(Debug::NOTICE);
//$mqtt->setAuth('sskaje', '123123');
$connected = $mqtt->connect();
if (!$connected) {
    die("Not connected\n");
}
# Set Retry Timeout for Publish and its following commands
$mqtt->setRetryTimeout(5);
$msg = str_repeat('1234567890', 1);
$myhandler = new MyPublishHandler();
Debug::Log(Debug::INFO, "QoS=2");
$c = 0;
do {
    # mosquitto_sub -t 'sskaje/#'  -q 1 -h test.mosquitto.org
    $r = $mqtt->publish_async('sskaje/test', $msg, 2, 0, $msgid);
    $myhandler->waitQueue[$r['msgid']] = $r;
    echo "======== QoS=2, Count={$c}, msgid={$msgid} \n";
} while (++$c < 100);
$mqtt->setHandler($myhandler);
$mqtt->loop();
# EOF