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
1082 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 debug_dbg(str):
16
# libAdamApiPython.adam_debug_print(libAdamApiPython.ADAM_LV_DBG, "[DBG] {}".format(str))
17
print(f"[DBG] {str}")
18
19
20
def debug_err(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 stop_cb():
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
debug_dbg("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 http_cb(req_type, req_data):
74
global license_key
75
global token
76
global stream_log_level
77
78
print(f"HTTP callback: type={req_type}")
79
debug_dbg(f"HTTP callback: reqType={req_type}")
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
app_path = libAdamApiPython.adam_get_app_data_dir_path()
100
with open(f"{app_path}/index.html") as fp:
101
html_data = fp.read()
102
103
print(f"reqType:{req_type}")
104
debug_dbg(f"call httpCB: reqType={req_type}")
105
if req_type == ADAM_HTTP_REQ_TYPE_GET:
106
debug_dbg("Show html")
107
# load AppPref
108
load_pref()
109
elif req_type == ADAM_HTTP_REQ_TYPE_POST:
110
debug_dbg("Edit html")
111
# set AppPref
112
set_pref(req_data.decode("utf-8"))
113
else:
114
debug_err(f"call httpCB: reqType={req_type}")
115
116
# set AppPref parameter
117
context = []
118
# Get App Install ID
119
install_id = f"{libAdamApiPython.InstallId:08X}"
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
debug_dbg(f"Context: {context}")
126
127
# replace parameters in html
128
for i, keywd in enumerate(template_literals):
129
html_data = html_data.replace(keywd, context[i])
130
header = create_respone_header(html_data)
131
132
except Exception as e:
133
debug_err(f"httpCB Exception: {e}")
134
html_data = f"Server Error: {traceback.format_exc()}"
135
header = create_respone_header(html_data, 500)
136
137
body = bytes(html_data, "utf-8")
138
return header, body
139
140
141
def get_stream_log_level_context(stream_log_level: int) -> list:
142
"""
143
Generate selected attribute for stream log level options.
144
"""
145
selected = 'selected="selected"'
146
unselected = ""
147
148
context = []
149
150
for i, _value in enumerate(enum_values):
151
if stream_log_level == i:
152
context.append(selected)
153
else:
154
context.append(unselected)
155
156
return context
157
158
159
def app_pref_cb(pref_tuple):
160
global license_key
161
global token
162
global stream_log_level
163
164
libAdamApiPython.adam_lock_appPref()
165
166
if pref_tuple == LICENSE_KEY_PREF:
167
license_key = memoryview(
168
libAdamApiPython.adam_get_appPref(LICENSE_KEY_PREF).encode()
169
)
170
elif pref_tuple == TOKEN_PREF:
171
token = memoryview(libAdamApiPython.adam_get_appPref(TOKEN_PREF).encode())
172
173
elif pref_tuple == LOGGING_PREF:
174
stream_log_level = libAdamApiPython.adam_get_appPref(LOGGING_PREF)
175
else:
176
print(f"Undefined AppPrefName: {pref_tuple}")
177
178
libAdamApiPython.adam_unlock_appPref()
179
180
181
def load_pref():
182
global license_key
183
global token
184
global stream_log_level
185
186
libAdamApiPython.adam_lock_appPref()
187
license_key = memoryview(
188
libAdamApiPython.adam_get_appPref(LICENSE_KEY_PREF).encode()
189
)
190
token = memoryview(libAdamApiPython.adam_get_appPref(TOKEN_PREF).encode())
191
stream_log_level = libAdamApiPython.adam_get_appPref(LOGGING_PREF)
192
193
libAdamApiPython.adam_unlock_appPref()
194
195
debug_dbg("loadPref adam_get_appPref")
196
debug_dbg(f" license_key:{license_key}")
197
debug_dbg(f" token:{token}")
198
debug_dbg(f" stream_log_level :{stream_log_level}")
199
200
libAdamApiPython.adam_debug_print(
201
libAdamApiPython.ADAM_LV_INF,
202
f"PLATEREC - license_key={license_key}, token={token}, stream_log_level={stream_log_level}",
203
)
204
205
if license_key and token:
206
license_key_pref = license_key.tobytes().decode("utf-8")
207
token_pref = token.tobytes().decode("utf-8")
208
write_env_file(token_pref, license_key_pref, stream_log_level)
209
210
211
def set_pref(pref_str):
212
global license_key
213
global token
214
global stream_log_level
215
216
debug_dbg(f"Set Pref: {pref_str}")
217
pref = pref_str.split(",")
218
license_key_pref = pref[0]
219
token_pref = pref[1]
220
log_level_pref = pref[2]
221
222
license_key = memoryview(license_key_pref.encode())
223
token = memoryview(token_pref.encode())
224
stream_log_level = enum_values.index(log_level_pref)
225
226
libAdamApiPython.adam_lock_appPref()
227
libAdamApiPython.adam_set_appPref({LICENSE_KEY_PREF: license_key_pref})
228
libAdamApiPython.adam_set_appPref({TOKEN_PREF: token_pref})
229
libAdamApiPython.adam_set_appPref({LOGGING_PREF: stream_log_level})
230
libAdamApiPython.adam_unlock_appPref()
231
232
debug_dbg("setPref adam_set_appPref")
233
debug_dbg(f" license_key:{license_key_pref}")
234
debug_dbg(f" license_token:{token_pref}")
235
debug_dbg(f" stream_log_level :{stream_log_level}")
236
237
write_env_file(token_pref, license_key_pref, stream_log_level)
238
239
240
def start_processing():
241
global loop
242
loop = libAdamApiPython.adamEventloop()
243
load_pref()
244
loop.dispatch()
245
del loop
246
print("Finish: Process")
247
248
249
if __name__ == "__main__":
250
print("Start: main thread")
251
# adam.setPrintLevel(0xffffffff)
252
253
libAdamApiPython.adam_set_stop_callback(stop_cb)
254
libAdamApiPython.adam_set_http_callback(http_cb)
255
libAdamApiPython.adam_set_appPref_callback(app_pref_cb)
256
257
# Case of executing image processing in same thread.
258
start_processing()
259
260
print("Finish: main thread")
261
262