-
Notifications
You must be signed in to change notification settings - Fork 0
/
Util.py
74 lines (63 loc) · 2.13 KB
/
Util.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
#-*- coding: utf-8 -*-
from binascii import hexlify, unhexlify
import re
import json
import tempfile
def formatPortSettins(settings):
assert type(settings) is dict
try:
settings["baund"] = int(settings.get("baund", 9600))
settings["bytesize"] = int(settings.get("bytesize", 8))
settings["stopbits"] = int(settings.get("stopbits", 1))
except Exception, msg:
return False, msg
return True, "success"
def checkData(data, _type):
if data == '':
return False, u"数据不能为空"
errch, msg = None, "success"
if _type == "hex":
data = ''.join(data.split())
if len(data) % 2 != 0:
errch, msg = True, u"HEX模式下,数据长度必须为偶数"
else:
for ch in data.upper():
if not ('0' <= ch <= '9' or 'A' <= ch <= 'F'):
errch, msg = ch, u"数据中含有非法的HEX字符"
break
return not errch, msg
def filterData(data,regex):
if data == '':
return ''
try:
re_filter=re.compile(regex,re.DOTALL)
if re_filter.search(data):
return data
except Exception, e:
raise
def configSave(jsondata):
with open('config.json','w+') as jsonFile:
try:
json.dump(jsondata,jsonFile,indent=4)
except Exception, e:
print 'Config file save failed.'
finally:
jsonFile.close()
def configRead():
with open('config.json','a+') as jsonFile:
data=jsonFile.read()
try:
configData=json.loads(data)
return configData
except Exception, e:
print 'Config file no found,create default.'
defaultConfig={"curIndex":0,"ComboBoxList":["COM1:115200:8:N:1"]}
configSave(defaultConfig)
return defaultConfig
finally:
jsonFile.close()
toVisualHex = lambda data: ' '.join([hexlify(c) for c in data]).upper()
toHex = lambda data: ''.join([unhexlify(data[i:i+2]) for i in xrange(0, len(data), 2)])
if __name__=="__main__":
configRead()
#configSave("1")