From a9a241ad19449c29b68cd4a5b539bcbec816e341 Mon Sep 17 00:00:00 2001 From: Evgeny Sorokin Date: Wed, 17 Jan 2024 03:35:59 +0300 Subject: lws: pump page rewritten to python --- bin/web_kbn.py | 29 ++++++++++++- include/py/homekit/util.py | 5 +-- localwebsite/classes/GPIORelaydClient.php | 18 -------- localwebsite/classes/InverterdClient.php | 69 ------------------------------- localwebsite/handlers/MiscHandler.php | 42 ------------------- localwebsite/htdocs/index.php | 2 - localwebsite/templates-web/pump.twig | 17 -------- web/kbn_templates/pump.j2 | 17 ++++++++ 8 files changed, 47 insertions(+), 152 deletions(-) delete mode 100644 localwebsite/classes/GPIORelaydClient.php delete mode 100644 localwebsite/classes/InverterdClient.php delete mode 100644 localwebsite/templates-web/pump.twig create mode 100644 web/kbn_templates/pump.j2 diff --git a/bin/web_kbn.py b/bin/web_kbn.py index d9d0035..09fa9c6 100644 --- a/bin/web_kbn.py +++ b/bin/web_kbn.py @@ -14,6 +14,7 @@ from homekit.config import config, AppConfigUnit from homekit.util import homekit_path, filesize_fmt, seconds_to_human_readable_string from homekit.modem import E3372, ModemsConfig, MacroNetWorkType from homekit.inverter.config import InverterdConfig +from homekit.relay.sunxi_h3_client import RelayClient from homekit import http @@ -24,7 +25,8 @@ class WebKbnConfig(AppConfigUnit): def schema(cls) -> Optional[dict]: return { 'listen_addr': cls._addr_schema(required=True), - 'assets_public_path': {'type': 'string'} + 'assets_public_path': {'type': 'string'}, + 'pump_addr': cls._addr_schema(required=True), } @@ -91,6 +93,13 @@ def get_modem_data(modem_cfg: dict, get_raw=False) -> Union[dict, tuple]: } +def get_pump_client() -> RelayClient: + addr = config.app_config['pump_addr'] + cl = RelayClient(host=addr.host, port=addr.port) + cl.connect() + return cl + + def get_inverter_client() -> inverterd.Client: cl = inverterd.Client(host=InverterdConfig()['remote_addr'].host) cl.connect() @@ -180,6 +189,7 @@ class WebSite(http.HTTPServer): self.get('/inverter.cgi', self.inverter) self.get('/inverter.ajx', self.inverter_ajx) + self.get('/pump.cgi', self.pump) async def render_page(self, req: http.Request, @@ -263,6 +273,23 @@ class WebSite(http.HTTPServer): status, rated, html = await asyncio.get_event_loop().run_in_executor(None, get_inverter_data) return self.ok({'html': html}) + async def pump(self, req: http.Request): + # TODO + # these are blocking calls + # should be rewritten using aio + + cl = get_pump_client() + + action = req.query.get('set', None) + if action in ('on', 'off'): + getattr(cl, action)() + raise HTTPFound('/pump.cgi') + + status = cl.status() + return await self.render_page(req, 'pump', + title='Насос', + context=dict(status=status)) + if __name__ == '__main__': config.load_app(WebKbnConfig) diff --git a/include/py/homekit/util.py b/include/py/homekit/util.py index f267488..78a78a0 100644 --- a/include/py/homekit/util.py +++ b/include/py/homekit/util.py @@ -12,7 +12,7 @@ import re import os from enum import Enum -from datetime import datetime, timedelta +from datetime import datetime from typing import Optional, List from zlib import adler32 @@ -256,8 +256,7 @@ def filesize_fmt(num, suffix="B") -> str: def seconds_to_human_readable_string(seconds: int) -> str: - duration = timedelta(seconds=seconds) - days, remainder = divmod(duration.total_seconds(), 86400) + days, remainder = divmod(seconds, 86400) hours, remainder = divmod(remainder, 3600) minutes, seconds = divmod(remainder, 60) diff --git a/localwebsite/classes/GPIORelaydClient.php b/localwebsite/classes/GPIORelaydClient.php deleted file mode 100644 index 89c8dc9..0000000 --- a/localwebsite/classes/GPIORelaydClient.php +++ /dev/null @@ -1,18 +0,0 @@ -send($status); - return $this->recv(); - } - - public function getStatus() { - $this->send('get'); - return $this->recv(); - } - -} \ No newline at end of file diff --git a/localwebsite/classes/InverterdClient.php b/localwebsite/classes/InverterdClient.php deleted file mode 100644 index b68b784..0000000 --- a/localwebsite/classes/InverterdClient.php +++ /dev/null @@ -1,69 +0,0 @@ -send("v $v"); - return $this->recv(); - } - - /** - * @throws Exception - */ - public function setFormat(string $fmt): string - { - $this->send("format $fmt"); - return $this->recv(); - } - - /** - * @throws Exception - */ - public function exec(string $command, array $arguments = []): string - { - $buf = "exec $command"; - if (!empty($arguments)) { - foreach ($arguments as $arg) - $buf .= " $arg"; - } - $this->send($buf); - return $this->recv(); - } - - /** - * @throws Exception - */ - public function recv() - { - $recv_buf = ''; - $buf = ''; - - while (true) { - $result = socket_recv($this->sock, $recv_buf, 1024, 0); - if ($result === false) - throw new Exception(__METHOD__ . ": socket_recv() failed: " . $this->getSocketError()); - - // peer disconnected - if ($result === 0) - break; - - $buf .= $recv_buf; - if (endsWith($buf, "\r\n\r\n")) - break; - } - - $response = explode("\r\n", $buf); - $status = array_shift($response); - if (!in_array($status, ['ok', 'err'])) - throw new Exception(__METHOD__.': unexpected status ('.$status.')'); - if ($status == 'err') - throw new Exception(empty($response) ? 'unknown inverterd error' : $response[0]); - - return trim(implode("\r\n", $response)); - } - -} \ No newline at end of file diff --git a/localwebsite/handlers/MiscHandler.php b/localwebsite/handlers/MiscHandler.php index 4c5a25e..efaca22 100644 --- a/localwebsite/handlers/MiscHandler.php +++ b/localwebsite/handlers/MiscHandler.php @@ -3,17 +3,6 @@ class MiscHandler extends RequestHandler { - public function GET_main() { - global $config; - $this->tpl->set_title('Главная'); - $this->tpl->set([ - 'grafana_sensors_url' => $config['grafana_sensors_url'], - 'grafana_inverter_url' => $config['grafana_inverter_url'], - 'cameras' => $config['cam_list']['labels'] - ]); - $this->tpl->render_page('index.twig'); - } - public function GET_sensors_page() { global $config; @@ -30,29 +19,6 @@ class MiscHandler extends RequestHandler $this->tpl->render_page('sensors.twig'); } - public function GET_pump_page() { - global $config; - - if (isset($_GET['alt']) && $_GET['alt'] == 1) - $config['pump_host'] = '192.168.5.223'; - - list($set) = $this->input('set'); - $client = new GPIORelaydClient($config['pump_host'], $config['pump_port']); - - if ($set == GPIORelaydClient::STATUS_ON || $set == GPIORelaydClient::STATUS_OFF) { - $client->setStatus($set); - redirect('/pump/'); - } - - $status = $client->getStatus(); - - $this->tpl->set([ - 'status' => $status - ]); - $this->tpl->set_title('Насос'); - $this->tpl->render_page('pump.twig'); - } - public function GET_cams() { global $config; @@ -160,12 +126,4 @@ class MiscHandler extends RequestHandler } } - public function GET_debug() { - print_r($_SERVER); - } - - public function GET_phpinfo() { - phpinfo(); - } - } diff --git a/localwebsite/htdocs/index.php b/localwebsite/htdocs/index.php index eeeaacb..cd32132 100644 --- a/localwebsite/htdocs/index.php +++ b/localwebsite/htdocs/index.php @@ -18,8 +18,6 @@ $router->add('inverter/set-osp/', 'Inverter set_osp'); // misc $router->add('/', 'Misc main'); $router->add('sensors/', 'Misc sensors_page'); -$router->add('pump/', 'Misc pump_page'); -$router->add('phpinfo/', 'Misc phpinfo'); $router->add('cams/', 'Misc cams'); $router->add('cams/([\d,]+)/', 'Misc cams id=$(1)'); $router->add('cams/stat/', 'Misc cams_stat'); diff --git a/localwebsite/templates-web/pump.twig b/localwebsite/templates-web/pump.twig deleted file mode 100644 index 3bce0e2..0000000 --- a/localwebsite/templates-web/pump.twig +++ /dev/null @@ -1,17 +0,0 @@ -{% include 'bc.twig' with { - history: [ - {text: "Насос" } - ] -} %} - -
- - Сейчас насос - {% if status == 'on' %} - включен.

- - {% else %} - выключен.

- - {% endif %} -
\ No newline at end of file diff --git a/web/kbn_templates/pump.j2 b/web/kbn_templates/pump.j2 new file mode 100644 index 0000000..28d5c9d --- /dev/null +++ b/web/kbn_templates/pump.j2 @@ -0,0 +1,17 @@ +{% extends "base.j2" %} + +{% block content %} +{{ breadcrumbs([{'text': 'Насос'}]) }} + +
+ + Сейчас насос + {% if status == 'on' %} + включен.

+ + {% else %} + выключен.

+ + {% endif %} +
+{% endblock %} -- cgit v1.2.3