-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathconfigv2_editor.py
365 lines (301 loc) · 11.8 KB
/
configv2_editor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock, mainthread
from kivy.config import ConfigParser
from kivy.uix.settings import Settings
from kivy.uix.label import Label
from kivy.logger import Logger
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, BooleanProperty, ListProperty, ObjectProperty
from multi_input_box import MultiInputBox
from functools import partial
import json
import configparser
import threading
import traceback
Builder.load_string('''
<ConfigV2Editor>:
placeholder: placeholder
BoxLayout:
canvas:
Color:
rgba: 0.3, 0.3, 0.3, 1
Rectangle:
size: self.size
pos: self.pos
orientation: 'vertical'
BoxLayout:
size_hint_y: None
height: dp(60)
padding: dp(8)
spacing: dp(16)
Button:
text: 'New Entry'
on_press: root.new_entry();
Button:
text: 'New Output Switch'
on_press: root.new_switch(True);
Button:
text: 'New Input Switch'
on_press: root.new_switch(False);
Button:
text: 'Back'
on_press: root.close()
BoxLayout:
id: placeholder
orientation: 'vertical'
<InterfaceWithScrollableSidebar>:
orientation: 'horizontal'
menu: menu
content: content
MyMenuSidebar:
id: menu
ContentPanel:
id: content
current_uid: menu.selected_uid
<MyMenuSidebar>:
size_hint_x: None
width: '200dp'
buttons_layout: menu
ScrollView:
GridLayout:
size_hint_y: None
height: self.minimum_height
pos: root.pos
cols: 1
id: menu
padding: 5
canvas.after:
Color:
rgb: .2, .2, .2
Rectangle:
pos: self.right - 1, self.y
size: 1, self.height
''')
class ConfigV2Editor(Screen):
sections = None
config = None
configdata = []
msp = None
force_close = False
start = False
progress = None
count = 0
tmo = None
def new_entry(self):
o = MultiInputBox(title='Add new entry')
o.setOptions(['section', 'key', 'value'], self._new_entry)
o.open()
def _new_entry(self, opts):
if opts and opts['section'] and opts['key'] and opts['value']:
self.app.comms.write(f"config-set \"{opts['section']}\" {opts['key']} \"{opts['value']}\"\n")
def new_switch(self, flg):
o = MultiInputBox(title=f"Add {'Output' if flg else 'Input'} Switch")
if flg:
o.setOptions(['Name', 'On Command', 'Off Command', 'Pin'], partial(self._new_switch, flg))
else:
o.setOptions(['Name', 'Command', 'Pin'], partial(self._new_switch, flg))
o.open()
def _new_switch(self, flg, opts):
if opts and opts['Name']:
sw = opts['Name']
self.app.comms.write(f"config-set switch {sw}.enable = true\n")
if flg:
for k, v in {'Off Command': 'input_off_command', 'On Command': 'input_on_command', 'Pin': 'output_pin'}.items():
self.app.comms.write(f"config-set switch {sw}.{v} = {opts[k]}\n")
else:
for k, v in {'Command': 'output_on_command', 'Pin': 'input_pin'}.items():
self.app.comms.write(f"config-set switch {sw}.{v} = {opts[k]}\n")
def _add_line(self, line):
if not self.start:
return
ll = line.lstrip().rstrip()
self.count += 1
if self.count > 10:
self._update_progress(ll)
self.count = 0
if not ll.startswith("#") and ll != "":
if ll == "ok":
# finished
if self.tmo:
self.tmo.cancel()
self.tmo = None
self.start = False
self._update_progress("Processing config....")
# run the build in a thread as it is so slow
Logger.debug("ConfigV2Editor: starting build")
t = threading.Thread(target=self._build, daemon=True)
t.start()
else:
self.configdata.append(ll)
def open(self):
if self.msp is None:
# first time opening we need to populate the settings screen
self.force_close = False
self.start = False
self.app = App.get_running_app()
self.ids.placeholder.add_widget(Label(text='Loading.... This may take a while!'))
self.progress = Label(text="Current line....")
self.ids.placeholder.add_widget(self.progress)
self.manager.current = 'config_editor'
self.config = ConfigParser.get_configparser('Smoothie Config')
if self.config is None:
self.config = ConfigParser(name='Smoothie Config')
else:
for section in self.config.sections():
self.config.remove_section(section)
# get config, parse and populate
self.start = False
self.app.comms.redirect_incoming(self._add_line)
# wait for any outstanding queries
Clock.schedule_once(self._send_command, 1)
else:
# already been populated just switch to the screen
self.manager.current = 'config_editor'
def _timed_out(self, dt):
Logger.error("ConfigV2Editor: Command timed out")
self.app.main_window.async_display("Error cat config.ini command timed out")
self.close()
def _send_command(self, dt):
# issue command
Logger.debug("ConfigV2Editor: fetching config.ini")
self.start = True
self.app.comms.write('cat /sd/config.ini\n')
self.app.comms.write('\n') # get an ok to indicate end of cat
self.tmo = Clock.schedule_once(self._timed_out, 10)
def _build(self):
self.app.comms.redirect_incoming(None)
try:
self.config.read_string('\n'.join(self.configdata))
except Exception as e:
Logger.error(f"ConfigV2Editor: Error parsing the config file: {e}")
self.app.main_window.async_display("Error parsing config file, see log")
self.close()
return
sections = []
try:
for section in self.config.sections():
self._update_progress(section)
subkeys = {}
for (key, v) in self.config.items(section):
if self.force_close:
return
o = v.find('#')
if o > 0:
# convert comment into desc and strip from value
comment = v[o + 1:]
v = v[0:o].rstrip()
self.config.set(section, key, v)
else:
comment = ""
if '.' in key:
(subkey, k) = key.split('.')
x = (k, key, v, comment)
else:
subkey = " "
x = (key, key, v, comment)
if subkey in subkeys:
subkeys[subkey].append(x)
else:
subkeys[subkey] = [x]
jsondata = []
for t, l in subkeys.items():
if t != " ":
jsondata.append({"type": "title", "title": t})
for i in l:
tit, key, v, comment = i
if v in ['true', 'false']:
tt = {"type": 'bool', 'values': ['false', 'true'], "title": tit, "desc": comment, "section": section, "key": key}
else:
tt = {"type": 'string', "title": tit, "desc": comment, "section": section, "key": key}
jsondata.append(tt)
sections.append((section, json.dumps(jsondata)))
except Exception as e:
Logger.error(f"ConfigV2Editor: Error building the config file: {e}")
self.app.main_window.async_display("Error building config file, see log")
self.close()
return
self.sections = sections
self._done()
@mainthread
def _update_progress(self, sec):
if self.progress is not None:
self.progress.text = sec
self.progress.texture_update()
@mainthread
def _done(self):
self._update_progress("Creating Settings Panel....")
try:
if self.msp is None:
self.msp = MySettingsPanel()
for s in self.sections:
self.msp.add_json_panel(s[0], self.config, data=s[1])
ss = self.ids.placeholder
ss.clear_widgets()
ss.add_widget(self.msp)
self.sections = None
self.progress = None
self.configdata = []
except Exception as e:
Logger.error(f"ConfigV2Editor: Error displaying the config panel: {e} {traceback.format_exc()}")
self.app.main_window.async_display("Error displaying config panel, see log")
@mainthread
def close(self):
# due to bugs in settings not getting cleared we leave it
# all open and just switch screens
self.manager.current = 'main'
class MyMenuSidebar(FloatLayout):
selected_uid = NumericProperty(0)
buttons_layout = ObjectProperty(None)
close_button = ObjectProperty(None)
def add_item(self, name, uid):
label = SettingSidebarLabel(text=name, uid=uid, menu=self)
if len(self.buttons_layout.children) == 0:
label.selected = True
if self.buttons_layout is not None:
self.buttons_layout.add_widget(label)
def on_selected_uid(self, *args):
for button in self.buttons_layout.children:
if button.uid != self.selected_uid:
button.selected = False
def on_close(self):
self.buttons_layout.clear_widgets()
self.selected_uid = 0
class SettingSidebarLabel(Label):
selected = BooleanProperty(False)
uid = NumericProperty(0)
menu = ObjectProperty(None)
def on_touch_down(self, touch):
if not self.collide_point(*touch.pos):
return
self.selected = True
self.menu.selected_uid = self.uid
class InterfaceWithScrollableSidebar(BoxLayout):
menu = ObjectProperty()
content = ObjectProperty()
def __init__(self, *args, **kwargs):
super(InterfaceWithScrollableSidebar, self).__init__(*args, **kwargs)
def add_panel(self, panel, name, uid):
self.menu.add_item(name, uid)
self.content.add_panel(panel, name, uid)
def on_close(self):
# print("InterfaceWithScrollableSidebar on_close()")
self.menu.on_close()
self.content.clear_widgets()
class MySettingsPanel(Settings):
def __init__(self, *args, **kwargs):
self.interface_cls = InterfaceWithScrollableSidebar
super(MySettingsPanel, self).__init__(*args, **kwargs)
# if App.get_running_app().is_desktop <= 1:
# # For RPI gets the instance of the ContentPanel which is a ScrollView
# # and sets the friction attr in the effects
# # This may only work with an panel of type SettingsWithNoMenu
# self.interface.effect_y.friction = 1.0
def on_close(self):
if self.interface is not None:
self.interface.on_close()
def on_config_change(self, config, section, key, value):
app = App.get_running_app()
app.comms.write(f'config-set "{section}" {key} "{value}"\n')