使用 PHP 在 Laravel 上的 mqtt

2022-01-05 00:00:00 raspberry-pi mqtt mosquitto php laravel

我在我的 raspberry 和我的 Ubuntu 上使用 MQTT.我使用终端作为开始订阅者和发布者,它运行良好.但是现在我想创建一个具有此功能的网站(使用 laravel).我用谷歌搜索了它,但我没有发现任何有趣的东西.有可能吗?怎么做?

I'm using the MQTT on my raspberry and on my Ubuntu. I use terminal for start subscriber and publisher and it works so good. But now I want to create a website (using laravel) with this features. I googled it, but I don't find anything interesting. Is it possible to do and how?

推荐答案

与 HTTP 不同,MQTT 通常用于在应用程序进程和 MQTT 服务器之间打开长时间运行的连接.

Unlike with HTTP, MQTT is typically used by opening a long-running connection between an application process and a MQTT server.

虽然完全有可能打开一个连接,发布一条消息,然后再次关闭套接字,但它并不能真正用于订阅消息流.

While it is perfectly possible to open a connection, publish a single message and then close the socket again, it doesn't really work for subscribing to a stream of messages.

PHP 的典型操作模式是启动一个进程,等待 HTTP 连接,处理请求,然后启动一个新进程.这与具有长时间运行进程的典型 MQTT 模式不太匹配.

PHP's typically mode of operation is to start a process, wait for an HTTP connection, handle the request and then start a new process. This doesn't fit well with the typical MQTT mode of having a long-running process.

随着人们使用 PHP 内置 HTTP 服务器,这种情况开始发生变化.我不确定 Laravel 是否提供了一种机制来在处理请求之间保持变量/TCP 连接.

This had started to change with people using the PHP built-in HTTP server. I am not sure if Laravel provides a mechanism to keep variables/TCP connections in place between handling requests.

或者,可以在长时间运行的 CLI PHP 脚本中订阅 MQTT 主题并将其保留在本地(例如数据库、KV 存储、memcache、redis),然后提供来自数据存储的数据.

Alternatively it is possible to subscribe to a MQTT topic in a long-running CLI PHP script and persisting it locally (for example a database, KV store, memcache, redis) and then serving the data from the datastore.

这在很大程度上取决于您要实现的目标.

It depends a lot on what you are trying to achieve.

相关文章