54 lines
2.2 KiB
PHP
54 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Printer;
|
|
use App\Models\PrinterTelemetry;
|
|
use Illuminate\Console\Attributes\Description;
|
|
use Illuminate\Console\Attributes\Signature;
|
|
use Illuminate\Console\Command;
|
|
use PhpMqtt\Client\ConnectionSettings;
|
|
use PhpMqtt\Client\MqttClient;
|
|
use Throwable;
|
|
|
|
#[Signature('printers:collect')]
|
|
#[Description('Collect a short telemetry sample from each registered Bambu printer')]
|
|
class CollectPrinterTelemetry extends Command
|
|
{
|
|
public function handle(): int
|
|
{
|
|
foreach (Printer::cursor() as $printer) {
|
|
$client = new MqttClient($printer->printerIp, config('services.mqtt.port'), 'hicklab3d_'.bin2hex(random_bytes(6)));
|
|
try {
|
|
$settings = (new ConnectionSettings)
|
|
->setUsername(config('services.mqtt.username'))
|
|
->setPassword($printer->mqttPassword)
|
|
->setConnectTimeout(5)
|
|
->setUseTls(true)
|
|
->setTlsVerifyPeer(config('services.mqtt.verify_tls'))
|
|
->setTlsVerifyPeerName(config('services.mqtt.verify_tls'));
|
|
$client->connect($settings, true);
|
|
$received = false;
|
|
$client->subscribe('device/'.$printer->serialNumber.'/report', function (string $topic, string $message) use ($printer, &$received): void {
|
|
$telemetry = json_decode($message, true);
|
|
if (is_array($telemetry)) {
|
|
PrinterTelemetry::create(['printerId' => $printer->id, 'telemetry' => $telemetry]);
|
|
$received = true;
|
|
}
|
|
});
|
|
$started = microtime(true);
|
|
while (! $received && microtime(true) - $started < 15) {
|
|
$client->loopOnce($started, true);
|
|
}
|
|
$client->disconnect();
|
|
$this->line($printer->printerName.($received ? ': received telemetry' : ': no telemetry received'));
|
|
} catch (Throwable $exception) {
|
|
report($exception);
|
|
$this->warn($printer->printerName.': connection failed');
|
|
}
|
|
}
|
|
|
|
return self::SUCCESS;
|
|
}
|
|
}
|