bluerhinos / phpmqtt Goto Github PK
View Code? Open in Web Editor NEWa simple php class to connect/publish/subscribe to a MQTT broker
License: Other
a simple php class to connect/publish/subscribe to a MQTT broker
License: Other
Hi, I call subscribe successfull, but have issue : string response from broker in wrong format. It has �NV01
NV01 is string that i published , a first char ? Why it appear here ? Thanks
I've been able to successfully publish QoS1 msgs to Mosquito just fine. However, the subs, also using QoS1, keep receiving the same messages over and over again. Does phpMQTT send the PUBACK back to the broker?
After download and use current version of lib, i get following error:
PHP Parse error: syntax error, unexpected '[', expecting ')' in /phpMQTT.php on line 84
I use PHP 5.3.3
Hi,
I habe MQTT server installed on Synology NAS and work fine.
I have the oublishing phpMQTT.php Script an work fine to.
But the subscrib script give error:
Fatal error: Maximum execution time of 60 seconds exceeded in C:\Inetpub\vhosts\user.com\httpdocs\phpMQTT.php on line 309
Can you help me set up correctly?
Thank you in advance
David
Hello, I would like to use your MQTT lib to publish commands against IBM Bluemix.
Basically it works fine. But after several call the whole PHP instance hangs. I assume that there is a small mistake in integrating the lib.
I your sample the connection is closed after publishing the command. Is there a way to keep the connection open? Idee is a PHP script called via Ajax. Hope this makes sense.
Thanks!
I m not able to connect to cloudMQTT using this phpMQTT from web host.
I m getting error
Warning: stream_socket_client(): unable to connect to tcp://---.cloudmqtt.com:----- (Connection refused) in /home/***/public_html/vendor/bluerhinos/phpmqtt/phpMQTT.php on line 90
require('../vendor/autoload.php');
header("Refresh:0");
use Bluerhinos\phpMQTT;
$server = "***.cloudmqtt.com"; // change if necessary
$port = ***; // change if necessary
$username = "***"; // set your username
$password = "***"; // set your password
$client_id = "***";
$mqtt = new phpMQTT($server, $port, $client_id);
if(!$mqtt->connect(true, NULL, $username, $password)) {
exit(1);
}
$topics['test'] = array("qos" => 0, "function" => "procmsg");
$mqtt->subscribe($topics, 0);
$start_time = time();
$done = 0;
while (!$done && !hasTimedout() && $mqtt->proc()) { }
$mqtt->close();
function procmsg($topic, $msg){
global $done;
//echo "Msg Recieved: ".date("r")."\nTopic:{$topic}\n$msg\n";
}
function hasTimedout()
{
global $start_time;
return (time() - $start_time > 1);
}
>
Both publish and subscribe is working through localhost. but when i uploaded to web hosting it's giving that error.
Hi
So I ran the PUBLISH to a simple unprotected MOSQUITTO broker running on a local PC, routed outside.... no problem - I can publish an item over and over and my local MQTT clients pick it up. However the SUBSCRIBE page seems to do nothing when given the same topic... and I publish something. The page just sits there and eventually times out.
Ideas?
The publisher is MARVELOUS as I want to send the time and some other stuff to one of my little wireless boards via MQTT on a regular basis... but it would be really nice if the subscribe page worked as well. My pages are on a paid server which hosts my PHP pages...
We've run into a problem with phpMQTT when subscribing to more than 16 topics in a single connection.
After 16 connections no more connections can be created.
After publishing around 1000 messages in quick succession, PHP client reports
errno 32, broken pipe.
Also seeing (on other runs of same app)...
Notice: fwrite(): send of 2 bytes failed with errno=11 Resource
temporarily unavailable in phpMQTT.php
I suspect this is to do with the non-blocking socket I/O in phpMQTT, as errno 11 is EAGAIN. But this does not appear to be handled by the library.
Is there a particular reason for using NBIO, and if so, could the library handly EAGAIN a bit better, please ? :)
stream_socket_client(): unable to connect to tcp
Why is $timesinceping updated by receiving data?
To do keepalive, we need to SEND data to sever(broker) repeatedly.
So, receiving data shouldn't affect the keepalive responses' algorithm.
when a client is just a subscriber, it should send ping repeatedly within $keepalive time, otherwise it will loose sessions and needs to reconnect.
To cofirm the opinion above, you could do the following.
Turn the debug flag on and subscribe a topic which is published messages every second,
you'll see the debug message "eof receive going to reconnect for good measure\n" periodically (in every $keepalive time).
Hi,
Thanks for the great script. I see in the issues that SSL/TLS support has been mentioned a few times. Would the following change not implement SSL/TLS?
Changing the following line
$this->socket = fsockopen($address, $this->port, $errno, $errstr, 60);
to
$this->socket = stream_socket_client('ssl://'.$address.':'.$this->port,$errno,$errstr);
I have tested this and the connection is successful without any SSL errors thrown and message is received by the broker. My question is is this actually a valid TLS connection? When testing on localhost I get:
routines:ssl3_get_server_certificate:certificate verify failed
Would this suggest the working connection is then truly encrypted?
I try to run code:
<?php
require("../phpMQTT.php");
$mqtt = new phpMQTT("localhost", 1883, "PHP MQTT Client");
if(!$mqtt->connect()){
exit(1);
}
$topics['ferries/IOW/#'] = 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";
}
?>
and i get error:
PHP Warning: Invalid argument supplied for foreach() in /volume1/web/test/phpMQTT.php on line 179
what's wrong?
I am using mosquitto server.
Hi,
I did the same as per the documentation but getting below exception.
PHP Warning: fsockopen(): unable to connect to wss://mydomain.com:1883 (Unable to find the socket transport "wss" - did you forget to enable it when you configured PHP?)
@bluerhinos Please help me to out of it.
Hey,
first - thanks for your work.
Is there any chance to get the ratain flag to work?
Maybe i'am doing something wrong?!
$mqtt = new phpMQTT("[redacted]", [redacted], "[redacted]"); if ($mqtt->connect(true, NULL, "[redacted]", "[redacted]")) { $mqtt->publish("/ak/POWER/20","20",1,1); $mqtt->close(); }
QoS 1 works so far.
Thanks and best regards,
andreas
phpMQTT.php Line 269 uses function_exists
but this doesn't play nicely if you're trying to use the library from within an OO class... could it be changed to is_callable
please? then you can do, eg
$topics['ferries/IOW/#'] = array('qos' => 0, 'function' => array($this, 'procmsg'));
Many thanks.
Please update the examples like so (insert namespace) :
$mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id);
Notice: Uninitialized string offset: 0 in C:\xampp\htdocs\websockets\phpMQTT.php on line 121
Notice: Uninitialized string offset: 0 in C:\xampp\htdocs\websockets\phpMQTT.php on line 125
Notice: Uninitialized string offset: 3 in C:\xampp\htdocs\websockets\phpMQTT.php on line 125
Fail or time out.
I'm new to MQTT. Please give solution for it.
Hi.
I wan't use this class but when i load nothing is happen.
Is loading...loading...
I need install something?
I have apache2, php5 installed
Do you have some a tutorial?
I can successfully publish messages (I know this because when subscribed with other clients I also receive messages), but I don't receive any messages while subscribed with example provided.
I run the script as cli. With debug set on true I get following output every second:
eof receive going to reconnect for good measure
but no messages. Also if I trace this client on broker I don't see any SUBSCRIBE calls from this client, only CONNECT calls.
Hi,
I tried to publish with qos 2, but does not work.
$conn->publish($request->getParameter('target'), $msg, 2);
Don't know if I'm missing some detail.
Thanks in advance
Hi, I'm trying to open the Publish and scriber page but i'm getting Error:
Fatal error: Class 'phpMQTT' not found in C:\xampp\htdocs\websockets\examples\subscribe.php on line 12 .
Links:
Publish : http://localhost/websockets/examples/publish.php
Subscribe : http://localhost/websockets/examples/subscribe.php
Hi,
I'm trying to use phpMQTT on my Windows7 machine using localhost. Apache & PHP setup is done by installing WAMP server. I'm running it as below -
Is my way of running correct?
I'm not getting published message in subscribed tab but getting following error -
" Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\phpMQTT-master\phpMQTT.php on line 156".
I have also enabled debug, copy of which is attached.
However I have another Python MQTT client running in command prompt which is getting the publish message from publisher.php.
I'm new to this, could you please help me on this ?
Thanks,
Dilip
How do you receive the returned message after you send it?
Hello @bluerhinos
My code is working by turn the light on/off
URLAPI calling: http://domainname.com/api/turnTheLight/5/1
routes: /api/{pin}/{action}
public function turnTheLight( Request $request ) {
$action = $request->route( 'action' );
$device = Device::find( $request->route( 'id' ) );
$client_id = $device->device_id;
$mqtt = new phpMQTT( $this->server, $this->port, $client_id );
if ( $mqtt->connect( true, null, $this->username, $this->password ) ) {
$mqtt->publish( '/turn/light', $action, 0 );
$mqtt->close();
$device->status = $action;
$device->save();
return response()->json( [
'statusCode' => 1,
'message' => 'Success',
] );
} else {
return response()->json( [ 'message' => 'Error!!' ], 204 );
}
}
But now I want to publish the topic include the deviceID and the pin of light /turn/light/{deviceID}/{pin}/{action}
Example: /turn/light/esp123456/5/1
That only effect with the deviceID: esp123456 and the light connected on pin 5th is ON
Below is Arduino code
void callback(char* topic, byte* payload, unsigned int length) {
String topicStr = topic;
//turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
if (payload[0] == '1') {
digitalWrite(5, HIGH);
client.publish("/state/light", "Light On");
}
//turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
else if (payload[0] == '0') {
digitalWrite(5, LOW);
client.publish("/state/light", "Light Off");
}
}
Please help me.
Can you add some tags/releases, so it is possible to lock version with composer?
I am unable to subscribe using subscription code. I am using subscriber code on server keeping it as a cron job so that when ever I receive published data, I can subscribe it. But I am unable to do it. In the subscriber code inside procmsg function I added code to hit DB, but nothing working. Individually when I run subscriber.php, it shows an infinite loop. Main target of my project to use MQTT is to subscribe data & save it in DB when published by device.
MQTT is working fine by running my php file in background process. But suddenly after few days it is throwing error like "Socket error on client client_name, disconnecting". After that error php file which is running in background stopped. Can any one help me to solve this issue?
Hi,
My MQTT serevr is running with SSL/TLS support(mosquitto-tls)
Is this support to publish with ca.crt/client.crt/client.key ??
Do you have some examples or suggestion on it ?
Hi
Now i started to get message from publisher.But it possible only when i run it in terminal only.
Is it possible to run it in the browser.And get message as it works inside terminal? I want that message should also get using browser....
I am trying to develop a web page which will print the received message from subscribing to the topic. but I am not able to do it can anyone please help me on this?
I'm trying to use phpMQTT to connect to an MQTT broker on a RabbitMQ server with a 52-characters username, but it is failing with the below error. While the error is similar to the one mentioned in #48, I'm not sure if it is the same cause:
Notice: Uninitialized string offset: 0 in /PATH_TO_PHP/phpMQTT.php on line 155 Notice: Uninitialized string offset: 0 in /PATH_TO_PHP/phpMQTT.php on line 159 Notice: Uninitialized string offset: 3 in /PATH_TO_PHP/phpMQTT.php on line 159 Connection failed! (Error: 0x00 0x00)
The error does not occur if I trim the username to 28 characters. But if I use at least one more character (29 or above), the above error occurs again.
MQTT specification recommends a 12-characters or less for each of the username and password field. But the specification also specifies that this is not requirement.
The MQTT broker on RabbitMQ expects the username to be the concatenation of the virtual-host-name and the username, separated by a colon ":". So a long username is valid.
The password was not an issue even though it is 64 characters.
Section 3.1 in MQTT v3.1 protocol specification:
It is recommended that user names are kept to 12 characters or fewer, but it is not required.
The above issue occurs when connecting from phpMQTT to a RabbitMQ server or to a Mosquitto server. But the same credentials used from other clients to the same servers works normally.
I have this snippet:
$mqtt = new phpMQTT(MQTT_SERVER, 1883, DOMAIN);
if ($mqtt->connect()) {
if (is_array($topic)) {
foreach ($topic as $t) {
$mqtt->publish(self::clean_uri($t), $message, 0);
sleep(1);
} else {
$mqtt->publish(self::clean_uri($topic), $message, 0);
}
$mqtt->close();
} else {
return false;
}
to allow my program to send the same message to several topics (single stream, per user stream, etc.). i added the sleep(1)
lines because sending messages one after another only sends the first one. i haven't tried with more than two topics but i notice the time required to send to many more will be long :P
any ideas?
Hello i don't know why i am getting this error...
Subscribe does not work. It gave wrong subscribe header error.
And continuously connect and disconnect from server.
function proc()
Every time it's print "eof receive going to reconnect for good measure\n"; Means nothing to read from channel and go to eof socket
I tried some tutorials and ended up getting same errors when running my file.
It says:
PHP Notice: Uninitialized string offset: 0 in /var/www/html/mqtt/classes/phpMQTT.php on line 155
PHP Notice: Uninitialized string offset: 0 in /var/www/html/mqtt/classes/phpMQTT.php on line 159
PHP Notice: Uninitialized string offset: 3 in /var/www/html/mqtt/classes/phpMQTT.php on line 159
Connection failed! (Error: 0x00 0x00)
considering i'm new in this thing, please make it simple to understand.
[2017-09-06 15:33:08] local.DEBUG: eof receive going to reconnect for good measure
[2017-09-06 15:32:43] local.DEBUG: ping sent
[2017-09-06 15:32:43] local.DEBUG: not found something so ping
[2017-09-06 15:32:43] local.DEBUG: ping sent
[2017-09-06 15:32:43] local.DEBUG: Recevid: 13
[2017-09-06 15:32:43] local.DEBUG: Fetching: 0
[2017-09-06 15:32:43] local.DEBUG: Recevid: 13
[2017-09-06 15:32:43] local.DEBUG: Fetching: 0
[2017-09-06 15:32:54] local.DEBUG: not found something so ping
[2017-09-06 15:32:54] local.DEBUG: ping sent
[2017-09-06 15:32:54] local.DEBUG: not found something so ping
[2017-09-06 15:32:54] local.DEBUG: ping sent
[2017-09-06 15:32:54] local.DEBUG: Recevid: 13
[2017-09-06 15:32:54] local.DEBUG: Fetching: 0
[2017-09-06 15:32:54] local.DEBUG: Recevid: 13
[2017-09-06 15:32:54] local.DEBUG: Fetching: 0
[2017-09-06 15:32:59] local.DEBUG: Recevid: 3
[2017-09-06 15:32:59] local.DEBUG: Fetching: 54
[2017-09-06 15:33:06] local.DEBUG: Recevid: 3
[2017-09-06 15:33:06] local.DEBUG: Fetching: 32
[2017-09-06 15:33:08] local.DEBUG: eof receive going to reconnect for good measure
[2017-09-06 15:33:08] local.DEBUG: Connected to Broker
[2017-09-06 15:33:08] local.DEBUG: Recevid: 3
[root@bemfa mqtt_plat]# composer require bluerhinos/phpmqtt
Do not run Composer as root/super user! See https://getcomposer.org/root for details
[InvalidArgumentException]
Could not find package bluerhinos/phpmqtt.
Did you mean this?
bluerhinos/phpmqtt
require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--update-with-all-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] []...
In the sample pub and sub clients, the client IDs are the same, so the subscriber gets kicked off the broker every time you publish, so you don't get the messages!
Make them different :)
Hi,
I am getting below error while running publish.php
. Please help me to resolve this. What could be the exact reasone for this. I have my server IP and port. (I dont' have $username and $password so kept it blank, only passing the IP, port and clientId.
Notice: Uninitialized string offset: 0 in C:\xampp\htdocs\mqtt\phpMQTT.php on line 141
Notice: Uninitialized string offset: 0 in C:\xampp\mqtt\phpMQTT.php on line 145
Notice: Uninitialized string offset: 3 in C:\xampp\mqtt\phpMQTT.php on line 145
Fail or time out
Please help me to solve this.
FYI: I checked the same thing in my localhost and server both but getting same output.
Ran into a connection problem while working with IBM MessageSight. Code that works with m2m.eclipse.org/iot.eclipse.org fails to connect with MessageSight. I tried several public brokers and was able to reproduce the error with dev.rabbitmq.com. Keep getting this for ever:
Connected to Broker
eof receive going to reconnect for good measure
Connected to Broker
eof receive going to reconnect for good measure
Connected to Broker
eof receive going to reconnect for good measure
Connected to Broker
Please try to connect with public broker dev.rabbitmq.com on 1883 and check.
Hi,
I'm new to you library, and while testing it out I have found an issue with publishing messages to a Mosquitto broker. I'm running mosquitto 1.0.3 on ubuntu, but I have been able to reproduce with 1.0.2 & 1.0.1.
When using the publish example, and only changing the host from example.com to localhost, i get the following error in the mosquitto log:
1349782626: New client connected from 127.0.0.1 as PHP MQTT Client.
1349782626: Socket error on client PHP MQTT Client, disconnecting.
Some testing, it appears to be the publish function causing the problem, not the connect. I'd love to get this working as mqtt with php seems like a great combo.
Thanks,
Wayne.
Hi there!
When trying to install true composer i get the following error:
[InvalidArgumentException]
Could not find a version of package bluerhinos/phpmqtt matching your minimum-stability (stable). Require it with an explicit version constraint allowing its desired stability.
PHP version: 5.6.33-0+deb8u1
Composer Version: 1.6.4
Can anyone help me?
Im running mosquitto mqtt broker in my machine.
If I subscribe with java client and publish by phpMQTT its working well. however if i publish and subscribe with phpMQTT, im not able to subscribe. Could you plz help me what is wrong with my pub/sub.
When I subscribe to topic : testparent/#
I will receive all retained messages that are located in the testparent/# topic but the actual testparent retained messages will be ignored. This is not compliant with other clients on the interwebs.
I have tried many servers to use, but it's not working. I am always getting the time out. Is there any special requirement to use the server? Or if I missing something on settings? Actually, I have some dynamic form that contains dynamic fields. After posting any of form I want to do a publish action to the mqtt server. It's working on localhost (wamp server) very good. But after uploading it on my Cpanel hosting it's showing me "time out"
$server = $config['mqtt_settings']['mqtt_server'];
$port = $config['mqtt_settings']['mqtt_port'];
$username = $config['mqtt_settings']['mqtt_username'];
$password = $config['mqtt_settings']['mqtt_password'];
$client_id = md5(uniqid(rand(), true));
$topic = $params['topic_name'];
unset($params['topic_name']);
$message = json_encode($params);
$mqtt = new phpMQTT($server, $port, $client_id);
if ($mqtt->connect(true, NULL, $username, $password)) {
$mqtt->publish($topic, $message, 0);
$ret = [
'status' => 'success',
'msg' => "you have successfully published to " . $topic
];
'op_by' => $config['user']->uid
]);
$mqtt->close();
} else {
$ret = [
'status' => 'warning',
'msg' => "Time out"
];
}
使用PHP调用MQTT.PHP,连接不上服务器,最后的结果是time out!
$client_id = "phpMQTT-publisher"; // make sure this is unique for connecting to sever - you could use uniqid()
$server = "xxxxx"; // change if necessary
$port = xxxxx; // change if necessary
$username = "xxxxx"; // set your username
$password = "xxxxx";
$mqtt = new phpMQTT($server, $port, $client_id);
if ($mqtt->connect(true, NULL, $username, $password)) {
$mqtt->publish("bluerhinos/phpMQTT/examples/publishtest", "Hello World! at " . date("r"), 0);
$mqtt->close();
} else {
echo "Time out!\n";
}
When I subscribe to a topic "test" I run from CLI I get the following errrors:
PHP Notice: Undefined variable: i in phpMQTT/phpMQTT.php on line 245
PHP Notice: Uninitialized string offset: 0 in phpMQTT/phpMQTT.php on line 213
PHP Notice: Uninitialized string offset: 1 in phpMQTT/phpMQTT.php on line 213
PHP Notice: Undefined variable: lenid in phpMQTT/phpMQTT.php on line 215
How to subscribers multi topics ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.