Skip to content

Overview

Machines

InvenTree has a builtin machine registry. There are different machine types available where each type can have different drivers. Drivers and even custom machine types can be provided by plugins.

Requires Redis

If the machines features is used in production setup using workers, a shared redis cache is required to function properly.

Registry

The machine registry is the main component which gets initialized on server start and manages all configured machines.

Initialization process

The machine registry initialization process can be divided into three stages:

  • Stage 1: Discover machine types: by looking for classes that inherit the BaseMachineType class
  • Stage 2: Discover drivers: by looking for classes that inherit the BaseDriver class (and are not referenced as base driver for any discovered machine type)
  • Stage 3: Machine loading:
    1. For each MachineConfig in database instantiate the MachineType class (drivers get instantiated here as needed and passed to the machine class. But only one instance of the driver class is maintained along the registry)
    2. The driver.init_driver function is called for each used driver
    3. The machine.initialize function is called for each machine, which calls the driver.init_machine function for each machine, then the machine.initialized state is set to true

Production setup (with a worker)

If a worker is connected, there exist multiple instances of the machine registry (one in each worker thread and one in the main thread) due to the nature of how python handles state in different processes. Therefore the machine instances and drivers are instantiated multiple times (The __init__ method is called multiple times). But the init functions and update hooks (e.g. init_machine) are only called once from the main process.

The registry, driver and machine state (e.g. machine status codes, errors, ...) is stored in the cache. Therefore a shared redis cache is needed. (The local in-memory cache which is used by default is not capable to cache across multiple processes)

Machine types

Each machine type can provide a different type of connection functionality between inventree and a physical machine. These machine types are already built into InvenTree.

Built-in types

Name Description
Label printer Directly print labels for various items.

Example machine type

If you want to create your own machine type, please also take a look at the already existing machine types in machines/machine_types/*.py. The following example creates a machine type called abc.

from django.utils.translation import gettext_lazy as _
from plugin.machine import BaseDriver, BaseMachineType, MachineStatus

class ABCBaseDriver(BaseDriver):
    """Base xyz driver."""

    machine_type = 'abc'

    def my_custom_required_method(self):
        """This function must be overridden."""
        raise NotImplementedError('The `my_custom_required_method` function must be overridden!')

    def my_custom_method(self):
        """This function can be overridden."""
        raise NotImplementedError('The `my_custom_method` function can be overridden!')

    required_overrides = [my_custom_required_method]

class ABCMachine(BaseMachineType):
    SLUG = 'abc'
    NAME = _('ABC')
    DESCRIPTION = _('This is an awesome machine type for ABC.')

    base_driver = ABCBaseDriver

    class ABCStatus(MachineStatus):
        CONNECTED = 100, _('Connected'), 'success'
        STANDBY = 101, _('Standby'), 'success'
        PRINTING = 110, _('Printing'), 'primary'

    MACHINE_STATUS = ABCStatus
    default_machine_status = ABCStatus.DISCONNECTED

Machine Type API

The machine type class gets instantiated for each machine on server startup and the reference is stored in the machine registry. (Therefore machine.NAME is the machine type name and machine.name links to the machine instances user defined name)

Base class for machine types.

Attributes:

Name Type Description
SLUG str

Slug string for identifying the machine type in format /[a-z-]+/ (required)

NAME str

User friendly name for displaying (required)

DESCRIPTION str

Description of what this machine type can do (required)

base_driver type[BaseDriver]

Reference to the base driver for this machine type

MACHINE_SETTINGS dict[str, SettingsKeyType]

Machine type specific settings dict (optional)

MACHINE_STATUS type[MachineStatus]

Set of status codes this machine type can have

default_machine_status MachineStatus

Default machine status with which this machine gets initialized

Source code in src/backend/InvenTree/machine/machine_type.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
class BaseMachineType(
    ClassValidationMixin,
    ClassProviderMixin,
    get_shared_class_instance_state_mixin(lambda x: f'machine:machine:{x.pk}'),
):
    """Base class for machine types.

    Attributes:
        SLUG: Slug string for identifying the machine type in format /[a-z-]+/ (required)
        NAME: User friendly name for displaying (required)
        DESCRIPTION: Description of what this machine type can do (required)

        base_driver: Reference to the base driver for this machine type

        MACHINE_SETTINGS: Machine type specific settings dict (optional)

        MACHINE_STATUS: Set of status codes this machine type can have
        default_machine_status: Default machine status with which this machine gets initialized
    """

    SLUG: str
    NAME: str
    DESCRIPTION: str

    base_driver: type[BaseDriver]

    MACHINE_SETTINGS: dict[str, SettingsKeyType]

    MACHINE_STATUS: type[MachineStatus]
    default_machine_status: MachineStatus

    # used by the ClassValidationMixin
    required_attributes = [
        'SLUG',
        'NAME',
        'DESCRIPTION',
        'base_driver',
        'MACHINE_STATUS',
        'default_machine_status',
    ]

    def __init__(self, machine_config: MachineConfig) -> None:
        """Base machine type __init__ function."""
        from machine import registry
        from machine.models import MachineSetting

        self.pk = machine_config.pk
        self.driver = registry.get_driver_instance(machine_config.driver)

        if not self.driver:
            self.handle_error(f"Driver '{machine_config.driver}' not found")
        if self.driver and not isinstance(self.driver, self.base_driver):
            self.handle_error(
                f"'{self.driver.NAME}' is incompatible with machine type '{self.NAME}'"
            )

        self.machine_settings: dict[str, SettingsKeyType] = getattr(
            self, 'MACHINE_SETTINGS', {}
        )
        self.driver_settings: dict[str, SettingsKeyType] = getattr(
            self.driver, 'MACHINE_SETTINGS', {}
        )

        self.setting_types: list[
            tuple[dict[str, SettingsKeyType], MachineSetting.ConfigType]
        ] = [
            (self.machine_settings, MachineSetting.ConfigType.MACHINE),
            (self.driver_settings, MachineSetting.ConfigType.DRIVER),
        ]

    def __str__(self):
        """String representation of a machine."""
        return f'{self.name}'

    def __repr__(self):
        """Python representation of a machine."""
        return f'<{self.__class__.__name__}: {self.name}>'

    # --- properties
    @property
    def machine_config(self):
        """Machine_config property which is a reference to the database entry."""
        # always fetch the machine_config if needed to ensure we get the newest reference
        from .models import MachineConfig

        return MachineConfig.objects.get(pk=self.pk)

    @property
    def name(self):
        """The machines name."""
        return self.machine_config.name

    @property
    def active(self):
        """The machines active status."""
        return self.machine_config.active

    # --- hook functions
    def initialize(self):
        """Machine initialization function, gets called after all machines are loaded."""
        if self.driver is None:
            return

        # check if all required settings are defined before continue with init process
        settings_valid, missing_settings = self.check_settings()
        if not settings_valid:
            error_parts = []
            for config_type, missing in missing_settings.items():
                if len(missing) > 0:
                    error_parts.append(
                        f'{config_type.name} settings: ' + ', '.join(missing)
                    )
            self.handle_error(f"Missing {' and '.join(error_parts)}")
            return

        try:
            self.driver.init_machine(self)
            self.initialized = True
        except Exception as e:
            self.handle_error(e)

    def update(self, old_state: dict[str, Any]):
        """Machine update function, gets called if the machine itself changes or their settings.

        Arguments:
            old_state: Dict holding the old machine state before update
        """
        if self.driver is None:
            return

        try:
            self.driver.update_machine(old_state, self)

            # check if the active state has changed and initialize the machine if necessary
            if old_state['active'] != self.active:
                if self.initialized is False and self.active is True:
                    self.initialize()
                elif self.initialized is True and self.active is False:
                    self.initialized = False
        except Exception as e:
            self.handle_error(e)

    def restart(self):
        """Machine restart function, can be used to manually restart the machine from the admin ui.

        This will first reset the machines state (errors, status, status_text) and then call the drivers restart function.
        """
        if self.driver is None:
            return

        try:
            # reset the machine state
            self.restart_required = False
            self.reset_errors()
            self.set_status(self.default_machine_status)
            self.set_status_text('')

            # call the driver restart function
            self.driver.restart_machine(self)
        except Exception as e:
            self.handle_error(e)

    # --- helper functions
    def handle_error(self, error: Union[Exception, str]):
        """Helper function for capturing errors with the machine.

        Arguments:
            error: Exception or string
        """
        self.set_shared_state('errors', self.errors + [error])

    def reset_errors(self):
        """Helper function for resetting the error list for a machine."""
        self.set_shared_state('errors', [])

    def get_setting(
        self, key: str, config_type_str: Literal['M', 'D'], cache: bool = False
    ):
        """Return the 'value' of the setting associated with this machine.

        Arguments:
            key: The 'name' of the setting value to be retrieved
            config_type_str: Either "M" (machine scoped settings) or "D" (driver scoped settings)
            cache: Whether to use RAM cached value (default = False)
        """
        from machine.models import MachineSetting

        config_type = MachineSetting.get_config_type(config_type_str)
        return MachineSetting.get_setting(
            key,
            machine_config=self.machine_config,
            config_type=config_type,
            cache=cache,
        )

    def set_setting(self, key: str, config_type_str: Literal['M', 'D'], value: Any):
        """Set plugin setting value by key.

        Arguments:
            key: The 'name' of the setting to set
            config_type_str: Either "M" (machine scoped settings) or "D" (driver scoped settings)
            value: The 'value' of the setting
        """
        from machine.models import MachineSetting

        config_type = MachineSetting.get_config_type(config_type_str)
        MachineSetting.set_setting(
            key,
            value,
            None,
            machine_config=self.machine_config,
            config_type=config_type,
        )

    def check_settings(self):
        """Check if all required settings for this machine are defined.

        Returns:
            is_valid: Are all required settings defined
            missing_settings: dict[ConfigType, list[str]] of all settings that are missing (empty if is_valid is 'True')
        """
        from machine.models import MachineSetting

        missing_settings: dict[MachineSetting.ConfigType, list[str]] = {}
        for settings, config_type in self.setting_types:
            _nbr, missing = MachineSetting.check_all_settings(
                settings_definition=settings,
                machine_config=self.machine_config,
                config_type=config_type,
            )
            missing_settings[config_type] = missing

        return all(
            len(missing) == 0 for missing in missing_settings.values()
        ), missing_settings

    def set_status(self, status: MachineStatus):
        """Set the machine status code. There are predefined ones for each MachineType.

        Import the MachineType to access it's `MACHINE_STATUS` enum.

        Arguments:
            status: The new MachineStatus code to set
        """
        self.set_shared_state('status', status.value)

    def set_status_text(self, status_text: str):
        """Set the machine status text. It can be any arbitrary text.

        Arguments:
            status_text: The new status text to set
        """
        self.set_shared_state('status_text', status_text)

    # --- state getters/setters
    @property
    def initialized(self) -> bool:
        """Initialized state of the machine."""
        return self.get_shared_state('initialized', False)

    @initialized.setter
    def initialized(self, value: bool):
        self.set_shared_state('initialized', value)

    @property
    def restart_required(self) -> bool:
        """Restart required state of the machine."""
        return self.get_shared_state('restart_required', False)

    @restart_required.setter
    def restart_required(self, value: bool):
        self.set_shared_state('restart_required', value)

    @property
    def errors(self) -> list[Union[str, Exception]]:
        """List of machine errors."""
        return self.get_shared_state('errors', [])

    @property
    def status(self) -> MachineStatus:
        """Machine status code."""
        status_code = self.get_shared_state('status', self.default_machine_status.value)
        return self.MACHINE_STATUS(status_code)

    @property
    def status_text(self) -> str:
        """Machine status text."""
        return self.get_shared_state('status_text', '')
machine_config property

Machine_config property which is a reference to the database entry.

name property

The machines name.

active property

The machines active status.

initialize()

Machine initialization function, gets called after all machines are loaded.

Source code in src/backend/InvenTree/machine/machine_type.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def initialize(self):
    """Machine initialization function, gets called after all machines are loaded."""
    if self.driver is None:
        return

    # check if all required settings are defined before continue with init process
    settings_valid, missing_settings = self.check_settings()
    if not settings_valid:
        error_parts = []
        for config_type, missing in missing_settings.items():
            if len(missing) > 0:
                error_parts.append(
                    f'{config_type.name} settings: ' + ', '.join(missing)
                )
        self.handle_error(f"Missing {' and '.join(error_parts)}")
        return

    try:
        self.driver.init_machine(self)
        self.initialized = True
    except Exception as e:
        self.handle_error(e)
update(old_state)

Machine update function, gets called if the machine itself changes or their settings.

Parameters:

Name Type Description Default
old_state dict[str, Any]

Dict holding the old machine state before update

required
Source code in src/backend/InvenTree/machine/machine_type.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def update(self, old_state: dict[str, Any]):
    """Machine update function, gets called if the machine itself changes or their settings.

    Arguments:
        old_state: Dict holding the old machine state before update
    """
    if self.driver is None:
        return

    try:
        self.driver.update_machine(old_state, self)

        # check if the active state has changed and initialize the machine if necessary
        if old_state['active'] != self.active:
            if self.initialized is False and self.active is True:
                self.initialize()
            elif self.initialized is True and self.active is False:
                self.initialized = False
    except Exception as e:
        self.handle_error(e)
restart()

Machine restart function, can be used to manually restart the machine from the admin ui.

This will first reset the machines state (errors, status, status_text) and then call the drivers restart function.

Source code in src/backend/InvenTree/machine/machine_type.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def restart(self):
    """Machine restart function, can be used to manually restart the machine from the admin ui.

    This will first reset the machines state (errors, status, status_text) and then call the drivers restart function.
    """
    if self.driver is None:
        return

    try:
        # reset the machine state
        self.restart_required = False
        self.reset_errors()
        self.set_status(self.default_machine_status)
        self.set_status_text('')

        # call the driver restart function
        self.driver.restart_machine(self)
    except Exception as e:
        self.handle_error(e)
handle_error(error)

Helper function for capturing errors with the machine.

Parameters:

Name Type Description Default
error Union[Exception, str]

Exception or string

required
Source code in src/backend/InvenTree/machine/machine_type.py
314
315
316
317
318
319
320
def handle_error(self, error: Union[Exception, str]):
    """Helper function for capturing errors with the machine.

    Arguments:
        error: Exception or string
    """
    self.set_shared_state('errors', self.errors + [error])
get_setting(key, config_type_str, cache=False)

Return the 'value' of the setting associated with this machine.

Parameters:

Name Type Description Default
key str

The 'name' of the setting value to be retrieved

required
config_type_str Literal['M', 'D']

Either "M" (machine scoped settings) or "D" (driver scoped settings)

required
cache bool

Whether to use RAM cached value (default = False)

False
Source code in src/backend/InvenTree/machine/machine_type.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def get_setting(
    self, key: str, config_type_str: Literal['M', 'D'], cache: bool = False
):
    """Return the 'value' of the setting associated with this machine.

    Arguments:
        key: The 'name' of the setting value to be retrieved
        config_type_str: Either "M" (machine scoped settings) or "D" (driver scoped settings)
        cache: Whether to use RAM cached value (default = False)
    """
    from machine.models import MachineSetting

    config_type = MachineSetting.get_config_type(config_type_str)
    return MachineSetting.get_setting(
        key,
        machine_config=self.machine_config,
        config_type=config_type,
        cache=cache,
    )
set_setting(key, config_type_str, value)

Set plugin setting value by key.

Parameters:

Name Type Description Default
key str

The 'name' of the setting to set

required
config_type_str Literal['M', 'D']

Either "M" (machine scoped settings) or "D" (driver scoped settings)

required
value Any

The 'value' of the setting

required
Source code in src/backend/InvenTree/machine/machine_type.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def set_setting(self, key: str, config_type_str: Literal['M', 'D'], value: Any):
    """Set plugin setting value by key.

    Arguments:
        key: The 'name' of the setting to set
        config_type_str: Either "M" (machine scoped settings) or "D" (driver scoped settings)
        value: The 'value' of the setting
    """
    from machine.models import MachineSetting

    config_type = MachineSetting.get_config_type(config_type_str)
    MachineSetting.set_setting(
        key,
        value,
        None,
        machine_config=self.machine_config,
        config_type=config_type,
    )
set_status(status)

Set the machine status code. There are predefined ones for each MachineType.

Import the MachineType to access it's MACHINE_STATUS enum.

Parameters:

Name Type Description Default
status MachineStatus

The new MachineStatus code to set

required
Source code in src/backend/InvenTree/machine/machine_type.py
387
388
389
390
391
392
393
394
395
def set_status(self, status: MachineStatus):
    """Set the machine status code. There are predefined ones for each MachineType.

    Import the MachineType to access it's `MACHINE_STATUS` enum.

    Arguments:
        status: The new MachineStatus code to set
    """
    self.set_shared_state('status', status.value)
set_status_text(status_text)

Set the machine status text. It can be any arbitrary text.

Parameters:

Name Type Description Default
status_text str

The new status text to set

required
Source code in src/backend/InvenTree/machine/machine_type.py
397
398
399
400
401
402
403
def set_status_text(self, status_text: str):
    """Set the machine status text. It can be any arbitrary text.

    Arguments:
        status_text: The new status text to set
    """
    self.set_shared_state('status_text', status_text)

Drivers

Drivers provide the connection layer between physical machines and inventree. There can be multiple drivers defined for the same machine type. Drivers are provided by plugins that are enabled and extend the corresponding base driver for the particular machine type. Each machine type already provides a base driver that needs to be inherited.

Example driver

A basic driver only needs to specify the basic attributes like SLUG, NAME, DESCRIPTION. The others are given by the used base driver, so take a look at Machine types. The following example will create an driver called abc for the xyz machine type. The class will be discovered if it is provided by an installed & activated plugin just like this:

from plugin import InvenTreePlugin
from plugin.machine.machine_types import ABCBaseDriver

class MyXyzAbcDriverPlugin(InvenTreePlugin):
    NAME = "XyzAbcDriver"
    SLUG = "xyz-driver"
    TITLE = "Xyz Abc Driver"
    # ...

class XYZDriver(ABCBaseDriver):
    SLUG = 'my-xyz-driver'
    NAME = 'My XYZ driver'
    DESCRIPTION = 'This is an awesome XYZ driver for a ABC machine'

Driver API

Base class for all machine drivers.

Attributes:

Name Type Description
SLUG str

Slug string for identifying the driver in format /[a-z-]+/ (required)

NAME str

User friendly name for displaying (required)

DESCRIPTION str

Description of what this driver does (required)

MACHINE_SETTINGS dict[str, SettingsKeyType]

Driver specific settings dict

Source code in src/backend/InvenTree/machine/machine_type.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class BaseDriver(
    ClassValidationMixin,
    ClassProviderMixin,
    get_shared_class_instance_state_mixin(lambda x: f'machine:driver:{x.SLUG}'),
):
    """Base class for all machine drivers.

    Attributes:
        SLUG: Slug string for identifying the driver in format /[a-z-]+/ (required)
        NAME: User friendly name for displaying (required)
        DESCRIPTION: Description of what this driver does (required)

        MACHINE_SETTINGS: Driver specific settings dict
    """

    SLUG: str
    NAME: str
    DESCRIPTION: str

    MACHINE_SETTINGS: dict[str, SettingsKeyType]

    machine_type: str

    required_attributes = ['SLUG', 'NAME', 'DESCRIPTION', 'machine_type']

    def __init__(self) -> None:
        """Base driver __init__ method."""
        super().__init__()

    def init_driver(self):
        """This method gets called after all machines are created and can be used to initialize the driver.

        After the driver is initialized, the self.init_machine function is
        called for each machine associated with that driver.
        """

    def init_machine(self, machine: 'BaseMachineType'):
        """This method gets called for each active machine using that driver while initialization.

        If this function raises an Exception, it gets added to the machine.errors
        list and the machine does not initialize successfully.

        Arguments:
            machine: Machine instance
        """

    def update_machine(
        self, old_machine_state: dict[str, Any], machine: 'BaseMachineType'
    ):
        """This method gets called for each update of a machine.

        Note:
            machine.restart_required can be set to True here if the machine needs a manual restart to apply the changes

        Arguments:
            old_machine_state: Dict holding the old machine state before update
            machine: Machine instance with the new state
        """

    def restart_machine(self, machine: 'BaseMachineType'):
        """This method gets called on manual machine restart e.g. by using the restart machine action in the Admin Center.

        Note:
            `machine.restart_required` gets set to False again before this function is called

        Arguments:
            machine: Machine instance
        """

    def get_machines(self, **kwargs):
        """Return all machines using this driver (By default only initialized machines).

        Keyword Arguments:
            name (str): Machine name
            machine_type (BaseMachineType): Machine type definition (class)
            initialized (bool | None): use None to get all machines (default: True)
            active (bool): machine needs to be active
            base_driver (BaseDriver): base driver (class)
        """
        from machine import registry

        kwargs.pop('driver', None)

        return registry.get_machines(driver=self, **kwargs)

    def handle_error(self, error: Union[Exception, str]):
        """Handle driver error.

        Arguments:
            error: Exception or string
        """
        self.set_shared_state('errors', self.errors + [error])

    # --- state getters/setters
    @property
    def errors(self) -> list[Union[str, Exception]]:
        """List of driver errors."""
        return self.get_shared_state('errors', [])
init_driver()

This method gets called after all machines are created and can be used to initialize the driver.

After the driver is initialized, the self.init_machine function is called for each machine associated with that driver.

Source code in src/backend/InvenTree/machine/machine_type.py
80
81
82
83
84
85
def init_driver(self):
    """This method gets called after all machines are created and can be used to initialize the driver.

    After the driver is initialized, the self.init_machine function is
    called for each machine associated with that driver.
    """
init_machine(machine)

This method gets called for each active machine using that driver while initialization.

If this function raises an Exception, it gets added to the machine.errors list and the machine does not initialize successfully.

Parameters:

Name Type Description Default
machine BaseMachineType

Machine instance

required
Source code in src/backend/InvenTree/machine/machine_type.py
87
88
89
90
91
92
93
94
95
def init_machine(self, machine: 'BaseMachineType'):
    """This method gets called for each active machine using that driver while initialization.

    If this function raises an Exception, it gets added to the machine.errors
    list and the machine does not initialize successfully.

    Arguments:
        machine: Machine instance
    """
update_machine(old_machine_state, machine)

This method gets called for each update of a machine.

Note

machine.restart_required can be set to True here if the machine needs a manual restart to apply the changes

Parameters:

Name Type Description Default
old_machine_state dict[str, Any]

Dict holding the old machine state before update

required
machine BaseMachineType

Machine instance with the new state

required
Source code in src/backend/InvenTree/machine/machine_type.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
def update_machine(
    self, old_machine_state: dict[str, Any], machine: 'BaseMachineType'
):
    """This method gets called for each update of a machine.

    Note:
        machine.restart_required can be set to True here if the machine needs a manual restart to apply the changes

    Arguments:
        old_machine_state: Dict holding the old machine state before update
        machine: Machine instance with the new state
    """
restart_machine(machine)

This method gets called on manual machine restart e.g. by using the restart machine action in the Admin Center.

Note

machine.restart_required gets set to False again before this function is called

Parameters:

Name Type Description Default
machine BaseMachineType

Machine instance

required
Source code in src/backend/InvenTree/machine/machine_type.py
110
111
112
113
114
115
116
117
118
def restart_machine(self, machine: 'BaseMachineType'):
    """This method gets called on manual machine restart e.g. by using the restart machine action in the Admin Center.

    Note:
        `machine.restart_required` gets set to False again before this function is called

    Arguments:
        machine: Machine instance
    """
get_machines(**kwargs)

Return all machines using this driver (By default only initialized machines).

Other Parameters:

Name Type Description
name str

Machine name

machine_type BaseMachineType

Machine type definition (class)

initialized bool | None

use None to get all machines (default: True)

active bool

machine needs to be active

base_driver BaseDriver

base driver (class)

Source code in src/backend/InvenTree/machine/machine_type.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def get_machines(self, **kwargs):
    """Return all machines using this driver (By default only initialized machines).

    Keyword Arguments:
        name (str): Machine name
        machine_type (BaseMachineType): Machine type definition (class)
        initialized (bool | None): use None to get all machines (default: True)
        active (bool): machine needs to be active
        base_driver (BaseDriver): base driver (class)
    """
    from machine import registry

    kwargs.pop('driver', None)

    return registry.get_machines(driver=self, **kwargs)
handle_error(error)

Handle driver error.

Parameters:

Name Type Description Default
error Union[Exception, str]

Exception or string

required
Source code in src/backend/InvenTree/machine/machine_type.py
136
137
138
139
140
141
142
def handle_error(self, error: Union[Exception, str]):
    """Handle driver error.

    Arguments:
        error: Exception or string
    """
    self.set_shared_state('errors', self.errors + [error])

Settings

Each machine can have different settings configured. There are machine settings that are specific to that machine type and driver settings that are specific to the driver, but both can be specified individually for each machine. Define them by adding a MACHINE_SETTINGS dictionary attribute to either the driver or the machine type. The format follows the same pattern as the SETTINGS for normal plugins documented on the SettingsMixin

class MyXYZDriver(ABCBaseDriver):
    MACHINE_SETTINGS = {
        'SERVER': {
            'name': _('Server'),
            'description': _('IP/Hostname to connect to the cups server'),
            'default': 'localhost',
            'required': True,
        }
    }

Settings can even marked as 'required': True which prevents the machine from starting if the setting is not defined.

Machine status

Machine status can be used to report the machine status to the users. They can be set by the driver for each machine, but get lost on a server restart.

Codes

Each machine type has a set of status codes defined that can be set for each machine by the driver. There also needs to be a default status code defined.

from plugin.machine import MachineStatus, BaseMachineType

class XYZStatus(MachineStatus):
    CONNECTED = 100, _('Connected'), 'success'
    STANDBY = 101, _('Standby'), 'success'
    DISCONNECTED = 400, _('Disconnected'), 'danger'

class XYZMachineType(BaseMachineType):
    # ...

    MACHINE_STATUS = XYZStatus
    default_machine_status = XYZStatus.DISCONNECTED

And to set a status code for a machine by the driver.

class MyXYZDriver(ABCBaseDriver):
    # ...
    def init_machine(self, machine):
        # ... do some init stuff here
        machine.set_status(XYZMachineType.MACHINE_STATUS.CONNECTED)

MachineStatus API

Base class for representing a set of machine status codes.

Use enum syntax to define the status codes, e.g.

CONNECTED = 200, _("Connected"), 'success'

The values of the status can be accessed with MachineStatus.CONNECTED.value.

Additionally there are helpers to access all additional attributes text, label, color.

Available colors

primary, secondary, warning, danger, success, warning, info

Status code ranges
1XX - Everything fine
2XX - Warnings (e.g. ink is about to become empty)
3XX - Something wrong with the machine (e.g. no labels are remaining on the spool)
4XX - Something wrong with the driver (e.g. cannot connect to the machine)
5XX - Unknown issues
Source code in src/backend/InvenTree/machine/machine_type.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class MachineStatus(StatusCode):
    """Base class for representing a set of machine status codes.

    Use enum syntax to define the status codes, e.g.
    ```python
    CONNECTED = 200, _("Connected"), 'success'
    ```

    The values of the status can be accessed with `MachineStatus.CONNECTED.value`.

    Additionally there are helpers to access all additional attributes `text`, `label`, `color`.

    Available colors:
        primary, secondary, warning, danger, success, warning, info

    Status code ranges:
        ```
        1XX - Everything fine
        2XX - Warnings (e.g. ink is about to become empty)
        3XX - Something wrong with the machine (e.g. no labels are remaining on the spool)
        4XX - Something wrong with the driver (e.g. cannot connect to the machine)
        5XX - Unknown issues
        ```
    """

Free text

There can also be a free text status code defined.

class MyXYZDriver(ABCBaseDriver):
    # ...
    def init_machine(self, machine):
        # ... do some init stuff here
        machine.set_status_text("Paper missing")