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.
|
- 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
|
||||||
|
|
|
@ -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).
|
||||||
|
|
||||||
|
|
|
@ -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
|
||||||
|
|
|
@ -40,12 +40,12 @@ class RemovedReason(Enum):
|
||||||
RemovedByThisClient = 0
|
RemovedByThisClient = 0
|
||||||
ForceDisconnectedByThisClient = 1
|
ForceDisconnectedByThisClient = 1
|
||||||
ForceDisconnectedByOtherClient = 2
|
ForceDisconnectedByOtherClient = 2
|
||||||
|
|
||||||
ButtonIsPrivate = 3
|
ButtonIsPrivate = 3
|
||||||
VerifyTimeout = 4
|
VerifyTimeout = 4
|
||||||
InternetBackendError = 5
|
InternetBackendError = 5
|
||||||
InvalidData = 6
|
InvalidData = 6
|
||||||
|
|
||||||
CouldntLoadDevice = 7
|
CouldntLoadDevice = 7
|
||||||
|
|
||||||
class ClickType(Enum):
|
class ClickType(Enum):
|
||||||
|
@ -81,22 +81,22 @@ class ScanWizardResult(Enum):
|
||||||
|
|
||||||
class ButtonScanner:
|
class ButtonScanner:
|
||||||
"""ButtonScanner class.
|
"""ButtonScanner class.
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
scanner = ButtonScanner()
|
scanner = ButtonScanner()
|
||||||
scanner.on_advertisement_packet = lambda scanner, bd_addr, name, rssi, is_private, already_verified: ...
|
scanner.on_advertisement_packet = lambda scanner, bd_addr, name, rssi, is_private, already_verified: ...
|
||||||
client.add_scanner(scanner)
|
client.add_scanner(scanner)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_cnt = itertools.count()
|
_cnt = itertools.count()
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._scan_id = next(ButtonScanner._cnt)
|
self._scan_id = next(ButtonScanner._cnt)
|
||||||
self.on_advertisement_packet = lambda scanner, bd_addr, name, rssi, is_private, already_verified: None
|
self.on_advertisement_packet = lambda scanner, bd_addr, name, rssi, is_private, already_verified: None
|
||||||
|
|
||||||
class ScanWizard:
|
class ScanWizard:
|
||||||
"""ScanWizard class
|
"""ScanWizard class
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
wizard = ScanWizard()
|
wizard = ScanWizard()
|
||||||
wizard.on_found_private_button = lambda scan_wizard: ...
|
wizard.on_found_private_button = lambda scan_wizard: ...
|
||||||
|
@ -105,9 +105,9 @@ class ScanWizard:
|
||||||
wizard.on_completed = lambda scan_wizard, result, bd_addr, name: ...
|
wizard.on_completed = lambda scan_wizard, result, bd_addr, name: ...
|
||||||
client.add_scan_wizard(wizard)
|
client.add_scan_wizard(wizard)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_cnt = itertools.count()
|
_cnt = itertools.count()
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._scan_wizard_id = next(ScanWizard._cnt)
|
self._scan_wizard_id = next(ScanWizard._cnt)
|
||||||
self._bd_addr = None
|
self._bd_addr = None
|
||||||
|
@ -119,31 +119,31 @@ class ScanWizard:
|
||||||
|
|
||||||
class ButtonConnectionChannel:
|
class ButtonConnectionChannel:
|
||||||
"""ButtonConnectionChannel class.
|
"""ButtonConnectionChannel class.
|
||||||
|
|
||||||
This class represents a connection channel to a Flic button.
|
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).
|
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.
|
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
|
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,
|
the corresponding properties to this object with a function. Each callback function has a channel parameter as the first one,
|
||||||
referencing this object.
|
referencing this object.
|
||||||
|
|
||||||
Available properties and the function parameters are:
|
Available properties and the function parameters are:
|
||||||
on_create_connection_channel_response: channel, error, connection_status
|
on_create_connection_channel_response: channel, error, connection_status
|
||||||
on_removed: channel, removed_reason
|
on_removed: channel, removed_reason
|
||||||
on_connection_status_changed: channel, connection_status, disconnect_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
|
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()
|
_cnt = itertools.count()
|
||||||
|
|
||||||
def __init__(self, bd_addr, latency_mode = LatencyMode.NormalLatency, auto_disconnect_time = 511):
|
def __init__(self, bd_addr, latency_mode = LatencyMode.NormalLatency, auto_disconnect_time = 511):
|
||||||
self._conn_id = next(ButtonConnectionChannel._cnt)
|
self._conn_id = next(ButtonConnectionChannel._cnt)
|
||||||
self._bd_addr = bd_addr
|
self._bd_addr = bd_addr
|
||||||
self._latency_mode = latency_mode
|
self._latency_mode = latency_mode
|
||||||
self._auto_disconnect_time = auto_disconnect_time
|
self._auto_disconnect_time = auto_disconnect_time
|
||||||
self._client = None
|
self._client = None
|
||||||
|
|
||||||
self.on_create_connection_channel_response = lambda channel, error, connection_status: None
|
self.on_create_connection_channel_response = lambda channel, error, connection_status: None
|
||||||
self.on_removed = lambda channel, removed_reason: None
|
self.on_removed = lambda channel, removed_reason: None
|
||||||
self.on_connection_status_changed = lambda channel, connection_status, disconnect_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_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 = 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
|
self.on_button_single_or_double_click_or_hold = lambda channel, click_type, was_queued, time_diff: None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def bd_addr(self):
|
def bd_addr(self):
|
||||||
return self._bd_addr
|
return self._bd_addr
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def latency_mode(self):
|
def latency_mode(self):
|
||||||
return self._latency_mode
|
return self._latency_mode
|
||||||
|
|
||||||
@latency_mode.setter
|
@latency_mode.setter
|
||||||
def latency_mode(self, latency_mode):
|
def latency_mode(self, latency_mode):
|
||||||
if self._client is None:
|
if self._client is None:
|
||||||
self._latency_mode = latency_mode
|
self._latency_mode = latency_mode
|
||||||
return
|
return
|
||||||
|
|
||||||
with self._client._lock:
|
with self._client._lock:
|
||||||
self._latency_mode = latency_mode
|
self._latency_mode = latency_mode
|
||||||
if not self._client._closed:
|
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})
|
self._client._send_command("CmdChangeModeParameters", {"conn_id": self._conn_id, "latency_mode": self._latency_mode, "auto_disconnect_time": self._auto_disconnect_time})
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def auto_disconnect_time(self):
|
def auto_disconnect_time(self):
|
||||||
return self._auto_disconnect_time
|
return self._auto_disconnect_time
|
||||||
|
|
||||||
@auto_disconnect_time.setter
|
@auto_disconnect_time.setter
|
||||||
def auto_disconnect_time(self, auto_disconnect_time):
|
def auto_disconnect_time(self, auto_disconnect_time):
|
||||||
if self._client is None:
|
if self._client is None:
|
||||||
self._auto_disconnect_time = auto_disconnect_time
|
self._auto_disconnect_time = auto_disconnect_time
|
||||||
return
|
return
|
||||||
|
|
||||||
with self._client._lock:
|
with self._client._lock:
|
||||||
self._auto_disconnect_time = auto_disconnect_time
|
self._auto_disconnect_time = auto_disconnect_time
|
||||||
if not self._client._closed:
|
if not self._client._closed:
|
||||||
|
@ -188,26 +188,26 @@ class ButtonConnectionChannel:
|
||||||
|
|
||||||
class FlicClient:
|
class FlicClient:
|
||||||
"""FlicClient class.
|
"""FlicClient class.
|
||||||
|
|
||||||
When this class is constructed, a socket connection is established.
|
When this class is constructed, a socket connection is established.
|
||||||
You may then send commands to the server and set timers.
|
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.
|
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.
|
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 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.
|
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 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.
|
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):
|
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_new_verified_button: bd_addr
|
||||||
on_no_space_for_new_connection: max_concurrently_connected_buttons
|
on_no_space_for_new_connection: max_concurrently_connected_buttons
|
||||||
on_got_space_for_new_connection: max_concurrently_connected_buttons
|
on_got_space_for_new_connection: max_concurrently_connected_buttons
|
||||||
on_bluetooth_controller_state_change: state
|
on_bluetooth_controller_state_change: state
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_EVENTS = [
|
_EVENTS = [
|
||||||
("EvtAdvertisementPacket", "<I6s17pb??", "scan_id bd_addr name rssi is_private already_verified"),
|
("EvtAdvertisementPacket", "<I6s17pb??", "scan_id bd_addr name rssi is_private already_verified"),
|
||||||
("EvtCreateConnectionChannelResponse", "<IBB", "conn_id error connection_status"),
|
("EvtCreateConnectionChannelResponse", "<IBB", "conn_id error connection_status"),
|
||||||
|
@ -229,9 +229,9 @@ 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", "", ""),
|
||||||
("CmdCreateScanner", "<I", "scan_id"),
|
("CmdCreateScanner", "<I", "scan_id"),
|
||||||
|
@ -245,17 +245,19 @@ class FlicClient:
|
||||||
("CmdCreateScanWizard", "<I", "scan_wizard_id"),
|
("CmdCreateScanWizard", "<I", "scan_wizard_id"),
|
||||||
("CmdCancelScanWizard", "<I", "scan_wizard_id")
|
("CmdCancelScanWizard", "<I", "scan_wizard_id")
|
||||||
]
|
]
|
||||||
|
|
||||||
_COMMAND_STRUCTS = list(map(lambda x: struct.Struct(x[1]), _COMMANDS))
|
_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_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(":"))))
|
||||||
|
|
||||||
def __init__(self, host, port = 5551):
|
def __init__(self, host, port = 5551):
|
||||||
self._sock = socket.create_connection((host, port), None)
|
self._sock = socket.create_connection((host, port), None)
|
||||||
self._lock = threading.RLock()
|
self._lock = threading.RLock()
|
||||||
|
@ -267,113 +269,113 @@ class FlicClient:
|
||||||
self._timers = queue.PriorityQueue()
|
self._timers = queue.PriorityQueue()
|
||||||
self._handle_event_thread_ident = None
|
self._handle_event_thread_ident = None
|
||||||
self._closed = False
|
self._closed = False
|
||||||
|
|
||||||
self.on_new_verified_button = lambda bd_addr: None
|
self.on_new_verified_button = lambda bd_addr: None
|
||||||
self.on_no_space_for_new_connection = lambda max_concurrently_connected_buttons: 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_got_space_for_new_connection = lambda max_concurrently_connected_buttons: None
|
||||||
self.on_bluetooth_controller_state_change = lambda state: None
|
self.on_bluetooth_controller_state_change = lambda state: None
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
"""Closes the client. The handle_events() method will return."""
|
"""Closes the client. The handle_events() method will return."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self._closed:
|
if self._closed:
|
||||||
return
|
return
|
||||||
|
|
||||||
if threading.get_ident() != self._handle_event_thread_ident:
|
if threading.get_ident() != self._handle_event_thread_ident:
|
||||||
self._send_command("CmdPing", {"ping_id": 0}) # To unblock socket select
|
self._send_command("CmdPing", {"ping_id": 0}) # To unblock socket select
|
||||||
|
|
||||||
self._closed = True
|
self._closed = True
|
||||||
|
|
||||||
def add_scanner(self, scanner):
|
def add_scanner(self, scanner):
|
||||||
"""Add a ButtonScanner object.
|
"""Add a ButtonScanner object.
|
||||||
|
|
||||||
The scan will start directly once the scanner is added.
|
The scan will start directly once the scanner is added.
|
||||||
"""
|
"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if scanner._scan_id in self._scanners:
|
if scanner._scan_id in self._scanners:
|
||||||
return
|
return
|
||||||
|
|
||||||
self._scanners[scanner._scan_id] = scanner
|
self._scanners[scanner._scan_id] = scanner
|
||||||
self._send_command("CmdCreateScanner", {"scan_id": scanner._scan_id})
|
self._send_command("CmdCreateScanner", {"scan_id": scanner._scan_id})
|
||||||
|
|
||||||
def remove_scanner(self, scanner):
|
def remove_scanner(self, scanner):
|
||||||
"""Remove a ButtonScanner object.
|
"""Remove a ButtonScanner object.
|
||||||
|
|
||||||
You will no longer receive advertisement packets.
|
You will no longer receive advertisement packets.
|
||||||
"""
|
"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if scanner._scan_id not in self._scanners:
|
if scanner._scan_id not in self._scanners:
|
||||||
return
|
return
|
||||||
|
|
||||||
del self._scanners[scanner._scan_id]
|
del self._scanners[scanner._scan_id]
|
||||||
self._send_command("CmdRemoveScanner", {"scan_id": scanner._scan_id})
|
self._send_command("CmdRemoveScanner", {"scan_id": scanner._scan_id})
|
||||||
|
|
||||||
def add_scan_wizard(self, scan_wizard):
|
def add_scan_wizard(self, scan_wizard):
|
||||||
"""Add a ScanWizard object.
|
"""Add a ScanWizard object.
|
||||||
|
|
||||||
The scan wizard will start directly once the scan wizard is added.
|
The scan wizard will start directly once the scan wizard is added.
|
||||||
"""
|
"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if scan_wizard._scan_wizard_id in self._scan_wizards:
|
if scan_wizard._scan_wizard_id in self._scan_wizards:
|
||||||
return
|
return
|
||||||
|
|
||||||
self._scan_wizards[scan_wizard._scan_wizard_id] = scan_wizard
|
self._scan_wizards[scan_wizard._scan_wizard_id] = scan_wizard
|
||||||
self._send_command("CmdCreateScanWizard", {"scan_wizard_id": scan_wizard._scan_wizard_id})
|
self._send_command("CmdCreateScanWizard", {"scan_wizard_id": scan_wizard._scan_wizard_id})
|
||||||
|
|
||||||
def cancel_scan_wizard(self, scan_wizard):
|
def cancel_scan_wizard(self, scan_wizard):
|
||||||
"""Cancel a ScanWizard.
|
"""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.
|
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".
|
If cancelled due to this command, "result" in the on_completed event will be "WizardCancelledByUser".
|
||||||
"""
|
"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if scan_wizard._scan_wizard_id not in self._scan_wizards:
|
if scan_wizard._scan_wizard_id not in self._scan_wizards:
|
||||||
return
|
return
|
||||||
|
|
||||||
self._send_command("CmdCancelScanWizard", {"scan_wizard_id": scan_wizard._scan_wizard_id})
|
self._send_command("CmdCancelScanWizard", {"scan_wizard_id": scan_wizard._scan_wizard_id})
|
||||||
|
|
||||||
def add_connection_channel(self, channel):
|
def add_connection_channel(self, channel):
|
||||||
"""Adds a connection channel to a specific Flic button.
|
"""Adds a connection channel to a specific Flic button.
|
||||||
|
|
||||||
This will start listening for a specific Flic button's connection and button events.
|
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.
|
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
|
The on_create_connection_channel_response callback property will be called on the
|
||||||
connection channel after this command has been received by the server.
|
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.
|
You may have as many connection channels as you wish for a specific Flic Button.
|
||||||
"""
|
"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if channel._conn_id in self._connection_channels:
|
if channel._conn_id in self._connection_channels:
|
||||||
return
|
return
|
||||||
|
|
||||||
channel._client = self
|
channel._client = self
|
||||||
|
|
||||||
self._connection_channels[channel._conn_id] = channel
|
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})
|
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):
|
def remove_connection_channel(self, channel):
|
||||||
"""Remove a connection channel.
|
"""Remove a connection channel.
|
||||||
|
|
||||||
This will stop listening for new events for a specific connection channel that has previously been added.
|
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.
|
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:
|
with self._lock:
|
||||||
if channel._conn_id not in self._connection_channels:
|
if channel._conn_id not in self._connection_channels:
|
||||||
return
|
return
|
||||||
|
|
||||||
self._send_command("CmdRemoveConnectionChannel", {"conn_id": channel._conn_id})
|
self._send_command("CmdRemoveConnectionChannel", {"conn_id": channel._conn_id})
|
||||||
|
|
||||||
def force_disconnect(self, bd_addr):
|
def force_disconnect(self, bd_addr):
|
||||||
"""Force disconnection or cancel pending connection of a specific Flic button.
|
"""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.
|
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})
|
self._send_command("CmdForceDisconnect", {"bd_addr": bd_addr})
|
||||||
|
|
||||||
def get_info(self, callback):
|
def get_info(self, callback):
|
||||||
"""Get info about the current state of the server.
|
"""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 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:
|
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,
|
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._get_info_response_queue.put(callback)
|
||||||
self._send_command("CmdGetInfo", {})
|
self._send_command("CmdGetInfo", {})
|
||||||
|
|
||||||
def get_button_uuid(self, bd_addr, callback):
|
def get_button_uuid(self, bd_addr, callback):
|
||||||
"""Get button uuid for a verified button.
|
"""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.
|
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.
|
Responses will arrive in the same order as requested.
|
||||||
|
|
||||||
The callback takes two parameters: bd_addr, uuid (hex string of 32 characters).
|
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.
|
Note: if the button isn't verified, the uuid sent to the callback will rather be None.
|
||||||
"""
|
"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._get_button_uuid_queue.put(callback)
|
self._get_button_uuid_queue.put(callback)
|
||||||
self._send_command("CmdGetButtonUUID", {"bd_addr": bd_addr})
|
self._send_command("CmdGetButtonUUID", {"bd_addr": bd_addr})
|
||||||
|
|
||||||
def set_timer(self, timeout_millis, callback):
|
def set_timer(self, timeout_millis, callback):
|
||||||
"""Set a timer
|
"""Set a timer
|
||||||
|
|
||||||
This timer callback will run after the specified timeout_millis on the thread that handles the events.
|
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
|
point_in_time = time.monotonic() + timeout_millis / 1000.0
|
||||||
self._timers.put((point_in_time, callback))
|
self._timers.put((point_in_time, callback))
|
||||||
|
|
||||||
if threading.get_ident() != self._handle_event_thread_ident:
|
if threading.get_ident() != self._handle_event_thread_ident:
|
||||||
self._send_command("CmdPing", {"ping_id": 0}) # To unblock socket select
|
self._send_command("CmdPing", {"ping_id": 0}) # To unblock socket select
|
||||||
|
|
||||||
def run_on_handle_events_thread(self, callback):
|
def run_on_handle_events_thread(self, callback):
|
||||||
"""Run a function on the thread that handles the events."""
|
"""Run a function on the thread that handles the events."""
|
||||||
if threading.get_ident() == self._handle_event_thread_ident:
|
if threading.get_ident() == self._handle_event_thread_ident:
|
||||||
callback()
|
callback()
|
||||||
else:
|
else:
|
||||||
self.set_timer(0, callback)
|
self.set_timer(0, callback)
|
||||||
|
|
||||||
def _send_command(self, name, items):
|
def _send_command(self, name, items):
|
||||||
for key, value in items.items():
|
for key, value in items.items():
|
||||||
if isinstance(value, Enum):
|
if isinstance(value, Enum):
|
||||||
items[key] = value.value
|
items[key] = value.value
|
||||||
|
|
||||||
if "bd_addr" in items:
|
if "bd_addr" in items:
|
||||||
items["bd_addr"] = FlicClient._bdaddr_string_to_bytes(items["bd_addr"])
|
items["bd_addr"] = FlicClient._bdaddr_string_to_bytes(items["bd_addr"])
|
||||||
|
|
||||||
opcode = FlicClient._COMMAND_NAME_TO_OPCODE[name]
|
opcode = FlicClient._COMMAND_NAME_TO_OPCODE[name]
|
||||||
data_bytes = FlicClient._COMMAND_STRUCTS[opcode].pack(*FlicClient._COMMAND_NAMED_TUPLES[opcode](**items))
|
data_bytes = FlicClient._COMMAND_STRUCTS[opcode].pack(*FlicClient._COMMAND_NAMED_TUPLES[opcode](**items))
|
||||||
bytes = bytearray(3)
|
bytes = bytearray(3)
|
||||||
|
@ -432,83 +434,83 @@ class FlicClient:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if not self._closed:
|
if not self._closed:
|
||||||
self._sock.sendall(bytes)
|
self._sock.sendall(bytes)
|
||||||
|
|
||||||
def _dispatch_event(self, data):
|
def _dispatch_event(self, data):
|
||||||
if len(data) == 0:
|
if len(data) == 0:
|
||||||
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]
|
||||||
data_tuple = FlicClient._EVENT_STRUCTS[opcode].unpack(data[1 : 1 + FlicClient._EVENT_STRUCTS[opcode].size])
|
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()
|
items = FlicClient._EVENT_NAMED_TUPLES[opcode]._make(data_tuple)._asdict()
|
||||||
|
|
||||||
# Process some kind of items whose data type is not supported by struct
|
# Process some kind of items whose data type is not supported by struct
|
||||||
if "bd_addr" in items:
|
if "bd_addr" in items:
|
||||||
items["bd_addr"] = FlicClient._bdaddr_bytes_to_string(items["bd_addr"])
|
items["bd_addr"] = FlicClient._bdaddr_bytes_to_string(items["bd_addr"])
|
||||||
|
|
||||||
if "name" in items:
|
if "name" in items:
|
||||||
items["name"] = items["name"].decode("utf-8")
|
items["name"] = items["name"].decode("utf-8")
|
||||||
|
|
||||||
if event_name == "EvtCreateConnectionChannelResponse":
|
if event_name == "EvtCreateConnectionChannelResponse":
|
||||||
items["error"] = CreateConnectionChannelError(items["error"])
|
items["error"] = CreateConnectionChannelError(items["error"])
|
||||||
items["connection_status"] = ConnectionStatus(items["connection_status"])
|
items["connection_status"] = ConnectionStatus(items["connection_status"])
|
||||||
|
|
||||||
if event_name == "EvtConnectionStatusChanged":
|
if event_name == "EvtConnectionStatusChanged":
|
||||||
items["connection_status"] = ConnectionStatus(items["connection_status"])
|
items["connection_status"] = ConnectionStatus(items["connection_status"])
|
||||||
items["disconnect_reason"] = DisconnectReason(items["disconnect_reason"])
|
items["disconnect_reason"] = DisconnectReason(items["disconnect_reason"])
|
||||||
|
|
||||||
if event_name == "EvtConnectionChannelRemoved":
|
if event_name == "EvtConnectionChannelRemoved":
|
||||||
items["removed_reason"] = RemovedReason(items["removed_reason"])
|
items["removed_reason"] = RemovedReason(items["removed_reason"])
|
||||||
|
|
||||||
if event_name.startswith("EvtButton"):
|
if event_name.startswith("EvtButton"):
|
||||||
items["click_type"] = ClickType(items["click_type"])
|
items["click_type"] = ClickType(items["click_type"])
|
||||||
|
|
||||||
if event_name == "EvtGetInfoResponse":
|
if event_name == "EvtGetInfoResponse":
|
||||||
items["bluetooth_controller_state"] = BluetoothControllerState(items["bluetooth_controller_state"])
|
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"] = FlicClient._bdaddr_bytes_to_string(items["my_bd_addr"])
|
||||||
items["my_bd_addr_type"] = BdAddrType(items["my_bd_addr_type"])
|
items["my_bd_addr_type"] = BdAddrType(items["my_bd_addr_type"])
|
||||||
items["bd_addr_of_verified_buttons"] = []
|
items["bd_addr_of_verified_buttons"] = []
|
||||||
|
|
||||||
pos = FlicClient._EVENT_STRUCTS[opcode].size
|
pos = FlicClient._EVENT_STRUCTS[opcode].size
|
||||||
for i in range(items["nb_verified_buttons"]):
|
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]))
|
items["bd_addr_of_verified_buttons"].append(FlicClient._bdaddr_bytes_to_string(data[1 + pos : 1 + pos + 6]))
|
||||||
pos += 6
|
pos += 6
|
||||||
|
|
||||||
if event_name == "EvtBluetoothControllerStateChange":
|
if event_name == "EvtBluetoothControllerStateChange":
|
||||||
items["state"] = BluetoothControllerState(items["state"])
|
items["state"] = BluetoothControllerState(items["state"])
|
||||||
|
|
||||||
if event_name == "EvtGetButtonUUIDResponse":
|
if event_name == "EvtGetButtonUUIDResponse":
|
||||||
items["uuid"] = "".join(map(lambda x: "%02x" % x, items["uuid"]))
|
items["uuid"] = "".join(map(lambda x: "%02x" % x, items["uuid"]))
|
||||||
if items["uuid"] == "00000000000000000000000000000000":
|
if items["uuid"] == "00000000000000000000000000000000":
|
||||||
items["uuid"] = None
|
items["uuid"] = None
|
||||||
|
|
||||||
if event_name == "EvtScanWizardCompleted":
|
if event_name == "EvtScanWizardCompleted":
|
||||||
items["result"] = ScanWizardResult(items["result"])
|
items["result"] = ScanWizardResult(items["result"])
|
||||||
|
|
||||||
# Process event
|
# Process event
|
||||||
if event_name == "EvtAdvertisementPacket":
|
if event_name == "EvtAdvertisementPacket":
|
||||||
scanner = self._scanners.get(items["scan_id"])
|
scanner = self._scanners.get(items["scan_id"])
|
||||||
if scanner is not None:
|
if scanner is not None:
|
||||||
scanner.on_advertisement_packet(scanner, items["bd_addr"], items["name"], items["rssi"], items["is_private"], items["already_verified"])
|
scanner.on_advertisement_packet(scanner, items["bd_addr"], items["name"], items["rssi"], items["is_private"], items["already_verified"])
|
||||||
|
|
||||||
if event_name == "EvtCreateConnectionChannelResponse":
|
if event_name == "EvtCreateConnectionChannelResponse":
|
||||||
channel = self._connection_channels[items["conn_id"]]
|
channel = self._connection_channels[items["conn_id"]]
|
||||||
if items["error"] != CreateConnectionChannelError.NoError:
|
if items["error"] != CreateConnectionChannelError.NoError:
|
||||||
del self._connection_channels[items["conn_id"]]
|
del self._connection_channels[items["conn_id"]]
|
||||||
channel.on_create_connection_channel_response(channel, items["error"], items["connection_status"])
|
channel.on_create_connection_channel_response(channel, items["error"], items["connection_status"])
|
||||||
|
|
||||||
if event_name == "EvtConnectionStatusChanged":
|
if event_name == "EvtConnectionStatusChanged":
|
||||||
channel = self._connection_channels[items["conn_id"]]
|
channel = self._connection_channels[items["conn_id"]]
|
||||||
channel.on_connection_status_changed(channel, items["connection_status"], items["disconnect_reason"])
|
channel.on_connection_status_changed(channel, items["connection_status"], items["disconnect_reason"])
|
||||||
|
|
||||||
if event_name == "EvtConnectionChannelRemoved":
|
if event_name == "EvtConnectionChannelRemoved":
|
||||||
channel = self._connection_channels[items["conn_id"]]
|
channel = self._connection_channels[items["conn_id"]]
|
||||||
del self._connection_channels[items["conn_id"]]
|
del self._connection_channels[items["conn_id"]]
|
||||||
channel.on_removed(channel, items["removed_reason"])
|
channel.on_removed(channel, items["removed_reason"])
|
||||||
|
|
||||||
if event_name == "EvtButtonUpOrDown":
|
if event_name == "EvtButtonUpOrDown":
|
||||||
channel = self._connection_channels[items["conn_id"]]
|
channel = self._connection_channels[items["conn_id"]]
|
||||||
channel.on_button_up_or_down(channel, items["click_type"], items["was_queued"], items["time_diff"])
|
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":
|
if event_name == "EvtButtonSingleOrDoubleClickOrHold":
|
||||||
channel = self._connection_channels[items["conn_id"]]
|
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"])
|
channel.on_button_single_or_double_click_or_hold(channel, items["click_type"], items["was_queued"], items["time_diff"])
|
||||||
|
|
||||||
if event_name == "EvtNewVerifiedButton":
|
if event_name == "EvtNewVerifiedButton":
|
||||||
self.on_new_verified_button(items["bd_addr"])
|
self.on_new_verified_button(items["bd_addr"])
|
||||||
|
|
||||||
if event_name == "EvtGetInfoResponse":
|
if event_name == "EvtGetInfoResponse":
|
||||||
self._get_info_response_queue.get()(items)
|
self._get_info_response_queue.get()(items)
|
||||||
|
|
||||||
if event_name == "EvtNoSpaceForNewConnection":
|
if event_name == "EvtNoSpaceForNewConnection":
|
||||||
self.on_no_space_for_new_connection(items["max_concurrently_connected_buttons"])
|
self.on_no_space_for_new_connection(items["max_concurrently_connected_buttons"])
|
||||||
|
|
||||||
if event_name == "EvtGotSpaceForNewConnection":
|
if event_name == "EvtGotSpaceForNewConnection":
|
||||||
self.on_got_space_for_new_connection(items["max_concurrently_connected_buttons"])
|
self.on_got_space_for_new_connection(items["max_concurrently_connected_buttons"])
|
||||||
|
|
||||||
if event_name == "EvtBluetoothControllerStateChange":
|
if event_name == "EvtBluetoothControllerStateChange":
|
||||||
self.on_bluetooth_controller_state_change(items["state"])
|
self.on_bluetooth_controller_state_change(items["state"])
|
||||||
|
|
||||||
if event_name == "EvtGetButtonUUIDResponse":
|
if event_name == "EvtGetButtonUUIDResponse":
|
||||||
self._get_button_uuid_queue.get()(items["bd_addr"], items["uuid"])
|
self._get_button_uuid_queue.get()(items["bd_addr"], items["uuid"])
|
||||||
|
|
||||||
if event_name == "EvtScanWizardFoundPrivateButton":
|
if event_name == "EvtScanWizardFoundPrivateButton":
|
||||||
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
||||||
scan_wizard.on_found_private_button(scan_wizard)
|
scan_wizard.on_found_private_button(scan_wizard)
|
||||||
|
|
||||||
if event_name == "EvtScanWizardFoundPublicButton":
|
if event_name == "EvtScanWizardFoundPublicButton":
|
||||||
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
||||||
scan_wizard._bd_addr = items["bd_addr"]
|
scan_wizard._bd_addr = items["bd_addr"]
|
||||||
scan_wizard._name = items["name"]
|
scan_wizard._name = items["name"]
|
||||||
scan_wizard.on_found_public_button(scan_wizard, scan_wizard._bd_addr, scan_wizard._name)
|
scan_wizard.on_found_public_button(scan_wizard, scan_wizard._bd_addr, scan_wizard._name)
|
||||||
|
|
||||||
if event_name == "EvtScanWizardButtonConnected":
|
if event_name == "EvtScanWizardButtonConnected":
|
||||||
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
||||||
scan_wizard.on_button_connected(scan_wizard, scan_wizard._bd_addr, scan_wizard._name)
|
scan_wizard.on_button_connected(scan_wizard, scan_wizard._bd_addr, scan_wizard._name)
|
||||||
|
|
||||||
if event_name == "EvtScanWizardCompleted":
|
if event_name == "EvtScanWizardCompleted":
|
||||||
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
scan_wizard = self._scan_wizards[items["scan_wizard_id"]]
|
||||||
del 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)
|
scan_wizard.on_completed(scan_wizard, items["result"], scan_wizard._bd_addr, scan_wizard._name)
|
||||||
|
|
||||||
def _handle_one_event(self):
|
def _handle_one_event(self):
|
||||||
if len(self._timers.queue) > 0:
|
if len(self._timers.queue) > 0:
|
||||||
current_timer = self._timers.queue[0]
|
current_timer = self._timers.queue[0]
|
||||||
|
@ -568,10 +570,10 @@ class FlicClient:
|
||||||
return True
|
return True
|
||||||
if len(select.select([self._sock], [], [], timeout)[0]) == 0:
|
if len(select.select([self._sock], [], [], timeout)[0]) == 0:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
len_arr = bytearray(2)
|
len_arr = bytearray(2)
|
||||||
view = memoryview(len_arr)
|
view = memoryview(len_arr)
|
||||||
|
|
||||||
toread = 2
|
toread = 2
|
||||||
while toread > 0:
|
while toread > 0:
|
||||||
nbytes = self._sock.recv_into(view, toread)
|
nbytes = self._sock.recv_into(view, toread)
|
||||||
|
@ -579,7 +581,7 @@ class FlicClient:
|
||||||
return False
|
return False
|
||||||
view = view[nbytes:]
|
view = view[nbytes:]
|
||||||
toread -= nbytes
|
toread -= nbytes
|
||||||
|
|
||||||
packet_len = len_arr[0] | (len_arr[1] << 8)
|
packet_len = len_arr[0] | (len_arr[1] << 8)
|
||||||
data = bytearray(packet_len)
|
data = bytearray(packet_len)
|
||||||
view = memoryview(data)
|
view = memoryview(data)
|
||||||
|
@ -590,13 +592,13 @@ class FlicClient:
|
||||||
return False
|
return False
|
||||||
view = view[nbytes:]
|
view = view[nbytes:]
|
||||||
toread -= nbytes
|
toread -= nbytes
|
||||||
|
|
||||||
self._dispatch_event(data)
|
self._dispatch_event(data)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def handle_events(self):
|
def handle_events(self):
|
||||||
"""Start the main loop for this client.
|
"""Start the main loop for this client.
|
||||||
|
|
||||||
This method will not return until the socket has been closed.
|
This method will not return until the socket has been closed.
|
||||||
Once it has returned, any use of this FlicClient is illegal.
|
Once it has returned, any use of this FlicClient is illegal.
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -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
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")}}]);
|
(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
|
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
|
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) {
|
||||||
|
|
|
@ -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
|
||||||
}, {})
|
}, {})
|
||||||
|
|
|
@ -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) {
|
||||||
|
|
|
@ -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%'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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)
|
||||||
|
|
|
@ -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
|
||||||
|
|
|
@ -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
|
||||||
|
|
||||||
|
|
|
@ -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:
|
||||||
|
|
|
@ -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
|
||||||
|
|
|
@ -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
|
||||||
|
|
|
@ -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
|
||||||
|
|
|
@ -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
|
||||||
|
|
|
@ -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,
|
||||||
|
|
|
@ -124,11 +124,9 @@ 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)
|
tls_version=tls_version, tls_ciphers=tls_ciphers, username=username,
|
||||||
MqttPlugin.__init__(self, host=host, port=port, tls_certfile=tls_certfile, tls_keyfile=tls_keyfile,
|
password=password, **kwargs)
|
||||||
tls_version=tls_version, tls_ciphers=tls_ciphers, username=username,
|
|
||||||
password=password, **kwargs)
|
|
||||||
|
|
||||||
self.base_topic = base_topic
|
self.base_topic = base_topic
|
||||||
self.timeout = timeout
|
self.timeout = timeout
|
||||||
|
@ -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
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue