mirror of
https://github.com/home-assistant/core.git
synced 2025-07-22 12:47:08 +00:00
1) Merged with mainline dev branch. 2) Removed assumption in homeassistant/__init__.py that states are visible if not specified. This assumption is intrinsic in the JavaScript. 3) Recompiled frontend to assist merge.
This commit is contained in:
commit
2b4c75543a
@ -28,6 +28,7 @@ omit =
|
||||
homeassistant/components/device_tracker/netgear.py
|
||||
homeassistant/components/device_tracker/nmap_tracker.py
|
||||
homeassistant/components/device_tracker/ddwrt.py
|
||||
homeassistant/components/sensor/transmission.py
|
||||
|
||||
|
||||
[report]
|
||||
|
@ -22,7 +22,7 @@ from homeassistant.const import (
|
||||
SERVICE_HOMEASSISTANT_STOP, EVENT_TIME_CHANGED, EVENT_STATE_CHANGED,
|
||||
EVENT_CALL_SERVICE, ATTR_NOW, ATTR_DOMAIN, ATTR_SERVICE, MATCH_ALL,
|
||||
EVENT_SERVICE_EXECUTED, ATTR_SERVICE_CALL_ID, EVENT_SERVICE_REGISTERED,
|
||||
TEMP_CELCIUS, TEMP_FAHRENHEIT, ATTR_FRIENDLY_NAME, ATTR_HIDDEN)
|
||||
TEMP_CELCIUS, TEMP_FAHRENHEIT, ATTR_FRIENDLY_NAME)
|
||||
import homeassistant.util as util
|
||||
|
||||
DOMAIN = "homeassistant"
|
||||
@ -621,16 +621,6 @@ class StateMachine(object):
|
||||
new_state = str(new_state)
|
||||
attributes = attributes or {}
|
||||
|
||||
# Last chance to enforce the visibility property. This is required for
|
||||
# components that don't use the Entity base class for their entities.
|
||||
# The sun component is an example of this. The Entity class cannot be
|
||||
# imported cleanly, so assume the state is shown. This means that for
|
||||
# visibility to be supported, the state must originate from a class
|
||||
# that uses the base class Entity or it must manually put the hidden
|
||||
# attribute in its attributes dictionary.
|
||||
if ATTR_HIDDEN not in attributes:
|
||||
attributes[ATTR_HIDDEN] = False
|
||||
|
||||
with self._lock:
|
||||
old_state = self._states.get(entity_id)
|
||||
|
||||
|
@ -1,2 +1,2 @@
|
||||
""" DO NOT MODIFY. Auto-generated by build_frontend script """
|
||||
VERSION = "9e21c99d2991dd288287d3d3bc3e64e0"
|
||||
VERSION = "e7801905cc2ea1ee349ec199604fb984"
|
||||
|
File diff suppressed because one or more lines are too long
@ -2,26 +2,58 @@
|
||||
|
||||
<link rel="import" href="../bower_components/google-apis/google-jsapi.html">
|
||||
|
||||
<polymer-element name="state-timeline" attributes="stateHistory">
|
||||
<polymer-element name="state-timeline" attributes="stateHistory isLoadingData">
|
||||
<template>
|
||||
<style>
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
#loadingbox {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.loadingmessage {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.hiddencharts {
|
||||
visibility:hidden;
|
||||
}
|
||||
|
||||
.singlelinechart {
|
||||
min-height:140px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div style='width: 100%; height: auto;' class="{{ {hiddencharts: !isLoading} | tokenList}}" >
|
||||
<div layout horizontal center fit id="splash">
|
||||
<div layout vertical center flex>
|
||||
<div id="loadingbox">
|
||||
<paper-spinner active="true"></paper-spinner><br />
|
||||
<div class="loadingmessage">{{spinnerMessage}}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<google-jsapi on-api-load="{{googleApiLoaded}}"></google-jsapi>
|
||||
<div id="timeline" style='width: 100%; height: auto;'></div>
|
||||
<div id="timeline" style='width: 100%; height: auto;' class="{{ {hiddencharts: isLoadingData, singlelinechart: isSingleDevice && hasLineChart } | tokenList}}"></div>
|
||||
<div id="line_graphs" style='width: 100%; height: auto;' class="{{ {hiddencharts: isLoadingData} | tokenList}}"></div>
|
||||
|
||||
</template>
|
||||
<script>
|
||||
Polymer({
|
||||
apiLoaded: false,
|
||||
stateHistory: null,
|
||||
isLoading: true,
|
||||
isLoadingData: false,
|
||||
spinnerMessage: "Loading data...",
|
||||
isSingleDevice: false,
|
||||
hasLineChart: false,
|
||||
|
||||
googleApiLoaded: function() {
|
||||
google.load("visualization", "1", {
|
||||
packages: ["timeline"],
|
||||
packages: ["timeline", "corechart"],
|
||||
callback: function() {
|
||||
this.apiLoaded = true;
|
||||
this.drawChart();
|
||||
@ -33,10 +65,17 @@
|
||||
this.drawChart();
|
||||
},
|
||||
|
||||
isLoadingDataChanged: function() {
|
||||
if(this.isLoadingData) {
|
||||
isLoading = true;
|
||||
}
|
||||
},
|
||||
|
||||
drawChart: function() {
|
||||
if (!this.apiLoaded || !this.stateHistory) {
|
||||
return;
|
||||
}
|
||||
this.isLoading = true;
|
||||
|
||||
var container = this.$.timeline;
|
||||
var chart = new google.visualization.Timeline(container);
|
||||
@ -55,21 +94,39 @@
|
||||
return;
|
||||
}
|
||||
|
||||
// people can pass in history of 1 entityId or a collection.
|
||||
|
||||
this.hasLineChart = false;
|
||||
this.isSingleDevice = false;
|
||||
|
||||
// people can pass in history of 1 entityId or a collection.
|
||||
var stateHistory;
|
||||
if (_.isArray(this.stateHistory[0])) {
|
||||
stateHistory = this.stateHistory;
|
||||
} else {
|
||||
stateHistory = [this.stateHistory];
|
||||
this.isSingleDevice = true;
|
||||
}
|
||||
|
||||
var lineChartDevices = {};
|
||||
var numTimelines = 0;
|
||||
// stateHistory is a list of lists of sorted state objects
|
||||
stateHistory.forEach(function(stateInfo) {
|
||||
if(stateInfo.length === 0) return;
|
||||
|
||||
var entityDisplay = stateInfo[0].entityDisplay;
|
||||
var newLastChanged, prevState = null, prevLastChanged = null;
|
||||
//get the latest update to get the graph type from the component attributes
|
||||
var attributes = stateInfo[stateInfo.length - 1].attributes;
|
||||
|
||||
//if the device has a unit of meaurment it will be added as a line graph further down
|
||||
if(attributes['unit_of_measurement']) {
|
||||
if(!lineChartDevices[attributes['unit_of_measurement']]){
|
||||
lineChartDevices[attributes['unit_of_measurement']] = [];
|
||||
}
|
||||
lineChartDevices[attributes['unit_of_measurement']].push(stateInfo);
|
||||
this.hasLineChart = true
|
||||
return;
|
||||
}
|
||||
|
||||
stateInfo.forEach(function(state) {
|
||||
if (prevState !== null && state.state !== prevState) {
|
||||
@ -86,10 +143,11 @@
|
||||
});
|
||||
|
||||
addRow(entityDisplay, prevState, prevLastChanged, new Date());
|
||||
numTimelines++;
|
||||
}.bind(this));
|
||||
|
||||
chart.draw(dataTable, {
|
||||
height: 55 + stateHistory.length * 42,
|
||||
height: 55 + numTimelines * 42,
|
||||
|
||||
// interactive properties require CSS, the JS api puts it on the document
|
||||
// instead of inside our Shadow DOM.
|
||||
@ -103,6 +161,163 @@
|
||||
format: 'H:mm'
|
||||
},
|
||||
});
|
||||
|
||||
/**************************************************
|
||||
The following code gererates line line graphs for devices with continuous
|
||||
values(which are devices that have a unit_of_measurment values defined).
|
||||
On each graph the devices are grouped by their unit of measurement, eg. all
|
||||
sensors measuring MB will be a separate line on single graph. The google
|
||||
chart API takes data as a 2 dimensional array in the format:
|
||||
|
||||
DateTime, device1, device2, device3
|
||||
2015-04-01, 1, 2, 0
|
||||
2015-04-01, 0, 1, 0
|
||||
2015-04-01, 2, 1, 1
|
||||
|
||||
NOTE: the first column is a javascript date objects.
|
||||
|
||||
The first thing we do is build up the data with rows for each time of a state
|
||||
change and initialise the values to 0. THen we loop through each device and
|
||||
fill in its data.
|
||||
|
||||
**************************************************/
|
||||
|
||||
|
||||
while (this.$.line_graphs.firstChild) {
|
||||
this.$.line_graphs.removeChild(this.$.line_graphs.firstChild);
|
||||
}
|
||||
|
||||
for (var key in lineChartDevices) {
|
||||
var deviceStates = lineChartDevices[key];
|
||||
|
||||
if(this.isSingleDevice) {
|
||||
container = this.$.timeline
|
||||
}
|
||||
else {
|
||||
container = document.createElement("DIV");
|
||||
this.$.line_graphs.appendChild(container);
|
||||
}
|
||||
|
||||
|
||||
var chart = new google.visualization.LineChart(container);
|
||||
|
||||
|
||||
var dataTable = new google.visualization.DataTable();
|
||||
dataTable.addColumn({ type: 'datetime', id: 'Time' });
|
||||
|
||||
var options = {
|
||||
legend: { position: 'top' },
|
||||
titlePosition: 'none',
|
||||
vAxes: {
|
||||
// Adds units to the left hand side of the graph
|
||||
0: {title: key}
|
||||
},
|
||||
hAxis: {
|
||||
format: 'H:mm'
|
||||
},
|
||||
lineWidth: 1,
|
||||
chartArea:{left:'60',width:"95%"},
|
||||
explorer: {
|
||||
actions: ['dragToZoom', 'rightClickToReset', 'dragToPan'],
|
||||
keepInBounds: true,
|
||||
axis: 'horizontal',
|
||||
maxZoomIn: 0.1
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
if(this.isSingleDevice) {
|
||||
options.legend.position = 'none';
|
||||
options.vAxes[0].title = null;
|
||||
options.chartArea.left = 40;
|
||||
options.chartArea.height = '80%';
|
||||
options.chartArea.top = 5;
|
||||
options.enableInteractivity = false;
|
||||
}
|
||||
|
||||
// Get a unique list of times of state changes for all the device
|
||||
// for a particular unit of measureent.
|
||||
var times = _.pluck(_.flatten(deviceStates), "lastChangedAsDate");
|
||||
times = _.uniq(times, function(e) {
|
||||
return e.getTime();
|
||||
});
|
||||
|
||||
times = _.sortBy(times, function(o) { return o; });
|
||||
|
||||
var data = [];
|
||||
var empty = new Array(deviceStates.length);
|
||||
for(var i = 0; i < empty.length; i++) {
|
||||
empty[i] = 0;
|
||||
}
|
||||
|
||||
var timeIndex = 1;
|
||||
var endDate = new Date();
|
||||
var prevDate = times[0];
|
||||
|
||||
for(var i = 0; i < times.length; i++) {
|
||||
var currentDate = new Date(prevDate);
|
||||
|
||||
// because we only have state changes we add an extra point at the same time
|
||||
// that holds the previous state which makes the line display correctly
|
||||
var beforePoint = new Date(times[i]);
|
||||
data.push([beforePoint].concat(empty));
|
||||
|
||||
data.push([times[i]].concat(empty));
|
||||
prevDate = times[i];
|
||||
timeIndex++;
|
||||
}
|
||||
data.push([endDate].concat(empty));
|
||||
|
||||
|
||||
var deviceCount = 0;
|
||||
deviceStates.forEach(function(device) {
|
||||
var attributes = device[device.length - 1].attributes;
|
||||
dataTable.addColumn('number', attributes['friendly_name']);
|
||||
|
||||
var currentState = 0;
|
||||
var previousState = 0;
|
||||
var lastIndex = 0;
|
||||
var count = 0;
|
||||
var prevTime = data[0][0];
|
||||
device.forEach(function(state) {
|
||||
|
||||
currentState = state.state;
|
||||
var start = state.lastChangedAsDate;
|
||||
if(state.state == 'None') {
|
||||
currentState = previousState;
|
||||
}
|
||||
for(var i = lastIndex; i < data.length; i++) {
|
||||
data[i][1 + deviceCount] = parseFloat(previousState);
|
||||
// this is where data gets filled in for each time for the particular device
|
||||
// because for each time two entires were create we fill the first one with the
|
||||
// previous value and the second one with the new value
|
||||
if(prevTime.getTime() == data[i][0].getTime() && data[i][0].getTime() == start.getTime()) {
|
||||
data[i][1 + deviceCount] = parseFloat(currentState);
|
||||
lastIndex = i;
|
||||
prevTime = data[i][0];
|
||||
break;
|
||||
}
|
||||
prevTime = data[i][0];
|
||||
}
|
||||
|
||||
previousState = currentState;
|
||||
|
||||
count++;
|
||||
}.bind(this));
|
||||
|
||||
//fill in the rest of the Array
|
||||
for(var i = lastIndex; i < data.length; i++) {
|
||||
data[i][1 + deviceCount] = parseFloat(previousState);
|
||||
}
|
||||
|
||||
deviceCount++;
|
||||
}.bind(this));
|
||||
|
||||
dataTable.addRows(data);
|
||||
chart.draw(dataTable, options);
|
||||
}
|
||||
this.isLoading = (!this.isLoadingData) ? false : true;
|
||||
|
||||
},
|
||||
|
||||
});
|
||||
|
@ -11,7 +11,7 @@
|
||||
<div>
|
||||
<state-card-content stateObj="{{stateObj}}" style='margin-bottom: 24px;'>
|
||||
</state-card-content>
|
||||
<state-timeline stateHistory="{{stateHistory}}"></state-timeline>
|
||||
<state-timeline stateHistory="{{stateHistory}}" isLoadingData="{{isLoadingHistoryData}}"></state-timeline>
|
||||
<more-info-content
|
||||
stateObj="{{stateObj}}"
|
||||
dialogOpen="{{dialogOpen}}"></more-info-content>
|
||||
@ -30,6 +30,7 @@ Polymer(Polymer.mixin({
|
||||
stateHistory: null,
|
||||
hasHistoryComponent: false,
|
||||
dialogOpen: false,
|
||||
isLoadingHistoryData: false,
|
||||
|
||||
observe: {
|
||||
'stateObj.attributes': 'reposition'
|
||||
@ -67,7 +68,7 @@ Polymer(Polymer.mixin({
|
||||
} else {
|
||||
newHistory = null;
|
||||
}
|
||||
|
||||
this.isLoadingHistoryData = false;
|
||||
if (newHistory !== this.stateHistory) {
|
||||
this.stateHistory = newHistory;
|
||||
}
|
||||
@ -87,6 +88,7 @@ Polymer(Polymer.mixin({
|
||||
this.stateHistoryStoreChanged();
|
||||
|
||||
if (this.hasHistoryComponent && stateHistoryStore.isStale(entityId)) {
|
||||
this.isLoadingHistoryData = true;
|
||||
stateHistoryActions.fetch(entityId);
|
||||
}
|
||||
},
|
||||
|
@ -26,7 +26,7 @@
|
||||
</span>
|
||||
|
||||
<div flex class="{{ {content: true, narrow: narrow, wide: !narrow} | tokenList }}">
|
||||
<state-timeline stateHistory="{{stateHistory}}"></state-timeline>
|
||||
<state-timeline stateHistory="{{stateHistory}}" isLoadingData="{{isLoadingData}}"></state-timeline>
|
||||
</div>
|
||||
</partial-base>
|
||||
</template>
|
||||
@ -36,6 +36,7 @@
|
||||
|
||||
Polymer(Polymer.mixin({
|
||||
stateHistory: null,
|
||||
isLoadingData: false,
|
||||
|
||||
attached: function() {
|
||||
this.listenToStores(true);
|
||||
@ -47,13 +48,18 @@
|
||||
|
||||
stateHistoryStoreChanged: function(stateHistoryStore) {
|
||||
if (stateHistoryStore.isStale()) {
|
||||
this.isLoadingData = true;
|
||||
stateHistoryActions.fetchAll();
|
||||
}
|
||||
else {
|
||||
this.isLoadingData = false;
|
||||
}
|
||||
|
||||
this.stateHistory = stateHistoryStore.all;
|
||||
},
|
||||
|
||||
handleRefreshClick: function() {
|
||||
this.isLoadingData = true;
|
||||
stateHistoryActions.fetchAll();
|
||||
},
|
||||
}, storeListenerMixIn));
|
||||
|
@ -50,8 +50,10 @@ def state_changes_during_period(start_time, end_time=None, entity_id=None):
|
||||
|
||||
result = defaultdict(list)
|
||||
|
||||
entity_ids = [entity_id] if entity_id is not None else None
|
||||
|
||||
# Get the states at the start time
|
||||
for state in get_states(start_time):
|
||||
for state in get_states(start_time, entity_ids):
|
||||
state.last_changed = start_time
|
||||
result[state.entity_id].append(state)
|
||||
|
||||
@ -98,6 +100,7 @@ def get_state(point_in_time, entity_id, run=None):
|
||||
return states[0] if states else None
|
||||
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def setup(hass, config):
|
||||
""" Setup history hooks. """
|
||||
hass.http.register_path(
|
||||
@ -113,6 +116,7 @@ def setup(hass, config):
|
||||
return True
|
||||
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
# pylint: disable=invalid-name
|
||||
def _api_last_5_states(handler, path_match, data):
|
||||
""" Return the last 5 states for an entity id as JSON. """
|
||||
|
100
homeassistant/components/modbus.py
Normal file
100
homeassistant/components/modbus.py
Normal file
@ -0,0 +1,100 @@
|
||||
"""
|
||||
components.modbus
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
Modbus component, using pymodbus (python3 branch)
|
||||
|
||||
typical declaration in configuration.yaml
|
||||
|
||||
#Modbus TCP
|
||||
modbus:
|
||||
type: tcp
|
||||
host: 127.0.0.1
|
||||
port: 2020
|
||||
|
||||
#Modbus RTU
|
||||
modbus:
|
||||
type: serial
|
||||
method: rtu
|
||||
port: /dev/ttyUSB0
|
||||
baudrate: 9600
|
||||
stopbits: 1
|
||||
bytesize: 8
|
||||
parity: N
|
||||
|
||||
"""
|
||||
import logging
|
||||
|
||||
from homeassistant.const import (EVENT_HOMEASSISTANT_START,
|
||||
EVENT_HOMEASSISTANT_STOP)
|
||||
|
||||
# The domain of your component. Should be equal to the name of your component
|
||||
DOMAIN = "modbus"
|
||||
|
||||
# List of component names (string) your component depends upon
|
||||
DEPENDENCIES = []
|
||||
|
||||
# Type of network
|
||||
MEDIUM = "type"
|
||||
|
||||
# if MEDIUM == "serial"
|
||||
METHOD = "method"
|
||||
SERIAL_PORT = "port"
|
||||
BAUDRATE = "baudrate"
|
||||
STOPBITS = "stopbits"
|
||||
BYTESIZE = "bytesize"
|
||||
PARITY = "parity"
|
||||
|
||||
# if MEDIUM == "tcp" or "udp"
|
||||
HOST = "host"
|
||||
IP_PORT = "port"
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
NETWORK = None
|
||||
TYPE = None
|
||||
|
||||
|
||||
def setup(hass, config):
|
||||
""" Setup Modbus component. """
|
||||
|
||||
# Modbus connection type
|
||||
# pylint: disable=global-statement, import-error
|
||||
global TYPE
|
||||
TYPE = config[DOMAIN][MEDIUM]
|
||||
|
||||
# Connect to Modbus network
|
||||
# pylint: disable=global-statement, import-error
|
||||
global NETWORK
|
||||
|
||||
if TYPE == "serial":
|
||||
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
|
||||
NETWORK = ModbusClient(method=config[DOMAIN][METHOD],
|
||||
port=config[DOMAIN][SERIAL_PORT],
|
||||
baudrate=config[DOMAIN][BAUDRATE],
|
||||
stopbits=config[DOMAIN][STOPBITS],
|
||||
bytesize=config[DOMAIN][BYTESIZE],
|
||||
parity=config[DOMAIN][PARITY])
|
||||
elif TYPE == "tcp":
|
||||
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
|
||||
NETWORK = ModbusClient(host=config[DOMAIN][HOST],
|
||||
port=config[DOMAIN][IP_PORT])
|
||||
elif TYPE == "udp":
|
||||
from pymodbus.client.sync import ModbusUdpClient as ModbusClient
|
||||
NETWORK = ModbusClient(host=config[DOMAIN][HOST],
|
||||
port=config[DOMAIN][IP_PORT])
|
||||
else:
|
||||
return False
|
||||
|
||||
def stop_modbus(event):
|
||||
""" Stop Modbus service"""
|
||||
NETWORK.close()
|
||||
|
||||
def start_modbus(event):
|
||||
""" Start Modbus service"""
|
||||
NETWORK.connect()
|
||||
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_modbus)
|
||||
|
||||
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_modbus)
|
||||
|
||||
# Tells the bootstrapper that the component was succesfully initialized
|
||||
return True
|
136
homeassistant/components/sensor/modbus.py
Normal file
136
homeassistant/components/sensor/modbus.py
Normal file
@ -0,0 +1,136 @@
|
||||
"""
|
||||
Support for Modbus sensors.
|
||||
|
||||
Configuration:
|
||||
To use the Modbus sensors you will need to add something like the following to
|
||||
your config/configuration.yaml
|
||||
|
||||
sensor:
|
||||
platform: modbus
|
||||
slave: 1
|
||||
registers:
|
||||
16:
|
||||
name: My integer sensor
|
||||
unit: C
|
||||
24:
|
||||
bits:
|
||||
0:
|
||||
name: My boolean sensor
|
||||
2:
|
||||
name: My other boolean sensor
|
||||
|
||||
VARIABLES:
|
||||
|
||||
- "slave" = slave number (ignored and can be omitted if not serial Modbus)
|
||||
- "unit" = unit to attach to value (optional, ignored for boolean sensors)
|
||||
- "registers" contains a list of relevant registers to read from
|
||||
it can contain a "bits" section, listing relevant bits
|
||||
|
||||
- each named register will create an integer sensor
|
||||
- each named bit will create a boolean sensor
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
import homeassistant.components.modbus as modbus
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.const import (
|
||||
TEMP_CELCIUS, TEMP_FAHRENHEIT,
|
||||
STATE_ON, STATE_OFF)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
""" Read config and create Modbus devices """
|
||||
sensors = []
|
||||
slave = config.get("slave", None)
|
||||
if modbus.TYPE == "serial" and not slave:
|
||||
_LOGGER.error("No slave number provided for serial Modbus")
|
||||
return False
|
||||
registers = config.get("registers")
|
||||
for regnum, register in registers.items():
|
||||
if register.get("name"):
|
||||
sensors.append(ModbusSensor(register.get("name"),
|
||||
slave,
|
||||
regnum,
|
||||
None,
|
||||
register.get("unit")))
|
||||
if register.get("bits"):
|
||||
bits = register.get("bits")
|
||||
for bitnum, bit in bits.items():
|
||||
if bit.get("name"):
|
||||
sensors.append(ModbusSensor(bit.get("name"),
|
||||
slave,
|
||||
regnum,
|
||||
bitnum))
|
||||
add_devices(sensors)
|
||||
|
||||
|
||||
class ModbusSensor(Entity):
|
||||
# pylint: disable=too-many-arguments
|
||||
""" Represents a Modbus Sensor """
|
||||
|
||||
def __init__(self, name, slave, register, bit=None, unit=None):
|
||||
self._name = name
|
||||
self.slave = int(slave) if slave else 1
|
||||
self.register = int(register)
|
||||
self.bit = int(bit) if bit else None
|
||||
self._value = None
|
||||
self._unit = unit
|
||||
|
||||
def __str__(self):
|
||||
return "%s: %s" % (self.name, self.state)
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
""" We should poll, because slaves are not allowed to
|
||||
initiate communication on Modbus networks"""
|
||||
return True
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
""" Returns a unique id. """
|
||||
return "MODBUS-SENSOR-{}-{}-{}".format(self.slave,
|
||||
self.register,
|
||||
self.bit)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
""" Returns the state of the sensor. """
|
||||
if self.bit:
|
||||
return STATE_ON if self._value else STATE_OFF
|
||||
else:
|
||||
return self._value
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
""" Get the name of the sensor. """
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
""" Unit of measurement of this entity, if any. """
|
||||
if self._unit == "C":
|
||||
return TEMP_CELCIUS
|
||||
elif self._unit == "F":
|
||||
return TEMP_FAHRENHEIT
|
||||
else:
|
||||
return self._unit
|
||||
|
||||
@property
|
||||
def state_attributes(self):
|
||||
attr = super().state_attributes
|
||||
return attr
|
||||
|
||||
def update(self):
|
||||
result = modbus.NETWORK.read_holding_registers(unit=self.slave,
|
||||
address=self.register,
|
||||
count=1)
|
||||
val = 0
|
||||
for i, res in enumerate(result.registers):
|
||||
val += res * (2**(i*16))
|
||||
if self.bit:
|
||||
self._value = val & (0x0001 << self.bit)
|
||||
else:
|
||||
self._value = val
|
186
homeassistant/components/sensor/transmission.py
Normal file
186
homeassistant/components/sensor/transmission.py
Normal file
@ -0,0 +1,186 @@
|
||||
"""
|
||||
homeassistant.components.sensor.transmission
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Monitors Transmission BitTorrent client API
|
||||
|
||||
Configuration:
|
||||
|
||||
To use the Transmission sensor you will need to add something like the
|
||||
following to your config/configuration.yaml
|
||||
|
||||
sensor:
|
||||
platform: transmission
|
||||
name: Transmission
|
||||
host: 192.168.1.26
|
||||
port: 9091
|
||||
username: YOUR_USERNAME
|
||||
password: YOUR_PASSWORD
|
||||
monitored_variables:
|
||||
- type: 'current_status'
|
||||
- type: 'download_speed'
|
||||
- type: 'upload_speed'
|
||||
|
||||
VARIABLES:
|
||||
|
||||
host
|
||||
*Required
|
||||
This is the IP address of your Transmission Daemon
|
||||
Example: 192.168.1.32
|
||||
|
||||
port
|
||||
*Optional
|
||||
The port your Transmission daemon uses, defaults to 9091
|
||||
Example: 8080
|
||||
|
||||
username
|
||||
*Required
|
||||
Your Transmission username
|
||||
|
||||
password
|
||||
*Required
|
||||
Your Transmission password
|
||||
|
||||
name
|
||||
*Optional
|
||||
The name to use when displaying this Transmission instance
|
||||
|
||||
monitored_variables
|
||||
*Required
|
||||
An array specifying the variables to monitor.
|
||||
|
||||
These are the variables for the monitored_variables array:
|
||||
|
||||
type
|
||||
*Required
|
||||
The variable you wish to monitor, see the configuration example above for a
|
||||
list of all available variables
|
||||
|
||||
|
||||
"""
|
||||
|
||||
from homeassistant.util import Throttle
|
||||
from datetime import timedelta
|
||||
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
|
||||
|
||||
from homeassistant.helpers.entity import Entity
|
||||
# pylint: disable=no-name-in-module, import-error
|
||||
import transmissionrpc
|
||||
|
||||
from transmissionrpc.error import TransmissionError
|
||||
|
||||
import logging
|
||||
|
||||
SENSOR_TYPES = {
|
||||
'current_status': ['Status', ''],
|
||||
'download_speed': ['Down Speed', 'MB/s'],
|
||||
'upload_speed': ['Up Speed', 'MB/s']
|
||||
}
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_THROTTLED_REFRESH = None
|
||||
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
""" Sets up the sensors """
|
||||
host = config.get(CONF_HOST)
|
||||
username = config.get(CONF_USERNAME, None)
|
||||
password = config.get(CONF_PASSWORD, None)
|
||||
port = config.get('port', 9091)
|
||||
|
||||
name = config.get("name", "Transmission")
|
||||
if not host:
|
||||
_LOGGER.error('Missing config variable %s', CONF_HOST)
|
||||
return False
|
||||
|
||||
# import logging
|
||||
# logging.getLogger('transmissionrpc').setLevel(logging.DEBUG)
|
||||
|
||||
transmission_api = transmissionrpc.Client(
|
||||
host, port=port, user=username, password=password)
|
||||
try:
|
||||
transmission_api.session_stats()
|
||||
except TransmissionError:
|
||||
_LOGGER.exception("Connection to Transmission API failed.")
|
||||
return False
|
||||
|
||||
# pylint: disable=global-statement
|
||||
global _THROTTLED_REFRESH
|
||||
_THROTTLED_REFRESH = Throttle(timedelta(seconds=1))(
|
||||
transmission_api.session_stats)
|
||||
|
||||
dev = []
|
||||
for variable in config['monitored_variables']:
|
||||
if variable['type'] not in SENSOR_TYPES:
|
||||
_LOGGER.error('Sensor type: "%s" does not exist', variable['type'])
|
||||
else:
|
||||
dev.append(TransmissionSensor(
|
||||
variable['type'], transmission_api, name))
|
||||
|
||||
add_devices(dev)
|
||||
|
||||
|
||||
class TransmissionSensor(Entity):
|
||||
""" A Transmission sensor """
|
||||
|
||||
def __init__(self, sensor_type, transmission_client, client_name):
|
||||
self._name = SENSOR_TYPES[sensor_type][0]
|
||||
self.transmission_client = transmission_client
|
||||
self.type = sensor_type
|
||||
self.client_name = client_name
|
||||
self._state = None
|
||||
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self.client_name + ' ' + self._name
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
""" Returns the state of the device. """
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
""" Unit of measurement of this entity, if any. """
|
||||
return self._unit_of_measurement
|
||||
|
||||
def refresh_transmission_data(self):
|
||||
""" Calls the throttled Transmission refresh method. """
|
||||
if _THROTTLED_REFRESH is not None:
|
||||
try:
|
||||
_THROTTLED_REFRESH()
|
||||
except TransmissionError:
|
||||
_LOGGER.exception(
|
||||
self.name + " Connection to Transmission API failed."
|
||||
)
|
||||
|
||||
def update(self):
|
||||
""" Gets the latest from Transmission and updates the state. """
|
||||
self.refresh_transmission_data()
|
||||
if self.type == 'current_status':
|
||||
if self.transmission_client.session:
|
||||
upload = self.transmission_client.session.uploadSpeed
|
||||
download = self.transmission_client.session.downloadSpeed
|
||||
if upload > 0 and download > 0:
|
||||
self._state = 'Up/Down'
|
||||
elif upload > 0 and download == 0:
|
||||
self._state = 'Seeding'
|
||||
elif upload == 0 and download > 0:
|
||||
self._state = 'Downloading'
|
||||
else:
|
||||
self._state = 'Idle'
|
||||
else:
|
||||
self._state = 'Unknown'
|
||||
|
||||
if self.transmission_client.session:
|
||||
if self.type == 'download_speed':
|
||||
mb_spd = float(self.transmission_client.session.downloadSpeed)
|
||||
mb_spd = mb_spd / 1024 / 1024
|
||||
self._state = round(mb_spd, 2 if mb_spd < 0.1 else 1)
|
||||
elif self.type == 'upload_speed':
|
||||
mb_spd = float(self.transmission_client.session.uploadSpeed)
|
||||
mb_spd = mb_spd / 1024 / 1024
|
||||
self._state = round(mb_spd, 2 if mb_spd < 0.1 else 1)
|
121
homeassistant/components/switch/modbus.py
Normal file
121
homeassistant/components/switch/modbus.py
Normal file
@ -0,0 +1,121 @@
|
||||
"""
|
||||
Support for Modbus switches.
|
||||
|
||||
Configuration:
|
||||
To use the Modbus switches you will need to add something like the following to
|
||||
your config/configuration.yaml
|
||||
|
||||
sensor:
|
||||
platform: modbus
|
||||
slave: 1
|
||||
registers:
|
||||
24:
|
||||
bits:
|
||||
0:
|
||||
name: My switch
|
||||
2:
|
||||
name: My other switch
|
||||
|
||||
VARIABLES:
|
||||
|
||||
- "slave" = slave number (ignored and can be omitted if not serial Modbus)
|
||||
- "registers" contains a list of relevant registers to read from
|
||||
- it must contain a "bits" section, listing relevant bits
|
||||
|
||||
- each named bit will create a switch
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
import homeassistant.components.modbus as modbus
|
||||
from homeassistant.helpers.entity import ToggleEntity
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
""" Read config and create Modbus devices """
|
||||
switches = []
|
||||
slave = config.get("slave", None)
|
||||
if modbus.TYPE == "serial" and not slave:
|
||||
_LOGGER.error("No slave number provided for serial Modbus")
|
||||
return False
|
||||
registers = config.get("registers")
|
||||
for regnum, register in registers.items():
|
||||
bits = register.get("bits")
|
||||
for bitnum, bit in bits.items():
|
||||
if bit.get("name"):
|
||||
switches.append(ModbusSwitch(bit.get("name"),
|
||||
slave,
|
||||
regnum,
|
||||
bitnum))
|
||||
add_devices(switches)
|
||||
|
||||
|
||||
class ModbusSwitch(ToggleEntity):
|
||||
""" Represents a Modbus Switch """
|
||||
|
||||
def __init__(self, name, slave, register, bit):
|
||||
self._name = name
|
||||
self.slave = int(slave) if slave else 1
|
||||
self.register = int(register)
|
||||
self.bit = int(bit)
|
||||
self._is_on = None
|
||||
self.register_value = None
|
||||
|
||||
def __str__(self):
|
||||
return "%s: %s" % (self.name, self.state)
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
""" We should poll, because slaves are not allowed to
|
||||
initiate communication on Modbus networks"""
|
||||
return True
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
""" Returns a unique id. """
|
||||
return "MODBUS-SWITCH-{}-{}-{}".format(self.slave,
|
||||
self.register,
|
||||
self.bit)
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
""" Returns True if switch is on. """
|
||||
return self._is_on
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
""" Get the name of the switch. """
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def state_attributes(self):
|
||||
attr = super().state_attributes
|
||||
return attr
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
if self.register_value is None:
|
||||
self.update()
|
||||
val = self.register_value | (0x0001 << self.bit)
|
||||
modbus.NETWORK.write_register(unit=self.slave,
|
||||
address=self.register,
|
||||
value=val)
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
if self.register_value is None:
|
||||
self.update()
|
||||
val = self.register_value & ~(0x0001 << self.bit)
|
||||
modbus.NETWORK.write_register(unit=self.slave,
|
||||
address=self.register,
|
||||
value=val)
|
||||
|
||||
def update(self):
|
||||
result = modbus.NETWORK.read_holding_registers(unit=self.slave,
|
||||
address=self.register,
|
||||
count=1)
|
||||
val = 0
|
||||
for i, res in enumerate(result.registers):
|
||||
val += res * (2**(i*16))
|
||||
self.register_value = val
|
||||
self._is_on = (val & (0x0001 << self.bit) > 0)
|
@ -42,3 +42,6 @@ psutil>=2.2.1
|
||||
|
||||
#pushover notifications
|
||||
python-pushover>=0.2
|
||||
|
||||
# Transmission Torrent Client
|
||||
transmissionrpc>=0.11
|
||||
|
78
scripts/homeassistant-pi.sh
Executable file
78
scripts/homeassistant-pi.sh
Executable file
@ -0,0 +1,78 @@
|
||||
#!/bin/sh
|
||||
|
||||
# To script is for running Home Assistant as a service and automatically starting it on boot.
|
||||
# Assuming you have cloned the HA repo into /home/pi/Apps/home-assistant adjust this path if necessary
|
||||
# This also assumes you installed HA on your raspberry pi using the instructions here:
|
||||
# https://home-assistant.io/getting-started/
|
||||
#
|
||||
# To install to the following:
|
||||
# sudo cp /home/pi/Apps/home-assistant/scripts/homeassistant-pi.sh /etc/init.d/homeassistant.sh
|
||||
# sudo chmod +x /etc/init.d/homeassistant.sh
|
||||
# sudo chown root:root /etc/init.d/homeassistant.sh
|
||||
#
|
||||
# If you want HA to start on boot also run the following:
|
||||
# sudo update-rc.d homeassistant.sh defaults
|
||||
# sudo update-rc.d homeassistant.sh enable
|
||||
#
|
||||
# You should now be able to start HA by running
|
||||
# sudo /etc/init.d/homeassistant.sh start
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: myservice
|
||||
# Required-Start: $remote_fs $syslog
|
||||
# Required-Stop: $remote_fs $syslog
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: Put a short description of the service here
|
||||
# Description: Put a long description of the service here
|
||||
### END INIT INFO
|
||||
|
||||
# Change the next 3 lines to suit where you install your script and what you want to call it
|
||||
DIR=/home/pi/Apps/home-assistant
|
||||
DAEMON="/home/pi/.pyenv/shims/python3 -m homeassistant"
|
||||
DAEMON_NAME=homeassistant
|
||||
|
||||
# Add any command line options for your daemon here
|
||||
DAEMON_OPTS=""
|
||||
|
||||
# This next line determines what user the script runs as.
|
||||
# Root generally not recommended but necessary if you are using the Raspberry Pi GPIO from Python.
|
||||
DAEMON_USER=pi
|
||||
|
||||
# The process ID of the script when it runs is stored here:
|
||||
PIDFILE=/var/run/$DAEMON_NAME.pid
|
||||
|
||||
. /lib/lsb/init-functions
|
||||
|
||||
do_start () {
|
||||
log_daemon_msg "Starting system $DAEMON_NAME daemon"
|
||||
start-stop-daemon --start --background --chdir $DIR --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
|
||||
log_end_msg $?
|
||||
}
|
||||
do_stop () {
|
||||
log_daemon_msg "Stopping system $DAEMON_NAME daemon"
|
||||
start-stop-daemon --stop --pidfile $PIDFILE --retry 10
|
||||
log_end_msg $?
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
|
||||
start|stop)
|
||||
do_${1}
|
||||
;;
|
||||
|
||||
restart|reload|force-reload)
|
||||
do_stop
|
||||
do_start
|
||||
;;
|
||||
|
||||
status)
|
||||
status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
|
||||
;;
|
||||
*)
|
||||
echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
|
||||
exit 1
|
||||
;;
|
||||
|
||||
esac
|
||||
exit 0
|
Loading…
x
Reference in New Issue
Block a user