PHP code example of hopex / bambulab-sdk
1. Go to this page and download the library: Download hopex/bambulab-sdk library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hopex / bambulab-sdk example snippets
declare(strict_types=1);
use Hopex\BambuLab\BambuClient;
use Hopex\BambuLab\Printer\DTO\PrinterCredentials;
use Hopex\BambuLab\Transport\MqttTransport;
nt(
credentials: $credentials,
transport: new MqttTransport(),
);
try {
$client->connect();
if (!$client->waitUntilReady(timeoutSeconds: 15)) {
throw new RuntimeException(
'Не удалось синхронизировать состояние принтера.',
);
}
$status = $client->state()->status();
echo sprintf(
"Состояние: %s\n",
$status->state?->value ?? 'UNKNOWN',
);
echo sprintf(
"Сопло: %.1f °C\n",
$status->nozzleTemperature ?? 0,
);
echo sprintf(
"Стол: %.1f °C\n",
$status->bedTemperature ?? 0,
);
} finally {
$client->disconnect();
}
$client->connect();
$client->connect(synchronize: false);
$client->tick();
$client->run();
$client->stop();
$client->disconnect();
$state = $client->state();
$status = $state->status();
echo $status->progress();
echo $status->remainingMinutes();
echo $status->currentLayer();
echo $status->totalLayers();
echo $status->bedTemperature();
echo $status->nozzleTemperature();
$raw = $client->state()->raw();
$job = $client->state()->currentJob();
if ($job !== null) {
echo $job->fileName;
echo $job->name;
echo $job->printType;
echo $job->progress;
echo $job->remainingMinutes;
echo $job->currentLayer;
echo $job->totalLayers;
}
$job?->isActive();
$job?->isRunning();
$job?->isPaused();
$job?->isPreparing();
$job?->isFinished();
$job?->isFailed();
use Hopex\BambuLab\Gcode\Enum\GcodeState;
$state = $client->state()->gcodeState();
if ($state === GcodeState::RUNNING) {
echo 'Печать выполняется';
}
$state?->isPrinting();
$state?->isPaused();
$state?->isFinished();
$state?->isFailed();
$state?->isIdle();
$state?->isPreparing();
use Hopex\BambuLab\Gcode\Enum\GcodeState;
$state = $client->waitForState(
GcodeState::RUNNING,
timeoutSeconds: 300,
);
if ($state === null) {
throw new RuntimeException(
'Принтер не начал печать.',
);
}
$state = $client->waitForState(
states: [
GcodeState::PAUSE,
GcodeState::FAILED,
],
timeoutSeconds: 60,
);
use Hopex\BambuLab\Printer\PrinterState;
$reached = $client->waitUntil(
condition: static fn(PrinterState $state): bool =>
($state->progress() ?? 0) >= 50,
timeoutSeconds: 3600,
);
use Hopex\BambuLab\Printer\DTO\PrintJobOptions;
$client->printer()->start(
new PrintJobOptions(
filename: 'model.3mf',
plate: 1,
useAms: false,
amsMapping: [],
bedLeveling: true,
flowCalibration: false,
vibrationCalibration: false,
layerInspection: false,
timelapse: false,
),
);
$client->printer()->pause();
$client->printer()->resume();
$client->printer()->stop();
$client->printer()->requestFullState();
$client->gcode()->send('G28');
$client->gcode()->send(
"G28\n"
. "G1 Z10 F600\n",
);
$client->light()->turnOn();
$client->light()->turnOff();
$light = $client->state()->lightState();
echo $light?->value ?? 'UNKNOWN';
$client->temperature()->setNozzle(220);
$client->temperature()->setBed(60);
$status = $client->state()->status();
echo $status->nozzleTemperature;
echo $status->nozzleTargetTemperature;
echo $status->bedTemperature;
echo $status->bedTargetTemperature;
echo $status->chamberTemperature;
echo $client
->temperature()
->maximumNozzleTemperature();
echo $client
->temperature()
->maximumBedTemperature();
$client->fans()->setPart(128);
$client->fans()->setAuxiliary(80);
$client->fans()->setChamber(100);
$client->fans()->setPartPercent(50);
$client->fans()->setAuxiliaryPercent(30);
$client->fans()->setChamberPercent(40);
$client->fans()->setPart(0);
$capabilities = $client
->device()
->capabilities();
if ($capabilities->hasAuxiliaryFan() === true) {
$client->fans()->setAuxiliaryPercent(50);
}
foreach ($client->files()->entries() as $entry) {
echo $entry->path;
echo $entry->size;
echo $entry->modifiedAt?->format('Y-m-d H:i:s');
}
foreach ($client->files()->files() as $file) {
echo $file->name;
}
foreach ($client->files()->directories() as $directory) {
echo $directory->name;
}
foreach ($client->files()->models() as $model) {
echo $model->name;
}
$gcodeFiles = $client
->files()
->byExtension('gcode');
$models = $client
->files()
->byExtension('.3mf');
$file = $client
->files()
->find('model.3mf');
if ($file !== null) {
echo $file->size;
}
$exists = $client
->files()
->exists('model.3mf');
use Hopex\BambuLab\Files\DTO\FileEntry;
$largeModels = $client->files()->filter(
static fn(FileEntry $entry): bool =>
$entry->isFile()
&& $entry->hasExtension('3mf')
&& ($entry->size ?? 0) >= 500_000,
);
$client->files()->upload(
localPath: '/path/to/model.3mf',
remotePath: 'model.3mf',
);
$client->files()->download(
remotePath: 'model.3mf',
localPath: '/path/to/downloaded-model.3mf',
);
$client
->files()
->delete('model.3mf');
$frame = $client
->camera()
->snapshot();
$frame->saveAs(
'/path/to/snapshot.jpg',
);
echo $frame->mimeType();
echo $frame->base64();
echo $frame->dataUri();
echo $frame->bytes();
echo $frame->size();
echo $frame->isEmpty();
$device = $client->device();
echo $device->host();
echo $device->serialNumber();
echo $device->wifiSignal();
echo $device->wifiSignalDbm();
echo $device->nozzleType();
echo $device->nozzleDiameter();
echo $device->lifecycle();
$device->hasSdCard();
$device->hasAms();
$device->cameraAvailable();
$device->cameraRecordingEnabled();
$device->timelapseEnabled();
$capabilities = $client
->device()
->capabilities();
var_dump([
'resolved' => $capabilities->isResolved(),
'camera' => $capabilities->hasCamera(),
'ams' => $capabilities->hasAms(),
'sd_card' => $capabilities->hasSdCard(),
'auxiliary_fan' => $capabilities->hasAuxiliaryFan(),
'chamber_fan' => $capabilities->hasChamberFan(),
'maximum_bed_temperature' =>
$capabilities->maximumBedTemperature(),
'maximum_nozzle_temperature' =>
$capabilities->maximumNozzleTemperature(),
]);
$client->firmware()->refresh();
echo $client
->firmware()
->current();
foreach ($client->firmware()->modules() as $module) {
echo $module->name;
echo $module->softwareVersion;
echo $module->hardwareVersion;
echo $module->serialNumber;
echo $module->isOta();
}
$upgrade = $client
->firmware()
->upgradeState();
if ($upgrade !== null) {
echo $upgrade->status;
echo $upgrade->progress;
echo $upgrade->errorCode;
}
foreach ($client->hms()->messages() as $message) {
echo $message->identifier();
echo $message->level->value;
echo $message->description;
}
$warnings = $client
->hms()
->warnings();
$errors = $client
->hms()
->errors();
$client->hms()->hasMessages();
$client->hms()->hasWarnings();
$client->hms()->hasErrors();
$client->hms()->hasUnknown();
use Hopex\BambuLab\Events\PrinterStateSnapshot;
$printStartedSubscription = $client->events()->onPrintStarted(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo 'Печать запущена';
},
);
$progressChangedSubscription = $client->events()->onProgressChanged(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo printf(
"%d%%\n",
$current->currentJob?->progress ?? 0,
);
},
);
$client->events()->onPrintPaused(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo 'Печать приостановлена';
},
);
$client->events()->onPrintResumed(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo 'Печать продолжена';
},
);
$client->events()->onPrintFinished(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo 'Печать завершена';
},
);
$client->events()->onPrintCancelled(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo 'Печать отменена';
},
);
$client->events()->onJobChanged(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo sprintf(
'%s -> %s',
$previous->currentJob?->fileName ?? 'NONE',
$current->currentJob?->fileName ?? 'NONE',
);
},
);
$client->events()->onProgressChanged(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo $current->currentJob?->progress;
},
);
$client->events()->onLayerChanged(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo sprintf(
'%d/%d',
$current->currentJob?->currentLayer ?? 0,
$current->currentJob?->totalLayers ?? 0,
);
},
);
$client->events()->onRemainingTimeChanged(
static function (
PrinterStateSnapshot $current,
PrinterStateSnapshot $previous,
): void {
echo $current->currentJob?->remainingMinutes;
},
);
$client->events()->onTemperatureChanged(...);
$client->events()->onLightChanged(...);
$client->events()->onHmsChanged(...);
$subscription->cancel();
$client->events()->clear();
use Hopex\BambuLab\Transport\ReconnectPolicy;
$client->connect();
$client->runWithReconnect(
new ReconnectPolicy(
attempts: 10,
delayMilliseconds: 3_000,
subscriptionWarmupMilliseconds: 1_000,
synchronizeAfterReconnect: true,
clearStateBeforeReconnect: true,
),
);
$client->tickWithReconnect(
new ReconnectPolicy(
attempts: 5,
delayMilliseconds: 2_000,
),
);
$client->reconnect();
use Hopex\BambuLab\Transport\Contracts\TransportContract;
use Hopex\BambuLab\Files\Contracts\FileTransferContract;
use Hopex\BambuLab\Camera\Contracts\CameraTransportContract;
Hopex\BambuLab\Exceptions\BambuException
use Hopex\BambuLab\Exceptions\BambuException;
try {
$client->connect();
} catch (BambuException $exception) {
echo $exception->getMessage();
}
$credentials = new PrinterCredentials(
host: getenv('BAMBU_HOST'),
accessCode: getenv('BAMBU_ACCESS_CODE'),
serialNumber: getenv('BAMBU_SERIAL_NUMBER'),
);