| 1 |
#!/usr/bin/env python3 |
| 2 |
# SPDX-FileCopyrightText: Christian Amsüss and the aiocoap contributors |
| 3 |
# |
| 4 |
# SPDX-License-Identifier: MIT |
| 5 |
|
| 6 |
"""A demo that opens a Kivy window and exposes it as a text and color display |
| 7 |
via CoAP |
| 8 |
|
| 9 |
The example is more comprehensive than the GTK ``./aiocoap-widgets`` demo (in |
| 10 |
that it offers GUI for registering at an RD, and to display log output) because |
| 11 |
unlike GTK it can also be run on Android, where neither command line arguments |
| 12 |
nor debug output are easily accessible. |
| 13 |
""" |
| 14 |
|
| 15 |
import asyncio |
| 16 |
import logging |
| 17 |
|
| 18 |
import aiocoap.cli.defaults |
| 19 |
from aiocoap import Context, Message, CHANGED, defaults |
| 20 |
from aiocoap.resource import Site, Resource, ObservableResource, WKCResource |
| 21 |
from aiocoap.resourcedirectory.client.register import Registerer |
| 22 |
|
| 23 |
from kivy.app import App |
| 24 |
from kivy.lang.builder import Builder |
| 25 |
from kivy.utils import escape_markup |
| 26 |
|
| 27 |
from widgets_common.kivy_resource import * |
| 28 |
|
| 29 |
kv = ''' |
| 30 |
TabbedPanel: |
| 31 |
do_default_tab: False |
| 32 |
TabbedPanelItem: |
| 33 |
text: 'Widgets' |
| 34 |
BoxLayout: |
| 35 |
padding: '5sp' |
| 36 |
spacing: '5sp' |
| 37 |
orientation: 'vertical' |
| 38 |
RstDocument: |
| 39 |
# Not that we'd intend to do any ReStructured text -- this is |
| 40 |
# just the most plain widget that just has a background color |
| 41 |
id: colorfield |
| 42 |
size_hint: 1, 1 |
| 43 |
background_color: (0, 0, 0, 1) |
| 44 |
Button: |
| 45 |
size_hint: 1, 0.1 |
| 46 |
id: btn |
| 47 |
text: 'Use CoAP discovery to write here or receive notifications of clicks.' |
| 48 |
TabbedPanelItem: |
| 49 |
text: 'RD' |
| 50 |
BoxLayout: |
| 51 |
pos: (0, 0) |
| 52 |
orientation: 'vertical' |
| 53 |
spacing: '5sp' |
| 54 |
BoxLayout: |
| 55 |
size_hint_max_y: '30sp' |
| 56 |
spacing: '5sp' |
| 57 |
orientation: 'horizontal' |
| 58 |
Label: |
| 59 |
text: 'RD URI:' |
| 60 |
TextInput: |
| 61 |
id: rd_uri |
| 62 |
text: 'coap://rd.coap.amsuess.com' |
| 63 |
multiline: False |
| 64 |
size_hint: 3, 1 |
| 65 |
BoxLayout: |
| 66 |
size_hint_max_y: '30sp' |
| 67 |
spacing: '5sp' |
| 68 |
orientation: 'horizontal' |
| 69 |
Label: |
| 70 |
text: 'Endpoint name:' |
| 71 |
TextInput: |
| 72 |
id: rd_ep |
| 73 |
text: 'kivy' |
| 74 |
multiline: False |
| 75 |
size_hint: 3, 1 |
| 76 |
BoxLayout: |
| 77 |
size_hint_max_y: '30sp' |
| 78 |
spacing: '5sp' |
| 79 |
orientation: 'horizontal' |
| 80 |
Label: |
| 81 |
text: 'Request reverse proxying:' |
| 82 |
CheckBox: |
| 83 |
id: rd_proxy |
| 84 |
size_hint: 3, 1 |
| 85 |
ToggleButton: |
| 86 |
size_hint_max_y: '30sp' |
| 87 |
id: rd_active |
| 88 |
text: 'Register' |
| 89 |
Label: |
| 90 |
size_hint_max_y: '30sp' |
| 91 |
id: rd_status |
| 92 |
text: '' |
| 93 |
Label: |
| 94 |
TabbedPanelItem: |
| 95 |
text: 'Logs' |
| 96 |
ScrollView: |
| 97 |
do_scroll_x: False |
| 98 |
do_scroll_y: True |
| 99 |
Label: |
| 100 |
id: logs |
| 101 |
markup: True |
| 102 |
# as recommended in ScrollView example |
| 103 |
size_hint_y: None |
| 104 |
height: self.texture_size[1] |
| 105 |
text_size: self.width, None |
| 106 |
''' |
| 107 |
|
| 108 |
class KivyLogFormatter(logging.Formatter): |
| 109 |
"""A logging.Formatter implementation that produces colored and escaped |
| 110 |
output for Kivy markup using widgets""" |
| 111 |
def usesTime(self): |
| 112 |
return True |
| 113 |
|
| 114 |
def color(self, level) -> str: |
| 115 |
normalized = (level - logging.DEBUG) / (logging.ERROR - logging.DEBUG) |
| 116 |
clipped = max(min(normalized, 1), 0) |
| 117 |
# gradient: white, green, red |
| 118 |
GREEN_X = 0.25 |
| 119 |
if clipped < GREEN_X: |
| 120 |
remapped = clipped / GREEN_X |
| 121 |
return (1 - remapped, 1, 1 - remapped) |
| 122 |
else: |
| 123 |
remapped = (clipped - GREEN_X) / (1 - GREEN_X) |
| 124 |
return (remapped ** 0.5, (1 - remapped) ** 0.5, 0) |
| 125 |
|
| 126 |
def formatMessage(self, record): |
| 127 |
color = bytes(int(c * 255) for c in self.color(record.levelno)).hex() |
| 128 |
return f'[color=808080][font_family=Roboto]{escape_markup(record.asctime)}[/font_family][/color] – [color={color}]{escape_markup(record.levelname)}[/color] – [color=808080]{escape_markup(record.name)}[/color] – {escape_markup(record.message)}' |
| 129 |
|
| 130 |
def formatException(self, record): |
| 131 |
result = super().formatException(record) |
| 132 |
return escape_markup(result) |
| 133 |
|
| 134 |
def formatStack(self, record): |
| 135 |
result = super().formatStack(record) |
| 136 |
return escape_markup(result) |
| 137 |
|
| 138 |
class HandlerToTextWidget(logging.Handler): |
| 139 |
"""A logging handler that renders into a Kivy text widget, and truncates |
| 140 |
early output to avoid ever-increasing memory requirements""" |
| 141 |
|
| 142 |
BUFLEN = 80000 |
| 143 |
|
| 144 |
def __init__(self, widget): |
| 145 |
super().__init__() |
| 146 |
self._widget = widget |
| 147 |
self._formatter = KivyLogFormatter() |
| 148 |
|
| 149 |
def emit(self, record): |
| 150 |
old_text = self._widget.text |
| 151 |
if len(old_text) > self.BUFLEN: |
| 152 |
old_text = old_text[-self.BUFLEN:] |
| 153 |
old_text = "…" + old_text[old_text.find('\n'):] |
| 154 |
self._widget.text = old_text + self._formatter.format(record) + "\n" |
| 155 |
|
| 156 |
class CoAPDisplay(App): |
| 157 |
rd_task = None |
| 158 |
|
| 159 |
def build(self): |
| 160 |
built = Builder.load_string(kv) |
| 161 |
|
| 162 |
coap_logger = logging.getLogger('coap') |
| 163 |
coap_logger.setLevel(logging.DEBUG) |
| 164 |
coap_logger.addHandler(HandlerToTextWidget(built.ids.logs)) |
| 165 |
|
| 166 |
coap_logger.info("aiocoap's selected server transports are " |
| 167 |
+ ":".join(defaults.get_default_servertransports())) |
| 168 |
|
| 169 |
for (name, f) in defaults.missing_module_functions.items(): |
| 170 |
missing = f() |
| 171 |
if missing: |
| 172 |
coap_logger.warning("Missing modules for feature %s: %s", name, missing) |
| 173 |
|
| 174 |
return built |
| 175 |
|
| 176 |
async def main(self): |
| 177 |
try: |
| 178 |
# Wrap main so that we have a chance of seeing exceptions raised |
| 179 |
# during CoAP setup |
| 180 |
await self._inner_main() |
| 181 |
except BaseException as e: |
| 182 |
log = logging.getLogger("coap") |
| 183 |
log.exception(e) |
| 184 |
raise e |
| 185 |
|
| 186 |
async def _inner_main(self): |
| 187 |
site = Site() |
| 188 |
site.add_resource(['text'], Text(self.root.ids.btn)) |
| 189 |
site.add_resource(['pressed'], PressState(self.root.ids.btn)) |
| 190 |
site.add_resource(['color'], Color(self.root.ids.colorfield, 'background_color')) |
| 191 |
site.add_resource(['.well-known', 'core'], |
| 192 |
WKCResource(site.get_resources_as_linkheader)) |
| 193 |
|
| 194 |
self.context = await Context.create_server_context(site, loggername='coap') |
| 195 |
|
| 196 |
self.root.ids.rd_active.bind(on_press=self.on_rd_active_pressed) |
| 197 |
|
| 198 |
def on_rd_active_pressed(self, btn): |
| 199 |
if btn.state == 'down': |
| 200 |
self.rd_task = asyncio.create_task(self.register_rd()) |
| 201 |
self.root.ids.rd_uri.disabled = True |
| 202 |
self.root.ids.rd_ep.disabled = True |
| 203 |
self.root.ids.rd_proxy.disabled = True |
| 204 |
else: |
| 205 |
btn.state = 'down' |
| 206 |
if self.rd_task is not None: |
| 207 |
self.rd_task.cancel() |
| 208 |
self.rd_task = None |
| 209 |
|
| 210 |
async def register_rd(self): |
| 211 |
try: |
| 212 |
rd_uri = self.root.ids.rd_uri.text |
| 213 |
rd_ep = self.root.ids.rd_ep.text |
| 214 |
rd_proxy = self.root.ids.rd_proxy.active |
| 215 |
|
| 216 |
params = {'ep': rd_ep} |
| 217 |
if rd_proxy: |
| 218 |
params['proxy'] = 'on' |
| 219 |
|
| 220 |
registerer = Registerer( |
| 221 |
self.context, |
| 222 |
rd=rd_uri, |
| 223 |
registration_parameters=params, |
| 224 |
loggername='coap.rd-ep', |
| 225 |
) |
| 226 |
old_set_state = registerer._set_state |
| 227 |
def new_set_state(state): |
| 228 |
self.root.ids.rd_status.text = 'Current status: %s' % state |
| 229 |
return old_set_state(state) |
| 230 |
registerer._set_state = new_set_state |
| 231 |
await asyncio.Future() |
| 232 |
except Exception as e: |
| 233 |
self.root.ids.rd_status.text = 'Failed (%s)' % e |
| 234 |
logging.getLogger("coap").exception(e) |
| 235 |
except asyncio.CancelledError: |
| 236 |
self.root.ids.rd_status.text = 'Shutting down registration…' |
| 237 |
await registerer.shutdown() |
| 238 |
self.root.ids.rd_status.text = 'Registration terminated' |
| 239 |
finally: |
| 240 |
self.root.ids.rd_active.state = 'normal' |
| 241 |
|
| 242 |
self.root.ids.rd_uri.disabled = False |
| 243 |
self.root.ids.rd_ep.disabled = False |
| 244 |
self.root.ids.rd_proxy.disabled = False |
| 245 |
|
| 246 |
def on_start(self): |
| •247 |
asyncio.get_running_loop().create_task(self.main()) |
| 248 |
|
| 249 |
if __name__ == '__main__': |
| 250 |
# Having dependency issues is hard to debug on Android; better print out |
| 251 |
# the state of affairs: |
| 252 |
aiocoap.cli.defaults.main() |
| 253 |
asyncio.run(CoAPDisplay().async_run()) |