---
title: tvcontroller
slug: develop/es/tvcontroller
docTags: 
createdAt: 2025-03-27T16:56:33.880Z
---

El objeto *controlador de TV&#xA0;*&#x70;roporciona una interfaz de comunicación entre televisores y productos BrightSign built-in. Este objeto está disponible a partir de BOS 9.0.16&#x38;**.**

Múltiples instancias de *tvcontroller* pueden acceder al televisor desde múltiples dominios (aplicación de nodo de usuario, aplicación HTML de usuario, etc.), o puede usar múltiples instancias del objeto JavaScript. Todas acceden al mismo hardware del televisor y todas reciben una notificación con un evento cuando el televisor envía un mensaje.

**IDL de tvcontroller**

```javascript
@brightsign/tvcontroller                                                                                                                                                                                                                                                                              
[Exposed=Window]                                                                                                                                                                                                                                                                                      
interface TvController {                                                                                                                                                                                                                                                                              
  Promise<void> send(Array data);                                                                                                                                                                                                                                                                     
  attribute EventHandler onreceive;                                                                                                                                                                                                                                                                   
};                                                                                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                                      
[Exposed=Window]                                                                                                                                   
interface ReceiveEvent : Event {                                                                                                                   
  readonly attribute Array data;                            
};   
```

## Creación de objetos

Para crear un objeto *tvcontroller* , cargue el módulo `brightsign/tvcontroller` usando el método `require()` y luego cree una instancia de *tvcontroller*:

```javascript
let tv_controller_class = require("@brightsign/tvcontroller");
let tv_controller = new tv_controller_class();
```

## TvController

Use esta interfaz para acceder a un televisor (por ejemplo, para enviar mensajes)

**send()**

```javascript
Promise<void> send(Array data)
```

**Atributo**

- `onreceive` <font color="#6554c0">EventHandler</font>:

## ReceiveEvent

Use esta interfaz para recibir una notificación con un evento cuando el televisor envía un mensaje

**Atributo**

- `datos` <font color="#6554c0">Array</font>: Este es un atributo de solo lectura

## Mensajes

Los mensajes se definen en formato Protobuf. El firmware de BrightSign incluye los enlaces JavaScript de los mensajes del protocolo buffer en la imagen del firmware. Para cargar los mensajes, cargue el siguiente módulo:

```javascript
let { messages } = require("messages_pb");
```

Se utiliza un único archivo Protobuf tanto para los mensajes del televisor a BrightSign Built-In como para los mensajes de BrightSign Built-In al televisor, porque los mismos mensajes se utilizan tanto para las notificaciones de verificación como de actualización. Cuando BrightSign actualiza un campo (por ejemplo, para configurar el volumen), el televisor envía de vuelta a BrightSign el mismo mensaje indicando que el volumen se actualizó. El volumen se puede actualizar con la interfaz de usuario del televisor, mediante control remoto. BrightSign también recibe eso como un evento del televisor.

Hay algunas excepciones:

- Brightsign Built-In no envía mensajes de vuelta al televisor para confirmar el reconocimiento de recepción del mensaje de solicitud, solo envía la información solicitada.
- Ambos lados pueden enviarse el mensaje `Configuración de energía` entre sí. Para evitar confusiones entre recibir un comando y un reconocimiento, tenemos los tipos de mensaje `Configuración de energía` y `PowerSettingsAck `. `PowerSettingsAck` se envía cuando el dispositivo recibe un mensaje `Configuración de energía` y cambia al modo de energía solicitado.

Este es el archivo Proto para la interfaz de comunicación:

```javascript
syntax = "proto3";

package messages;

message WhiteBalance {
    int32 red_gain = 1;   // Red channel gain (e.g., 0 to 100)
    int32 green_gain = 2; // Green channel gain (e.g., 0 to 100)
    int32 blue_gain = 3;  // Blue channel gain (e.g., 0 to 100)
}

// Message to set the TV HDMI input.
message VideoOutputSettings {
    enum VideoOutputSelection {
        HDMI_1 = 0;
        HDMI_2 = 1;
        // Add more as needed
    }
    VideoOutputSelection selected_input = 1;
}

// There may be more PowerStatus modes in the future
enum PowerStatus {
    STANDBY = 0;
    ON = 1;
    FAST_TV_START = 2;
}

// Message to set the power status
message PowerSettings {
    PowerStatus status = 1;
}

// PowerSettingsAck message is an acknowledge to power status 
// change request.
// Sender should wait for Ack after changing PowerSettings
// via PowerSettings message, or via GPIO when waking device
// up
message PowerSettingsAck {
    PowerStatus status = 1;
}

// Whatever this value is set to, the TV must store it on their side.
// And then when the TV goes into standby using an IR command, the TV
// must send that value to the BrightSign player.
//
// PowerSettingsUpdate message is mainly to be used as a trigger 
// to enable/disable "Fast TV Start".
//
message PowerSettingsUpdate {
    PowerStatus status = 1;
}

// Message to set the power lock status
message PowerLockSettings {
    enum PowerLockStatus {
        DISABLED = 0;
        ENABLED = 1;
    }
    PowerLockStatus status = 1;
}

// Message to set or get the USB device connection.
message USBConnectionSettings {
    enum USBConnection {
        CONNECTED_TO_TV = 0;
        CONNECTED_TO_SET_TOP_BOX = 1;
    }
    USBConnection connection = 1;
}

// Message to forward the IR commands received by the TV.
message IRCommandMessage {
    uint32 code = 1;
    string encoding = 2;
}

enum Request {
    DEVICE_INFO = 0;
    VIDEO_OUTPUT_SETTINGS = 1;
    POWER_SETTINGS_ACK = 2;
    USB_CONNECTION_SETTINGS = 3;
    VOLUME = 4;
    GAMMA = 5;
    BRIGHTNESS = 6;
    CONTRAST = 7;
    WHITE_BALANCE = 8;
    IDLE_STANDBY_TIMEOUT_SECONDS = 9;
    POWER_SETTINGS = 10;
    POWER_SETTINGS_UPDATE = 11;
    POWER_LOCK_SETTINGS = 12;
}

message WifiInfo {
    string mac_address = 1; // "XX:XX:XX:XX:XX:XX"
}

message DeviceInfo {
    string mac_address = 1; // "XX:XX:XX:XX:XX:XX"
    string serial_no = 2;
    string os_version = 3; // "X.X.X.X"
    int32 hw_revision = 4; //
    WifiInfo wifi_info = 5;
}

message FirmwareUpdate {
    string file_path = 1; 
}

message FirmwareUpdateComplete {
    enum FirmwareUpdateStatus {
        SUCCESS = 0;
        FAIL = 1;
    }
    FirmwareUpdateStatus status = 1;
    string reason = 2;
}

// Command message that will be sent from the set top box to the TV.
message TvCommand {
    oneof command {
        VideoOutputSettings video_output_settings = 1;
        PowerSettings power_settings = 2;
        PowerSettingsAck power_settings_ack = 3;
        USBConnectionSettings usb_connection_settings = 4;
        IRCommandMessage ir_command = 5;
        int32 volume = 6;
        float gamma = 7;
        int32 brightness = 8;
        int32 contrast = 9;
        WhiteBalance white_balance = 10;
        Request request = 11;
        DeviceInfo device_info = 12;
        int32 idle_standby_timeout_seconds = 13;
        FirmwareUpdate firmware_update = 14;
        FirmwareUpdateComplete firmware_update_complete = 15;
        PowerSettingsUpdate power_settings_update = 16;
        PowerLockSettings power_lock_settings = 17;
    }
}
```

## Ejemplos de uso

### Configurar el valor gamma del televisor

En esta comunicación unidireccional, BrightSign realiza la solicitud y el televisor actualiza y devuelve el valor gamma.&#x20;

`Enviar` toma un array de JavaScript, pero `codificar` devuelve `Uint8Array`.  `Uint8Array` debe convertirse a `Matriz` usando `Array.from()` antes de llamar a `enviar`.

`decodificar` también espera un `Uint8Array`, pero el evento `recibir` devuelve `Matriz`. `Matriz` debe convertirse a `Uint8Array` antes de llamar a `decodificar` usando `Uint8Array.from()`

```javascript
let tv_controller_class = require("@brightsign/tvcontroller");
let tv_controller = new tv_controller_class();
let { messages } = require("messages_pb");

tv_controller.addEventListener("receive", (event) => {
  // Decode the binary data
  let tv = messages.TvCommand.decode(Uint8Array.from(event.detail));
  switch (tv.command) {
    case 'gamma':
      let gamma = tv.gamma;
      console.log("Gamma value is updated to: " + gamma);
      break;
    default:
      console.log("Unknown command type: " + tv.command);
      break;
  }
});

const tvCommand = { gamma: 2.3 };
// Encode the data
const bytes = messages.TvCommand.encode(tvCommand).finish();
// Send it as an Array
tv_controller.send(Array.from(bytes));
```

### Enviar información del dispositivo BrightSign

En el siguiente ejemplo, tv\_controller está configurado para enviar información del dispositivo cuando el televisor la solicite. La aplicación configura un receptor de eventos receive y espera un evento de solicitud.&#x20;

Solo hay una solicitud disponible actualmente, `DEVICE_INFO`, (cualquier otra producirá un error). Una solicitud `DEVICE_INFO` completa los campos requeridos y envía un mensaje de vuelta.

```javascript
let tv_controller_class = require("@brightsign/tvcontroller");
let tv_controller = new tv_controller_class();
let { messages } = require("messages_pb");

tv_controller.addEventListener("receive", (event)=>{
  // Decode the binary data
  let tv = messages.TvCommand.decode(Uint8Array.from(event.detail));
  switch (tv.command) {
    case 'request':
      // We only have DEVICE_INFO request for now
      if (tv.request != messages.Request.DEVICE_INFO) {
        throw new Error("Request is not DEVICE_INFO");
      }

      const tvCommand = {
        deviceInfo: {
          serialNo: "1234567890",
          osVersion: "1.2.3.4",
          hwRevision: 1,
          macAddress: "XX:XX:XX:XX:XX:XX",
          wifiInfo: {
            macAddress: "XX:XX:XX:XX:XX:XX"
          }
        }
      };
      const bytes = messages.TvCommand.encode(tvCommand).finish();
      tv_controller.send(Array.from(bytes));
      break;
    default:
      console.log("Unknown command type: " + tv.command);
      break;
  }
});
```

