forked from platypush/platypush
More LINT fixes
This commit is contained in:
parent
2a78f81a7b
commit
f1faa1141e
33 changed files with 182 additions and 182 deletions
|
@ -9,6 +9,8 @@ Given the high speed of development in the first phase, changes are being report
|
|||
|
||||
- Major LINT fixes.
|
||||
|
||||
### Removed
|
||||
|
||||
- Removed unmaintained integrations: TorrentCast and Booking.com
|
||||
|
||||
## [0.20.8] - 2021-04-04
|
||||
|
|
|
@ -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)
|
||||
[![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)
|
||||
[![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).
|
||||
|
||||
|
|
|
@ -62,11 +62,10 @@ class Alarm:
|
|||
return cron.get_next()
|
||||
except (AttributeError, croniter.CroniterBadCronError):
|
||||
try:
|
||||
# lgtm [py/call-to-non-callable]
|
||||
timestamp = datetime.datetime.fromisoformat(self.when).replace(tzinfo=gettz())
|
||||
timestamp = datetime.datetime.fromisoformat(self.when).replace(
|
||||
tzinfo=gettz()) # lgtm [py/call-to-non-callable]
|
||||
except (TypeError, ValueError):
|
||||
# lgtm [py/call-to-non-callable]
|
||||
timestamp = (datetime.datetime.now().replace(tzinfo=gettz()) +
|
||||
timestamp = (datetime.datetime.now().replace(tzinfo=gettz()) + # lgtm [py/call-to-non-callable]
|
||||
datetime.timedelta(seconds=int(self.when)))
|
||||
|
||||
return timestamp.timestamp() if timestamp >= now else None
|
||||
|
|
|
@ -40,12 +40,12 @@ class RemovedReason(Enum):
|
|||
RemovedByThisClient = 0
|
||||
ForceDisconnectedByThisClient = 1
|
||||
ForceDisconnectedByOtherClient = 2
|
||||
|
||||
|
||||
ButtonIsPrivate = 3
|
||||
VerifyTimeout = 4
|
||||
InternetBackendError = 5
|
||||
InvalidData = 6
|
||||
|
||||
|
||||
CouldntLoadDevice = 7
|
||||
|
||||
class ClickType(Enum):
|
||||
|
@ -81,22 +81,22 @@ class ScanWizardResult(Enum):
|
|||
|
||||
class ButtonScanner:
|
||||
"""ButtonScanner class.
|
||||
|
||||
|
||||
Usage:
|
||||
scanner = ButtonScanner()
|
||||
scanner.on_advertisement_packet = lambda scanner, bd_addr, name, rssi, is_private, already_verified: ...
|
||||
client.add_scanner(scanner)
|
||||
"""
|
||||
|
||||
|
||||
_cnt = itertools.count()
|
||||
|
||||
|
||||
def __init__(self):
|
||||
self._scan_id = next(ButtonScanner._cnt)
|
||||
self.on_advertisement_packet = lambda scanner, bd_addr, name, rssi, is_private, already_verified: None
|
||||
|
||||
class ScanWizard:
|
||||
"""ScanWizard class
|
||||
|
||||
|
||||
Usage:
|
||||
wizard = ScanWizard()
|
||||
wizard.on_found_private_button = lambda scan_wizard: ...
|
||||
|
@ -105,9 +105,9 @@ class ScanWizard:
|
|||
wizard.on_completed = lambda scan_wizard, result, bd_addr, name: ...
|
||||
client.add_scan_wizard(wizard)
|
||||
"""
|
||||
|
||||
|
||||
_cnt = itertools.count()
|
||||
|
||||
|
||||
def __init__(self):
|
||||
self._scan_wizard_id = next(ScanWizard._cnt)
|
||||
self._bd_addr = None
|
||||
|
@ -119,31 +119,31 @@ class ScanWizard:
|
|||
|
||||
class ButtonConnectionChannel:
|
||||
"""ButtonConnectionChannel class.
|
||||
|
||||
|
||||
This class represents a connection channel to a Flic button.
|
||||
Add this button connection channel to a FlicClient by executing client.add_connection_channel(connection_channel).
|
||||
You may only have this connection channel added to one FlicClient at a time.
|
||||
|
||||
|
||||
Before you add the connection channel to the client, you should set up your callback functions by assigning
|
||||
the corresponding properties to this object with a function. Each callback function has a channel parameter as the first one,
|
||||
referencing this object.
|
||||
|
||||
|
||||
Available properties and the function parameters are:
|
||||
on_create_connection_channel_response: channel, error, connection_status
|
||||
on_removed: channel, removed_reason
|
||||
on_connection_status_changed: channel, connection_status, disconnect_reason
|
||||
on_button_up_or_down / on_button_click_or_hold / on_button_single_or_double_click / on_button_single_or_double_click_or_hold: channel, click_type, was_queued, time_diff
|
||||
"""
|
||||
|
||||
|
||||
_cnt = itertools.count()
|
||||
|
||||
|
||||
def __init__(self, bd_addr, latency_mode = LatencyMode.NormalLatency, auto_disconnect_time = 511):
|
||||
self._conn_id = next(ButtonConnectionChannel._cnt)
|
||||
self._bd_addr = bd_addr
|
||||
self._latency_mode = latency_mode
|
||||
self._auto_disconnect_time = auto_disconnect_time
|
||||
self._client = None
|
||||
|
||||
|
||||
self.on_create_connection_channel_response = lambda channel, error, connection_status: None
|
||||
self.on_removed = lambda channel, removed_reason: None
|
||||
self.on_connection_status_changed = lambda channel, connection_status, disconnect_reason: None
|
||||
|
@ -151,36 +151,36 @@ class ButtonConnectionChannel:
|
|||
self.on_button_click_or_hold = lambda channel, click_type, was_queued, time_diff: None
|
||||
self.on_button_single_or_double_click = lambda channel, click_type, was_queued, time_diff: None
|
||||
self.on_button_single_or_double_click_or_hold = lambda channel, click_type, was_queued, time_diff: None
|
||||
|
||||
|
||||
@property
|
||||
def bd_addr(self):
|
||||
return self._bd_addr
|
||||
|
||||
|
||||
@property
|
||||
def latency_mode(self):
|
||||
return self._latency_mode
|
||||
|
||||
|
||||
@latency_mode.setter
|
||||
def latency_mode(self, latency_mode):
|
||||
if self._client is None:
|
||||
self._latency_mode = latency_mode
|
||||
return
|
||||
|
||||
|
||||
with self._client._lock:
|
||||
self._latency_mode = latency_mode
|
||||
if not self._client._closed:
|
||||
self._client._send_command("CmdChangeModeParameters", {"conn_id": self._conn_id, "latency_mode": self._latency_mode, "auto_disconnect_time": self._auto_disconnect_time})
|
||||
|
||||
|
||||
@property
|
||||
def auto_disconnect_time(self):
|
||||
return self._auto_disconnect_time
|
||||
|
||||
|
||||
@auto_disconnect_time.setter
|
||||
def auto_disconnect_time(self, auto_disconnect_time):
|
||||
if self._client is None:
|
||||
self._auto_disconnect_time = auto_disconnect_time
|
||||
return
|
||||
|
||||
|
||||
with self._client._lock:
|
||||
self._auto_disconnect_time = auto_disconnect_time
|
||||
if not self._client._closed:
|
||||
|
@ -188,26 +188,26 @@ class ButtonConnectionChannel:
|
|||
|
||||
class FlicClient:
|
||||
"""FlicClient class.
|
||||
|
||||
|
||||
When this class is constructed, a socket connection is established.
|
||||
You may then send commands to the server and set timers.
|
||||
Once you are ready with the initialization you must call the handle_events() method which is a main loop that never exits, unless the socket is closed.
|
||||
For a more detailed description of all commands, events and enums, check the protocol specification.
|
||||
|
||||
|
||||
All commands are wrapped in more high level functions and events are reported using callback functions.
|
||||
|
||||
|
||||
All methods called on this class will take effect only if you eventually call the handle_events() method.
|
||||
|
||||
|
||||
The ButtonScanner is used to set up a handler for advertisement packets.
|
||||
The ButtonConnectionChannel is used to interact with connections to flic buttons and receive their events.
|
||||
|
||||
|
||||
Other events are handled by the following callback functions that can be assigned to this object (and a list of the callback function parameters):
|
||||
on_new_verified_button: bd_addr
|
||||
on_no_space_for_new_connection: max_concurrently_connected_buttons
|
||||
on_got_space_for_new_connection: max_concurrently_connected_buttons
|
||||
on_bluetooth_controller_state_change: state
|
||||
"""
|
||||
|
||||
|
||||
_EVENTS = [
|
||||
("EvtAdvertisementPacket", "<I6s17pb??", "scan_id bd_addr name rssi is_private already_verified"),
|
||||
("EvtCreateConnectionChannelResponse", "<IBB", "conn_id error connection_status"),
|
||||
|
@ -229,9 +229,9 @@ class FlicClient:
|
|||
("EvtScanWizardButtonConnected", "<I", "scan_wizard_id"),
|
||||
("EvtScanWizardCompleted", "<IB", "scan_wizard_id result")
|
||||
]
|
||||
_EVENT_STRUCTS = list(map(lambda x: None if x == 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_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 is None else namedtuple(x[0], x[2]), _EVENTS))
|
||||
|
||||
_COMMANDS = [
|
||||
("CmdGetInfo", "", ""),
|
||||
("CmdCreateScanner", "<I", "scan_id"),
|
||||
|
@ -245,17 +245,19 @@ class FlicClient:
|
|||
("CmdCreateScanWizard", "<I", "scan_wizard_id"),
|
||||
("CmdCancelScanWizard", "<I", "scan_wizard_id")
|
||||
]
|
||||
|
||||
|
||||
_COMMAND_STRUCTS = list(map(lambda x: struct.Struct(x[1]), _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))
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _bdaddr_bytes_to_string(bdaddr_bytes):
|
||||
return ":".join(map(lambda x: "%02x" % x, reversed(bdaddr_bytes)))
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _bdaddr_string_to_bytes(bdaddr_string):
|
||||
return bytearray.fromhex("".join(reversed(bdaddr_string.split(":"))))
|
||||
|
||||
|
||||
def __init__(self, host, port = 5551):
|
||||
self._sock = socket.create_connection((host, port), None)
|
||||
self._lock = threading.RLock()
|
||||
|
@ -267,113 +269,113 @@ class FlicClient:
|
|||
self._timers = queue.PriorityQueue()
|
||||
self._handle_event_thread_ident = None
|
||||
self._closed = False
|
||||
|
||||
|
||||
self.on_new_verified_button = lambda bd_addr: None
|
||||
self.on_no_space_for_new_connection = lambda max_concurrently_connected_buttons: None
|
||||
self.on_got_space_for_new_connection = lambda max_concurrently_connected_buttons: None
|
||||
self.on_bluetooth_controller_state_change = lambda state: None
|
||||
|
||||
|
||||
def close(self):
|
||||
"""Closes the client. The handle_events() method will return."""
|
||||
with self._lock:
|
||||
if self._closed:
|
||||
return
|
||||
|
||||
|
||||
if threading.get_ident() != self._handle_event_thread_ident:
|
||||
self._send_command("CmdPing", {"ping_id": 0}) # To unblock socket select
|
||||
|
||||
|
||||
self._closed = True
|
||||
|
||||
|
||||
def add_scanner(self, scanner):
|
||||
"""Add a ButtonScanner object.
|
||||
|
||||
|
||||
The scan will start directly once the scanner is added.
|
||||
"""
|
||||
with self._lock:
|
||||
if scanner._scan_id in self._scanners:
|
||||
return
|
||||
|
||||
|
||||
self._scanners[scanner._scan_id] = scanner
|
||||
self._send_command("CmdCreateScanner", {"scan_id": scanner._scan_id})
|
||||
|
||||
|
||||
def remove_scanner(self, scanner):
|
||||
"""Remove a ButtonScanner object.
|
||||
|
||||
|
||||
You will no longer receive advertisement packets.
|
||||
"""
|
||||
with self._lock:
|
||||
if scanner._scan_id not in self._scanners:
|
||||
return
|
||||
|
||||
|
||||
del self._scanners[scanner._scan_id]
|
||||
self._send_command("CmdRemoveScanner", {"scan_id": scanner._scan_id})
|
||||
|
||||
|
||||
def add_scan_wizard(self, scan_wizard):
|
||||
"""Add a ScanWizard object.
|
||||
|
||||
|
||||
The scan wizard will start directly once the scan wizard is added.
|
||||
"""
|
||||
with self._lock:
|
||||
if scan_wizard._scan_wizard_id in self._scan_wizards:
|
||||
return
|
||||
|
||||
|
||||
self._scan_wizards[scan_wizard._scan_wizard_id] = scan_wizard
|
||||
self._send_command("CmdCreateScanWizard", {"scan_wizard_id": scan_wizard._scan_wizard_id})
|
||||
|
||||
|
||||
def cancel_scan_wizard(self, scan_wizard):
|
||||
"""Cancel a ScanWizard.
|
||||
|
||||
|
||||
Note: The effect of this command will take place at the time the on_completed event arrives on the scan wizard object.
|
||||
If cancelled due to this command, "result" in the on_completed event will be "WizardCancelledByUser".
|
||||
"""
|
||||
with self._lock:
|
||||
if scan_wizard._scan_wizard_id not in self._scan_wizards:
|
||||
return
|
||||
|
||||
|
||||
self._send_command("CmdCancelScanWizard", {"scan_wizard_id": scan_wizard._scan_wizard_id})
|
||||
|
||||
|
||||
def add_connection_channel(self, channel):
|
||||
"""Adds a connection channel to a specific Flic button.
|
||||
|
||||
|
||||
This will start listening for a specific Flic button's connection and button events.
|
||||
Make sure the Flic is either in public mode (by holding it down for 7 seconds) or already verified before calling this method.
|
||||
|
||||
|
||||
The on_create_connection_channel_response callback property will be called on the
|
||||
connection channel after this command has been received by the server.
|
||||
|
||||
|
||||
You may have as many connection channels as you wish for a specific Flic Button.
|
||||
"""
|
||||
with self._lock:
|
||||
if channel._conn_id in self._connection_channels:
|
||||
return
|
||||
|
||||
|
||||
channel._client = self
|
||||
|
||||
|
||||
self._connection_channels[channel._conn_id] = channel
|
||||
self._send_command("CmdCreateConnectionChannel", {"conn_id": channel._conn_id, "bd_addr": channel.bd_addr, "latency_mode": channel._latency_mode, "auto_disconnect_time": channel._auto_disconnect_time})
|
||||
|
||||
|
||||
def remove_connection_channel(self, channel):
|
||||
"""Remove a connection channel.
|
||||
|
||||
|
||||
This will stop listening for new events for a specific connection channel that has previously been added.
|
||||
Note: The effect of this command will take place at the time the on_removed event arrives on the connection channel object.
|
||||
"""
|
||||
with self._lock:
|
||||
if channel._conn_id not in self._connection_channels:
|
||||
return
|
||||
|
||||
|
||||
self._send_command("CmdRemoveConnectionChannel", {"conn_id": channel._conn_id})
|
||||
|
||||
|
||||
def force_disconnect(self, bd_addr):
|
||||
"""Force disconnection or cancel pending connection of a specific Flic button.
|
||||
|
||||
|
||||
This removes all connection channels for all clients connected to the server for this specific Flic button.
|
||||
"""
|
||||
self._send_command("CmdForceDisconnect", {"bd_addr": bd_addr})
|
||||
|
||||
|
||||
def get_info(self, callback):
|
||||
"""Get info about the current state of the server.
|
||||
|
||||
|
||||
The server will send back its information directly and the callback will be called once the response arrives.
|
||||
The callback takes only one parameter: info. This info parameter is a dictionary with the following objects:
|
||||
bluetooth_controller_state, my_bd_addr, my_bd_addr_type, max_pending_connections, max_concurrently_connected_buttons,
|
||||
|
@ -381,47 +383,47 @@ class FlicClient:
|
|||
"""
|
||||
self._get_info_response_queue.put(callback)
|
||||
self._send_command("CmdGetInfo", {})
|
||||
|
||||
|
||||
def get_button_uuid(self, bd_addr, callback):
|
||||
"""Get button uuid for a verified button.
|
||||
|
||||
|
||||
The server will send back its information directly and the callback will be called once the response arrives.
|
||||
Responses will arrive in the same order as requested.
|
||||
|
||||
|
||||
The callback takes two parameters: bd_addr, uuid (hex string of 32 characters).
|
||||
|
||||
|
||||
Note: if the button isn't verified, the uuid sent to the callback will rather be None.
|
||||
"""
|
||||
with self._lock:
|
||||
self._get_button_uuid_queue.put(callback)
|
||||
self._send_command("CmdGetButtonUUID", {"bd_addr": bd_addr})
|
||||
|
||||
|
||||
def set_timer(self, timeout_millis, callback):
|
||||
"""Set a timer
|
||||
|
||||
|
||||
This timer callback will run after the specified timeout_millis on the thread that handles the events.
|
||||
"""
|
||||
point_in_time = time.monotonic() + timeout_millis / 1000.0
|
||||
self._timers.put((point_in_time, callback))
|
||||
|
||||
|
||||
if threading.get_ident() != self._handle_event_thread_ident:
|
||||
self._send_command("CmdPing", {"ping_id": 0}) # To unblock socket select
|
||||
|
||||
|
||||
def run_on_handle_events_thread(self, callback):
|
||||
"""Run a function on the thread that handles the events."""
|
||||
if threading.get_ident() == self._handle_event_thread_ident:
|
||||
callback()
|
||||
else:
|
||||
self.set_timer(0, callback)
|
||||
|
||||
|
||||
def _send_command(self, name, items):
|
||||
for key, value in items.items():
|
||||
if isinstance(value, Enum):
|
||||
items[key] = value.value
|
||||
|
||||
|
||||
if "bd_addr" in items:
|
||||
items["bd_addr"] = FlicClient._bdaddr_string_to_bytes(items["bd_addr"])
|
||||
|
||||
|
||||
opcode = FlicClient._COMMAND_NAME_TO_OPCODE[name]
|
||||
data_bytes = FlicClient._COMMAND_STRUCTS[opcode].pack(*FlicClient._COMMAND_NAMED_TUPLES[opcode](**items))
|
||||
bytes = bytearray(3)
|
||||
|
@ -432,83 +434,83 @@ class FlicClient:
|
|||
with self._lock:
|
||||
if not self._closed:
|
||||
self._sock.sendall(bytes)
|
||||
|
||||
|
||||
def _dispatch_event(self, data):
|
||||
if len(data) == 0:
|
||||
return
|
||||
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
|
||||
|
||||
|
||||
event_name = FlicClient._EVENTS[opcode][0]
|
||||
data_tuple = FlicClient._EVENT_STRUCTS[opcode].unpack(data[1 : 1 + FlicClient._EVENT_STRUCTS[opcode].size])
|
||||
items = FlicClient._EVENT_NAMED_TUPLES[opcode]._make(data_tuple)._asdict()
|
||||
|
||||
|
||||
# Process some kind of items whose data type is not supported by struct
|
||||
if "bd_addr" in items:
|
||||
items["bd_addr"] = FlicClient._bdaddr_bytes_to_string(items["bd_addr"])
|
||||
|
||||
|
||||
if "name" in items:
|
||||
items["name"] = items["name"].decode("utf-8")
|
||||
|
||||
|
||||
if event_name == "EvtCreateConnectionChannelResponse":
|
||||
items["error"] = CreateConnectionChannelError(items["error"])
|
||||
items["connection_status"] = ConnectionStatus(items["connection_status"])
|
||||
|
||||
|
||||
if event_name == "EvtConnectionStatusChanged":
|
||||
items["connection_status"] = ConnectionStatus(items["connection_status"])
|
||||
items["disconnect_reason"] = DisconnectReason(items["disconnect_reason"])
|
||||
|
||||
|
||||
if event_name == "EvtConnectionChannelRemoved":
|
||||
items["removed_reason"] = RemovedReason(items["removed_reason"])
|
||||
|
||||
|
||||
if event_name.startswith("EvtButton"):
|
||||
items["click_type"] = ClickType(items["click_type"])
|
||||
|
||||
|
||||
if event_name == "EvtGetInfoResponse":
|
||||
items["bluetooth_controller_state"] = BluetoothControllerState(items["bluetooth_controller_state"])
|
||||
items["my_bd_addr"] = FlicClient._bdaddr_bytes_to_string(items["my_bd_addr"])
|
||||
items["my_bd_addr_type"] = BdAddrType(items["my_bd_addr_type"])
|
||||
items["bd_addr_of_verified_buttons"] = []
|
||||
|
||||
|
||||
pos = FlicClient._EVENT_STRUCTS[opcode].size
|
||||
for i in range(items["nb_verified_buttons"]):
|
||||
items["bd_addr_of_verified_buttons"].append(FlicClient._bdaddr_bytes_to_string(data[1 + pos : 1 + pos + 6]))
|
||||
pos += 6
|
||||
|
||||
|
||||
if event_name == "EvtBluetoothControllerStateChange":
|
||||
items["state"] = BluetoothControllerState(items["state"])
|
||||
|
||||
|
||||
if event_name == "EvtGetButtonUUIDResponse":
|
||||
items["uuid"] = "".join(map(lambda x: "%02x" % x, items["uuid"]))
|
||||
if items["uuid"] == "00000000000000000000000000000000":
|
||||
items["uuid"] = None
|
||||
|
||||
|
||||
if event_name == "EvtScanWizardCompleted":
|
||||
items["result"] = ScanWizardResult(items["result"])
|
||||
|
||||
|
||||
# Process event
|
||||
if event_name == "EvtAdvertisementPacket":
|
||||
scanner = self._scanners.get(items["scan_id"])
|
||||
if scanner is not None:
|
||||
scanner.on_advertisement_packet(scanner, items["bd_addr"], items["name"], items["rssi"], items["is_private"], items["already_verified"])
|
||||
|
||||
|
||||
if event_name == "EvtCreateConnectionChannelResponse":
|
||||
channel = self._connection_channels[items["conn_id"]]
|
||||
if items["error"] != CreateConnectionChannelError.NoError:
|
||||
del self._connection_channels[items["conn_id"]]
|
||||
channel.on_create_connection_channel_response(channel, items["error"], items["connection_status"])
|
||||
|
||||
|
||||
if event_name == "EvtConnectionStatusChanged":
|
||||
channel = self._connection_channels[items["conn_id"]]
|
||||
channel.on_connection_status_changed(channel, items["connection_status"], items["disconnect_reason"])
|
||||
|
||||
|
||||
if event_name == "EvtConnectionChannelRemoved":
|
||||
channel = self._connection_channels[items["conn_id"]]
|
||||
del self._connection_channels[items["conn_id"]]
|
||||
channel.on_removed(channel, items["removed_reason"])
|
||||
|
||||
|
||||
if event_name == "EvtButtonUpOrDown":
|
||||
channel = self._connection_channels[items["conn_id"]]
|
||||
channel.on_button_up_or_down(channel, items["click_type"], items["was_queued"], items["time_diff"])
|
||||
|
@ -521,44 +523,44 @@ class FlicClient:
|
|||
if event_name == "EvtButtonSingleOrDoubleClickOrHold":
|
||||
channel = self._connection_channels[items["conn_id"]]
|
||||
channel.on_button_single_or_double_click_or_hold(channel, items["click_type"], items["was_queued"], items["time_diff"])
|
||||
|
||||
|
||||
if event_name == "EvtNewVerifiedButton":
|
||||
self.on_new_verified_button(items["bd_addr"])
|
||||
|
||||
|
||||
if event_name == "EvtGetInfoResponse":
|
||||
self._get_info_response_queue.get()(items)
|
||||
|
||||
|
||||
if event_name == "EvtNoSpaceForNewConnection":
|
||||
self.on_no_space_for_new_connection(items["max_concurrently_connected_buttons"])
|
||||
|
||||
|
||||
if event_name == "EvtGotSpaceForNewConnection":
|
||||
self.on_got_space_for_new_connection(items["max_concurrently_connected_buttons"])
|
||||
|
||||
|
||||
if event_name == "EvtBluetoothControllerStateChange":
|
||||
self.on_bluetooth_controller_state_change(items["state"])
|
||||
|
||||
|
||||
if event_name == "EvtGetButtonUUIDResponse":
|
||||
self._get_button_uuid_queue.get()(items["bd_addr"], items["uuid"])
|
||||
|
||||
|
||||
if event_name == "EvtScanWizardFoundPrivateButton":
|
||||
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
||||
scan_wizard.on_found_private_button(scan_wizard)
|
||||
|
||||
|
||||
if event_name == "EvtScanWizardFoundPublicButton":
|
||||
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
||||
scan_wizard._bd_addr = items["bd_addr"]
|
||||
scan_wizard._name = items["name"]
|
||||
scan_wizard.on_found_public_button(scan_wizard, scan_wizard._bd_addr, scan_wizard._name)
|
||||
|
||||
|
||||
if event_name == "EvtScanWizardButtonConnected":
|
||||
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
||||
scan_wizard.on_button_connected(scan_wizard, scan_wizard._bd_addr, scan_wizard._name)
|
||||
|
||||
|
||||
if event_name == "EvtScanWizardCompleted":
|
||||
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
||||
del self._scan_wizards[items["scan_wizard_id"]]
|
||||
scan_wizard.on_completed(scan_wizard, items["result"], scan_wizard._bd_addr, scan_wizard._name)
|
||||
|
||||
|
||||
def _handle_one_event(self):
|
||||
if len(self._timers.queue) > 0:
|
||||
current_timer = self._timers.queue[0]
|
||||
|
@ -568,10 +570,10 @@ class FlicClient:
|
|||
return True
|
||||
if len(select.select([self._sock], [], [], timeout)[0]) == 0:
|
||||
return True
|
||||
|
||||
|
||||
len_arr = bytearray(2)
|
||||
view = memoryview(len_arr)
|
||||
|
||||
|
||||
toread = 2
|
||||
while toread > 0:
|
||||
nbytes = self._sock.recv_into(view, toread)
|
||||
|
@ -579,7 +581,7 @@ class FlicClient:
|
|||
return False
|
||||
view = view[nbytes:]
|
||||
toread -= nbytes
|
||||
|
||||
|
||||
packet_len = len_arr[0] | (len_arr[1] << 8)
|
||||
data = bytearray(packet_len)
|
||||
view = memoryview(data)
|
||||
|
@ -590,13 +592,13 @@ class FlicClient:
|
|||
return False
|
||||
view = view[nbytes:]
|
||||
toread -= nbytes
|
||||
|
||||
|
||||
self._dispatch_event(data)
|
||||
return True
|
||||
|
||||
|
||||
def handle_events(self):
|
||||
"""Start the main loop for this client.
|
||||
|
||||
|
||||
This method will not return until the socket has been closed.
|
||||
Once it has returned, any use of this FlicClient is illegal.
|
||||
"""
|
||||
|
|
|
@ -45,14 +45,12 @@ def get_args(kwargs):
|
|||
if k == 'resolution':
|
||||
v = json.loads('[{}]'.format(v))
|
||||
else:
|
||||
# noinspection PyBroadException
|
||||
try:
|
||||
v = int(v)
|
||||
except:
|
||||
# noinspection PyBroadException
|
||||
except (ValueError, TypeError):
|
||||
try:
|
||||
v = float(v)
|
||||
except:
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
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
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
|
@ -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")}}]);
|
||||
//# sourceMappingURL=chunk-437beeb4.a95dbde9.js.map
|
||||
(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-44b22f6e.6f0bfcc8.js.map
|
1
platypush/backend/http/webapp/dist/static/js/chunk-44b22f6e.6f0bfcc8.js.map
vendored
Normal file
1
platypush/backend/http/webapp/dist/static/js/chunk-44b22f6e.6f0bfcc8.js.map
vendored
Normal file
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
1
platypush/backend/http/webapp/dist/static/js/chunk-6c14c2d1.a89e7f1b.js.map
vendored
Normal file
1
platypush/backend/http/webapp/dist/static/js/chunk-6c14c2d1.a89e7f1b.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
1
platypush/backend/http/webapp/dist/static/js/chunk-cc8a6536.a5da26b6.js.map
vendored
Normal file
1
platypush/backend/http/webapp/dist/static/js/chunk-cc8a6536.a5da26b6.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
|
@ -56,8 +56,8 @@ export default {
|
|||
return
|
||||
}
|
||||
|
||||
if (null in this.handlers) {
|
||||
handlers.push(this.handlers[null])
|
||||
if (null in this.handlers) { // lgtm [js/implicit-operand-conversion]
|
||||
handlers.push(this.handlers[null]) // lgtm [js/implicit-operand-conversion]
|
||||
}
|
||||
|
||||
if (event.args.type in this.handlers) {
|
||||
|
|
|
@ -132,7 +132,7 @@ export default {
|
|||
const animations = Object.entries(this.animations?.groups || {}).reduce((obj, [groupId, animation]) => {
|
||||
obj[groupId] = {}
|
||||
if (animation)
|
||||
obj[groupId][null] = animation
|
||||
obj[groupId][null] = animation // lgtm [js/implicit-operand-conversion]
|
||||
|
||||
return obj
|
||||
}, {})
|
||||
|
|
|
@ -110,8 +110,8 @@ export class ColorConverter {
|
|||
if (isNaN(blue))
|
||||
blue = 0;
|
||||
|
||||
// lgtm [js/automatic-semicolon-insertion]
|
||||
return [red, green, blue].map((c) => Math.min(Math.max(0, c), 255))
|
||||
return [red, green, blue].map(
|
||||
(c) => Math.min(Math.max(0, c), 255)) // lgtm [js/automatic-semicolon-insertion]
|
||||
}
|
||||
|
||||
rgbToXY(red, green, blue) {
|
||||
|
|
|
@ -191,11 +191,9 @@ export default {
|
|||
|
||||
if (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%'
|
||||
}
|
||||
|
||||
if (ratio <= 4/3) {
|
||||
} else if (ratio <= 4/3) {
|
||||
this.$refs.img.style.height = '100%'
|
||||
}
|
||||
}
|
||||
|
|
|
@ -90,8 +90,7 @@ class FFmpegFileWriter(FileVideoWriter, FFmpegWriter):
|
|||
"""
|
||||
|
||||
def __init__(self, *args, output_file: str, **kwargs):
|
||||
FileVideoWriter.__init__(self, *args, output_file=output_file, **kwargs)
|
||||
FFmpegWriter.__init__(self, *args, pix_fmt='rgb24', output_file=self.output_file, **kwargs)
|
||||
super().__init__(*args, output_file=output_file, pix_fmt='rgb24', **kwargs)
|
||||
|
||||
|
||||
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):
|
||||
StreamWriter.__init__(self, *args, **kwargs)
|
||||
FFmpegWriter.__init__(self, *args, pix_fmt='rgb24', output_format=output_format, output_opts=output_opts or (
|
||||
super().__init__(*args, pix_fmt='rgb24', output_format=output_format, output_opts=output_opts or (
|
||||
'-tune', 'zerolatency', '-preset', 'superfast', '-trellis', '0',
|
||||
'-fflags', 'nobuffer'), **kwargs)
|
||||
self._reader = threading.Thread(target=self._reader_thread)
|
||||
|
|
|
@ -156,7 +156,7 @@ class GpioSensorMcp3008Plugin(GpioSensorPlugin):
|
|||
channel = self.channels[i]
|
||||
if 'conv_function' in channel:
|
||||
# noinspection PyUnusedLocal
|
||||
x = value
|
||||
x = value # lgtm [py/unused-local-variable]
|
||||
value = eval(channel['conv_function'])
|
||||
|
||||
values[channel['name']] = value
|
||||
|
|
|
@ -1,9 +1,12 @@
|
|||
import logging
|
||||
import os
|
||||
import requests
|
||||
|
||||
from platypush.message import Message
|
||||
from platypush.plugins import Plugin, action
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HttpRequestPlugin(Plugin):
|
||||
"""
|
||||
|
@ -63,12 +66,11 @@ class HttpRequestPlugin(Plugin):
|
|||
else:
|
||||
output = response.text
|
||||
|
||||
# noinspection PyBroadException
|
||||
try:
|
||||
# If the response is a Platypush JSON, extract it
|
||||
output = Message.build(output)
|
||||
except:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.debug(e)
|
||||
|
||||
return output
|
||||
|
||||
|
|
|
@ -126,7 +126,7 @@ class HttpWebpagePlugin(Plugin):
|
|||
<head>
|
||||
<title>{title}</title>
|
||||
<style>{style}</style>
|
||||
</head>'''.format(title=title, style=style, content=content) + \
|
||||
</head>'''.format(title=title, style=style) + \
|
||||
'<body>{{' + content + '}}</body></html>'
|
||||
|
||||
with open(outfile, 'w', encoding='utf-8') as f:
|
||||
|
|
|
@ -6,10 +6,10 @@ import re
|
|||
import threading
|
||||
from typing import Optional
|
||||
|
||||
import platypush.backend
|
||||
import platypush.plugins
|
||||
import platypush.message.event
|
||||
import platypush.message.response
|
||||
import platypush.backend # lgtm [py/import-and-import-from]
|
||||
import platypush.plugins # lgtm [py/import-and-import-from]
|
||||
import platypush.message.event # lgtm [py/import-and-import-from]
|
||||
import platypush.message.response # lgtm [py/import-and-import-from]
|
||||
|
||||
from platypush.backend import Backend
|
||||
from platypush.config import Config
|
||||
|
|
|
@ -24,7 +24,7 @@ class MqttPlugin(Plugin):
|
|||
def __init__(self, host=None, port=1883, tls_cafile=None,
|
||||
tls_certfile=None, tls_keyfile=None,
|
||||
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)
|
||||
: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).
|
||||
If None is specified then ``Config.get('device_id')`` will be used.
|
||||
:type client_id: str
|
||||
|
||||
:param timeout: Client timeout in seconds (default: None).
|
||||
:type timeout: int
|
||||
"""
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
@ -75,6 +78,7 @@ class MqttPlugin(Plugin):
|
|||
self.tls_version = self.get_tls_version(tls_version)
|
||||
self.tls_insecure = tls_insecure
|
||||
self.tls_ciphers = tls_ciphers
|
||||
self.timeout = timeout
|
||||
|
||||
@staticmethod
|
||||
def get_tls_version(version: Optional[str] = None):
|
||||
|
@ -99,6 +103,19 @@ class MqttPlugin(Plugin):
|
|||
|
||||
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
|
||||
def _expandpath(path: Optional[str] = None) -> Optional[str]:
|
||||
return os.path.abspath(os.path.expanduser(path)) if path else None
|
||||
|
|
|
@ -52,9 +52,7 @@ class SwitchSwitchbotPlugin(SwitchPlugin, BluetoothBlePlugin):
|
|||
:param devices: Devices to control, as a MAC address -> name map
|
||||
:type devices: dict
|
||||
"""
|
||||
|
||||
SwitchPlugin.__init__(self, **kwargs)
|
||||
BluetoothBlePlugin.__init__(self, interface=interface)
|
||||
super().__init__(interface=interface, **kwargs)
|
||||
|
||||
self.connect_timeout = connect_timeout if connect_timeout else 5
|
||||
self.scan_timeout = scan_timeout if scan_timeout else 2
|
||||
|
|
|
@ -37,8 +37,7 @@ class WeatherDarkskyPlugin(HttpRequestPlugin, WeatherPlugin):
|
|||
:type units: str
|
||||
"""
|
||||
|
||||
HttpRequestPlugin.__init__(self, method='get', output='json')
|
||||
WeatherPlugin.__init__(self, **kwargs)
|
||||
super().__init__(method='get', output='json', **kwargs)
|
||||
self.darksky_token = darksky_token
|
||||
self.units = units
|
||||
self.lat = lat
|
||||
|
|
|
@ -29,11 +29,11 @@ class WeatherOpenweathermapPlugin(HttpRequestPlugin, WeatherPlugin):
|
|||
for weather lookup.
|
||||
:param units: Supported: ``metric`` (default), ``standard`` and ``imperial``.
|
||||
"""
|
||||
HttpRequestPlugin.__init__(self, method='get', output='json')
|
||||
WeatherPlugin.__init__(self, **kwargs)
|
||||
super().__init__(method='get', output='json', **kwargs)
|
||||
self._token = token
|
||||
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
|
||||
|
||||
def _get_location_query(self, location: Optional[str] = None, city_id: Optional[int] = None,
|
||||
|
|
|
@ -124,11 +124,9 @@ class ZigbeeMqttPlugin(MqttPlugin, SwitchPlugin):
|
|||
: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)
|
||||
"""
|
||||
|
||||
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,
|
||||
password=password, **kwargs)
|
||||
super().__init__(host=host, port=port, tls_certfile=tls_certfile, tls_keyfile=tls_keyfile,
|
||||
tls_version=tls_version, tls_ciphers=tls_ciphers, username=username,
|
||||
password=password, **kwargs)
|
||||
|
||||
self.base_topic = base_topic
|
||||
self.timeout = timeout
|
||||
|
@ -198,19 +196,6 @@ class ZigbeeMqttPlugin(MqttPlugin, SwitchPlugin):
|
|||
except Exception as 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):
|
||||
return self.base_topic + '/' + topic
|
||||
|
||||
|
|
Loading…
Reference in a new issue