|
import json
from urllib import request, parse
import logging
from datetime import timedelta
import voluptuous as vol
import threading
import RPi.GPIO as GPIO
import time
import datetime
import random
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION, ATTR_FRIENDLY_NAME, TEMP_CELSIUS)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_time_interval
import homeassistant.util.dt as dt_util
# 配置文件中三个配置项的名称
CONF_GPIOPINS = "gpiopins"
CONF_INTERVAL = "interval"
_LOGGER = logging.getLogger(__name__)
TIME_BETWEEN_UPDATES = timedelta(seconds=3)
ATTR_UPDATE_TIME = "更新时间"
ATTRIBUTION = "来自FOX007数据"
_GPIOPINS = [16,12,1,7,8]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_INTERVAL): cv.string,
# 配置项的options是一个列表,列表内容只能是OPTIONS中定义的三个可选项
vol.Optional(CONF_GPIOPINS, default=[]):
vol.All(cv.ensure_list, [vol.In(_GPIOPINS)]), #需要判断 读出来的数据是否在 已知数组 _GPIOPINS 里面,可以不判断
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""根据配置文件,setup_platform函数会自动被系统调用."""
interval = config.get(CONF_INTERVAL)
# 根据配置文件options中的内容,添加若干个设备
dev = []
for gpiopin in config[CONF_GPIOPINS]:
# 定义一个新的数据对象,
data = breathing_led(hass,gpiopin)
dev.append(FlashLedSensor(data, gpiopin))
add_devices(dev, True)
class FlashLedSensor(Entity):
"""定义一个呼吸灯传感器的类,继承自HomeAssistant的Entity类."""
def __init__(self, data, pin):
"""初始化."""
self._data = data
self._ledpin = pin
#定义图标
self._object_id = format("flashled_%d" % pin) #唯一ID
self._friendly_name = "呼吸灯" #名称
self._icon = "mdi:walk" #图标
self._unit_of_measurement = "μg/m3" #显示的:单位
self._state = None
self._updatetime = None
self._updatecount = 0
GPIO.setmode(GPIO.BCM)
GPIO.setup(self._ledpin, GPIO.OUT, initial = GPIO.HIGH)
@property
def name(self):
"""返回实体的名字."""
return self._object_id
@property
def registry_name(self):
"""返回实体的friendly_name属性."""
return self._friendly_name
@property
def state(self):
"""返回当前的状态."""
return self._state
@property
def icon(self):
"""返回icon属性."""
return self._icon
@property
def unit_of_measurement(self):
"""返回unit_of_measuremeng属性."""
return self._unit_of_measurement
@property
def device_state_attributes(self):
"""设置其它一些属性值."""
if self._state is not None:
return {
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_UPDATE_TIME: self._updatetime
}
def update(self):
"""更新函数,在sensor组件下系统会定时自动调用(时间间隔在配置文件中可以调整,缺省为30秒)."""
self._updatetime = self._data.updatetime
self._state = self._data.updatecount
#定义呼吸灯线程
class breathing_led(object):
def __init__(self,hass,gpiopin):
self._gpiopin = gpiopin
self._updatetime = None
self._updatecount = 0
self._betweentime = timedelta(seconds=(3+random.randint(1,3)))
self.update(dt_util.now())
# 每隔TIME_BETWEEN_UPDATES,调用一次update(),从京东万象获取数据
track_time_interval(hass, self.update, self._betweentime)
@property
def updatetime(self):
"""更新时间."""
return self._updatetime
@property
def updatecount(self):
return self._updatecount
def update(self,now):
_LOGGER.error(format("Led GPIO %d" % self._gpiopin))
GPIO.setmode(GPIO.BCM)
GPIO.setup(self._gpiopin,GPIO.OUT)
p = GPIO.PWM(self._gpiopin,100)
p.start(0)
for dc in range(0,101,1):
p.ChangeDutyCycle(dc)
time.sleep(0.015)
for dv in range(0,101,1):
p.ChangeDutyCycle(100-dv)
time.sleep(0.015)
p.stop()
GPIO.cleanup()
self._updatetime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self._updatecount +=1
配置文件
configuration.yaml
sensor:
- platform: flashled
scan_interval: 60
interval: 10
gpiopins:
- 1
|
|