Skip to content

Commit

Permalink
script/dnet: implement PEP 8
Browse files Browse the repository at this point in the history
  • Loading branch information
lunar-mining committed Sep 10, 2023
1 parent 3be0e7a commit 259ecbc
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 46 deletions.
18 changes: 11 additions & 7 deletions script/dnet/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,18 @@
from rpc import JsonRpc
from view import View


class Dnetview:

def __init__(self):
self.ev = asyncio.get_event_loop()
self.queue = asyncio.Queue()

self.config = self.get_config()
self.model = Model()
self.view = View(self.model)

async def subscribe(self, rpc, name, port):
info = {}

while True:
try:
logging.debug(f"Start {name} RPC on port {port}")
Expand Down Expand Up @@ -77,7 +77,8 @@ async def start_connect_slots(self, nodes):
async with asyncio.TaskGroup() as tg:
for i, node in enumerate(nodes):
rpc = JsonRpc()
subscribe = tg.create_task(self.subscribe(rpc, node['name'], node['port']))
subscribe = tg.create_task(self.subscribe(
rpc, node['name'], node['port']))
nodes = tg.create_task(self.update_info())

async def update_info(self):
Expand All @@ -99,17 +100,19 @@ async def update_info(self):
logging.debug("update_model(): error {}", e)

def main(self):
logging.basicConfig(filename='dnet.log', encoding='utf-8', level=logging.DEBUG)
logging.basicConfig(filename='dnet.log',
encoding='utf-8',
level=logging.DEBUG)
nodes = self.config.get("nodes")

self.ev.create_task(self.start_connect_slots(nodes))
self.ev.create_task(self.view.update_view())
self.ev.create_task(self.view.render_info())

loop = urwid.MainLoop(self.view.ui, self.view.palette,
unhandled_input=self.unhandled_input,
event_loop=urwid.AsyncioEventLoop(loop=self.ev))

unhandled_input=self.unhandled_input,
event_loop=urwid.AsyncioEventLoop(
loop=self.ev))
loop.run()

def unhandled_input(self, key):
Expand All @@ -118,6 +121,7 @@ def unhandled_input(self, key):
task.cancel()
raise urwid.ExitMainLoop()


if __name__ == '__main__':
dnet = Dnetview()
dnet.main()
13 changes: 6 additions & 7 deletions script/dnet/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

import logging


class Model:

def __init__(self):
self.info = Info()
self.nodes = {}
Expand All @@ -27,10 +29,8 @@ def update_node(self, key, value):

def handle_nodes(self, node):
channel_lookup = {}

name = list(node.keys())[0]
values = list(node.values())[0]

info = values["result"]
channels = info["channels"]

Expand Down Expand Up @@ -70,7 +70,6 @@ def handle_nodes(self, node):
def handle_event(self, event):
name = list(event.keys())[0]
values = list(event.values())[0]

params = values.get("params")
event = params[0].get("event")
info = params[0].get("info")
Expand All @@ -92,7 +91,9 @@ def handle_event(self, event):
def __repr__(self):
return f"{self.nodes}"


class Info:

def __init__(self):
self.outbounds = {}
self.inbound = {}
Expand All @@ -119,10 +120,8 @@ def update_msg(self, key, value):
self.msgs[key] = [value]

def __repr__(self):
return (
f"outbound: {self.outbounds}"
return (f"outbound: {self.outbounds}"
f"inbound: {self.inbound}"
f"manual: {self.manual}"
f"seed: {self.seed}"
f"msg: {self.msgs}"
)
f"msg: {self.msgs}")
8 changes: 7 additions & 1 deletion script/dnet/rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,15 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

import asyncio, json, random, time, logging
import json
import time
import random
import logging
import asyncio


class JsonRpc:

async def start(self, server, port):
reader, writer = await asyncio.open_connection(server, port)
self.reader = reader
Expand Down
3 changes: 3 additions & 0 deletions script/dnet/scroll.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
# Add support for ScrollBar class (see stig.tui.scroll)
# https://github.com/urwid/urwid/issues/226
class ListBox_patched(urwid.ListBox):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._rows_max = None
Expand Down Expand Up @@ -330,6 +331,7 @@ def rows_max(self, size=None, focus=False):
DEFAULT_TROUGH_CHAR = " "
DEFAULT_SIDE = SCROLLBAR_RIGHT


class ScrollBar(urwid.WidgetDecoration):

_thumb_char = DEFAULT_THUMB_CHAR
Expand Down Expand Up @@ -570,4 +572,5 @@ def mouse_event(self, size, event, button, col, row, focus):

return False


__all__ = ["Scrollable", "ScrollBar"]
63 changes: 32 additions & 31 deletions script/dnet/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,33 @@
import urwid
import logging
import asyncio
import datetime
import datetime as dt

from scroll import ScrollBar, Scrollable
from model import Model

event_loop = asyncio.get_event_loop()


class LeftList(urwid.ListBox):

def focus_next(self):
try:
self.body.set_focus(self.body.get_next(self.body.get_focus()[1])[1])
self.body.set_focus(self.body.get_next(
self.body.get_focus()[1])[1])
except:
pass

def focus_previous(self):
try:
self.body.set_focus(self.body.get_prev(self.body.get_focus()[1])[1])
self.body.set_focus(self.body.get_prev(
self.body.get_focus()[1])[1])
except:
pass


class NodeView(urwid.WidgetWrap):

def __init__(self, info):
self.name = info
self.text = urwid.Text(f"{self.name}")
Expand All @@ -62,7 +69,9 @@ def get_widget(self):
def get_name(self):
return self.name


class ConnectView(urwid.WidgetWrap):

def __init__(self, info):
self.name = info
self.text = urwid.Text(f"{self.name}")
Expand All @@ -74,8 +83,6 @@ def selectable(self):
return True

def keypress(self, size, key):
#if key in ('q'):
# raise urwid.ExitMainLoop()
return key

def update_w(self):
Expand All @@ -87,7 +94,9 @@ def get_widget(self):
def get_name(self):
return self.name


class SlotView(urwid.WidgetWrap):

def __init__(self, info):
self.name = info
self.text = urwid.Text(f"{self.name}")
Expand All @@ -99,8 +108,6 @@ def selectable(self):
return True

def keypress(self, size, key):
#if key in ('q'):
# raise urwid.ExitMainLoop()
return key

def update_w(self):
Expand All @@ -112,6 +119,7 @@ def get_widget(self):
def get_name(self):
return self.name


class View():
palette = [
('body','light gray','black', 'standout'),
Expand All @@ -124,26 +132,24 @@ def __init__(self, model):
self.pile = urwid.Pile([info_text])
scroll = ScrollBar(Scrollable(self.pile))
rightbox = urwid.LineBox(scroll)

self.listbox_content = []
self.listwalker = urwid.SimpleListWalker(self.listbox_content)
self.list = LeftList(self.listwalker)
leftbox = urwid.LineBox(self.list)

columns = urwid.Columns([leftbox, rightbox], focus_column=0)
self.ui = urwid.Frame(urwid.AttrWrap( columns, 'body' ))

async def update_view(self):
names = []
while True:
names = []
await asyncio.sleep(0.1)
for item in self.listwalker.contents:
name = item.get_name()
names.append(name)

for name, values in self.model.nodes.items():
if name in names:
continue

else:
widget = NodeView(name)
self.listwalker.contents.append(widget)
Expand Down Expand Up @@ -172,44 +178,39 @@ async def update_view(self):
widget = ConnectView(" manual")
self.listwalker.contents.append(widget)

await asyncio.sleep(0.1)

async def render_info(self):
while True:
await asyncio.sleep(0.1)
self.pile.contents.clear()
focus_w = self.list.get_focus()
match focus_w[0].get_widget():

case "NodeView":
self.pile.contents.append((
urwid.Text(f"Node selected"),
self.pile.options()))

case "ConnectView":
self.pile.contents.append((
urwid.Text("Connection selected"),
self.pile.options()))

case "SlotView":
name = focus_w[0].get_name()
# Remove the prepend
name = name[7:]
numbered_name = focus_w[0].get_name()
# Remove numbering
name = numbered_name[7:]

if name in self.model.info.msgs.keys():
values = (
self.model.info.msgs.get(name)
)
values = (self.model.info.msgs.get(name))

for value in values:
nanotime = (
int(value[0])
)
time = (
datetime.datetime.fromtimestamp(
nanotime/1000000000).strftime(
'%Y-%m-%d %H:%M:%S.%f')
)
nano = (int(value[0]))
time = (dt.datetime
.fromtimestamp(nano/1000000000)
.strftime('%Y-%m-%d %H:%M:%S.%f'))
event = value[1]
msg = value[2]
#logging.debug(values)
self.pile.contents.append((
urwid.Text(
self.pile.contents.append((urwid.Text(
f"{time}: {event}: {msg}"),
self.pile.options()))
self.pile.options()))

0 comments on commit 259ecbc

Please sign in to comment.