-
Notifications
You must be signed in to change notification settings - Fork 2
/
__init__.py
528 lines (427 loc) · 13.6 KB
/
__init__.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# This file is part of the octopusLAB project
# The MIT License (MIT)
# Copyright (c) 2016-2020 Jan Copak, Petr Kracik, Vasek Chalupnicek, Jan Cespivo, Milan Spacek
"""
from shell import shell
shell()
> cat / edit / ls / mkdir / cp / rm / find / df ...
--------
autostart:
>>> from config import Config
>>> cc = Config("boot")
>>> cc.set("import_shell",1)
>>> cc.save()
--------
last update:
"""
__version__ = "0.33.3-20200630" # 533
# toto: kill, wget/wsend?, ...
SEPARATOR_WIDTH = 50
_command_registry = {}
_background_jobs = {}
_wc = None # global wifi_connect
def _thread_wrapper(func, job_id, *arguments):
try:
func(*arguments)
finally:
del _background_jobs[job_id]
print('[{job_id}] stopped'.format(job_id=job_id))
def _background_func(func, command_list):
def _wrapper(*arguments):
from _thread import start_new_thread
from time import ticks_ms
job_id = start_time = ticks_ms()
start_new_thread(_thread_wrapper, (func, job_id) + arguments)
_background_jobs[job_id] = {'start_time': start_time, 'command_list': command_list}
print('[{job_id}] started'.format(job_id=job_id))
return _wrapper
def _register_command(func_name):
def _command(func):
_command_registry[func_name] = func
return func
return _command
def command(func_or_name):
if callable(func_or_name):
return _register_command(func_or_name.__name__)(func_or_name)
elif isinstance(func_or_name, str):
name = func_or_name
return _register_command(name)
raise ImportError('bad decorator command')
@command
def sleep(seconds):
from time import sleep
sleep(float(seconds))
@command
def ifconfig():
if _wc is None:
print("ifconfig: Connection not active")
return
from .terminal import terminal_color
print('-' * SEPARATOR_WIDTH)
try:
print('IP address:', terminal_color(_wc.sta_if.ifconfig()[0]))
print('subnet mask:', _wc.sta_if.ifconfig()[1])
print('gateway:', _wc.sta_if.ifconfig()[2])
print('DNS server:', _wc.sta_if.ifconfig()[3])
except Exception as e:
print("Exception: {0}".format(e))
from ubinascii import hexlify
try:
MAC = terminal_color(hexlify(_wc.sta_if.config('mac'), ':').decode())
except:
MAC = "Err: w.sta_if"
print("HWaddr (MAC): " + MAC)
print('-' * SEPARATOR_WIDTH)
@command
def cat(file='/main.py', title=False): # concatenate - prepare
"""print data: f("filename") """
fi = open(file, 'r')
if title:
from .terminal import printTitle
printTitle("file > " + file)
# file statistic
lines = 0
words = 0
characters = 0
for line in fi:
wordslist = line.split()
lines = lines + 1
words = words + len(wordslist)
characters = characters + len(line)
print("Statistic > lines: " + str(lines) + " | words: " + str(
words) + " | chars: " + str(characters))
print('-' * SEPARATOR_WIDTH)
fi = open(file, 'r')
for line in fi:
print(line, end="")
print()
globals()["cat"] = cat
@command
def edit(file="/main.py"):
from .editor import edit
edit(file)
@command
def ls(directory="", line=False, cols=2, goPrint=True):
from .terminal import terminal_color
debug = False
# if goPrint: printTitle("list > " + directory)
# from os import listdir
from uos import ilistdir
from os import stat
ls_all = ilistdir(directory)
if debug:
print(directory)
print(str(ls_all))
# ls.sort()
if goPrint:
col = 0
print("%8s %s " % ("d/[B]", "name"))
for f in ls_all:
if f[1] == 16384:
# print(terminal_color(str(f[0])))
print("%8s %s " % ("---", terminal_color(str(f[0]))))
if f[1] == 32768:
# print(str(f[0]) + "" + str(stat(f[0])[6]))
try:
print(
"%8s %s" % (str(stat(f[0])[6]), terminal_color(str(f[0]), 36)))
except:
# print("%8s %s" % ( str(stat(directory+f[0])[6]), terminal_color(str(f[0]),36)))
print("%8s %s" % ("?", terminal_color(str(f[0]), 36)))
"""if line:
print("%25s" % f,end="")
col += 1
if col % cols:
print()
else:"""
print()
return ls
# globals()["ls"]=ls
@command
def cp(fileSource, fileTarget="/main.py"):
from .terminal import printTitle, runningEffect
printTitle("file_copy to " + fileTarget)
print("(Always be careful)")
fs = open(fileSource)
data = fs.read()
fs.close()
runningEffect()
ft = open(fileTarget, 'w')
ft.write(data)
ft.close()
print(" ok")
@command
def mkdir(directory):
try:
from os import mkdir
mkdir(directory)
except Exception as e:
print("Exception: {0}".format(e))
@command
def rm(file=None):
if file:
from .terminal import printTitle, runningEffect
printTitle("remove file > " + file)
try:
from os import remove
print("(Always be careful)")
remove(file)
runningEffect()
except Exception as e:
print("Exception: {0}".format(e))
else:
print("Input param: path + file name")
@command
def find(xstr, directory="examples"): # ?getcwd()
from os import listdir
from .terminal import printTitle
printTitle("find file > " + xstr)
ls = listdir(directory)
ls.sort()
for f in ls:
if f.find(xstr) > -1:
print(f)
@command
def df(echo=True):
from os import statvfs
if echo:
print("> flash info: " + str(statvfs("/")))
flash_free = int(statvfs("/")[0]) * int(statvfs("/")[3])
if echo:
print("> flash free: " + str(flash_free))
return flash_free
@command
def free(echo=True):
from gc import mem_free
if echo:
print("--- RAM free ---> " + str(mem_free()))
return mem_free()
@command
def top():
import os, ubinascii, machine
from time import ticks_ms, ticks_diff
from machine import RTC
from gc import mem_free, mem_alloc
import esp32
from .terminal import terminal_color, printBar
def add0(sn):
ret_str = str(sn)
if int(sn) < 10:
ret_str = "0" + str(sn)
return ret_str
def get_hhmmss(separator=":"):
rtc = RTC() # real time
# get_hhmm(separator) | separator = string: "-" / " "
hh = add0(rtc.datetime()[4])
mm = add0(rtc.datetime()[5])
ss = add0(rtc.datetime()[6])
return hh + separator + mm + separator + ss
def f2c(Fahrenheit):
Celsius = (Fahrenheit - 32) * 5.0/9.0
return Celsius
bar100 = 30
print(terminal_color("-" * (bar100 + 20)))
print(terminal_color("free Memory and Flash >"))
# mem_alloc() * 100
if mem_free() > 3000000:
ram100 = 4093504
else:
ram100 = 95000 # hypotetic maximum
b1 = ram100 / bar100
ram = mem_free()
print("RAM: ", end="")
printBar(bar100 - int(ram / b1), int(ram / b1))
print(terminal_color(str(ram / 1000) + " kB"))
flash100 = 2097152
b1 = flash100 / bar100
flash = df(False)
print("Flash: ", end="")
printBar(bar100 - int(flash / b1), int(flash / b1))
print(terminal_color(str(flash / 1000) + " kB"))
print(terminal_color("-" * (bar100 + 20)))
uid = ubinascii.hexlify(machine.unique_id()).decode()
print(terminal_color("> ESP32 unique_id: ") + str(uid))
print(terminal_color("> uPy version: ") + str(os.uname()[3]))
print(terminal_color("> octopusLAB shell: ") + __version__)
print(terminal_color("-" * (bar100 + 20)))
raw_c = int(f2c(esp32.raw_temperature())*10)/10
print(terminal_color("> proc. raw_temperature: ") + terminal_color(str(raw_c) + " C", 31))
now = ticks_ms()
for job_id, job_info in _background_jobs.items():
job_duration = ticks_diff(now, job_info['start_time'])
job_command = ' '.join(job_info['command_list'])
print(
terminal_color(
"[{job_id}] {job_duration}s {job_command}".format(
job_id=job_id,
job_duration=job_duration / 1000,
job_command=job_command,
),
35
),
)
print(terminal_color(get_hhmmss(), 36))
@command
def wifi(comm="on"):
global _wc
# TODO: Remove depend libraries or document them
if _wc is None:
from utils.wifi_connect import WiFiConnect
_wc = WiFiConnect()
if comm == "on":
if _wc.connect():
print("WiFi: OK")
else:
print("WiFi: Connect error, check configuration")
if comm == "scan":
staactive = _wc.sta_if.active()
if not staactive:
_wc.sta_if.active(True)
from ubinascii import hexlify
print("networks:")
print('-' * SEPARATOR_WIDTH)
nets = [[item[0].decode('utf-8'), hexlify(item[1], ":").decode(), item[2], item[3], item[4]] for item in _wc.sta_if.scan()]
for net in nets:
print(str(net))
print('-' * SEPARATOR_WIDTH)
_wc.sta_if.active(staactive)
if comm == "off":
try:
_wc.sta_if.disconnect()
_wc.sta_if.active(False)
except Exception as e:
print("Exception: {0}".format(e))
@command
def ping(host='google.com'):
from lib.uping import ping
try:
ping(host)
except OSError as e:
if e.args[0] == -202:
print("ping: {}: Name or service not known".format(host))
else:
print("OSError, exception: {0}".format(e))
except Exception as e:
print("Exception: {0}".format(e))
@command # TODO
def upgrade(urlTar="https://octopusengine.org/download/micropython/stable.tar"):
from ..setup import deploy
from .terminal import printTitle
printTitle("upgrade from url > ")
print(urlTar)
try:
deploy(urlTar)
except Exception as e:
print("Exception: {0}".format(e))
@command
def clear():
print(chr(27) + "[2J") # clear terminal
print("\x1b[2J\x1b[H") # cursor up
@command
def run(filepath, *args):
# exec(open(file).read(), globals())
exec(open(filepath).read(), { "_ARGS": args })
@command
def ver():
print(__version__)
@command
def wgetapi(urlApi="https://www.octopusengine.org/api"):
# https://www.octopusengine.org/api/message.php
# get api text / jsoun / etc
from urequests import get
urltxt = urlApi + "/text123.txt"
dt_str = "?"
try:
response = get(urltxt)
dt_str = response.text
except Exception as e:
print("Err. read txt from URL", e)
print(dt_str)
@command
def wget(url="https://www.octopusengine.org/api/text123.txt",path="download"):
from .wget import wget
wget(url, path)
@command
def pwd():
from uos import getcwd
print(getcwd())
@command
def cd(directory=""):
from uos import chdir
try:
chdir(directory)
except OSError:
print("cd: {}: No such file or directory".format(directory))
@command
def exit():
raise SystemExit
@command
def help():
print("octopusLAB - simple shell help:")
cat("shell/octopus_shell_help.txt", False)
print()
class _release_cwd:
def __enter__(self):
from uos import getcwd
self.current_directory = getcwd()
def __exit__(self, type, value, traceback):
from uos import chdir
chdir(self.current_directory)
def parse_input(input_str):
command_list = input_str.strip().split()
# support for background jobs via `&` at the end of line
# TODO tests:
# arguments = ['one', 'two', 'three&']
# arguments = ['one', 'two', 'three', '&']
# arguments = ['&']
# arguments = ['one&']
# arguments = ['one', 'two', 'three']
# arguments = ['one']
# arguments = []
if command_list and command_list[-1][-1] == '&':
run_in_background = True
command_list[-1] = command_list[-1][:-1]
if not command_list[-1]:
command_list = command_list[:-1]
else:
run_in_background = False
return command_list, run_in_background
def shell():
from uos import getcwd
from sys import print_exception
from .terminal import terminal_color
with _release_cwd():
while True:
try:
input_str = input(
terminal_color("uPyShell", 32) + ":~" + getcwd() + "$ "
)
except KeyboardInterrupt:
print('^C')
continue
except EOFError:
print()
return
command_list, run_in_background = parse_input(input_str)
if not command_list:
continue
# hacky support for run ./file.py
if command_list[0][:2] == "./":
cmd = command_list.pop(0)
command_list = ['run', cmd[2:]] + command_list
cmd, *arguments = command_list
try:
func = _command_registry[cmd]
except KeyError:
print('{cmd}: command not found'.format(cmd=cmd))
continue
if run_in_background:
func = _background_func(func, command_list)
try:
func(*arguments)
except Exception as exc:
print_exception(exc)
except KeyboardInterrupt:
print('^C')
except SystemExit:
return