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

原理

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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,923评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,154评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,775评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,960评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,976评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,972评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,893评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,709评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,159评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,400评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,552评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,265评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,876评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,528评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,701评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,552评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,451评论 2 352

推荐阅读更多精彩内容