diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2024-02-20 00:56:00 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2024-02-20 00:56:00 +0300 |
commit | 95ac1f0d6786d6f4331cfc8387ef816c1db24618 (patch) | |
tree | 67e9c963ae7686eb46c75699b31ccd5385bacf77 /include | |
parent | 952e41d59412f5aad5898d0bccb3af800d104f24 (diff) |
comletely delete old lws, rewrite vk_sms_checker on python
Diffstat (limited to 'include')
-rw-r--r-- | include/py/homekit/database/__init__.py | 10 | ||||
-rw-r--r-- | include/py/homekit/database/__init__.pyi | 4 | ||||
-rw-r--r-- | include/py/homekit/database/bots.py | 5 | ||||
-rw-r--r-- | include/py/homekit/database/mysql.py | 77 | ||||
-rw-r--r-- | include/py/homekit/modem/e3372.py | 20 | ||||
-rw-r--r-- | include/py/homekit/telegram/telegram.py | 2 |
6 files changed, 76 insertions, 42 deletions
diff --git a/include/py/homekit/database/__init__.py b/include/py/homekit/database/__init__.py index b50cbce..c958959 100644 --- a/include/py/homekit/database/__init__.py +++ b/include/py/homekit/database/__init__.py @@ -6,6 +6,7 @@ __all__ = [ 'get_clickhouse', 'SimpleState', + 'MySQLHomeDatabase', 'SensorsDatabase', 'InverterDatabase', 'BotsDatabase' @@ -14,12 +15,13 @@ __all__ = [ def __getattr__(name: str): if name in __all__: - if name.endswith('Database'): - file = name[:-8].lower() - elif 'mysql' in name: + ln = name.lower() + if 'mysql' in ln: file = 'mysql' - elif 'clickhouse' in name: + elif 'clickhouse' in ln: file = 'clickhouse' + elif name.endswith('Database'): + file = name[:-8].lower() else: file = 'simple_state' diff --git a/include/py/homekit/database/__init__.pyi b/include/py/homekit/database/__init__.pyi index 31aae5d..3c057dc 100644 --- a/include/py/homekit/database/__init__.pyi +++ b/include/py/homekit/database/__init__.pyi @@ -1,6 +1,6 @@ from .mysql import ( - get_mysql as get_mysql, - mysql_now as mysql_now + mysql_now as mysql_now, + MySQLHomeDatabase as MySQLHomeDatabase ) from .clickhouse import get_clickhouse as get_clickhouse diff --git a/include/py/homekit/database/bots.py b/include/py/homekit/database/bots.py index fb5f326..fae8fb6 100644 --- a/include/py/homekit/database/bots.py +++ b/include/py/homekit/database/bots.py @@ -1,6 +1,6 @@ import pytz -from .mysql import mysql_now, MySQLDatabase, datetime_fmt +from .mysql import mysql_now, MySQLDatabase, datetime_fmt, MySQLCredsConfig, MySQLCloudCredsConfig from ..api.types import ( SoundSensorLocation ) @@ -26,6 +26,9 @@ class OpenwrtLogRecord: class BotsDatabase(MySQLDatabase): + def creds(self) -> MySQLCredsConfig: + return MySQLCloudCredsConfig() + def add_openwrt_logs(self, lines: List[Tuple[datetime, str]], access_point: int): diff --git a/include/py/homekit/database/mysql.py b/include/py/homekit/database/mysql.py index fe97cd4..a0b73fa 100644 --- a/include/py/homekit/database/mysql.py +++ b/include/py/homekit/database/mysql.py @@ -1,47 +1,74 @@ import time import logging +from abc import ABC, abstractmethod from mysql.connector import connect, MySQLConnection, Error from typing import Optional -from ..config import config +from ..config import ConfigUnit -link: Optional[MySQLConnection] = None logger = logging.getLogger(__name__) - datetime_fmt = '%Y-%m-%d %H:%M:%S' -def get_mysql() -> MySQLConnection: - global link +class MySQLCredsConfig(ConfigUnit, ABC): + @classmethod + def schema(cls) -> Optional[dict]: + schema = {} + for k in ('host', 'database', 'user', 'password'): + schema[k] = dict(type='string', required=True) + return schema + - if link is not None: - return link +class MySQLHomeCredsConfig(MySQLCredsConfig): + NAME = 'mysql_home_creds' - link = connect( - host=config['mysql']['host'], - user=config['mysql']['user'], - password=config['mysql']['password'], - database=config['mysql']['database'], - ) - link.time_zone = '+01:00' - return link + +class MySQLCloudCredsConfig(MySQLCredsConfig): + NAME = 'mysql_cloud_creds' def mysql_now() -> str: return time.strftime('%Y-%m-%d %H:%M:%S') -class MySQLDatabase: - def __init__(self): - self.db = get_mysql() +class MySQLDatabase(ABC): + _enable_pings: bool + _link: MySQLConnection + _time_zone: Optional[str] + + @abstractmethod + def creds(self) -> MySQLCredsConfig: + pass + + def __init__(self, enable_pings=False, time_zone='+01:00'): + self._enable_pings = enable_pings + self._time_zone = time_zone + self._connect() + + def _connect(self): + c = self.creds() + self._link = connect( + host=c['host'], + user=c['user'], + password=c['password'], + database=c['database'], + ) + if self._time_zone: + self._link.time_zone = self._time_zone def cursor(self, **kwargs): - try: - self.db.ping(reconnect=True, attempts=2) - except Error as e: - logger.exception(e) - self.db = get_mysql() - return self.db.cursor(**kwargs) + if self._enable_pings: + try: + self._link.ping(reconnect=True, attempts=2) + except Error as e: + logger.exception(e) + self._connect() + return self._link.cursor(**kwargs) def commit(self): - self.db.commit() + self._link.commit() + + +class MySQLHomeDatabase(MySQLDatabase): + def creds(self) -> MySQLCredsConfig: + return MySQLHomeCredsConfig()
\ No newline at end of file diff --git a/include/py/homekit/modem/e3372.py b/include/py/homekit/modem/e3372.py index f68db5a..8164b88 100644 --- a/include/py/homekit/modem/e3372.py +++ b/include/py/homekit/modem/e3372.py @@ -1,6 +1,7 @@ import requests import xml.etree.ElementTree as ElementTree +from datetime import datetime from ..util import Addr from enum import Enum from ..http import HTTPMethod @@ -21,14 +22,14 @@ class Error(Enum): ERROR_WRONG_TOKEN = 125001 ERROR_WRONG_SESSION = 125002 ERROR_WRONG_SESSION_TOKEN = 125003 - - + + class WifiStatus(Enum): WIFI_CONNECTING = '900' WIFI_CONNECTED = '901' WIFI_DISCONNECTED = '902' WIFI_DISCONNECTING = '903' - + class Cradle(Enum): CRADLE_CONNECTING = '900' @@ -38,8 +39,8 @@ class Cradle(Enum): CRADLE_CONNECTFAILED = '904' CRADLE_CONNECTSTATUSNULL = '905' CRANDLE_CONNECTSTATUSERRO = '906' - - + + class MacroEVDOLevel(Enum): MACRO_EVDO_LEVEL_ZERO = '0' MACRO_EVDO_LEVEL_ONE = '1' @@ -47,8 +48,8 @@ class MacroEVDOLevel(Enum): MACRO_EVDO_LEVEL_THREE = '3' MACRO_EVDO_LEVEL_FOUR = '4' MACRO_EVDO_LEVEL_FIVE = '5' - - + + class MacroNetWorkType(Enum): MACRO_NET_WORK_TYPE_NOSERVICE = 0 MACRO_NET_WORK_TYPE_GSM = 1 @@ -127,7 +128,7 @@ class E3372: _get_raw_data: bool _headers: dict[str, str] _authorized: bool - + def __init__(self, addr: Addr, need_auth: bool = True, @@ -174,7 +175,7 @@ class E3372: def sms_count(self): self.auth() return self.request('sms/sms-count') - + def sms_send(self, phone: str, text: str): self.auth() return self.request('sms/send-sms', HTTPMethod.POST, { @@ -204,6 +205,7 @@ class E3372: messages = [] for message_elem in root.find('Messages').findall('Message'): message_dict = {child.tag: child.text for child in message_elem} + message_dict['UnixTime'] = int(datetime.strptime(message_dict['Date'], '%Y-%m-%d %H:%M:%S').timestamp()) messages.append(message_dict) return messages diff --git a/include/py/homekit/telegram/telegram.py b/include/py/homekit/telegram/telegram.py index f42363e..7d7471b 100644 --- a/include/py/homekit/telegram/telegram.py +++ b/include/py/homekit/telegram/telegram.py @@ -11,7 +11,7 @@ _logger = logging.getLogger(__name__) def send_message(text: str, chat: str, parse_mode: str = 'HTML', - disable_web_page_preview: bool = False,): + disable_web_page_preview: bool = False): data, token = _send_telegram_data(text, chat, parse_mode, disable_web_page_preview) req = requests.post('https://api.telegram.org/bot%s/sendMessage' % token, data=data) return req.json() |