美文网首页
homeassistant组件开发之pc远程关机锁屏开关

homeassistant组件开发之pc远程关机锁屏开关

作者: 一只特例独行de猪 | 来源:发表于2019-11-10 19:28 被阅读0次

原理

pc安装UnifiedRemote并对其进行抓包:http://10.10.10.165:9510/client/#/remote/Unified.Power

image.png

实现http远程控制pc电脑, 如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import requests
import json
HOST = 'http://10.10.10.165:9510'
try:
    response = requests.post( HOST +'/client/connect')
    connect_id = json.loads(response.text)['id']
    print connect_id
    header = {
        'UR-Connection-ID': connect_id,
    }

    formData = '{"Action":0,"Request":0,"Version":10,"Password":"80c322d3-2153-4734-9af8-d2b91d5b57b7","Platform":"web","Source":"web-5ab01735-4ba4-457a-b5a3-7de1a6557088"}'
    res = requests.post(HOST +'/client/request', data = formData, headers = header)
    print res.text

    formData = '{"Capabilities":{"Actions":true,"Sync":true,"Grid":true,"Fast":false,"Loading":true,"Encryption2":true},"Action":1,"Request":1,"Source":"web-5ab01735-4ba4-457a-b5a3-7de1a6557088"}'
    res = requests.post(HOST +'/client/request', data = formData, headers = header)
    print res.text


    formData = '{"ID":"Unified.Power","Action":7,"Request":7,"Run":{"Name":"lock"},"Source":"web-5ab01735-4ba4-457a-b5a3-7de1a6557088"}'
    res = requests.post(HOST +'/client/request', data = formData, headers = header)
    print res.text
except requests.exceptions.RequestException as e:
    print e

homeassistant组件开发参考command_line switch代码
遇到接口 cv.schema_with_slug_keys(SWITCH_SCHEMA)}未定义
应该是版本问题造成的,查看本地源码解决
cat /home/pi/homeassistant/lib/python3.5/site-packages/homeassistant/components/switch/command_line.py

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {vol.Required(CONF_SWITCHES): vol.Schema({cv.slug: SWITCH_SCHEMA})},
)

更多官方接口:http://dev-docs.home-assistant.io/en/master/

使用

switch配置示例:

  - platform: UnifiedRemote
    switches:
      pc_lock:
        friendly_name: 锁屏
        host: 'http://10.10.10.165:9510'
        cmd: 'lock'
      pc_shutdown2:
        friendly_name: 电脑关机
        host: 'http://10.10.10.165:9510'
        cmd: 'shutdown'

UnifiedRemote.py源码,存放到.homeassistant/custom_components/switch/

"""
Support for UnifiedRemote switch.
Developer by EthanZhu
version 1.0 server
"""
import logging
import voluptuous as vol
import requests
import json
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA, ENTITY_ID_FORMAT)
from homeassistant.const import (CONF_NAME, CONF_FRIENDLY_NAME, CONF_SWITCHES)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_HOST = "host"
CONF_CMD = "cmd"
#HOST = 'http://10.10.10.165:9510'
#CMD = 'lock' #shutdown、restart、sleep

SWITCH_SCHEMA = vol.Schema(
    {
        vol.Optional(CONF_FRIENDLY_NAME): cv.string,
        vol.Required(CONF_HOST): cv.string,
        vol.Required(CONF_CMD): cv.string,
    }
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {vol.Required(CONF_SWITCHES): vol.Schema({cv.slug: SWITCH_SCHEMA})},
)

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the UnifiedRemote switch."""
    devices = config.get(CONF_SWITCHES, {})
    switches = []

    for object_id, device_config in devices.items():
        switches.append(
            UnifiedRemoteSwitch(
                hass,
                object_id,
                device_config.get(CONF_FRIENDLY_NAME, object_id),
                device_config.get(CONF_HOST),
                device_config.get(CONF_CMD),
            )
        )

    if not switches:
        _LOGGER.error("No switches added")
        return False
    add_devices(switches)
    
class UnifiedRemoteSwitch(SwitchDevice):
    """Representation  switch."""

    def __init__(self, hass, object_id, name, host, cmd):
        """Initialize the switch."""
        self._hass = hass
        self.entity_id = ENTITY_ID_FORMAT.format(object_id)
        self._host = host
        self._cmd = cmd
        self._name = name
        self._state = False

    @property
    def name(self):
        """Return the name of the Smart Plug, if any."""
        return self._name

    @property
    def is_on(self):
        """Return true if switch is on."""
        return self._state

    def turn_on(self, **kwargs):
        """Turn the switch on."""
        self._state = True

    def turn_off(self):
        """Turn the switch off."""
        self._state = False
        self._state = self.pressPlug(self._host, self._cmd, False)
            
    def update(self):
        """Update device state."""
        _LOGGER.info('===Update device state===')
        try:
            response = requests.post( self._host +'/client/')
            self._state = True
        except requests.exceptions.RequestException as e:
            self._state = False
            
    def pressPlug(self, unifiedRemoteHost, cmd, fOn):
        try:
            HOST = unifiedRemoteHost
            response = requests.post( HOST +'/client/connect')
            connect_id = json.loads(response.text)['id']
            _LOGGER.debug('connect_id is %s', connect_id)
            header = {
                'UR-Connection-ID': connect_id,
            }
        
            formData = '{"Action":0,"Request":0,"Version":10,"Password":"80c322d3-2153-4734-9af8-d2b91d5b57b7","Platform":"web","Source":"web-5ab01735-4ba4-457a-b5a3-7de1a6557088"}'
            res = requests.post(HOST +'/client/request', data = formData, headers = header)
            #print res.text
        
            formData = '{"Capabilities":{"Actions":true,"Sync":true,"Grid":true,"Fast":false,"Loading":true,"Encryption2":true},"Action":1,"Request":1,"Source":"web-5ab01735-4ba4-457a-b5a3-7de1a6557088"}'
            res = requests.post(HOST +'/client/request', data = formData, headers = header)
            #print res.text
            
            formData = '{"ID":"Unified.Power","Action":7,"Request":7,"Run":{"Name":"' + cmd + '"},"Source":"web-5ab01735-4ba4-457a-b5a3-7de1a6557088"}'
            res = requests.post(HOST +'/client/request', data = formData, headers = header)
            #print res.text
            return fOn
        except requests.exceptions.RequestException as e:
            #_LOGGER.error(e)
            return fOn
image.png

相关文章

  • homeassistant组件开发之pc远程关机锁屏开关

    原理 pc安装UnifiedRemote并对其进行抓包:http://10.10.10.165:9510/clie...

  • 无人值守远程办公:远程开机、关机

    问题:电脑办公室,人在家,如何打开办公室里的电脑,进行操作 需求点:远程开机,远程关机,远程桌面 1、远程开关机实...

  • Android基础知识:Broadcast Receiver(2

    废话 今天我们来学习Android的系统广播,我们在操作Android系统的时候都会发出广播,比如开关机、锁屏、解...

  • Kobo电纸书操作说明

    一、机器硬件操作 中上部按键是灯光开关键 右上部划钮是开/锁屏键,划住久一些时间是强制开关机 底部一小孔里面有个复...

  • Python 远程开关机

    用 Python 关机你肯定听过或者实践过,那么用 Python 开机呢?这是一个神奇的方法,教你如何用 Pyth...

  • Mac黑科技系列-给你的微信增加逆天功能

    想不想一台Mac机子登录多个微信账号? 想不想通过微信远程控制你的电脑(屏幕保护、清空废纸篓、锁屏、休眠、关机、重...

  • 锐捷实战系列(四) 交换机的硬开关机

    实训目的 了解聚星云中交换机的硬开关机。 实训背景 在聚星云中,交换机、路由器、PC都可以由用户自主进行硬开关机。...

  • mac 常用快捷键(随时补充)

    control + command + Q 锁屏control + ? (电源关闭按钮) 关机Fn + F11 显...

  • iOS远程控制事件

    最近开发收到一个产品需求 :需要在用户看直播的时候,APP退到后台,锁屏界面增加远程控件、通知远程栏控件虽然项目用...

  • 烧钱

    最近手机一直频繁的开关机,弄得玩个手机呀也是挺心累的,再加上妈妈的手机也不知道她平时怎么按的,竟然锁屏了,怎么也解...

网友评论

      本文标题:homeassistant组件开发之pc远程关机锁屏开关

      本文链接:https://www.haomeiwen.com/subject/fouabctx.html