| 12345678910111213141516171819202122232425262728293031 |
- <?php
- namespace app\service;
- use Webman\Channel\Client as ChannelClient;
- final class MqttPublisher
- {
- public static function publish(string $topic, string $payload, int $qos = 1, bool $retain = false): string
- {
- if (!config('mqtt.enabled')) {
- throw new \RuntimeException('MQTT is disabled.');
- }
- MqttTopic::assertPublishable($topic);
- if (strlen($payload) > config('mqtt.max_payload_bytes', 1048576)) {
- throw new \InvalidArgumentException('MQTT payload exceeds the configured size limit.');
- }
- if (!in_array($qos, [0, 1, 2], true)) {
- throw new \InvalidArgumentException('MQTT QoS must be 0, 1, or 2.');
- }
- $traceId = bin2hex(random_bytes(8));
- ChannelClient::connect();
- ChannelClient::publish('mqtt.publish', compact('topic', 'payload', 'qos', 'retain', 'traceId'));
- return $traceId;
- }
- }
|