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:
Ryan Kraus committed 2015-04-22 21:04:52 -04:00
commit 2b4c75543a
14 files changed
+864 -22

No files matched your search

+1
View File
@@ -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]
+1 -11
View File
@@ -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 -1
View File
@@ -1,2 +1,2 @@
""" DO NOT MODIFY. Auto-generated by build_frontend script """
VERSION = "9e21c99d2991dd288287d3d3bc3e64e0"
VERSION = "e7801905cc2ea1ee349ec199604fb984"
@@ -18,4 +18,4 @@ for(r&&o&&(n=t[++i]);++i<o;)n=e(n,t[i],i,t);return n}function ae(t,e,n,r){var i=
escape:bt,evaluate:Ot,interpolate:It,variable:"",imports:{_:e}};var yu=function(){function e(){}return function(n){if(hi(n)){e.prototype=n;var r=new e;e.prototype=null}return r||t.Object()}}(),du=nn(Ie),gu=nn(Se,!0),mu=rn(),wu=rn(!0),Tu=pu?function(t,e){return pu.set(t,e),t}:eo;zo||(Xe=Lo&&Fo?function(t){var e=t.byteLength,n=Jo?Uo(e/lu):0,r=n*lu,i=new Lo(e);if(n){var o=new Jo(i,0,n);o.set(new Jo(t,0,n))}return e!=r&&(o=new Fo(i,r),o.set(new Fo(t,r))),i}:to(null));var Eu=Xo&&Ko?function(t){return new Ft(t)}:to(null),bu=pu?function(t){return pu.get(t)}:uo,Ou=function(){return vu.funcNames?"constant"==to.name?Le("name"):function(t){for(var e=t.name,n=_u[e],r=n?n.length:0;r--;){var i=n[r],o=i.func;if(null==o||o==t)return i.name}return e}:to("")}(),Iu=function(){var t=0,e=0;return function(n,r){var i=Fu(),o=W-(i-e);if(e=i,o>0){if(++t>=U)return n}else t=0;return Tu(n,r)}}(),Su=Qr(function(t,e){return ua(t)||oi(t)?ge(t,be(e,!1,!0)):[]}),Au=ln(),Nu=ln(!0),Cu=Qr(function(t,e){t||(t=[]),e=be(e);var n=e.length,r=pe(t,e);for(e.sort(o);n--;){var i=parseFloat(e[n]);if(i!=u&&jn(i)){var u=i;Ho.call(t,i,1)}}return r}),Du=bn(),xu=bn(!0),Ru=Qr(function(t){return Ke(be(t,!1,!0))}),Mu=Qr(function(t,e){return ua(t)||oi(t)?ge(t,e):[]}),ku=Qr(mr),ju=Qr(function(t,e){var n=t?t.length:0;return qn(n)&&(t=Hn(t)),pe(t,be(e))}),Lu=tn(function(t,e,n){xo.call(t,n)?++t[n]:t[n]=1}),zu=fn(du),qu=fn(gu,!0),Pu=_n(Xt,du),Uu=_n(Zt,gu),Wu=tn(function(t,e,n){xo.call(t,n)?t[n].push(e):t[n]=[e]}),Vu=tn(function(t,e,n){t[n]=e}),Gu=Qr(function(t,e,n){var r=-1,i="function"==typeof e,o=t?t.length:0,u=qn(o)?_o(o):[];return du(t,function(t){var o=i?e:null!=t&&t[e];u[++r]=o?o.apply(t,n):A}),u}),Ku=tn(function(t,e,n){t[n?0:1].push(e)},function(){return[[],[]]}),$u=mn(ue,du),Hu=mn(ae,gu),Fu=nu||function(){return(new vo).getTime()},Bu=Qr(function(t,e,n){var r=C;if(n.length){var i=T(n,Bu.placeholder);r|=k}return On(t,r,e,n,i)}),Ju=Qr(function(t,e){e=e.length?be(e):Ii(t);for(var n=-1,r=e.length;++n<r;){var i=e[n];t[i]=On(t[i],C,t)}return t}),Yu=Qr(function(t,e,n){var r=C|D;if(n.length){var i=T(n,Yu.placeholder);r|=k}return On(e,r,t,n,i)}),Xu=sn(R),Zu=sn(M),Qu=Qr(function(t,e){return de(t,1,e)}),ta=Qr(function(t,e,n){return de(t,e,n)}),ea=pn(),na=pn(!0),ra=gn(k),ia=gn(j),oa=Qr(function(t,e){return On(t,z,null,null,null,be(e))}),ua=Yo||function(t){return m(t)&&qn(t.length)&&Mo.call(t)==B};vu.dom||(si=function(t){return!!t&&1===t.nodeType&&m(t)&&!ca(t)});var aa=ru||function(t){return"number"==typeof t&&Zo(t)},sa=s(/x/)||Fo&&!s(Fo)?function(t){return Mo.call(t)==Z}:s,ca=Wo?function(t){if(!t||Mo.call(t)!=et)return!1;var e=t.valueOf,n=vi(e)&&(n=Wo(e))&&Wo(n);return n?t==n||Wo(t)==n:Kn(t)}:Kn,fa=en(he),la=Qr(function(t){var e=t[0];return null==e?e:(t.push(fe),fa.apply(A,t))}),ha=hn(Ie),pa=hn(Se),_a=vn(mu),va=vn(wu),ya=yn(Ie),da=yn(Se),ga=Qo?function(t){if(t)var e=t.constructor,n=t.length;return"function"==typeof e&&e.prototype===t||"function"!=typeof t&&n&&qn(n)?$n(t):hi(t)?Qo(t):[]}:$n,ma=en(ke),wa=Qr(function(t,e){if(null==t)return{};if("function"!=typeof e[0]){var e=re(be(e),bo);return Wn(t,ge(Ni(t),e))}var n=Ye(e[0],e[1],3);return Vn(t,function(t,e,r){return!n(t,e,r)})}),Ta=Qr(function(t,e){return null==t?{}:"function"==typeof e[0]?Vn(t,Ye(e[0],e[1],3)):Wn(t,be(e))}),Ea=un(function(t,e,n){return e=e.toLowerCase(),t+(n?e.charAt(0).toUpperCase()+e.slice(1):e)}),ba=un(function(t,e,n){return t+(n?"-":"")+e.toLowerCase()}),Oa=dn(),Ia=dn(!0);8!=iu(zt+"08")&&(Gi=function(t,e,n){return(n?Ln(t,e,n):null==e)?e=0:e&&(e=+e),t=Fi(t),iu(t,e||(Ct.test(t)?16:10))});var Sa=un(function(t,e,n){return t+(n?"_":"")+e.toLowerCase()}),Aa=un(function(t,e,n){return t+(n?" ":"")+(e.charAt(0).toUpperCase()+e.slice(1))}),Na=Qr(function(t,e){try{return t.apply(A,e)}catch(n){return li(n)?n:new yo(n)}}),Ca=cn(ie),Da=cn(oe,!0);return e.prototype=n.prototype,r.prototype=yu(n.prototype),r.prototype.constructor=r,i.prototype=yu(n.prototype),i.prototype.constructor=i,ot.prototype["delete"]=Gt,ot.prototype.get=Kt,ot.prototype.has=$t,ot.prototype.set=Ht,Ft.prototype.push=Jt,Yr.Cache=ot,e.after=Hr,e.ary=Fr,e.assign=fa,e.at=ju,e.before=Br,e.bind=Bu,e.bindAll=Ju,e.bindKey=Yu,e.callback=Qi,e.chain=Er,e.chunk=Jn,e.compact=Yn,e.constant=to,e.countBy=Lu,e.create=Oi,e.curry=Xu,e.curryRight=Zu,e.debounce=Jr,e.defaults=la,e.defer=Qu,e.delay=ta,e.difference=Su,e.drop=Xn,e.dropRight=Zn,e.dropRightWhile=Qn,e.dropWhile=tr,e.fill=er,e.filter=Rr,e.flatten=rr,e.flattenDeep=ir,e.flow=ea,e.flowRight=na,e.forEach=Pu,e.forEachRight=Uu,e.forIn=_a,e.forInRight=va,e.forOwn=ya,e.forOwnRight=da,e.functions=Ii,e.groupBy=Wu,e.indexBy=Vu,e.initial=ur,e.intersection=ar,e.invert=Ai,e.invoke=Gu,e.keys=ga,e.keysIn=Ni,e.map=jr,e.mapValues=Ci,e.matches=no,e.matchesProperty=ro,e.memoize=Yr,e.merge=ma,e.mixin=io,e.negate=Xr,e.omit=wa,e.once=Zr,e.pairs=Di,e.partial=ra,e.partialRight=ia,e.partition=Ku,e.pick=Ta,e.pluck=Lr,e.property=ao,e.propertyOf=so,e.pull=fr,e.pullAt=Cu,e.range=co,e.rearg=oa,e.reject=zr,e.remove=lr,e.rest=hr,e.restParaLine truncated
servicesLoaded:{get:function(){return r(f.ACTION_NEW_SERVICES)}},statesLoaded:{get:function(){return r(f.ACTION_NEW_STATES)}}}),e}(l),y=new v;y.dispatchToken=c.register(function(t){switch(t.actionType){case f.ACTION_FETCH_ALL:_=[],y.emitChange();break;case f.ACTION_NEW_LOADED_COMPONENTS:case f.ACTION_NEW_EVENTS:case f.ACTION_NEW_SERVICES:case f.ACTION_NEW_STATES:r(t.actionType)||(_.push(t.actionType),p=p||i(),y.emitChange());break;case f.ACTION_LOG_OUT:p=!1,_=[],y.emitChange()}}),t.exports=y},function(t,e,n){"use strict";var r=function(t){return t&&t.__esModule?t["default"]:t},i=function(){function t(t,e){for(var n in e){var r=e[n];r.configurable=!0,r.value&&(r.writable=!0)}Object.defineProperties(t,e)}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)},u=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},a=r(n(1)),s=r(n(2)),c=r(n(3)),f="STATE_LISTENING",l="STATE_TRANSMITTING",h="STATE_IDLE",p="STATE_ERROR",_=h,v="",y="",d=function(t){function e(){u(this,e),null!=t&&t.apply(this,arguments)}return o(e,t),i(e,{state:{get:function(){return _}},isListening:{get:function(){return _===f}},isTransmitting:{get:function(){return _===l}},hasError:{get:function(){return _===p}},interimTranscript:{get:function(){return v}},finalTranscript:{get:function(){return y}}}),e}(c),g=new d;g.STATE_LISTENING=f,g.STATE_TRANSMITTING=l,g.STATE_IDLE=h,g.STATE_ERROR=p,g.dispatchToken=a.register(function(t){switch(t.actionType){case s.ACTION_LISTENING_START:_=f,v="",y="",g.emitChange();break;case s.ACTION_LISTENING_TRANSMITTING:_=l,v="",y=t.finalTranscript,g.emitChange();break;case s.ACTION_LISTENING_DONE:_=h,g.emitChange();break;case s.ACTION_LISTENING_ERROR:_=p,g.emitChange();break;case s.ACTION_LISTENING_RESULT:v=t.interimTranscript,y=t.finalTranscript,g.emitChange()}}),t.exports=g},function(t,e,n){"use strict";function r(t){var e=t.split(" "),n=i(e,2),r=n[0],o=n[1],u=r.split(":"),a=i(u,3),s=a[0],c=a[1],f=a[2],l=o.split("-"),h=i(l,3),p=h[0],_=h[1],v=h[2];return new Date(v,parseInt(_)-1,p,s,c,f)}var i=function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t)){for(var n,r=[],i=t[Symbol.iterator]();!(n=i.next()).done&&(r.push(n.value),!e||r.length!==e););return r}throw new TypeError("Invalid attempt to destructure non-iterable instance")};e.parseDateTime=r,Object.defineProperty(e,"__esModule",{value:!0})},function(t,e,n){"use strict";function r(t){a.dispatch({actionType:s.ACTION_NEW_LOADED_COMPONENTS,components:t})}function i(){return u("GET","components").then(r)}var o=function(t){return t&&t.__esModule?t["default"]:t};e.newLoaded=r,e.fetchAll=i,Object.defineProperty(e,"__esModule",{value:!0});var u=o(n(5)),a=o(n(1)),s=o(n(2))},function(t,e,n){"use strict";function r(t){s.dispatch({actionType:c.ACTION_NEW_EVENTS,events:t})}function i(){a("GET","events").then(r)}function o(t){var e=void 0===arguments[1]?{}:arguments[1];return a("POST","events/"+t,e).then(function(){f("Event "+t+" successful fired!"),s.dispatch({actionType:c.ACTION_EVENT_FIRED,eventType:t,eventData:e})})}var u=function(t){return t&&t.__esModule?t["default"]:t};e.newEvents=r,e.fetchAll=i,e.fire=o,Object.defineProperty(e,"__esModule",{value:!0});var a=u(n(5)),s=u(n(1)),c=u(n(2)),f=n(10).notify},function(t,e,n){"use strict";function r(){return"EventSource"in window}function i(t){null!==p&&y();var e="/api/stream";t&&(e+="?api_password="+t),p=new EventSource(e),_=t,p.addEventListener("open",function(){v(),c.dispatch({actionType:f.ACTION_STREAM_START}),l.stop(),l.fetchAll()},!1),p.addEventListener("message",function(t){v(),"ping"!==t.data&&c.dispatch({actionType:f.ACTION_REMOTE_EVENT_RECEIVED,event:JSON.parse(t.data)})},!1),p.addEventListener("error",function(){p.readyState!==EventSource.CLOSED&&c.dispatch({actionType:f.ACTION_STREAM_ERROR})},!1)}function o(){y(),c.dispatch({actionType:f.ACTION_STREAM_STOP}),l.start()}var u=function(t){return t&&t.__esModule?t:{"default":t}},a=function(t){return t&&t.__esModule?t["default"]:t};e.isSupported=r,e.start=i,e.stop=o,Object.defineProperty(e,"__esModule",{value:!0});var s=a(n(6)),c=a(n(1)),f=a(n(2)),l=u(n(13)),h=6e4,p=null,_=null,v=s.debounce(function(){i(_)},h),y=function(){p.close(),p=null,_=null,v.cancel()}},function(t,e,n){"use strict";function r(t,e){var n=e.useStreaming,r=void 0===n?l.isSupported:n,i=e.rememberLogin,o=void 0===i?!1:i;s.dispatch({actionType:c.ACTION_VALIDATING_AUTH_TOKEN}),a("GET","",!1,{authToken:t}).then(function(){s.dispatch({actionType:c.ACTION_VALID_AUTH_TOKEN,authToken:t,rememberLogin:o}),r?l.start(t):f.start()},function(t){s.dispatch({actionType:c.ACTION_INVALID_AUTH_TOKEN,message:t.message})})}function i(){s.dispatch({actionType:c.ACTION_LOG_OUT})}var o=function(t){reLine truncated
return pickBy("isBefore",args)};moment.max=function(){var args=[].slice.call(arguments,0);return pickBy("isAfter",args)};moment.utc=function(input,format,locale,strict){var c;if(typeof locale==="boolean"){strict=locale;locale=undefined}c={};c._isAMomentObject=true;c._useUTC=true;c._isUTC=true;c._l=locale;c._i=input;c._f=format;c._strict=strict;c._pf=defaultParsingFlags();return makeMoment(c).utc()};moment.unix=function(input){return moment(input*1e3)};moment.duration=function(input,key){var duration=input,match=null,sign,ret,parseIso,diffRes;if(moment.isDuration(input)){duration={ms:input._milliseconds,d:input._days,M:input._months}}else if(typeof input==="number"){duration={};if(key){duration[key]=input}else{duration.milliseconds=input}}else if(!!(match=aspNetTimeSpanJsonRegex.exec(input))){sign=match[1]==="-"?-1:1;duration={y:0,d:toInt(match[DATE])*sign,h:toInt(match[HOUR])*sign,m:toInt(match[MINUTE])*sign,s:toInt(match[SECOND])*sign,ms:toInt(match[MILLISECOND])*sign}}else if(!!(match=isoDurationRegex.exec(input))){sign=match[1]==="-"?-1:1;parseIso=function(inp){var res=inp&&parseFloat(inp.replace(",","."));return(isNaN(res)?0:res)*sign};duration={y:parseIso(match[2]),M:parseIso(match[3]),d:parseIso(match[4]),h:parseIso(match[5]),m:parseIso(match[6]),s:parseIso(match[7]),w:parseIso(match[8])}}else if(duration==null){duration={}}else if(typeof duration==="object"&&("from"in duration||"to"in duration)){diffRes=momentsDifference(moment(duration.from),moment(duration.to));duration={};duration.ms=diffRes.milliseconds;duration.M=diffRes.months}ret=new Duration(duration);if(moment.isDuration(input)&&hasOwnProp(input,"_locale")){ret._locale=input._locale}return ret};moment.version=VERSION;moment.defaultFormat=isoFormat;moment.ISO_8601=function(){};moment.momentProperties=momentProperties;moment.updateOffset=function(){};moment.relativeTimeThreshold=function(threshold,limit){if(relativeTimeThresholds[threshold]===undefined){return false}if(limit===undefined){return relativeTimeThresholds[threshold]}relativeTimeThresholds[threshold]=limit;return true};moment.lang=deprecate("moment.lang is deprecated. Use moment.locale instead.",function(key,value){return moment.locale(key,value)});moment.locale=function(key,values){var data;if(key){if(typeof values!=="undefined"){data=moment.defineLocale(key,values)}else{data=moment.localeData(key)}if(data){moment.duration._locale=moment._locale=data}}return moment._locale._abbr};moment.defineLocale=function(name,values){if(values!==null){values.abbr=name;if(!locales[name]){locales[name]=new Locale}locales[name].set(values);moment.locale(name);return locales[name]}else{delete locales[name];return null}};moment.langData=deprecate("moment.langData is deprecated. Use moment.localeData instead.",function(key){return moment.localeData(key)});moment.localeData=function(key){var locale;if(key&&key._locale&&key._locale._abbr){key=key._locale._abbr}if(!key){return moment._locale}if(!isArray(key)){locale=loadLocale(key);if(locale){return locale}key=[key]}return chooseLocale(key)};moment.isMoment=function(obj){return obj instanceof Moment||obj!=null&&hasOwnProp(obj,"_isAMomentObject")};moment.isDuration=function(obj){return obj instanceof Duration};for(i=lists.length-1;i>=0;--i){makeList(lists[i])}moment.normalizeUnits=function(units){return normalizeUnits(units)};moment.invalid=function(flags){var m=moment.utc(NaN);if(flags!=null){extend(m._pf,flags)}else{m._pf.userInvalidated=true}return m};moment.parseZone=function(){return moment.apply(null,arguments).parseZone()};moment.parseTwoDigitYear=function(input){return toInt(input)+(toInt(input)>68?1900:2e3)};moment.isDate=isDate;extend(moment.fn=Moment.prototype,{clone:function(){return moment(this)},valueOf:function(){return+this._d-(this._offset||0)*6e4},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){var m=moment(this).utc();if(0<m.year()&&m.year()<=9999){if("function"===typeof Date.prototype.toISOString){return this.toDate().toISOString()}else{return formatMoment(m,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}}else{return formatMoment(m,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}},toArray:function(){var m=this;return[m.year(),m.month(),m.date(),m.hours(),m.minutes(),m.seconds(),m.milliseconds()]},isValid:function(){return isValid(this)},isDSTShifted:function(){if(this._a){return this.isValid()&&compareArrays(this._a,(this._isUTC?moment.utc(this._a):moment(this._a)).toArray())>0}return false},parsingFlags:function(){return extend({},this._pf)},invalidAt:function(){return this._pf.overflow},utc:function(keepLocalTime){return this.utcOffset(0,keepLocalTime)},local:function(keepLocalTime){if(this._isUTC){this.utcOffset(0,keepLocalTime);this._isUTC=false;if(keepLocalTime){this.subtract(this._dateUtcOffset(),"m")}}return this},format:function(inputString){var output=formatMoment(this,inputSLine truncated
return pickBy("isBefore",args)};moment.max=function(){var args=[].slice.call(arguments,0);return pickBy("isAfter",args)};moment.utc=function(input,format,locale,strict){var c;if(typeof locale==="boolean"){strict=locale;locale=undefined}c={};c._isAMomentObject=true;c._useUTC=true;c._isUTC=true;c._l=locale;c._i=input;c._f=format;c._strict=strict;c._pf=defaultParsingFlags();return makeMoment(c).utc()};moment.unix=function(input){return moment(input*1e3)};moment.duration=function(input,key){var duration=input,match=null,sign,ret,parseIso,diffRes;if(moment.isDuration(input)){duration={ms:input._milliseconds,d:input._days,M:input._months}}else if(typeof input==="number"){duration={};if(key){duration[key]=input}else{duration.milliseconds=input}}else if(!!(match=aspNetTimeSpanJsonRegex.exec(input))){sign=match[1]==="-"?-1:1;duration={y:0,d:toInt(match[DATE])*sign,h:toInt(match[HOUR])*sign,m:toInt(match[MINUTE])*sign,s:toInt(match[SECOND])*sign,ms:toInt(match[MILLISECOND])*sign}}else if(!!(match=isoDurationRegex.exec(input))){sign=match[1]==="-"?-1:1;parseIso=function(inp){var res=inp&&parseFloat(inp.replace(",","."));return(isNaN(res)?0:res)*sign};duration={y:parseIso(match[2]),M:parseIso(match[3]),d:parseIso(match[4]),h:parseIso(match[5]),m:parseIso(match[6]),s:parseIso(match[7]),w:parseIso(match[8])}}else if(duration==null){duration={}}else if(typeof duration==="object"&&("from"in duration||"to"in duration)){diffRes=momentsDifference(moment(duration.from),moment(duration.to));duration={};duration.ms=diffRes.milliseconds;duration.M=diffRes.months}ret=new Duration(duration);if(moment.isDuration(input)&&hasOwnProp(input,"_locale")){ret._locale=input._locale}return ret};moment.version=VERSION;moment.defaultFormat=isoFormat;moment.ISO_8601=function(){};moment.momentProperties=momentProperties;moment.updateOffset=function(){};moment.relativeTimeThreshold=function(threshold,limit){if(relativeTimeThresholds[threshold]===undefined){return false}if(limit===undefined){return relativeTimeThresholds[threshold]}relativeTimeThresholds[threshold]=limit;return true};moment.lang=deprecate("moment.lang is deprecated. Use moment.locale instead.",function(key,value){return moment.locale(key,value)});moment.locale=function(key,values){var data;if(key){if(typeof values!=="undefined"){data=moment.defineLocale(key,values)}else{data=moment.localeData(key)}if(data){moment.duration._locale=moment._locale=data}}return moment._locale._abbr};moment.defineLocale=function(name,values){if(values!==null){values.abbr=name;if(!locales[name]){locales[name]=new Locale}locales[name].set(values);moment.locale(name);return locales[name]}else{delete locales[name];return null}};moment.langData=deprecate("moment.langData is deprecated. Use moment.localeData instead.",function(key){return moment.localeData(key)});moment.localeData=function(key){var locale;if(key&&key._locale&&key._locale._abbr){key=key._locale._abbr}if(!key){return moment._locale}if(!isArray(key)){locale=loadLocale(key);if(locale){return locale}key=[key]}return chooseLocale(key)};moment.isMoment=function(obj){return obj instanceof Moment||obj!=null&&hasOwnProp(obj,"_isAMomentObject")};moment.isDuration=function(obj){return obj instanceof Duration};for(i=lists.length-1;i>=0;--i){makeList(lists[i])}moment.normalizeUnits=function(units){return normalizeUnits(units)};moment.invalid=function(flags){var m=moment.utc(NaN);if(flags!=null){extend(m._pf,flags)}else{m._pf.userInvalidated=true}return m};moment.parseZone=function(){return moment.apply(null,arguments).parseZone()};moment.parseTwoDigitYear=function(input){return toInt(input)+(toInt(input)>68?1900:2e3)};moment.isDate=isDate;extend(moment.fn=Moment.prototype,{clone:function(){return moment(this)},valueOf:function(){return+this._d-(this._offset||0)*6e4},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){var m=moment(this).utc();if(0<m.year()&&m.year()<=9999){if("function"===typeof Date.prototype.toISOString){return this.toDate().toISOString()}else{return formatMoment(m,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}}else{return formatMoment(m,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}},toArray:function(){var m=this;return[m.year(),m.month(),m.date(),m.hours(),m.minutes(),m.seconds(),m.milliseconds()]},isValid:function(){return isValid(this)},isDSTShifted:function(){if(this._a){return this.isValid()&&compareArrays(this._a,(this._isUTC?moment.utc(this._a):moment(this._a)).toArray())>0}return false},parsingFlags:function(){return extend({},this._pf)},invalidAt:function(){return this._pf.overflow},utc:function(keepLocalTime){return this.utcOffset(0,keepLocalTime)},local:function(keepLocalTime){if(this._isUTC){this.utcOffset(0,keepLocalTime);this._isUTC=false;if(keepLocalTime){this.subtract(this._dateUtcOffset(),"m")}}return this},format:function(inputString){var output=formatMoment(this,inputSLine truncated
@@ -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));
+5 -1
View File
@@ -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
View 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
View 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
@@ -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
View 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)
+3
View File
@@ -42,3 +42,6 @@ psutil>=2.2.1
#pushover notifications
python-pushover>=0.2
# Transmission Torrent Client
transmissionrpc>=0.11
+78
View 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