Controlar pc via mqtt

Boas pessoal, hoje vou partilhar convosco uma integração do vosso pc que ligado por cabo de rede conseguem ter um controlo do mesmo, podendo ligar, desligar, mandar notificações, ligar e desligar o ecrã, abrir programas.
Para teres esta integração vais precisar de ter o add-on mosquitto instalado e o auto discovery ativo.
Antes de iniciares este tutorial certifica-te de que o teu pc suporta ou se tem ativo o wake on lan.
Para isso vamos instalar o software do seguinte link…

https://iotlink.gitlab.io/downloads.html

Depois de instalado vamos fazer a configuração do ficheiro com os teus dados de mqtt…

Apos esta configuração já deves de ter os sensores do lado do HA.

sensores

Estes são os sensores que vais ter disponível no HA, cada sensor tem mais entidades, por exemplo no sensor power vais ter disponível informações relativas a bateria no caso de um portátil e o estado do pc. Depois podes explorar e usar os que mais te interessa.

Apos estas configurações tens de fazer a integração do wake on lan e dos vários scripts que podes usar…

homeassistant:

###############################################################################
#                                                                             #
#                             L I G H T                                       #
#                                                                             #
############################################################################### 

###############################################################################
#                                                                             #
#                         S W I T C H                                         #
#                                                                             #
###############################################################################
switch:

  - platform: wake_on_lan
    name: Media Center
    host: ip da maquina
    mac: mac ethernet

###############################################################################
#                                                                             #
#                               S E N S O R                                   #
#                                                                             #
############################################################################### 
sensor:

  - platform: template
    sensors:
      estado_wol:
        friendly_name: "Estado do PC WOL"
        value_template: >-
          {% if is_state('binary_sensor.desktop_at5u3r9_power_status', 'on') %}
            Ligado
          {% else %}
            Desligado
          {% endif %}
        icon_template: >-
          {% if is_state('binary_sensor.desktop_at5u3r9_power_status', 'on') %}
            mdi:television
          {% else %}
            mdi:television-off
          {% endif %}
###############################################################################
#                                                                             #
#                       I N P U T _ B O O L E A N                             #
#                                                                             #
############################################################################### 

###############################################################################
#                                                                             #
#                       I N P U T _ B O O L E A N                             #
#                                                                             #
############################################################################### 
input_select:
  ligar_desligar_reiniciar:
    name: O que queres fazer?
    options:
      - Escolher
      - Ligar
      - Desligar
      - Reiniciar
      - Refresh
      - Ligar Ecrã
      - Desligar Ecrã
      - Abrir Chome HA
    initial: Escolher
    icon: mdi:desktop-tower-monitor

###############################################################################
#                                                                             #
#                     I N P U T _ D A T E T I M E                             #
#                                                                             #
############################################################################### 

###############################################################################
#                                                                             #
#                              S C R I P T S                                  #
#                                                                             #
###############################################################################
script:

  my_computer_shutdown:
    alias: "Desligar PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/shutdown"
          payload: ""

  my_computer_suspend:
    alias: "Suspender PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/suspend"
          payload: ""

  my_computer_hibernate:
    alias: "Hibernar PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/hibernate"
          payload: ""

  my_computer_reboot:
    alias: "Reboot PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/reboot"
          payload: ""

  my_computer_lock:
    alias: "Bloquear PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/lock"
          payload: ""

  my_computer_logoff:
    alias: "Logoff"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/logoff"
          payload: ""

  my_computer_vol_mute:
    alias: "Mute PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/volume/mute"
          payload: ""

  my_computer_vol_max:
    alias: "Vol Max PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/volume/set"
          payload: "100"

  my_computer_displays_on:
    alias: "Ligar Display"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/displays/on"
          payload: ""

  my_computer_displays_off:
    alias: "Desligar Display"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/displays/off"
          payload: ""

  my_computer_refresh:
    alias: "Refresh PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/refresh"
          payload: ""

  my_computer_notify:
    alias: "Notificar PC"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/notify"
          payload: '{ "title": "Alerta!!!", "message": "Anda cá a cima.", "iconUrl": "" }'

  my_computer_run_chrome:
    alias: "Abrir chrome"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-011p0hu/commands/run"
          payload: '{ "command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "args": "https://www.home-assistant.io/", "path": "C:\\Program Files (x86)\\Google\\Chrome\\Application", "user": "", "visible": true, "fallback": true }'

  my_computer_run_ccleaner:
    alias: "Run CCleaner"
    sequence:
      - service: mqtt.publish
        data:
          topic: "iotlink/workgroup/desktop-at5u3r9/commands/run"
          payload: '{ "command": "C:\\Program Files\\CCleaner\\CCleaner64.exe", "args": "/AUTO", "path": "C:\\Program Files\\CCleaner\\", "user": "", "visible": true, "fallback": true }'

deixo também o flow de node red para controlar o input_select

[{"id":"7fcb8f4d.f6213","type":"server-state-changed","z":"51a3a3cd.b4d0fc","name":"Opções media center","server":"e461daef.3d6cc8","version":1,"exposeToHomeAssistant":false,"haConfig":[{"property":"name","value":""},{"property":"icon","value":""}],"entityidfilter":"input_select.ligar_desligar_reiniciar","entityidfiltertype":"exact","outputinitially":false,"state_type":"str","haltifstate":"","halt_if_type":"str","halt_if_compare":"is","outputs":1,"output_only_on_state_change":true,"for":0,"forType":"num","forUnits":"minutes","ignorePrevStateNull":false,"ignorePrevStateUnknown":false,"ignorePrevStateUnavailable":false,"ignoreCurrentStateUnknown":false,"ignoreCurrentStateUnavailable":false,"x":100,"y":1020,"wires":[["ffd15060.4f071"]]},{"id":"ffd15060.4f071","type":"switch","z":"51a3a3cd.b4d0fc","name":"","property":"payload","propertyType":"msg","rules":[{"t":"eq","v":"Ligar","vt":"str"},{"t":"eq","v":"Desligar","vt":"str"},{"t":"eq","v":"Reiniciar","vt":"str"},{"t":"eq","v":"Refresh","vt":"str"},{"t":"eq","v":"Ligar Ecrã","vt":"str"},{"t":"eq","v":"Desligar Ecrã","vt":"str"},{"t":"eq","v":"Abrir Chome HA","vt":"str"}],"checkall":"true","repair":false,"outputs":7,"x":270,"y":1020,"wires":[["270150e9.9994a"],["4d46ef0b.1a777"],["f9534ba8.e7b668"],["e7fa0991.63c648"],["acbe812c.f0184"],["c0c50983.862968"],["ba8abe13.fd9cd"]],"outputLabels":["Ligar","Desligar","Reiniciar","Refresh","Ligar Ecrã","Desligar Ecrã","Abrir Chome HA"]},{"id":"270150e9.9994a","type":"api-call-service","z":"51a3a3cd.b4d0fc","name":"Liga PC","server":"e461daef.3d6cc8","version":1,"debugenabled":false,"service_domain":"switch","service":"turn_on","entityId":"switch.media_center","data":"","dataType":"jsonata","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":440,"y":860,"wires":[["28b00fbe.402b9"]]},{"id":"28b00fbe.402b9","type":"delay","z":"51a3a3cd.b4d0fc","name":"","pauseType":"delay","timeout":"2","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"x":740,"y":1020,"wires":[["20beb227.83170e"]]},{"id":"20beb227.83170e","type":"api-call-service","z":"51a3a3cd.b4d0fc","name":"reset input","server":"e461daef.3d6cc8","version":1,"debugenabled":false,"service_domain":"input_select","service":"select_first","entityId":"input_select.ligar_desligar_reiniciar","data":"","dataType":"json","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":890,"y":1020,"wires":[[]]},{"id":"4d46ef0b.1a777","type":"api-call-service","z":"51a3a3cd.b4d0fc","name":"Desliga PC","server":"e461daef.3d6cc8","version":1,"debugenabled":false,"service_domain":"script","service":"turn_on","entityId":"script.my_computer_shutdown","data":"","dataType":"jsonata","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":450,"y":920,"wires":[["28b00fbe.402b9"]]},{"id":"f9534ba8.e7b668","type":"api-call-service","z":"51a3a3cd.b4d0fc","name":"Reiniciar PC","server":"e461daef.3d6cc8","version":1,"debugenabled":false,"service_domain":"script","service":"turn_on","entityId":"script.my_computer_reboot","data":"","dataType":"jsonata","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":450,"y":980,"wires":[["28b00fbe.402b9"]]},{"id":"e7fa0991.63c648","type":"api-call-service","z":"51a3a3cd.b4d0fc","name":"Refresh","server":"e461daef.3d6cc8","version":1,"debugenabled":false,"service_domain":"script","service":"turn_on","entityId":"script.my_computer_refresh","data":"","dataType":"jsonata","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":440,"y":1040,"wires":[["28b00fbe.402b9"]]},{"id":"acbe812c.f0184","type":"api-call-service","z":"51a3a3cd.b4d0fc","name":"Liga Ecrã","server":"e461daef.3d6cc8","version":1,"debugenabled":false,"service_domain":"script","service":"turn_on","entityId":"script.my_computer_displays_on","data":"","dataType":"jsonata","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":440,"y":1100,"wires":[["28b00fbe.402b9"]]},{"id":"c0c50983.862968","type":"api-call-service","z":"51a3a3cd.b4d0fc","name":"Desliga Ecrã","server":"e461daef.3d6cc8","version":1,"debugenabled":false,"service_domain":"script","service":"turn_on","entityId":"script.my_computer_displays_off","data":"","dataType":"jsonata","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":450,"y":1160,"wires":[["28b00fbe.402b9"]]},{"id":"ba8abe13.fd9cd","type":"api-call-service","z":"51a3a3cd.b4d0fc","name":"Abre Chrome","server":"e461daef.3d6cc8","version":1,"debugenabled":false,"service_domain":"script","service":"turn_on","entityId":"script.my_computer_run_chrome","data":"","dataType":"jsonata","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":450,"y":1220,"wires":[["28b00fbe.402b9"]]},{"id":"e461daef.3d6cc8","type":"server","name":"partilha","legacy":false,"addon":false,"rejectUnauthorizedCerts":true,"ha_boolean":"y|yes|true|on|home|open","connectionDelay":true,"cacheJson":true}]

Após teres os scripts tens de fazer uma alteração que é o nome do teu pc que tem de estar igual no topic, ou seja tens de substituir o desktop-011p0hu pelo teu… Para obteres essa info vais as propriedades “Este pc” e tens lá o nome que precisas. De salientar que tens de meter o nome em minúsculas independentemente do que lá esteja… Deixo uma foto para exemplo.

nome do pc

Fiz uns cards que também vou partilhar caso queiram usar.

type: entities
entities:
  - entity: input_select.ligar_desligar_reiniciar
state_color: true
title: Opções do PC
type: entity
entity: sensor.estado_wol
type: conditional
conditions:
  - entity: sensor.estado_wol
    state: Ligado
card:
  type: vertical-stack
  cards:
    - type: entity
      entity: sensor.desktop_at5u3r9_system_boot_time
      name: 'Ligado desde:'
    - type: gauge
      entity: sensor.desktop_at5u3r9_cpu_usage
      min: 0
      max: 100
      severity:
        green: 0
        yellow: 50
        red: 70
    - type: picture-glance
      title: Média Center
      image: 'https://demo.home-assistant.io/stub_config/kitchen.png'
      entities: []
      camera_image: camera.desktop_at5u3r9_screen_0
      camera_view: live

Este tutorial foi inspirado no seguinte link…

queria também deixar aqui um agradecimento ao membro @igoralmeida364 pela dica.
Este tutorial é feito em packages, caso não uses terás de adaptar ao teu sistema que usas…

Espero que seja util…

5 Likes

Esqueceste de mencionar que o mosquitto tem de ter o discovery ativo.
E para o wake on lan funcionar, a placa do PC tem de suportar essa funcionalidade, e em alguns casos tem de ser ativado manualmente.

2 Likes

Feito. Obrigado pelo reparo…


Copyright © 2017-2021. Todos os direitos reservados
CPHA.pt - info@cpha.pt


FAQ | Termos de Serviço/Regras | Política de Privacidade