Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
parkpow
GitHub Repository: parkpow/deep-license-plate-recognition
Path: blob/master/stream/ipro-adam-app/python/pymain.py
644 views
1
# import threading;
2
3
# debug
4
import traceback
5
6
# import numpy as np;
7
# import cv2;
8
import libAdamApiPython
9
10
# if print() output is delay, enalbe the following lines.
11
# sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering=1)
12
# sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', buffering=1)
13
14
15
def debugDbg(str):
16
# libAdamApiPython.adam_debug_print(libAdamApiPython.ADAM_LV_DBG, "[DBG] {}".format(str))
17
print(f"[DBG] {str}")
18
19
20
def debugErr(str):
21
# libAdamApiPython.adam_debug_print(libAdamApiPython.ADAM_LV_ERR, "[ERR] {}".format(str))
22
print(f"[ERR] {str}")
23
24
25
loop = None
26
license_key = memoryview(b"")
27
token = memoryview(b"")
28
stream_log_level = 0
29
enum_values = ["10", "20", "30", "40", "50"]
30
31
32
# Store pref names as constants
33
LICENSE_KEY_PREF = "LICENSE_KEY"
34
TOKEN_PREF = "TOKEN"
35
LOGGING_PREF = "LOGGING"
36
37
38
def stopCB():
39
global loop
40
print("Stop callback")
41
loop.exit()
42
43
44
ADAM_HTTP_REQ_TYPE_GET = 0
45
ADAM_HTTP_REQ_TYPE_POST = 1
46
47
48
def create_respone_header(body, status=200):
49
content_length = len(body)
50
assert len(str(status)) == 3, "status code must be 3 digits"
51
header = f"HTTP/1.1 {status} OK\r\nContent-Type: text/html\r\nContent-Length: {content_length}\r\n"
52
53
return header
54
55
56
def write_env_file(token, license_key, log_level):
57
debugDbg("Writing stream credentials to /ai_data/env-file.ini")
58
59
env_vars = {
60
"TOKEN": token,
61
"LICENSE_KEY": license_key,
62
"LOGGING": enum_values[log_level],
63
}
64
65
# Write or overwrite environment variables to ini file
66
env_file_path = "/ai_data/env-file.ini"
67
with open(env_file_path, "w") as env_file:
68
env_file.write("[DEFAULT]\n")
69
for key, value in env_vars.items():
70
env_file.write(f"{key}={value}\n")
71
72
73
def httpCB(reqType, reqData):
74
global license_key
75
global token
76
global stream_log_level
77
78
print("HTTP callback: type=%d" % reqType)
79
debugDbg("HTTP callback: reqType=%d" % reqType)
80
81
# body = b'body'
82
# header = "header"
83
# return (header, body)
84
85
# Html key words to be replaced
86
template_literals = [
87
"@pInstallID",
88
"@LICENSE_KEY_PREF",
89
"@TOKEN_PREF",
90
"@LOGGING_PREF_10",
91
"@LOGGING_PREF_20",
92
"@LOGGING_PREF_30",
93
"@LOGGING_PREF_40",
94
"@LOGGING_PREF_50",
95
]
96
97
try:
98
# get data directory
99
appPath = libAdamApiPython.adam_get_app_data_dir_path()
100
with open(f"{appPath}/index.html") as fp:
101
htmlData = fp.read()
102
103
print("reqType:%d" % reqType)
104
debugDbg("call httpCB: reqType=%d" % reqType)
105
if reqType == ADAM_HTTP_REQ_TYPE_GET:
106
debugDbg("Show html")
107
# load AppPref
108
loadPref()
109
elif reqType == ADAM_HTTP_REQ_TYPE_POST:
110
debugDbg("Edit html")
111
# set AppPref
112
setPref(reqData.decode("utf-8"))
113
else:
114
debugErr("call httpCB: reqType=%d" % reqType)
115
116
# set AppPref parameter
117
context = []
118
# Get App Install ID
119
install_id = "%08X" % libAdamApiPython.InstallId
120
context.append(install_id)
121
context.append(license_key.tobytes().decode("utf-8"))
122
context.append(token.tobytes().decode("utf-8"))
123
context.extend(get_stream_log_level_context(stream_log_level))
124
125
debugDbg(f"Context: {context}")
126
127
# replace parameters in html
128
cnt = 0
129
for keywd in template_literals:
130
htmlData = htmlData.replace(keywd, context[cnt])
131
cnt += 1
132
header = create_respone_header(htmlData)
133
134
except Exception as e:
135
debugErr(f"httpCB Exception: {e}")
136
htmlData = f"Server Error: {traceback.format_exc()}"
137
header = create_respone_header(htmlData, 500)
138
139
body = bytes(htmlData, "utf-8")
140
return header, body
141
142
143
def get_stream_log_level_context(stream_log_level: int) -> list:
144
"""
145
Generate selected attribute for stream log level options.
146
"""
147
selected = 'selected="selected"'
148
unselected = ""
149
150
context = []
151
152
for i, _value in enumerate(enum_values):
153
if stream_log_level == i:
154
context.append(selected)
155
else:
156
context.append(unselected)
157
158
return context
159
160
161
def appPrefCB(prefTuple):
162
global license_key
163
global token
164
global stream_log_level
165
166
libAdamApiPython.adam_lock_appPref()
167
168
if prefTuple == LICENSE_KEY_PREF:
169
license_key = memoryview(
170
libAdamApiPython.adam_get_appPref(LICENSE_KEY_PREF).encode()
171
)
172
elif prefTuple == TOKEN_PREF:
173
token = memoryview(libAdamApiPython.adam_get_appPref(TOKEN_PREF).encode())
174
175
elif prefTuple == LOGGING_PREF:
176
stream_log_level = libAdamApiPython.adam_get_appPref(LOGGING_PREF)
177
else:
178
print("Undefined AppPrefName: %s" % prefTuple)
179
180
libAdamApiPython.adam_unlock_appPref()
181
182
183
def loadPref():
184
global license_key
185
global token
186
global stream_log_level
187
188
libAdamApiPython.adam_lock_appPref()
189
license_key = memoryview(
190
libAdamApiPython.adam_get_appPref(LICENSE_KEY_PREF).encode()
191
)
192
token = memoryview(libAdamApiPython.adam_get_appPref(TOKEN_PREF).encode())
193
stream_log_level = libAdamApiPython.adam_get_appPref(LOGGING_PREF)
194
195
libAdamApiPython.adam_unlock_appPref()
196
197
debugDbg("loadPref adam_get_appPref")
198
debugDbg(f" license_key:{license_key}")
199
debugDbg(f" token:{token}")
200
debugDbg(f" stream_log_level :{stream_log_level}")
201
202
libAdamApiPython.adam_debug_print(
203
libAdamApiPython.ADAM_LV_INF,
204
f"PLATEREC - license_key={license_key}, token={token}, stream_log_level={stream_log_level}",
205
)
206
207
if license_key and token:
208
license_key_pref = license_key.tobytes().decode("utf-8")
209
token_pref = token.tobytes().decode("utf-8")
210
write_env_file(token_pref, license_key_pref, stream_log_level)
211
212
213
def setPref(pref_str):
214
global license_key
215
global token
216
global stream_log_level
217
218
debugDbg(f"Set Pref: {pref_str}")
219
pref = pref_str.split(",")
220
license_key_pref = pref[0]
221
token_pref = pref[1]
222
log_level_pref = pref[2]
223
224
license_key = memoryview(license_key_pref.encode())
225
token = memoryview(token_pref.encode())
226
stream_log_level = enum_values.index(log_level_pref)
227
228
libAdamApiPython.adam_lock_appPref()
229
libAdamApiPython.adam_set_appPref({LICENSE_KEY_PREF: license_key_pref})
230
libAdamApiPython.adam_set_appPref({TOKEN_PREF: token_pref})
231
libAdamApiPython.adam_set_appPref({LOGGING_PREF: stream_log_level})
232
libAdamApiPython.adam_unlock_appPref()
233
234
debugDbg("setPref adam_set_appPref")
235
debugDbg(f" license_key:{license_key_pref}")
236
debugDbg(f" license_token:{token_pref}")
237
debugDbg(f" stream_log_level :{stream_log_level}")
238
239
write_env_file(token_pref, license_key_pref, stream_log_level)
240
241
242
def startProcessing():
243
global loop
244
loop = libAdamApiPython.adamEventloop()
245
loadPref()
246
loop.dispatch()
247
del loop
248
print("Finish: Process")
249
250
251
if __name__ == "__main__":
252
print("Start: main thread")
253
# adam.setPrintLevel(0xffffffff)
254
255
libAdamApiPython.adam_set_stop_callback(stopCB)
256
libAdamApiPython.adam_set_http_callback(httpCB)
257
libAdamApiPython.adam_set_appPref_callback(appPrefCB)
258
259
# Case of executing image processing in same thread.
260
startProcessing()
261
262
print("Finish: main thread")
263
264