MqttPublisher.php 925 B

12345678910111213141516171819202122232425262728293031
  1. <?php
  2. namespace app\service;
  3. use Webman\Channel\Client as ChannelClient;
  4. final class MqttPublisher
  5. {
  6. public static function publish(string $topic, string $payload, int $qos = 1, bool $retain = false): string
  7. {
  8. if (!config('mqtt.enabled')) {
  9. throw new \RuntimeException('MQTT is disabled.');
  10. }
  11. MqttTopic::assertPublishable($topic);
  12. if (strlen($payload) > config('mqtt.max_payload_bytes', 1048576)) {
  13. throw new \InvalidArgumentException('MQTT payload exceeds the configured size limit.');
  14. }
  15. if (!in_array($qos, [0, 1, 2], true)) {
  16. throw new \InvalidArgumentException('MQTT QoS must be 0, 1, or 2.');
  17. }
  18. $traceId = bin2hex(random_bytes(8));
  19. ChannelClient::connect();
  20. ChannelClient::publish('mqtt.publish', compact('topic', 'payload', 'qos', 'retain', 'traceId'));
  21. return $traceId;
  22. }
  23. }