-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathgeneric_helper.py
More file actions
372 lines (300 loc) · 11 KB
/
Copy pathgeneric_helper.py
File metadata and controls
372 lines (300 loc) · 11 KB
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
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Generic helper
Collection of helper functions used in other modules
"""
import gc
import json
import logging as logging
from machine import machine
import os
import random
import sys
import time
import binascii as ubinascii
from typing import Optional, Union
class GenericHelper(object):
"""docstring for GenericHelper"""
def __init__(self):
pass # pragma: no cover
@staticmethod
def create_logger(logger_name: Optional[str] = None) -> logging.Logger:
"""
Create a logger.
:param logger_name: The logger name
:type logger_name: str, optional
:returns: Configured logger
:rtype: logging.Logger
"""
custom_format = '[%(asctime)s] [%(levelname)-8s] [%(filename)-15s @'\
' %(funcName)-15s:%(lineno)4s] %(message)s'
# configure logging
logging.basicConfig(level=logging.INFO,
format=custom_format,
stream=sys.stdout)
if logger_name and (isinstance(logger_name, str)):
logger = logging.getLogger(logger_name)
else:
logger = logging.getLogger(__name__)
# set the logger level to DEBUG if specified differently
logger.setLevel(logging.DEBUG)
return logger
@staticmethod
def set_level(logger: logging.Logger, level: str) -> None:
"""
Set the level of a logger.
:param logger: The logger to set the level
:type logger: logging.Logger
:param level: The new level
:type level: str
"""
if level.lower() == 'debug':
logger.setLevel(level=logging.DEBUG)
elif level.lower() == 'info':
logger.setLevel(level=logging.INFO)
elif level.lower() == 'warning':
logger.setLevel(level=logging.WARNING)
elif level.lower() == 'error':
logger.setLevel(level=logging.ERROR)
elif level.lower() == 'critical':
logger.setLevel(level=logging.CRITICAL)
else:
pass
@staticmethod
def set_logger_verbose_level(logger: logging.Logger,
verbose_level: int,
debug_output: bool):
"""
Set the logger verbose level and debug output
:param logger: The logger to apply the settings to
:type logger: logging.Logger
:param verbose_level: The verbose level
:type verbose_level: int
:param debug_output: The debug mode
:type debug_output: bool
"""
LOG_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
LOG_LEVELS = LOG_LEVELS[::-1]
if verbose_level is None:
if not debug_output:
# disable the logger
logger.disabled = True
else:
log_level = min(len(LOG_LEVELS) - 1, max(verbose_level, 0))
log_level_name = LOG_LEVELS[log_level]
# set the level of the logger
logger.setLevel(log_level_name)
@staticmethod
def get_random_value(lower: int = 0, upper: int = 255) -> int:
"""
Get a random value within the given range
:param lower: The lower boundary
:type lower: int, optional
:param upper: The upper boundary, inclusive, default 255
:type upper: int, optional
:returns: The random value.
:rtype: int
"""
return random.randint(lower, upper)
@staticmethod
def get_uuid(length: Optional[int] = None) -> bytes:
"""
Get the UUID of the device.
:param length: The length of the UUID
:type length: int, optional
:returns: The uuid.
:rtype: bytes
"""
uuid = ubinascii.hexlify(machine.unique_id())
if length is not None:
uuid_len = len(uuid)
amount = abs(length) // uuid_len + (abs(length) % uuid_len > 0)
if length < 0:
return (uuid * amount)[length:]
else:
return (uuid * amount)[:length]
else:
return uuid
@staticmethod
def df(path: str = '//', unit: Optional[str] = None) -> Union[int, str]:
"""
Get free disk space
:param path: Path to obtain informations
:type path: str, optional
:param unit: Unit of returned size [None, 'byte', 'kB', 'MB']
:type unit: str, optional
:returns: Available disk space in byte or as string in kB or MB
:rtype: int or str
"""
info = os.statvfs(path)
result = -1
if unit is None:
result = info[0] * info[3]
elif unit.lower() == 'byte':
result = ('{} byte'.format((info[0] * info[3])))
elif unit.lower() == 'kb':
result = ('{0:.3f} kB'.format((info[0] * info[3]) / 1024))
elif unit.lower() == 'mb':
result = ('{0:.3f} MB'.format((info[0] * info[3]) / 1048576))
return result
@staticmethod
def get_free_memory() -> dict:
"""
Get free memory (RAM)
:param update: Flag to collect latest informations
:type update: bool, optional
:returns: Informations about system RAM
:rtype: dict
"""
gc.collect()
free = gc.mem_free()
allocated = gc.mem_alloc()
total = free + allocated
if total:
percentage = '{0:.2f}%'.format((free / total) * 100)
else:
percentage = '100.00%'
memory_stats = {'free': free,
'total': total,
'percentage': percentage}
return memory_stats
@staticmethod
def free(full: bool = False) -> Union[int, str]:
"""
Get detailed informations about free RAM
:param full: Flag to return str with total, free, percentage
:type full: bool, optional
:returns: Informations, percentage by default
:rtype: int or str
"""
memory_stats = GenericHelper.get_free_memory()
if full is False:
return memory_stats['percentage']
else:
return ('Total: {0:.1f} kB, Free: {1:.2f} kB ({2})'.
format(memory_stats['total'] / 1024,
memory_stats['free'] / 1024,
memory_stats['percentage']))
@staticmethod
def get_system_infos_raw() -> dict:
"""
Get the raw system infos.
:returns: The raw system infos.
:rtype: dict
"""
sys_info = dict()
memory_info = GenericHelper.get_free_memory()
sys_info['df'] = GenericHelper.df(path='/', unit='kB')
sys_info['free_ram'] = memory_info['free']
sys_info['total_ram'] = memory_info['total']
sys_info['percentage_ram'] = memory_info['percentage']
sys_info['frequency'] = machine.freq()
sys_info['uptime'] = time.ticks_ms()
return sys_info
@staticmethod
def get_system_infos_human() -> dict:
"""
Get the human formatted system infos
:returns: The human formatted system infos.
:rtype: dict
"""
sys_info = dict()
memory_info = GenericHelper.get_free_memory()
# (year, month, mday, hour, minute, second, weekday, yearday)
# (0, 1, 2, 3, 4, 5, 6, 7)
seconds = int(time.ticks_ms() / 1000)
uptime = time.gmtime(seconds)
days = "{days:01d}".format(days=int(seconds / 86400))
sys_info['df'] = GenericHelper.df(path='/', unit='kB')
sys_info['free_ram'] = "{} kB".format(memory_info['free'] / 1000.0)
sys_info['total_ram'] = "{} kB".format(memory_info['total'] / 1000.0)
sys_info['percentage_ram'] = memory_info['percentage']
sys_info['frequency'] = "{} MHz".format(int(machine.freq() / 1000000))
sys_info['uptime'] = "{d} days, {hour:02d}:{min:02d}:{sec:02d}".format(
d=days,
hour=uptime[3],
min=uptime[4],
sec=uptime[5])
return sys_info
@staticmethod
def str_to_dict(data: str) -> dict:
"""
Convert string to dictionary
:param data: The data
:type data: str
:returns: Dictionary of string
:rtype: dict
"""
return json.loads(data.replace("'", "\""))
@staticmethod
def save_json(data: dict, path: str, mode: str = 'w') -> None:
"""
Save data as JSON file.
:param data: The data
:type data: dict
:param path: The path to the JSON file
:type path: str
:param mode: The mode of file operation
:type mode: str, optional
"""
with open(path, mode) as file:
json.dump(data, file)
@staticmethod
def load_json(path: str, mode: str = 'r') -> dict:
"""
Load data from JSON file.
:param path: The path to the JSON file
:type path: str
:param mode: The mode of file operation
:type mode: str, optional
:returns: Loaded data
:rtype: dict
"""
read_data = dict()
with open(path, mode) as file:
read_data = json.load(file)
return read_data
@staticmethod
def save_file(data: str, path: str, mode: str = 'wb') -> None:
"""
Save data to a file.
:param data: The data
:type data: str
:param path: The path to the file
:type path: str
:param mode: The mode of file operation
:type mode: str, optional
"""
# save to file as binary by default
with open(path, mode) as file:
file.write(data)
@staticmethod
def load_file(path: str, mode: str = 'rb') -> str:
"""
Wrapper for read_file.
:param path: The path to the file to read
:type path: str
:returns: The raw file content.
:rtype: str
:param mode: The mode of file operation
:type mode: str, optional
:returns: Content of file
:rtype: str
"""
return GenericHelper.read_file(path=path, mode=mode)
@staticmethod
def read_file(path: str, mode: str = 'rb') -> str:
"""
Read file content.
:param path: The path to the file to read
:type path: str
:param mode: The mode of file operation
:type mode: str, optional
:returns: The raw file content.
:rtype: str
"""
read_data = ""
with open(path, mode) as file:
read_data = file.read()
return read_data