> For the complete documentation index, see [llms.txt](https://docs.blynk.io/en/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.blynk.io/en/html-widget-developer-guide/datastreams.md).

# Datastreams

Read and write the datastreams assigned to the widget. Every datastream is addressed by its 0-based **index** — its position in the widget's Datastreams settings — or by a **selector**.

### The value object

`getValue`, `getValues` and `onValueUpdated` all deliver the same `ValueObject`. **Every field is always present**, even ones that don't apply to the stream's type — those default to `null`, `''` or `[]` instead of being left out. Use `type` to decide which ones are meaningful.

| Field               | Type             | Description                                                                             |
| ------------------- | ---------------- | --------------------------------------------------------------------------------------- |
| `index`             | `number`         | 0-based datastream index (its position in the widget settings)                          |
| `id`                | `number \| null` | Server-side datastream ID; use it with the `{ id }` selector                            |
| `value`             | `string \| null` | Current value **as a string**. `null` before the first value arrives                    |
| `lastUpdated`       | `number \| null` | Unix timestamp (ms) of the last update, or `null`                                       |
| `type`              | `string`         | `"INT"`, `"DOUBLE"`, `"STRING"`, `"ENUM"`, `"LOCATION"`, … — compare case-insensitively |
| `label`             | `string`         | Datastream name as configured on the template                                           |
| `displayName`       | `string`         | Display alias; `''` when not set                                                        |
| `pinType`           | `string`         | Pin type, e.g. `"VIRTUAL"`, or `''`                                                     |
| `color`             | `string`         | Accent color from the widget settings, or `''`                                          |
| `min`, `max`        | `number \| null` | Range bounds; `null` for non-numeric streams                                            |
| `unit`              | `string`         | Measurement unit name, or `''`                                                          |
| `unitSystem`        | `string \| null` | `'METRIC'`, `'IMPERIAL'` or `null` when the unit has no system                          |
| `suffix`            | `string`         | Unit suffix for display, or `''`                                                        |
| `decimalFormat`     | `string`         | Decimal format pattern such as `"#.##"`, or `''`                                        |
| `mappings`          | `string[]`       | Enum option labels; `[]` for non-enum streams                                           |
| `enumFallbackValue` | `string \| null` | Label for an enum index outside `mappings`; `null` when not configured                  |

```js
// INT temperature
{ index: 0, id: 4521, value: "23", lastUpdated: 1737654321000, type: "INT",
  label: "Temperature", displayName: "Room temperature", pinType: "VIRTUAL", color: "#22c55e",
  min: -40, max: 85, unit: "Celsius", unitSystem: "METRIC", suffix: "°C", decimalFormat: "",
  mappings: [], enumFallbackValue: null }

// ENUM mode — value is the index of the selected option, as a string
{ index: 1, id: 4530, value: "1", lastUpdated: 1737654321000, type: "ENUM",
  label: "Mode", displayName: "", pinType: "VIRTUAL", color: "#a855f7",
  min: null, max: null, unit: "", unitSystem: null, suffix: "", decimalFormat: "",
  mappings: ["Off", "Eco", "Turbo"], enumFallbackValue: "Unknown" }
```

For `"ENUM"` streams, resolve the label with `mappings[parseInt(value, 10)]`, falling back to `enumFallbackValue`, then to the raw value.

***

### Datastream selectors

Besides a 0-based index, `getValue` and `sendValue` accept a selector object with **exactly one** property:

| Selector                  | Matches                                                                                                                                     |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `{ id: 42 }`              | The server-side datastream ID (the `id` field of a `ValueObject`)                                                                           |
| `{ name: 'Temperature' }` | The datastream **name** (`label`), not its display alias. Up to 255 characters                                                              |
| `{ pin: 'V5' }`           | A datastream on that **virtual** pin. `V0`, `V1`, … case-insensitive. Datastreams on digital or analog pins are addressed by `id` or `name` |

* Selectors search **only the widget's assigned datastreams**.
* The resolved value object carries `index`, so you can reuse it for history and map requests, which take indexes only.
* **Web:** a selector resolves only after the dashboard has delivered the widget's datastreams. Resolve selectors after the first value update, or address datastreams by index until then.

| Code                            | When                                                                                         |
| ------------------------------- | -------------------------------------------------------------------------------------------- |
| `invalid_selector`              | The selector doesn't carry exactly one of `id`, `name`, `pin`, or a value has the wrong type |
| `datastream_not_found`          | No assigned datastream matches (on web, also before the datastreams have loaded)             |
| `ambiguous_datastream_selector` | Several assigned datastreams match. `details.indexes` lists them — select by index instead   |

```js
const temperature = await bridge.getValue({ name: 'Temperature' });
const history = await bridge.getHistoricalData({
  period: 'DAY', dataStreams: [{ index: temperature.index, sourceType: 'AVG' }]
});
```

***

### Get a datastream value

> Returns the current value of one datastream.

```js
bridge.getValue(target)  // → Promise<ValueObject>
```

**Parameters**

| Name     | Type               | Required | Description                                                      |
| -------- | ------------------ | -------- | ---------------------------------------------------------------- |
| `target` | `number \| object` | yes      | 0-based datastream index, or a [selector](#datastream-selectors) |

**Resolves with** a [`ValueObject`](#the-value-object).

**Rejects with**

| Code                                                                        | When                                                                               |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `invalid_request`                                                           | `target` is missing, or the index is not configured on the widget                  |
| `invalid_selector`, `datastream_not_found`, `ambiguous_datastream_selector` | The selector can't be resolved — see [Datastream selectors](#datastream-selectors) |
| `device_unavailable`                                                        | Called outside a Blynk host                                                        |
| `bridge_destroyed`                                                          | Called after `destroy()`                                                           |

**Example**

```js
bridge.getValue(0).then(v => {
  if (v.value === null) { valueEl.textContent = '--'; return; }
  const num = parseFloat(v.value);
  const decimals = v.decimalFormat ? (v.decimalFormat.split('.')[1]?.length ?? 0) : null;
  const display = decimals === null ? String(num) : num.toFixed(decimals);
  valueEl.textContent = v.suffix ? `${display} ${v.suffix}` : display;
});

// ENUM — a dropdown of the options that writes back the chosen index
bridge.getValue({ name: 'Mode' }).then(v => {
  if (v.type.toUpperCase() !== 'ENUM') return;
  const current = parseInt(v.value, 10);
  v.mappings.forEach((label, idx) => {
    const opt = document.createElement('option');
    opt.value = String(idx);
    opt.text = label;
    opt.selected = idx === current;
    selectEl.appendChild(opt);
  });
  selectEl.addEventListener('change', () => bridge.sendValue(v.index, selectEl.value));
});
```

***

### Get all datastream values

> Returns the current values of every datastream assigned to the widget.

```js
bridge.getValues()  // → Promise<ValueObject[]>
```

**Parameters:** none.

**Resolves with** an array of [`ValueObject`](#the-value-object)s, positioned by index. Always key rendering off `v.index`, not off the position you iterate.

**Rejects with** `device_unavailable`, `bridge_destroyed`.

> **Web:** the array is built from the values the dashboard has already pushed into the iframe. Before the first push it is `[]`, and a stream that hasn't reported yet leaves a hole. So an empty array means *"no datastreams configured **or** nothing has arrived yet"* — render a neutral state and let `onValueUpdated` fill the UI in. `forEach` and `for…of` handle holes safely; indexed access can return `undefined`. **Mobile** returns the full list from the app.

**Example**

```js
bridge.getValues().then(values => {
  values.forEach(v => {
    if (v.type.toUpperCase() === 'ENUM') {
      const idx = parseInt(v.value, 10);
      renderEnum(v.index, v.mappings[idx] ?? v.enumFallbackValue ?? v.value);
    } else {
      renderNumeric(v.index, parseFloat(v.value), v.suffix, v.decimalFormat);
    }
  });
});
```

***

### Send a datastream value

> Writes a value to a datastream (and on to the device).

```js
bridge.sendValue(target, value)  // → void
```

**Parameters**

| Name     | Type               | Required | Description                                                      |
| -------- | ------------------ | -------- | ---------------------------------------------------------------- |
| `target` | `number \| object` | yes      | 0-based datastream index, or a [selector](#datastream-selectors) |
| `value`  | `string \| number` | yes      | Value to write                                                   |

**Returns** nothing. `sendValue` is **synchronous and fire-and-forget** — there is no delivery confirmation. Reflect the new state optimistically and let `onValueUpdated` confirm it.

**Errors**

* An index that isn't configured on the widget is reported through `sendError` (so your `onError` sees it), and the value is dropped.
* A selector that can't be resolved is reported through `sendError` **and thrown synchronously** as a `BlynkBridgeError`. Wrap selector-based writes in `try/catch`.
* Outside a Blynk host, or after `destroy()`, the call does nothing.

**Example**

```js
bridge.sendValue(0, '23.5');
bridge.sendValue(1, 'ON');

try {
  bridge.sendValue({ pin: 'V5' }, 21);
} catch (e) {
  // already reported through onError
}
```

Value updates pushed by the host arrive in [`onValueUpdated`](https://docs.blynk.io/en/html-widget-developer-guide/callbacks.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.blynk.io/en/html-widget-developer-guide/datastreams.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
