More LINT fixes

This commit is contained in:
Fabio Manganiello 2021-04-06 21:10:48 +02:00
parent 2a78f81a7b
commit f1faa1141e
33 changed files with 182 additions and 182 deletions

View file

@ -9,6 +9,8 @@ Given the high speed of development in the first phase, changes are being report
- Major LINT fixes. - Major LINT fixes.
### Removed
- Removed unmaintained integrations: TorrentCast and Booking.com - Removed unmaintained integrations: TorrentCast and Booking.com
## [0.20.8] - 2021-04-04 ## [0.20.8] - 2021-04-04

View file

@ -7,6 +7,8 @@ Platypush
[![License](https://img.shields.io/github/license/BlackLight/platypush.svg)](https://git.platypush.tech/platypush/platypush/-/blob/master/LICENSE.txt) [![License](https://img.shields.io/github/license/BlackLight/platypush.svg)](https://git.platypush.tech/platypush/platypush/-/blob/master/LICENSE.txt)
[![Last Commit](https://img.shields.io/github/last-commit/BlackLight/platypush.svg)](https://git.platypush.tech/platypush/platypush/-/commits/master/) [![Last Commit](https://img.shields.io/github/last-commit/BlackLight/platypush.svg)](https://git.platypush.tech/platypush/platypush/-/commits/master/)
[![Contributions](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://git.platypush.tech/platypush/platypush/-/blob/master/CONTRIBUTING.md) [![Contributions](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://git.platypush.tech/platypush/platypush/-/blob/master/CONTRIBUTING.md)
[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/BlackLight/platypush.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/BlackLight/platypush/context:python)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/BlackLight/platypush.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/BlackLight/platypush/context:javascript)
- Recommended read: [**Getting started with Platypush**](https://blog.platypush.tech/article/Ultimate-self-hosted-automation-with-Platypush). - Recommended read: [**Getting started with Platypush**](https://blog.platypush.tech/article/Ultimate-self-hosted-automation-with-Platypush).

View file

@ -62,11 +62,10 @@ class Alarm:
return cron.get_next() return cron.get_next()
except (AttributeError, croniter.CroniterBadCronError): except (AttributeError, croniter.CroniterBadCronError):
try: try:
# lgtm [py/call-to-non-callable] timestamp = datetime.datetime.fromisoformat(self.when).replace(
timestamp = datetime.datetime.fromisoformat(self.when).replace(tzinfo=gettz()) tzinfo=gettz()) # lgtm [py/call-to-non-callable]
except (TypeError, ValueError): except (TypeError, ValueError):
# lgtm [py/call-to-non-callable] timestamp = (datetime.datetime.now().replace(tzinfo=gettz()) + # lgtm [py/call-to-non-callable]
timestamp = (datetime.datetime.now().replace(tzinfo=gettz()) +
datetime.timedelta(seconds=int(self.when))) datetime.timedelta(seconds=int(self.when)))
return timestamp.timestamp() if timestamp >= now else None return timestamp.timestamp() if timestamp >= now else None

View file

@ -229,8 +229,8 @@ class FlicClient:
("EvtScanWizardButtonConnected", "<I", "scan_wizard_id"), ("EvtScanWizardButtonConnected", "<I", "scan_wizard_id"),
("EvtScanWizardCompleted", "<IB", "scan_wizard_id result") ("EvtScanWizardCompleted", "<IB", "scan_wizard_id result")
] ]
_EVENT_STRUCTS = list(map(lambda x: None if x == None else struct.Struct(x[1]), _EVENTS)) _EVENT_STRUCTS = list(map(lambda x: None if x is None else struct.Struct(x[1]), _EVENTS))
_EVENT_NAMED_TUPLES = list(map(lambda x: None if x == None else namedtuple(x[0], x[2]), _EVENTS)) _EVENT_NAMED_TUPLES = list(map(lambda x: None if x is None else namedtuple(x[0], x[2]), _EVENTS))
_COMMANDS = [ _COMMANDS = [
("CmdGetInfo", "", ""), ("CmdGetInfo", "", ""),
@ -250,9 +250,11 @@ class FlicClient:
_COMMAND_NAMED_TUPLES = list(map(lambda x: namedtuple(x[0], x[2]), _COMMANDS)) _COMMAND_NAMED_TUPLES = list(map(lambda x: namedtuple(x[0], x[2]), _COMMANDS))
_COMMAND_NAME_TO_OPCODE = dict((x[0], i) for i, x in enumerate(_COMMANDS)) _COMMAND_NAME_TO_OPCODE = dict((x[0], i) for i, x in enumerate(_COMMANDS))
@staticmethod
def _bdaddr_bytes_to_string(bdaddr_bytes): def _bdaddr_bytes_to_string(bdaddr_bytes):
return ":".join(map(lambda x: "%02x" % x, reversed(bdaddr_bytes))) return ":".join(map(lambda x: "%02x" % x, reversed(bdaddr_bytes)))
@staticmethod
def _bdaddr_string_to_bytes(bdaddr_string): def _bdaddr_string_to_bytes(bdaddr_string):
return bytearray.fromhex("".join(reversed(bdaddr_string.split(":")))) return bytearray.fromhex("".join(reversed(bdaddr_string.split(":"))))
@ -438,7 +440,7 @@ class FlicClient:
return return
opcode = data[0] opcode = data[0]
if opcode >= len(FlicClient._EVENTS) or FlicClient._EVENTS[opcode] == None: if opcode >= len(FlicClient._EVENTS) or FlicClient._EVENTS[opcode] is None:
return return
event_name = FlicClient._EVENTS[opcode][0] event_name = FlicClient._EVENTS[opcode][0]

View file

@ -45,14 +45,12 @@ def get_args(kwargs):
if k == 'resolution': if k == 'resolution':
v = json.loads('[{}]'.format(v)) v = json.loads('[{}]'.format(v))
else: else:
# noinspection PyBroadException
try: try:
v = int(v) v = int(v)
except: except (ValueError, TypeError):
# noinspection PyBroadException
try: try:
v = float(v) v = float(v)
except: except (ValueError, TypeError):
pass pass
kwargs[k] = v kwargs[k] = v

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,2 +1,2 @@
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-437beeb4"],{"3dc6":function(e,t,s){},beca:function(e,t,s){"use strict";s("3dc6")},c845:function(e,t,s){"use strict";s.r(t);var r=s("7a23"),a=Object(r["K"])("data-v-b7b0e3c0");Object(r["u"])("data-v-b7b0e3c0");var o={class:"image-carousel"},i={ref:"background",class:"background"},n={key:1,class:"row info-container"},h={class:"col-6 weather-container"},c={key:0},u={class:"col-6 date-time-container"};Object(r["s"])();var m=a((function(e,t,s,a,m,d){var f=Object(r["z"])("Loading"),l=Object(r["z"])("Weather"),w=Object(r["z"])("DateTime");return Object(r["r"])(),Object(r["e"])("div",o,[m.images.length?Object(r["f"])("",!0):(Object(r["r"])(),Object(r["e"])(f,{key:0})),Object(r["h"])("div",i,null,512),Object(r["h"])("img",{ref:"img",src:d.imgURL,alt:"Your carousel images",style:{display:m.images.length?"block":"none"}},null,12,["src"]),d._showDate||d._showTime?(Object(r["r"])(),Object(r["e"])("div",n,[Object(r["h"])("div",h,[d._showWeather?(Object(r["r"])(),Object(r["e"])(l,{key:1,"show-icon":d._showWeatherIcon,"show-summary":d._showWeatherSummary,"show-temperature":d._showTemperature,"icon-color":s.weatherIconColor,"icon-size":s.weatherIconSize,animate:d._animateWeatherIcon},null,8,["show-icon","show-summary","show-temperature","icon-color","icon-size","animate"])):(Object(r["r"])(),Object(r["e"])("span",c," "))]),Object(r["h"])("div",u,[d._showTime||d._showDate?(Object(r["r"])(),Object(r["e"])(w,{key:0,"show-date":d._showDate,"show-time":d._showTime,"show-seconds":d._showSeconds},null,8,["show-date","show-time","show-seconds"])):Object(r["f"])("",!0)])])):Object(r["f"])("",!0)])})),d=(s("a9e3"),s("96cf"),s("1da1")),f=s("3e54"),l=s("3a5e"),w=s("365a"),g=s("5b43"),b={name:"ImageCarousel",components:{Weather:g["default"],DateTime:w["default"],Loading:l["a"]},mixins:[f["a"]],props:{imgDir:{type:String,required:!0},refreshSeconds:{type:Number,default:15},showDate:{default:!1},showTime:{default:!1},showSeconds:{default:!1},showWeather:{default:!1},showTemperature:{default:!0},showWeatherIcon:{default:!0},showWeatherSummary:{default:!0},weatherIconColor:{type:String,default:"white"},weatherIconSize:{type:Number,default:70},animateWeatherIcon:{default:!0}},data:function(){return{images:[],currentImage:void 0,loading:!1}},computed:{imgURL:function(){var e=8008;return"backend.http"in this.$root.config&&"port"in this.$root.config["backend.http"]&&(e=this.$root.config["backend.http"].port),"//"+window.location.hostname+":"+e+this.currentImage},_showDate:function(){return this.parseBoolean(this.showDate)},_showTime:function(){return this.parseBoolean(this.showTime)},_showSeconds:function(){return this.parseBoolean(this.showSeconds)},_showTemperature:function(){return this.parseBoolean(this.showTemperature)},_showWeather:function(){return this.parseBoolean(this.showWeather)},_showWeatherIcon:function(){return this.parseBoolean(this.showWeatherIcon)},_showWeatherSummary:function(){return this.parseBoolean(this.showWeatherSummary)},_animateWeatherIcon:function(){return this.parseBoolean(this.animateWeatherIcon)}},methods:{refresh:function(){var e=this;return Object(d["a"])(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){while(1)switch(t.prev=t.next){case 0:if(e.images.length){t.next=10;break}return e.loading=!0,t.prev=2,t.next=5,e.request("utils.search_web_directory",{directory:e.imgDir,extensions:[".jpg",".jpeg",".png"]});case 5:e.images=t.sent,e.shuffleImages();case 7:return t.prev=7,e.loading=!1,t.finish(7);case 10:e.images.length&&(e.currentImage=e.images.pop());case 11:case"end":return t.stop()}}),t,null,[[2,,7,10]])})))()},onNewImage:function(){if(this.$refs.img&&(this.$refs.background.style["background-image"]="url("+this.imgURL+")",this.$refs.img.style.width="auto",this.$refs.img.width>this.$refs.img.height)){var e=this.$refs.img.width/this.$refs.img.height;4/3<=e<=16/9&&(this.$refs.img.style.width="100%"),e<=4/3&&(this.$refs.img.style.height="100%")}},shuffleImages:function(){for(var e=this.images.length-1;e>0;e--){var t=Math.floor(Math.random()*(e+1)),s=this.images[e];this.images[e]=this.images[t],this.images[t]=s}}},mounted:function(){this.$refs.img.addEventListener("load",this.onNewImage),this.$refs.img.addEventListener("error",this.refresh),this.refresh(),setInterval(this.refresh,Math.round(1e3*this.refreshSeconds))}};s("beca"),s("e6ce");b.render=m,b.__scopeId="data-v-b7b0e3c0";t["default"]=b},e012:function(e,t,s){},e6ce:function(e,t,s){"use strict";s("e012")}}]); (window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-44b22f6e"],{"12e6":function(e,t,s){},bdd7:function(e,t,s){"use strict";s("e88d")},c845:function(e,t,s){"use strict";s.r(t);var r=s("7a23"),a=Object(r["K"])("data-v-72b02f7c");Object(r["u"])("data-v-72b02f7c");var o={class:"image-carousel"},i={ref:"background",class:"background"},n={key:1,class:"row info-container"},h={class:"col-6 weather-container"},c={key:0},u={class:"col-6 date-time-container"};Object(r["s"])();var m=a((function(e,t,s,a,m,d){var f=Object(r["z"])("Loading"),l=Object(r["z"])("Weather"),w=Object(r["z"])("DateTime");return Object(r["r"])(),Object(r["e"])("div",o,[m.images.length?Object(r["f"])("",!0):(Object(r["r"])(),Object(r["e"])(f,{key:0})),Object(r["h"])("div",i,null,512),Object(r["h"])("img",{ref:"img",src:d.imgURL,alt:"Your carousel images",style:{display:m.images.length?"block":"none"}},null,12,["src"]),d._showDate||d._showTime?(Object(r["r"])(),Object(r["e"])("div",n,[Object(r["h"])("div",h,[d._showWeather?(Object(r["r"])(),Object(r["e"])(l,{key:1,"show-icon":d._showWeatherIcon,"show-summary":d._showWeatherSummary,"show-temperature":d._showTemperature,"icon-color":s.weatherIconColor,"icon-size":s.weatherIconSize,animate:d._animateWeatherIcon},null,8,["show-icon","show-summary","show-temperature","icon-color","icon-size","animate"])):(Object(r["r"])(),Object(r["e"])("span",c," "))]),Object(r["h"])("div",u,[d._showTime||d._showDate?(Object(r["r"])(),Object(r["e"])(w,{key:0,"show-date":d._showDate,"show-time":d._showTime,"show-seconds":d._showSeconds},null,8,["show-date","show-time","show-seconds"])):Object(r["f"])("",!0)])])):Object(r["f"])("",!0)])})),d=(s("a9e3"),s("96cf"),s("1da1")),f=s("3e54"),l=s("3a5e"),w=s("365a"),g=s("5b43"),b={name:"ImageCarousel",components:{Weather:g["default"],DateTime:w["default"],Loading:l["a"]},mixins:[f["a"]],props:{imgDir:{type:String,required:!0},refreshSeconds:{type:Number,default:15},showDate:{default:!1},showTime:{default:!1},showSeconds:{default:!1},showWeather:{default:!1},showTemperature:{default:!0},showWeatherIcon:{default:!0},showWeatherSummary:{default:!0},weatherIconColor:{type:String,default:"white"},weatherIconSize:{type:Number,default:70},animateWeatherIcon:{default:!0}},data:function(){return{images:[],currentImage:void 0,loading:!1}},computed:{imgURL:function(){var e=8008;return"backend.http"in this.$root.config&&"port"in this.$root.config["backend.http"]&&(e=this.$root.config["backend.http"].port),"//"+window.location.hostname+":"+e+this.currentImage},_showDate:function(){return this.parseBoolean(this.showDate)},_showTime:function(){return this.parseBoolean(this.showTime)},_showSeconds:function(){return this.parseBoolean(this.showSeconds)},_showTemperature:function(){return this.parseBoolean(this.showTemperature)},_showWeather:function(){return this.parseBoolean(this.showWeather)},_showWeatherIcon:function(){return this.parseBoolean(this.showWeatherIcon)},_showWeatherSummary:function(){return this.parseBoolean(this.showWeatherSummary)},_animateWeatherIcon:function(){return this.parseBoolean(this.animateWeatherIcon)}},methods:{refresh:function(){var e=this;return Object(d["a"])(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){while(1)switch(t.prev=t.next){case 0:if(e.images.length){t.next=10;break}return e.loading=!0,t.prev=2,t.next=5,e.request("utils.search_web_directory",{directory:e.imgDir,extensions:[".jpg",".jpeg",".png"]});case 5:e.images=t.sent,e.shuffleImages();case 7:return t.prev=7,e.loading=!1,t.finish(7);case 10:e.images.length&&(e.currentImage=e.images.pop());case 11:case"end":return t.stop()}}),t,null,[[2,,7,10]])})))()},onNewImage:function(){if(this.$refs.img&&(this.$refs.background.style["background-image"]="url("+this.imgURL+")",this.$refs.img.style.width="auto",this.$refs.img.width>this.$refs.img.height)){var e=this.$refs.img.width/this.$refs.img.height;e>=4/3&&e<=16/9?this.$refs.img.style.width="100%":e<=4/3&&(this.$refs.img.style.height="100%")}},shuffleImages:function(){for(var e=this.images.length-1;e>0;e--){var t=Math.floor(Math.random()*(e+1)),s=this.images[e];this.images[e]=this.images[t],this.images[t]=s}}},mounted:function(){this.$refs.img.addEventListener("load",this.onNewImage),this.$refs.img.addEventListener("error",this.refresh),this.refresh(),setInterval(this.refresh,Math.round(1e3*this.refreshSeconds))}};s("da08"),s("bdd7");b.render=m,b.__scopeId="data-v-72b02f7c";t["default"]=b},da08:function(e,t,s){"use strict";s("12e6")},e88d:function(e,t,s){}}]);
//# sourceMappingURL=chunk-437beeb4.a95dbde9.js.map //# sourceMappingURL=chunk-44b22f6e.6f0bfcc8.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -56,8 +56,8 @@ export default {
return return
} }
if (null in this.handlers) { if (null in this.handlers) { // lgtm [js/implicit-operand-conversion]
handlers.push(this.handlers[null]) handlers.push(this.handlers[null]) // lgtm [js/implicit-operand-conversion]
} }
if (event.args.type in this.handlers) { if (event.args.type in this.handlers) {

View file

@ -132,7 +132,7 @@ export default {
const animations = Object.entries(this.animations?.groups || {}).reduce((obj, [groupId, animation]) => { const animations = Object.entries(this.animations?.groups || {}).reduce((obj, [groupId, animation]) => {
obj[groupId] = {} obj[groupId] = {}
if (animation) if (animation)
obj[groupId][null] = animation obj[groupId][null] = animation // lgtm [js/implicit-operand-conversion]
return obj return obj
}, {}) }, {})

View file

@ -110,8 +110,8 @@ export class ColorConverter {
if (isNaN(blue)) if (isNaN(blue))
blue = 0; blue = 0;
// lgtm [js/automatic-semicolon-insertion] return [red, green, blue].map(
return [red, green, blue].map((c) => Math.min(Math.max(0, c), 255)) (c) => Math.min(Math.max(0, c), 255)) // lgtm [js/automatic-semicolon-insertion]
} }
rgbToXY(red, green, blue) { rgbToXY(red, green, blue) {

View file

@ -191,11 +191,9 @@ export default {
if (this.$refs.img.width > this.$refs.img.height) { if (this.$refs.img.width > this.$refs.img.height) {
const ratio = this.$refs.img.width / this.$refs.img.height const ratio = this.$refs.img.width / this.$refs.img.height
if (4/3 <= ratio <= 16/9) { if (ratio >= 4/3 && ratio <= 16/9) {
this.$refs.img.style.width = '100%' this.$refs.img.style.width = '100%'
} } else if (ratio <= 4/3) {
if (ratio <= 4/3) {
this.$refs.img.style.height = '100%' this.$refs.img.style.height = '100%'
} }
} }

View file

@ -90,8 +90,7 @@ class FFmpegFileWriter(FileVideoWriter, FFmpegWriter):
""" """
def __init__(self, *args, output_file: str, **kwargs): def __init__(self, *args, output_file: str, **kwargs):
FileVideoWriter.__init__(self, *args, output_file=output_file, **kwargs) super().__init__(*args, output_file=output_file, pix_fmt='rgb24', **kwargs)
FFmpegWriter.__init__(self, *args, pix_fmt='rgb24', output_file=self.output_file, **kwargs)
class FFmpegStreamWriter(StreamWriter, FFmpegWriter, ABC): class FFmpegStreamWriter(StreamWriter, FFmpegWriter, ABC):
@ -100,8 +99,7 @@ class FFmpegStreamWriter(StreamWriter, FFmpegWriter, ABC):
""" """
def __init__(self, *args, output_format: str, output_opts: Optional[Tuple] = None, **kwargs): def __init__(self, *args, output_format: str, output_opts: Optional[Tuple] = None, **kwargs):
StreamWriter.__init__(self, *args, **kwargs) super().__init__(*args, pix_fmt='rgb24', output_format=output_format, output_opts=output_opts or (
FFmpegWriter.__init__(self, *args, pix_fmt='rgb24', output_format=output_format, output_opts=output_opts or (
'-tune', 'zerolatency', '-preset', 'superfast', '-trellis', '0', '-tune', 'zerolatency', '-preset', 'superfast', '-trellis', '0',
'-fflags', 'nobuffer'), **kwargs) '-fflags', 'nobuffer'), **kwargs)
self._reader = threading.Thread(target=self._reader_thread) self._reader = threading.Thread(target=self._reader_thread)

View file

@ -156,7 +156,7 @@ class GpioSensorMcp3008Plugin(GpioSensorPlugin):
channel = self.channels[i] channel = self.channels[i]
if 'conv_function' in channel: if 'conv_function' in channel:
# noinspection PyUnusedLocal # noinspection PyUnusedLocal
x = value x = value # lgtm [py/unused-local-variable]
value = eval(channel['conv_function']) value = eval(channel['conv_function'])
values[channel['name']] = value values[channel['name']] = value

View file

@ -1,9 +1,12 @@
import logging
import os import os
import requests import requests
from platypush.message import Message from platypush.message import Message
from platypush.plugins import Plugin, action from platypush.plugins import Plugin, action
logger = logging.getLogger(__name__)
class HttpRequestPlugin(Plugin): class HttpRequestPlugin(Plugin):
""" """
@ -63,12 +66,11 @@ class HttpRequestPlugin(Plugin):
else: else:
output = response.text output = response.text
# noinspection PyBroadException
try: try:
# If the response is a Platypush JSON, extract it # If the response is a Platypush JSON, extract it
output = Message.build(output) output = Message.build(output)
except: except Exception as e:
pass logger.debug(e)
return output return output

View file

@ -126,7 +126,7 @@ class HttpWebpagePlugin(Plugin):
<head> <head>
<title>{title}</title> <title>{title}</title>
<style>{style}</style> <style>{style}</style>
</head>'''.format(title=title, style=style, content=content) + \ </head>'''.format(title=title, style=style) + \
'<body>{{' + content + '}}</body></html>' '<body>{{' + content + '}}</body></html>'
with open(outfile, 'w', encoding='utf-8') as f: with open(outfile, 'w', encoding='utf-8') as f:

View file

@ -6,10 +6,10 @@ import re
import threading import threading
from typing import Optional from typing import Optional
import platypush.backend import platypush.backend # lgtm [py/import-and-import-from]
import platypush.plugins import platypush.plugins # lgtm [py/import-and-import-from]
import platypush.message.event import platypush.message.event # lgtm [py/import-and-import-from]
import platypush.message.response import platypush.message.response # lgtm [py/import-and-import-from]
from platypush.backend import Backend from platypush.backend import Backend
from platypush.config import Config from platypush.config import Config

View file

@ -24,7 +24,7 @@ class MqttPlugin(Plugin):
def __init__(self, host=None, port=1883, tls_cafile=None, def __init__(self, host=None, port=1883, tls_cafile=None,
tls_certfile=None, tls_keyfile=None, tls_certfile=None, tls_keyfile=None,
tls_version=None, tls_ciphers=None, tls_insecure=False, tls_version=None, tls_ciphers=None, tls_insecure=False,
username=None, password=None, client_id=None, **kwargs): username=None, password=None, client_id=None, timeout=None, **kwargs):
""" """
:param host: If set, MQTT messages will by default routed to this host unless overridden in `send_message` (default: None) :param host: If set, MQTT messages will by default routed to this host unless overridden in `send_message` (default: None)
:type host: str :type host: str
@ -60,6 +60,9 @@ class MqttPlugin(Plugin):
:param client_id: ID used to identify the client on the MQTT server (default: None). :param client_id: ID used to identify the client on the MQTT server (default: None).
If None is specified then ``Config.get('device_id')`` will be used. If None is specified then ``Config.get('device_id')`` will be used.
:type client_id: str :type client_id: str
:param timeout: Client timeout in seconds (default: None).
:type timeout: int
""" """
super().__init__(**kwargs) super().__init__(**kwargs)
@ -75,6 +78,7 @@ class MqttPlugin(Plugin):
self.tls_version = self.get_tls_version(tls_version) self.tls_version = self.get_tls_version(tls_version)
self.tls_insecure = tls_insecure self.tls_insecure = tls_insecure
self.tls_ciphers = tls_ciphers self.tls_ciphers = tls_ciphers
self.timeout = timeout
@staticmethod @staticmethod
def get_tls_version(version: Optional[str] = None): def get_tls_version(version: Optional[str] = None):
@ -99,6 +103,19 @@ class MqttPlugin(Plugin):
assert 'Unrecognized TLS version: {}'.format(version) assert 'Unrecognized TLS version: {}'.format(version)
def _mqtt_args(self, **kwargs):
return {
'host': kwargs.get('host', self.host),
'port': kwargs.get('port', self.port),
'timeout': kwargs.get('timeout', self.timeout),
'tls_certfile': kwargs.get('tls_certfile', self.tls_certfile),
'tls_keyfile': kwargs.get('tls_keyfile', self.tls_keyfile),
'tls_version': kwargs.get('tls_version', self.tls_version),
'tls_ciphers': kwargs.get('tls_ciphers', self.tls_ciphers),
'username': kwargs.get('username', self.username),
'password': kwargs.get('password', self.password),
}
@staticmethod @staticmethod
def _expandpath(path: Optional[str] = None) -> Optional[str]: def _expandpath(path: Optional[str] = None) -> Optional[str]:
return os.path.abspath(os.path.expanduser(path)) if path else None return os.path.abspath(os.path.expanduser(path)) if path else None

View file

@ -52,9 +52,7 @@ class SwitchSwitchbotPlugin(SwitchPlugin, BluetoothBlePlugin):
:param devices: Devices to control, as a MAC address -> name map :param devices: Devices to control, as a MAC address -> name map
:type devices: dict :type devices: dict
""" """
super().__init__(interface=interface, **kwargs)
SwitchPlugin.__init__(self, **kwargs)
BluetoothBlePlugin.__init__(self, interface=interface)
self.connect_timeout = connect_timeout if connect_timeout else 5 self.connect_timeout = connect_timeout if connect_timeout else 5
self.scan_timeout = scan_timeout if scan_timeout else 2 self.scan_timeout = scan_timeout if scan_timeout else 2

View file

@ -37,8 +37,7 @@ class WeatherDarkskyPlugin(HttpRequestPlugin, WeatherPlugin):
:type units: str :type units: str
""" """
HttpRequestPlugin.__init__(self, method='get', output='json') super().__init__(method='get', output='json', **kwargs)
WeatherPlugin.__init__(self, **kwargs)
self.darksky_token = darksky_token self.darksky_token = darksky_token
self.units = units self.units = units
self.lat = lat self.lat = lat

View file

@ -29,11 +29,11 @@ class WeatherOpenweathermapPlugin(HttpRequestPlugin, WeatherPlugin):
for weather lookup. for weather lookup.
:param units: Supported: ``metric`` (default), ``standard`` and ``imperial``. :param units: Supported: ``metric`` (default), ``standard`` and ``imperial``.
""" """
HttpRequestPlugin.__init__(self, method='get', output='json') super().__init__(method='get', output='json', **kwargs)
WeatherPlugin.__init__(self, **kwargs)
self._token = token self._token = token
self._location_query = None self._location_query = None
self._location_query = self._get_location_query(location=location, city_id=city_id, lat=lat, long=long) self._location_query = self._get_location_query(location=location, city_id=city_id, lat=lat, long=long,
zip_code=zip_code)
self.units = units self.units = units
def _get_location_query(self, location: Optional[str] = None, city_id: Optional[int] = None, def _get_location_query(self, location: Optional[str] = None, city_id: Optional[int] = None,

View file

@ -124,9 +124,7 @@ class ZigbeeMqttPlugin(MqttPlugin, SwitchPlugin):
:param username: If the connection requires user authentication, specify the username (default: None) :param username: If the connection requires user authentication, specify the username (default: None)
:param password: If the connection requires user authentication, specify the password (default: None) :param password: If the connection requires user authentication, specify the password (default: None)
""" """
super().__init__(host=host, port=port, tls_certfile=tls_certfile, tls_keyfile=tls_keyfile,
SwitchPlugin.__init__(self)
MqttPlugin.__init__(self, host=host, port=port, tls_certfile=tls_certfile, tls_keyfile=tls_keyfile,
tls_version=tls_version, tls_ciphers=tls_ciphers, username=username, tls_version=tls_version, tls_ciphers=tls_ciphers, username=username,
password=password, **kwargs) password=password, **kwargs)
@ -198,19 +196,6 @@ class ZigbeeMqttPlugin(MqttPlugin, SwitchPlugin):
except Exception as e: except Exception as e:
self.logger.warning('Error on MQTT client disconnection: {}'.format(str(e))) self.logger.warning('Error on MQTT client disconnection: {}'.format(str(e)))
def _mqtt_args(self, **kwargs):
return {
'host': kwargs.get('host', self.host),
'port': kwargs.get('port', self.port),
'timeout': kwargs.get('timeout', self.timeout),
'tls_certfile': kwargs.get('tls_certfile', self.tls_certfile),
'tls_keyfile': kwargs.get('tls_keyfile', self.tls_keyfile),
'tls_version': kwargs.get('tls_version', self.tls_version),
'tls_ciphers': kwargs.get('tls_ciphers', self.tls_ciphers),
'username': kwargs.get('username', self.username),
'password': kwargs.get('password', self.password),
}
def _topic(self, topic): def _topic(self, topic):
return self.base_topic + '/' + topic return self.base_topic + '/' + topic