MDK Logo

Run a Bitdeer Worker

Start an MDK Worker for a Bitdeer D40 container.

TL;DR

Run mdk run from your project folder (holding mdk.yaml). Runtime: mdk run, which writes the Kernel key to .mdk/kernel.key, or a host script, which writes it to ~/.mdk/.kernel-key wherever you run it.

  • Under mdk run, mock: true starts the Worker's own mock; a host script needs npm run mock d40_m56 -- --port 10883 --id D40-DEV, run from the repository root
  • Your D40 container, or the mock, connects to the Worker (not the other way round): point it at the Worker's address, port 10883 by default, with the container ID the Worker declares in containerId
  • Check the device reports telemetry with curl through the Gateway: READY proves the Worker registered, not that its device answers

Overview

This page details how to run the Bitdeer D40 container Worker. The package is a directory-loaded Worker Plugin (mdk-contract.json plus handler files) that mdk run hosts from mdk.yaml, or that your own Node.js service hosts on WorkerRuntimeV2. Select the development (mock) or real-container path.

The Bitdeer D40 speaks MQTT, and the Worker embeds the broker that a container publishes into, rather than the Worker connecting out to the container. Every device on the same listen address shares one broker, and devices are keyed by containerId.

Prerequisites

Deployment-specific requirements:

  • An MDK project with mdk.yaml (mdk onboard), or a Node.js service or script in your deployment that hosts the Worker. @tetherto/mdk-worker-bitdeer is not published to npm, so the package resolves only through the workspace of an MDK repository clone after npm install at its root: keep the project or script inside that clone
  • A supported D40 container configured to publish into the Worker's embedded MQTT broker, reachable on that broker's port (default 10883)
  • An MQTT username and password for each container that supports MQTT login, for the broker login

Development

Run against a mock

The Bitdeer Worker ships a mock D40 container that publishes canned telemetry as an MQTT client. Declare the Worker under spec.workers in the mdk.yaml mdk onboard wrote, replacing any entry onboarding seeded for it, with mock: true, and mdk run starts the broker and one mock per device, which dials the port the device names:

spec:
  workers:
    - name: bitdeer
      package: '@tetherto/mdk-worker-bitdeer'
      config:
        mock: true
        devices:
          - id: D40-DEV
            opts: { host: 127.0.0.1, port: 10883, containerId: D40-DEV, model: m56 }
mdk run

Expected output includes a line for the Worker, with your own key:

✔ worker bitdeer ready 88fd3586a748d91b

The mock can dial before the broker listens, so a [mock] mqtt 127.0.0.1:10883: connect ECONNREFUSED line may print first; the mock retries and connects. A warning that the Worker may be missing device options can also print: Worker troubleshooting covers what it checks.

Check the stack from a second terminal in the project directory:

mdk status

Expected output ends with:

  WORKER   REGISTERED  STATE  HEALTH   DEVICES
  bitdeer  yes         READY  HEALTHY  1

✔ Health: healthy

READY and HEALTHY prove the Worker registered, not that its device answers: what a healthy run shows covers the difference. To see a reading, check the device reports telemetry.

To host the Worker yourself instead of with mdk run, start the Worker first, since it hosts the broker, and the mock second, both from the repository root:

  1. Save this script as bitdeer-dev.js in the repository root. It is the boot call from Connect a container, pointed at 127.0.0.1, with the container ID the mock publishes under and no broker login:

    'use strict'
    
    const os = require('os')
    const path = require('path')
    const { getKernel } = require('@tetherto/mdk-core')
    const { WorkerRuntimeV2 } = require('@tetherto/mdk-worker')
    
    const main = async () => {
      const kernel = await getKernel({ handleSignals: true })
    
      const runtime = new WorkerRuntimeV2(path.dirname(require.resolve('@tetherto/mdk-worker-bitdeer/package.json')), {
        workerId: 'bitdeer-dev',
        storeDir: path.join(os.tmpdir(), 'mdk-dev', 'bitdeer'),
        allowedKeys: [kernel.getClientPublicKey()],
        config: { model: 'm56', mqttHost: '127.0.0.1', mqttPort: 10883 },
        devices: [{ deviceId: 'D40-DEV', config: { containerId: 'D40-DEV' } }]
      })
      await runtime.start()
      const registration = await kernel.registerWorker(runtime.getPublicKey())
      if (!registration.registered) throw new Error(`Worker not registered: ${registration.error}`)
      kernel._cleanup.push(() => runtime.stop()) // Ctrl+C stops the Worker before the Kernel
    
      console.log('Worker registered:', registration.workerId)
      console.log('Kernel HRPC key:', kernel.getPublicKey().toString('hex'))
      console.log('Ctrl+C to stop.')
    }
    
    main().catch((err) => { console.error(err); process.exit(1) })
  2. Run the script:

    node bitdeer-dev.js
  3. Start a mock D40 M56 in a second terminal, pointed at the Worker's broker port and using the same container ID:

    npm run mock d40_m56 -- --port 10883 --id D40-DEV

Expected output from bitdeer-dev.js, with your own key:

Worker registered: bitdeer-dev
Kernel HRPC key: a94550e7f07fc2a1ebe38aa1cd482664c164d1d751f6470966611cdc40c65906
Ctrl+C to stop.

A Kernel that refuses the Worker stops the script with Error: Worker not registered: <error> and a stack trace instead: Worker troubleshooting covers each error.

Ctrl+C stops the Worker, then the Kernel; stop the services cleanly covers the contract. Stop the mock with Ctrl+C in its own terminal when you are done; nothing else stops it.

Once the mock connects, the Worker serves live telemetry (container power, temperature, tank and exhaust status). In the host script, the telemetry check reads it. The mock's model and container ID options are in the Bitdeer README.

The Kernel keeps its state in ~/.mdk, wherever you run a host script: its store, its trusted keys, and its key in ~/.mdk/.kernel-key. To run more than one Kernel on a machine, keep each one's state next to its Worker's.

Keep the Kernel's state next to the Worker's

Pass the Kernel a root and key file under the same temp folder as the Worker's store:

const kernelRoot = path.join(os.tmpdir(), 'mdk-dev', 'bitdeer-kernel')
const kernel = await getKernel({
  handleSignals: true,
  root: kernelRoot,
  keyFile: path.join(kernelRoot, '.kernel-key')
})

A Gateway in another process needs this keyFile and trustedKeysDir: path.join(kernelRoot, '.trusted-keys'); one started in the same process with kernel needs neither. The telemetry check in Worker troubleshooting spreads its own root and keyFile: false into getKernel(), so use it or this change, not both.

Connect a container

2.1 Pick your model

Use the Bitdeer README to confirm the model value for your D40 variant: a1346, m30, m56, or s19xp. This guide uses m56, replace it with the value for your container.

2.2 Declare your container

Point the mdk.yaml entry at the real container network and drop mock. The broker binds mqttHost and serves mqttPort; configure the container to dial that address:

spec:
  workers:
    - name: bitdeer
      package: '@tetherto/mdk-worker-bitdeer'
      config:
        model: m56
        mqttHost: 10.0.20.5              # the Worker's address on the container network
        mqttPort: 10883
        devices:
          - id: D40-M56-001
            opts:
              containerId: D40-M56-001
              mqttCredentials: { username: d40-m56-001, password: "${D40_M56_001_MQTT_PASSWORD}" }

The password is a ${D40_M56_001_MQTT_PASSWORD} placeholder, so it stays out of mdk.yaml. Add it to the project's .env, quoted as writing a value in .env describes:

D40_M56_001_MQTT_PASSWORD='<your-mqtt-password>'

Keep .env out of version control and readable by you alone (chmod 600 .env). The CLI resolves the placeholder when it loads mdk.yaml, and stops with an error naming the variable when it is unset.

Without mdk run, add this to the Node.js service or script that hosts the Worker. The snippet declares one D40 container; replace the example container ID, address and login with your container's values. Set D40_M56_001_MQTT_PASSWORD to the container's MQTT password before you start it; with a missing or empty password the Worker fails to start, and the error ends in ERR_MQTT_CREDENTIALS_INVALID:

const path = require('path')
const { getKernel } = require('@tetherto/mdk-core')
const { WorkerRuntimeV2 } = require('@tetherto/mdk-worker')

const main = async () => {
  const kernel = await getKernel()

  const runtime = new WorkerRuntimeV2(path.dirname(require.resolve('@tetherto/mdk-worker-bitdeer/package.json')), {
    workerId: 'bitdeer-rack-1',
    storeDir: './store/bitdeer-rack-1',
    allowedKeys: [kernel.getClientPublicKey()],
    config: { model: 'm56', mqttHost: '10.0.20.5', mqttPort: 10883 },
    devices: [{
      deviceId: 'D40-M56-001',
      config: {
        containerId: 'D40-M56-001',
        mqttCredentials: { username: 'd40-m56-001', password: process.env.D40_M56_001_MQTT_PASSWORD }
      }
    }]
  })
  await runtime.start()
  const registration = await kernel.registerWorker(runtime.getPublicKey())
  if (!registration.registered) throw new Error(`Worker not registered: ${registration.error}`)
}

main().catch((err) => { console.error(err); process.exit(1) })

allowedKeys lists the RPC callers the Worker accepts. The Worker refuses to start without it (ERR_WORKER_ALLOWED_KEYS_REQUIRED), so pass the Kernel's client key.

The broker is a network service the containers connect to, so secure it like one:

  • mqttCredentials gives each container its own MQTT login; a client's login decides which container it speaks for. Configure the same username and password on the container
  • mqttHost binds the broker to one interface. Without it, and without a device host, the broker listens on every interface (0.0.0.0)
  • mqttTls in the Worker config serves MQTTS (tls.createServer options, key and cert as PEM strings) where the containers support it

Without mqttCredentials, the broker accepts anonymous clients on every interface. Any host that reaches the broker port can connect as any registered container that has no open connection, such as one that is offline or restarting, then send that container's telemetry and receive its commands. The broker refuses publishes to command topics, confines each client to one container, and refuses a container another open connection holds; the Bitdeer README lists what a client may and may not do. The Worker prints a warning at start when it serves a non-loopback mqttHost without mqttCredentials. Keep the broker port off every network but the container network.

Make sure the container is configured to publish into this Worker's broker port before registering. Commands act on physical cooling and power hardware, prioritize thermal safety.

The device list is fixed at construction. There is no registerThing/updateThing/forgetThings equivalent: adding, updating, or removing a container means editing the device list and restarting the Worker.

The full device and Worker option reference, the telemetry and command tables, and the shared install pattern are in the Bitdeer README and the install pattern.

Check the device reports telemetry

Under mdk run, add the telemetry route to an app once, sign in, then read the device from a second terminal:

curl -sS -H "Authorization: Bearer $TOKEN" http://localhost:3847/apps/fleet/api/fleet/devices/D40-DEV/telemetry

Expected output against the mock, with your own values, shortened:

{"deviceId":"D40-DEV","metrics":{"container_power":277100,"temperature":28.8,"tank_status":"tank1:disabled,tank2:enabled","exhaust_status":"enabled",...

For a real container, put its device ID, D40-M56-001, in the path.

In a script that boots your Kernel, add the telemetry check instead. In bitdeer-dev.js, call it after the line that prints the Kernel key:

const { checkKernelOpts, checkTelemetry } = require('./check-telemetry')

const kernel = await getKernel({ handleSignals: true, ...checkKernelOpts })
// ...
console.log('Kernel HRPC key:', kernel.getPublicKey().toString('hex'))
await checkTelemetry(kernel, 'D40-DEV')
console.log('Ctrl+C to stop.')

For a real container, make the same change to the script from Connect a container and pass its device ID, D40-M56-001.

The check waits up to a minute for the mock to connect, so start the mock in its second terminal. The telemetry lines print once it connects.

Expected output against the mock, with your own key and values:

Worker registered: bitdeer-dev
Kernel HRPC key: 10a8ff609ec4954cabb359fa04e09cc7041558aa269a33970e5e416ac583ed82
Telemetry from D40-DEV:
  container_power: 282700
  temperature: 28.8
  tank_status: tank1:disabled,tank2:enabled
  exhaust_status: enabled
Ctrl+C to stop.

An error instead of a value? Read a failed check.

Troubleshooting

Reads come from the container's last MQTT publish. Until the container connects and publishes, and whenever it has been silent for 30 s or has disconnected, every telemetry channel and command fails with ERR_OFFLINE. Check that the container dials the Worker's mqttHost and mqttPort with the right login. A broker that cannot bind its port fails every channel with ERR_MQTT_BIND_FAILED.

If the Worker doesn't come up, or broker port 10883 is already in use, the network and port checks in Worker troubleshooting apply here too: the underlying HRPC and DHT requirements are the same across every Worker.

If you replace a Worker after deleting its storeDir, the Kernel may still hold its old key or device bindings. An authorized client can call terminateWorker(oldWorkerId) to release those bindings before registering the replacement. See Worker bindings.

Next steps

On this page